feature/IO-3291-Tasks-Notifications: Checkpoint

This commit is contained in:
Dave Richer
2025-07-08 13:52:59 -04:00
parent 9b53bd9b40
commit 2e3944099b
4 changed files with 133 additions and 185 deletions

View File

@@ -1,95 +1,88 @@
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { Badge, Button, Space, Spin, Switch, Tooltip, Typography } from "antd"; import { Badge, Spin, Typography } from "antd";
import { CheckCircleFilled, CheckCircleOutlined, EyeFilled, EyeOutlined } from "@ant-design/icons";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { forwardRef, useEffect, useRef } from "react"; import { forwardRef, useMemo, useRef } from "react";
import { DateTimeFormat } from "../../utils/DateFormatter.jsx"; import { DateTimeFormat } from "../../utils/DateFormatter.jsx";
import day from "../../utils/day.js"; import day from "../../utils/day.js";
import "./task-center.styles.scss"; import "./task-center.styles.scss";
const { Text, Title } = Typography; const { Text, Title } = Typography;
const TaskCenterComponent = forwardRef( const TaskCenterComponent = forwardRef(({ visible, tasks, loading, onTaskClick }, ref) => {
({ visible, tasks, loading, showIncompleteOnly, toggleIncomplete, markAllComplete, onTaskClick }, ref) => { const { t } = useTranslation();
const { t } = useTranslation(); const virtuosoRef = useRef(null);
const virtuosoRef = useRef(null);
useEffect(() => { // Organize tasks into sections
if (virtuosoRef.current) { const sections = useMemo(() => {
virtuosoRef.current.scrollToIndex({ index: 0, behavior: "smooth" }); const now = day();
} const today = now.startOf("day");
}, [showIncompleteOnly]);
// Filter tasks based on showIncompleteOnly const overdue = tasks.filter((task) => task.due_date && day(task.due_date).isBefore(today));
const filteredTasks = showIncompleteOnly ? tasks.filter((task) => !task.completed) : tasks; const dueToday = tasks.filter((task) => task.due_date && day(task.due_date).isSame(today, "day"));
const upcoming = tasks.filter((task) => task.due_date && day(task.due_date).isAfter(today));
const noDueDate = tasks.filter((task) => !task.due_date);
const renderTask = (index, task) => { return [
const handleClick = () => { { title: t("tasks.labels.overdue"), data: overdue },
onTaskClick(task.id); // Use the prop handler { title: t("tasks.labels.due_today"), data: dueToday },
}; { title: t("tasks.labels.upcoming"), data: upcoming },
{ title: t("tasks.labels.no_due_date"), data: noDueDate }
].filter((section) => section.data.length > 0);
}, [tasks, t]);
return ( const renderTask = (index, task) => {
<div const handleClick = () => {
key={`${task.id}-${index}`} onTaskClick(task.id);
className={`task-item ${task.completed ? "task-completed" : "task-incomplete"}`}
onClick={handleClick}
>
<Badge dot={!task.completed}>
<div className="task-content">
<Title level={5} className="task-title">
<span className="ro-number">
{t("notifications.labels.ro-number", {
ro_number: task.job?.ro_number || t("general.labels.na")
})}
</span>
<Text type="secondary" className="relative-time" title={DateTimeFormat(task.created_at)}>
{day(task.created_at).fromNow()}
</Text>
</Title>
<Text strong={!task.completed} className="task-body">
{task.title}
</Text>
</div>
</Badge>
</div>
);
}; };
return ( return (
<div className={`task-center ${visible ? "visible" : ""}`} ref={ref}> <div key={`${task.id}-${index}`} className="task-item task-incomplete" onClick={handleClick}>
<div className="task-header"> <Badge dot>
<Space direction="horizontal"> <div className="task-content">
<h3>{t("tasks.labels.my_tasks_center")}</h3> <Title level={5} className="task-title">
{loading && <Spin spinning={loading} size="small" />} <span className="ro-number">
</Space> {t("notifications.labels.ro-number", {
<div className="task-controls"> ro_number: task.job?.ro_number || t("general.labels.na")
<Tooltip title={t("tasks.labels.show-incomplete-only")}> })}
<Space size={4} align="center" className="task-toggle"> </span>
{showIncompleteOnly ? <EyeFilled /> : <EyeOutlined />} <Text type="secondary" className="relative-time" title={DateTimeFormat(task.created_at)}>
<Switch checked={showIncompleteOnly} onChange={(checked) => toggleIncomplete(checked)} size="small" /> {day(task.created_at).fromNow()}
</Space> </Text>
</Tooltip> </Title>
<Tooltip title={t("tasks.labels.mark-all-complete")}> <Text strong className="task-body">
<Button {task.title}
type="link" </Text>
icon={tasks.every((t) => t.completed) ? <CheckCircleFilled /> : <CheckCircleOutlined />}
onClick={markAllComplete}
disabled={!tasks.some((t) => !t.completed)}
/>
</Tooltip>
</div> </div>
</div> </Badge>
<Virtuoso
ref={virtuosoRef}
style={{ height: "400px", width: "100%" }}
data={filteredTasks}
totalCount={filteredTasks.length}
itemContent={renderTask}
/>
</div> </div>
); );
} };
);
const renderSection = (section, sectionIndex) => (
<div key={`section-${sectionIndex}`} className="task-section">
<Title level={4} className="section-title">
{section.title}
</Title>
{section.data.map((task, index) => renderTask(`${sectionIndex}-${index}`, task))}
</div>
);
return (
<div className={`task-center ${visible ? "visible" : ""}`} ref={ref}>
<div className="task-header">
<h3>{t("tasks.labels.my_tasks_center")}</h3>
{loading && <Spin spinning={loading} size="small" />}
</div>
<Virtuoso
ref={virtuosoRef}
style={{ height: "400px", width: "100%" }}
data={sections}
totalCount={sections.length}
itemContent={(index, section) => renderSection(section, index)}
/>
</div>
);
});
TaskCenterComponent.displayName = "TaskCenterComponent"; TaskCenterComponent.displayName = "TaskCenterComponent";

