feature/IO-3291-Tasks-Notifications: Checkpoint

This commit is contained in:
Dave Richer
2025-07-10 13:18:01 -04:00
parent 79e379b61a
commit 1127864ba9
10 changed files with 749 additions and 470 deletions

View File

@@ -342,7 +342,11 @@ function Header(props) {
</div>
)}
<div ref={taskCenterRef}>
<TaskCenterContainer visible={taskCenterVisible} onClose={() => setTaskCenterVisible(false)} />
<TaskCenterContainer
incompleteTaskCount={incompleteTaskCount}
visible={taskCenterVisible}
onClose={() => setTaskCenterVisible(false)}
/>
</div>
</Layout.Header>
);

View File

@@ -13,7 +13,7 @@ import {
} from "@ant-design/icons";
const TaskCenterComponent = forwardRef(
({ visible, tasks, loading, error, onTaskClick, onLoadMore, hasMore, createNewTask }, ref) => {
({ visible, tasks, loading, error, onTaskClick, onLoadMore, hasMore, createNewTask, incompleteTaskCount }, ref) => {
const { t } = useTranslation();
const virtuosoRef = useRef(null);
@@ -56,11 +56,17 @@ const TaskCenterComponent = forwardRef(
const getPriorityColor = (priority) => priorityColors[priority] || null;
const groupContent = (groupIndex) => {
const { label } = groups[groupIndex];
const { label, tasks } = groups[groupIndex];
let displayCount = tasks.length;
if (label === t("tasks.labels.no_due_date")) {
displayCount =
incompleteTaskCount -
groups.reduce((sum, group, idx) => (idx !== groupIndex ? sum + group.tasks.length : sum), 0);
}
return (
<div className="section-title">
{sectionIcons[label]}
{label} ({groups[groupIndex].tasks.length})
{label} ({displayCount})
</div>
);
};
@@ -112,9 +118,9 @@ const TaskCenterComponent = forwardRef(
return (
<div className={`task-center ${visible ? "visible" : ""}`} ref={ref}>
<div className="task-header">
<h3>
{t("tasks.labels.my_tasks_center")} ({tasks.length})
</h3>
<Badge count={incompleteTaskCount} size="medium" offset={[13, -5]}>
<h3>{t("tasks.labels.my_tasks_center")}</h3>
</Badge>
<div className="task-header-actions">
<Button className="create-task-button" type="link" icon={<PlusCircleOutlined />} onClick={createNewTask} />
{loading && <Spin spinning={loading} size="small" />}

View File

@@ -10,7 +10,7 @@ import { setModalContext } from "../../redux/modals/modals.actions";
import { QUERY_TASKS_NO_DUE_DATE_PAGINATED, QUERY_TASKS_WITH_DUE_DATES } from "../../graphql/tasks.queries";
const POLL_INTERVAL = 60 * 1000; // milliseconds
const LIMIT = 50; // Tasks per page for no-due-date tasks
const LIMIT = 5; // Tasks per page for no-due-date tasks
const mapStateToProps = createStructuredSelector({
bodyshop: selectBodyshop,
@@ -21,7 +21,14 @@ const mapDispatchToProps = (dispatch) => ({
setTaskUpsertContext: (context) => dispatch(setModalContext({ context, modal: "taskUpsert" }))
});
const TaskCenterContainer = ({ visible, onClose, bodyshop, currentUser, setTaskUpsertContext }) => {
const TaskCenterContainer = ({
visible,
onClose,
bodyshop,
currentUser,
setTaskUpsertContext,
incompleteTaskCount
}) => {
const [tasks, setTasks] = useState([]);
const { isConnected } = useSocket();
const isEmployee = useIsEmployee(bodyshop, currentUser);
@@ -123,6 +130,7 @@ const TaskCenterContainer = ({ visible, onClose, bodyshop, currentUser, setTaskU
onLoadMore={handleLoadMore}
hasMore={hasMore}
createNewTask={createNewTask}
incompleteTaskCount={incompleteTaskCount}
/>
);
};

View File

@@ -54,8 +54,8 @@ export function TaskListContainer({
bodyshop: bodyshop.id,
[relationshipType]: relationshipId,
deleted: deleted === "true",
completed: completed === "true", //TODO: Find where mine is set.
assigned_to: onlyMine ? bodyshop?.employees?.find((e) => e.user_email === currentUser.email)?.id : undefined, // replace currentUserID with the actual ID of the current user
completed: completed === "true",
assigned_to: onlyMine ? bodyshop?.employees?.find((e) => e.user_email === currentUser.email)?.id : undefined,
offset: page ? (page - 1) * pageLimit : 0,
limit: pageLimit,
order: [

View File

@@ -1,4 +1,3 @@
// SocketProvider.js
import { useEffect, useRef, useState } from "react";
import SocketIO from "socket.io-client";
import { auth } from "../../firebase/firebase.utils";
@@ -16,7 +15,14 @@ import {
import { useMutation } from "@apollo/client";
import { useTranslation } from "react-i18next";
import { useSplitTreatments } from "@splitsoftware/splitio-react";
import { SocketContext, INITIAL_NOTIFICATIONS } from "./useSocket.js";
import { INITIAL_NOTIFICATIONS, SocketContext } from "./useSocket.js";
import {
QUERY_MY_TASKS_COUNT,
QUERY_TASKS_NO_DUE_DATE_PAGINATED,
QUERY_TASKS_WITH_DUE_DATES
} from "../../graphql/tasks.queries";
const LIMIT = 50; // Tasks per page for no-due-date tasks
/**
* Socket Provider - Scenario Notifications / Web Socket related items
@@ -168,6 +174,103 @@ const SocketProvider = ({ children, bodyshop, navigate, currentUser }) => {
case "alert-update":
store.dispatch(addAlerts(message.payload));
break;
case "task-created":
case "task-updated":
case "task-deleted":
const payload = message.payload;
const assignedToId = bodyshop?.employees?.find((e) => e.user_email === currentUser?.email)?.id;
if (!assignedToId || payload.assigned_to !== assignedToId) return;
// Handle due date tasks cache update
const dueVars = {
bodyshop: bodyshop?.id,
assigned_to: assignedToId,
order: [{ due_date: "asc" }, { created_at: "desc" }]
};
let hasDueCache = false;
try {
client.readQuery({ query: QUERY_TASKS_WITH_DUE_DATES, variables: dueVars });
hasDueCache = true;
} catch (e) {}
if (hasDueCache) {
client
.query({ query: QUERY_TASKS_WITH_DUE_DATES, variables: dueVars, fetchPolicy: "network-only" })
.then(({ data }) => {
client.writeQuery({ query: QUERY_TASKS_WITH_DUE_DATES, variables: dueVars, data });
})
.catch((e) => console.error("Task due refetch error:", e));
}
// Handle no due date tasks cache update
const originalNoDueVars = {
bodyshop: bodyshop?.id,
assigned_to: assignedToId,
order: [{ created_at: "desc" }],
limit: LIMIT,
offset: 0
};
let currentLength = 0;
try {
const existing = client.readQuery({
query: QUERY_TASKS_NO_DUE_DATE_PAGINATED,
variables: originalNoDueVars
});
currentLength = existing?.tasks?.length || 0;
} catch (e) {}
if (currentLength > 0) {
let fetchLimit = currentLength;
if (message.type === "task-created") {
fetchLimit += 1;
} else if (message.type === "task-deleted") {
fetchLimit = Math.max(currentLength - 1, 0);
}
if (fetchLimit > 0) {
const fetchVars = { ...originalNoDueVars, limit: fetchLimit };
client
.query({
query: QUERY_TASKS_NO_DUE_DATE_PAGINATED,
variables: fetchVars,
fetchPolicy: "network-only"
})
.then(({ data }) => {
client.writeQuery({
query: QUERY_TASKS_NO_DUE_DATE_PAGINATED,
variables: originalNoDueVars,
data: {
tasks: data.tasks,
tasks_aggregate: data.tasks_aggregate
}
});
})
.catch((e) => console.error("Task no due refetch error:", e));
} else {
client.writeQuery({
query: QUERY_TASKS_NO_DUE_DATE_PAGINATED,
variables: originalNoDueVars,
data: { tasks: [], tasks_aggregate: { aggregate: { count: 0 } } }
});
}
}
// Handle task count cache update
const countVars = {
assigned_to: assignedToId,
bodyshopid: bodyshop?.id
};
let hasCountCache = false;
try {
client.readQuery({ query: QUERY_MY_TASKS_COUNT, variables: countVars });
hasCountCache = true;
} catch (e) {}
if (hasCountCache) {
client
.query({ query: QUERY_MY_TASKS_COUNT, variables: countVars, fetchPolicy: "network-only" })
.then(({ data }) => {
client.writeQuery({ query: QUERY_MY_TASKS_COUNT, variables: countVars, data });
})
.catch((e) => console.error("Task count refetch error:", e));
}
break;
default:
break;
}

View File

@@ -6344,11 +6344,13 @@
- joblineid
- assigned_to
- due_date
- deleted
- partsorderid
- completed
- description
- billid
- title
- jobid
- priority
retry_conf:
interval_sec: 10

958
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,14 +16,14 @@
"job-totals-fixtures:local": "docker exec node-app /usr/bin/node /app/download-job-totals-fixtures.js"
},
"dependencies": {
"@aws-sdk/client-cloudwatch-logs": "^3.826.0",
"@aws-sdk/client-elasticache": "^3.826.0",
"@aws-sdk/client-s3": "^3.826.0",
"@aws-sdk/client-secrets-manager": "^3.826.0",
"@aws-sdk/client-ses": "^3.826.0",
"@aws-sdk/credential-provider-node": "^3.826.0",
"@aws-sdk/lib-storage": "^3.826.0",
"@aws-sdk/s3-request-presigner": "^3.826.0",
"@aws-sdk/client-cloudwatch-logs": "^3.844.0",
"@aws-sdk/client-elasticache": "^3.844.0",
"@aws-sdk/client-s3": "^3.844.0",
"@aws-sdk/client-secrets-manager": "^3.844.0",
"@aws-sdk/client-ses": "^3.844.0",
"@aws-sdk/credential-provider-node": "^3.844.0",
"@aws-sdk/lib-storage": "^3.844.0",
"@aws-sdk/s3-request-presigner": "^3.844.0",
"@opensearch-project/opensearch": "^2.13.0",
"@socket.io/admin-ui": "^0.5.1",
"@socket.io/redis-adapter": "^8.3.0",
@@ -31,14 +31,14 @@
"aws4": "^1.13.2",
"axios": "^1.8.4",
"better-queue": "^3.8.12",
"bullmq": "^5.53.2",
"bullmq": "^5.56.3",
"chart.js": "^4.4.8",
"cloudinary": "^2.6.1",
"compression": "^1.8.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"crisp-status-reporter": "^1.2.2",
"dd-trace": "^5.55.0",
"dd-trace": "^5.58.0",
"dinero.js": "^1.9.1",
"dotenv": "^16.4.5",
"express": "^4.21.1",
@@ -65,7 +65,7 @@
"socket.io": "^4.8.1",
"socket.io-adapter": "^2.5.5",
"ssh2-sftp-client": "^11.0.0",
"twilio": "^5.7.0",
"twilio": "^5.7.3",
"uuid": "^11.1.0",
"winston": "^3.17.0",
"winston-cloudwatch": "^6.3.0",
@@ -81,7 +81,7 @@
"mock-require": "^3.0.3",
"p-limit": "^3.1.0",
"prettier": "^3.5.3",
"supertest": "^7.1.1",
"supertest": "^7.1.3",
"vitest": "^3.2.3"
}
}

View File

@@ -152,9 +152,56 @@ const handlePaymentsChange = async (req, res) =>
* @param {Object} res - Express response object.
* @returns {Promise<Object>} JSON response with a success message.
*/
const handleTasksChange = async (req, res) =>
const handleTasksChange = async (req, res) => {
console.log("Handling tasks change notification...!!!!!!!!!!!!");
// Handle Notification Event
processNotificationEvent(req, res, "req.body.event.new.jobid", "Tasks Notifications Event Handled.");
const {
logger,
ioRedis,
ioHelpers: { getBodyshopRoom }
} = req;
const event = req.body.event;
const op = event.op;
let taskData;
let type;
let bodyshopId;
if (op === "INSERT") {
taskData = event.data.new;
if (taskData.deleted) {
logger.log("tasks-event-insert-deleted", "warn", "notifications", null, { id: taskData.id });
} else {
type = "task-created";
bodyshopId = taskData.bodyshopid;
}
} else if (op === "UPDATE") {
const newData = event.data.new;
const oldData = event.data.old;
taskData = newData;
bodyshopId = newData.bodyshopid;
if (newData.deleted && !oldData.deleted) {
type = "task-deleted";
taskData = { id: newData.id };
} else if (!newData.deleted && oldData.deleted) {
type = "task-created";
} else if (!newData.deleted) {
type = "task-updated";
}
} else {
logger.log("tasks-event-unknown-op", "warn", "notifications", null, { op });
}
if (bodyshopId && ioRedis && type) {
const room = getBodyshopRoom(bodyshopId);
ioRedis.to(room).emit("bodyshop-message", { type, payload: taskData });
logger.log("tasks-event-emitted", "info", "notifications", null, { type, bodyshopId });
} else if (type) {
logger.log("tasks-event-missing-data", "error", "notifications", null, { bodyshopId, hasIo: !!ioRedis, type });
}
};
/**
* Handle time tickets change notifications.
*

View File

@@ -26,6 +26,7 @@ const redisSocketEvents = ({
try {
const user = await admin.auth().verifyIdToken(token);
socket.user = user;
socket.bodyshopId = bodyshopId;
await addUserSocketMapping(user.email, socket.id, bodyshopId);
next();
} catch (error) {
@@ -55,12 +56,8 @@ const redisSocketEvents = ({
return;
}
socket.user = user;
socket.bodyshopId = bodyshopId;
await refreshUserSocketTTL(user.email, bodyshopId);
createLogEvent(
socket,
"debug",
`Token updated successfully for socket ID: ${socket.id} (bodyshop: ${bodyshopId})`
);
socket.emit("token-updated", { success: true });
} catch (error) {
if (error.code === "auth/id-token-expired") {
@@ -82,7 +79,6 @@ const redisSocketEvents = ({
try {
const room = getBodyshopRoom(bodyshopUUID);
socket.join(room);
// createLogEvent(socket, "debug", `Client joined bodyshop room: ${room}`);
} catch (error) {
createLogEvent(socket, "error", `Error joining room: ${error}`);
}
@@ -92,7 +88,6 @@ const redisSocketEvents = ({
try {
const room = getBodyshopRoom(bodyshopUUID);
socket.leave(room);
createLogEvent(socket, "debug", `Client left bodyshop room: ${room}`);
} catch (error) {
createLogEvent(socket, "error", `Error joining room: ${error}`);
}
@@ -102,8 +97,6 @@ const redisSocketEvents = ({
try {
const room = getBodyshopRoom(bodyshopUUID);
io.to(room).emit("bodyshop-message", message);
// We do not need this as these can be debugged live
// createLogEvent(socket, "debug", `Broadcast message to bodyshop ${room}`);
} catch (error) {
createLogEvent(socket, "error", `Error getting room: ${error}`);
}
@@ -200,11 +193,6 @@ const redisSocketEvents = ({
io.to(socketId).emit("sync-notification-read", { notificationId, timestamp });
}
});
createLogEvent(
socket,
"debug",
`Synced notification ${notificationId} read for ${userEmail} in bodyshop ${bodyshopId}`
);
}
} catch (error) {
createLogEvent(socket, "error", `Error syncing notification read: ${error.message}`);
@@ -223,7 +211,6 @@ const redisSocketEvents = ({
io.to(socketId).emit("sync-all-notifications-read", { timestamp });
}
});
createLogEvent(socket, "debug", `Synced all notifications read for ${email} in bodyshop ${bodyshopId}`);
}
} catch (error) {
createLogEvent(socket, "error", `Error syncing all notifications read: ${error.message}`);
@@ -231,12 +218,34 @@ const redisSocketEvents = ({
});
};
// Task Events
const registerTaskEvents = (socket) => {
socket.on("task-created", (payload) => {
if (!payload) return;
const room = getBodyshopRoom(socket.bodyshopId);
io.to(room).emit("bodyshop-message", { type: "task-created", payload });
});
socket.on("task-updated", (payload) => {
if (!payload) return;
const room = getBodyshopRoom(socket.bodyshopId);
io.to(room).emit("bodyshop-message", { type: "task-updated", payload });
});
socket.on("task-deleted", (payload) => {
if (!payload || !payload.id) return;
const room = getBodyshopRoom(socket.bodyshopId);
io.to(room).emit("bodyshop-message", { type: "task-deleted", payload });
});
};
// Call Handlers
registerRoomAndBroadcastEvents(socket);
registerUpdateEvents(socket);
registerMessagingEvents(socket);
registerDisconnectEvents(socket);
registerSyncEvents(socket);
registerTaskEvents(socket);
};
// Associate Middleware and Handlers