View File

@@ -1,15 +1,14 @@
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { useMutation, useQuery } from "@apollo/client"; import { useQuery } from "@apollo/client";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { createStructuredSelector } from "reselect"; import { createStructuredSelector } from "reselect";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors"; import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import { useSocket } from "../../contexts/SocketIO/useSocket"; import { useSocket } from "../../contexts/SocketIO/useSocket";
import { useIsEmployee } from "../../utils/useIsEmployee"; import { useIsEmployee } from "../../utils/useIsEmployee";
import { useNotification } from "../../contexts/Notifications/notificationContext"; import { QUERY_MY_TASKS_PAGINATED } from "../../graphql/tasks.queries";
import { MUTATION_TOGGLE_TASK_COMPLETED, QUERY_MY_TASKS_PAGINATED } from "../../graphql/tasks.queries";
import TaskCenterComponent from "./task-center.component"; import TaskCenterComponent from "./task-center.component";
import dayjs from "../../utils/day"; import dayjs from "../../utils/day";
import { setModalContext } from "../../redux/modals/modals.actions"; // Import setModalContext import { setModalContext } from "../../redux/modals/modals.actions";
const POLL_INTERVAL = 60; // seconds const POLL_INTERVAL = 60; // seconds
@@ -24,20 +23,28 @@ const mapDispatchToProps = (dispatch) => ({
const TaskCenterContainer = ({ visible, onClose, bodyshop, currentUser, setTaskUpsertContext }) => { const TaskCenterContainer = ({ visible, onClose, bodyshop, currentUser, setTaskUpsertContext }) => {
const [tasks, setTasks] = useState([]); const [tasks, setTasks] = useState([]);
const [showIncompleteOnly, setShowIncompleteOnly] = useState(true);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const { isConnected } = useSocket(); const { isConnected } = useSocket();
const isEmployee = useIsEmployee(bodyshop, currentUser); const isEmployee = useIsEmployee(bodyshop, currentUser);
const notification = useNotification();
const assignedToId = bodyshop?.employees?.find((e) => e.user_email === currentUser.email)?.id;
const where = useMemo(() => { // Compute assignedToId with useMemo to ensure stability
return { const assignedToId = useMemo(() => {
const employee = bodyshop?.employees?.find((e) => e.user_email === currentUser?.email);
if (employee?.id) {
console.log("AssignedToId computed:", employee.id); // Debug log
return employee.id;
}
return null;
}, [bodyshop, currentUser]);
const where = useMemo(
() => ({
assigned_to: { _eq: assignedToId }, assigned_to: { _eq: assignedToId },
deleted: { _eq: false }, deleted: { _eq: false },
...(showIncompleteOnly ? { completed: { _eq: false } } : {}) completed: { _eq: false }
}; }),
}, [assignedToId, showIncompleteOnly]); [assignedToId]
);
const { const {
data, data,
@@ -50,49 +57,24 @@ const TaskCenterContainer = ({ visible, onClose, bodyshop, currentUser, setTaskU
where, where,
offset: 0, offset: 0,
limit: 50, limit: 50,
order: [{ created_at: "desc" }] order: [{ due_date: "asc_nulls_last" }, { created_at: "desc" }]
}, },
skip: !bodyshop?.id || !assignedToId || !isEmployee, // Skip query if any required data is missing
skip: !bodyshop?.id || !assignedToId || !isEmployee || !currentUser?.email,
fetchPolicy: "cache-and-network", fetchPolicy: "cache-and-network",
pollInterval: isConnected ? 0 : dayjs.duration(POLL_INTERVAL, "seconds").asMilliseconds() pollInterval: isConnected ? 0 : dayjs.duration(POLL_INTERVAL, "seconds").asMilliseconds(),
// Log errors for debugging
onError: (error) => {
console.error("Query error:", error);
}
}); });
const [toggleTaskCompleted] = useMutation(MUTATION_TOGGLE_TASK_COMPLETED);
useEffect(() => { useEffect(() => {
if (data?.tasks) { if (data?.tasks) {
setTasks(data.tasks); setTasks(data.tasks);
} }
}, [data]); }, [data]);
const handleToggleIncomplete = (val) => {
setShowIncompleteOnly(val);
};
const handleMarkAllComplete = async () => {
setLoading(true);
try {
const incompleteTasks = tasks.filter((t) => !t.completed);
await Promise.all(
incompleteTasks.map((task) =>
toggleTaskCompleted({
variables: {
id: task.id,
completed: true,
completed_at: dayjs().toISOString()
}
})
)
);
notification.success({ message: "Tasks marked complete" });
refetch();
} catch (err) {
notification.error({ message: "Failed to mark tasks complete" });
} finally {
setLoading(false);
}
};
const handleTaskClick = useCallback( const handleTaskClick = useCallback(
(id) => { (id) => {
const task = tasks.find((t) => t.id === id); const task = tasks.find((t) => t.id === id);
@@ -105,7 +87,7 @@ const TaskCenterContainer = ({ visible, onClose, bodyshop, currentUser, setTaskU
}); });
} }
}, },
[tasks, setModalContext] [tasks, setTaskUpsertContext]
); );
return ( return (
@@ -114,10 +96,7 @@ const TaskCenterContainer = ({ visible, onClose, bodyshop, currentUser, setTaskU
onClose={onClose} onClose={onClose}
tasks={tasks} tasks={tasks}
loading={loading || queryLoading} loading={loading || queryLoading}
showIncompleteOnly={showIncompleteOnly} onTaskClick={handleTaskClick}
toggleIncomplete={handleToggleIncomplete}
markAllComplete={handleMarkAllComplete}
onTaskClick={handleTaskClick} // Pass the updated handler
/> />
); );
}; };

View File

@@ -18,7 +18,7 @@
} }
.task-header { .task-header {
padding: 4px 16px; padding: 8px 16px;
border-bottom: 1px solid #f0f0f0; border-bottom: 1px solid #f0f0f0;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@@ -30,57 +30,20 @@
font-size: 14px; font-size: 14px;
color: rgba(0, 0, 0, 0.85); color: rgba(0, 0, 0, 0.85);
} }
}
.task-controls { .task-section {
display: flex; margin-bottom: 8px;
align-items: center; }
gap: 8px;
.task-toggle { .section-title {
align-items: center; padding: 8px 16px;
background: #f5f5f5;
.anticon { margin: 0;
font-size: 14px; font-size: 14px;
color: #1677ff; color: rgba(0, 0, 0, 0.85);
vertical-align: middle; font-weight: 500;
} border-bottom: 1px solid #e8e8e8;
}
.ant-switch {
&.ant-switch-small {
min-width: 28px;
height: 16px;
line-height: 16px;
.ant-switch-handle {
width: 12px;
height: 12px;
}
&.ant-switch-checked {
background-color: #1677ff;
.ant-switch-handle {
left: calc(100% - 14px);
}
}
}
}
.ant-btn-link {
padding: 0;
color: #1677ff;
&:hover {
color: #69b1ff;
}
&:disabled {
color: rgba(0, 0, 0, 0.25);
cursor: not-allowed;
}
}
}
} }
.task-item { .task-item {
@@ -91,21 +54,12 @@
width: 100%; width: 100%;
box-sizing: border-box; box-sizing: border-box;
cursor: pointer; cursor: pointer;
background: #fff;
&:hover { &:hover {
background: #fafafa; background: #fafafa;
} }
&.task-completed {
background: #fff;
color: rgba(0, 0, 0, 0.65);
}
&.task-incomplete {
background: #f5f5f5;
color: rgba(0, 0, 0, 0.85);
}
.task-content { .task-content {
width: 100%; width: 100%;
} }
@@ -137,7 +91,8 @@
.task-body { .task-body {
margin-top: 4px; margin-top: 4px;
color: inherit; color: rgba(0, 0, 0, 0.85);
font-weight: 500;
} }
} }

View File

@@ -287,6 +287,27 @@ export const QUERY_JOB_TASKS_PAGINATED = gql`
} }
`; `;
export const QUERY_MY_COMPLETE_TASKS_PAGINATED = gql`
${PARTIAL_TASK_FIELDS}
query QUERY_MY_TASKS_PAGINATED(
$offset: Int
$limit: Int
$assigned_to: uuid!
$bodyshop: uuid!
$where: tasks_bool_exp
$order: [tasks_order_by!]!
) {
tasks(offset: $offset, limit: $limit, order_by: $order, where: $where) {
...TaskFields
}
tasks_aggregate(where: $where) {
aggregate {
count
}
}
}
`;
export const QUERY_MY_TASKS_PAGINATED = gql` export const QUERY_MY_TASKS_PAGINATED = gql`
${PARTIAL_TASK_FIELDS} ${PARTIAL_TASK_FIELDS}
query QUERY_MY_TASKS_PAGINATED( query QUERY_MY_TASKS_PAGINATED(