feature/IO-3225-Notifications-1.5: DB Changes
This commit is contained in:
@@ -2928,3 +2928,33 @@ exports.INSERT_NEW_DOCUMENT = `
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
exports.GET_AUTOADD_NOTIFICATION_USERS = `
|
||||
query GET_AUTOADD_NOTIFICATION_USERS($shopId: uuid!) {
|
||||
bodyshops_by_pk(id: $shopId) {
|
||||
id
|
||||
notification_followers
|
||||
}
|
||||
associations(where: {
|
||||
_and: [
|
||||
{ shopid: { _eq: $shopId } },
|
||||
{ active: { _eq: true } },
|
||||
{ notifications_autoadd: { _eq: true } }
|
||||
]
|
||||
}) {
|
||||
id
|
||||
useremail
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
exports.INSERT_JOB_WATCHERS = `
|
||||
mutation INSERT_JOB_WATCHERS($watchers: [job_watchers_insert_input!]!) {
|
||||
insert_job_watchers(objects: $watchers) {
|
||||
affected_rows
|
||||
returning {
|
||||
user_email
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
134
server/notifications/autoAddWatchers.js
Normal file
134
server/notifications/autoAddWatchers.js
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* @module autoAddWatchers
|
||||
* @description
|
||||
* This module handles automatically adding watchers to new jobs based on the notifications_autoadd
|
||||
* boolean field in the associations table and the notification_followers JSON field in the bodyshops table.
|
||||
* It ensures users are not added twice and logs the process.
|
||||
*/
|
||||
|
||||
const { client: gqlClient } = require("../graphql-client/graphql-client");
|
||||
const queries = require("../graphql-client/queries");
|
||||
const { isEmpty } = require("lodash");
|
||||
|
||||
// If true, the user who commits the action will NOT receive notifications; if false, they will.
|
||||
const FILTER_SELF_FROM_WATCHERS = process.env?.FILTER_SELF_FROM_WATCHERS !== "false";
|
||||
|
||||
/**
|
||||
* Adds watchers to a new job based on notifications_autoadd and notification_followers.
|
||||
*
|
||||
* @param {Object} req - The request object containing event data and logger.
|
||||
* @returns {Promise<void>} Resolves when watchers are added or if no action is needed.
|
||||
* @throws {Error} If critical data (e.g., jobId, shopId) is missing.
|
||||
*/
|
||||
const autoAddWatchers = async (req) => {
|
||||
const { event, trigger } = req.body;
|
||||
const { logger } = req;
|
||||
|
||||
// Validate that this is an INSERT event
|
||||
if (trigger?.name !== "notifications_jobs_autoadd" || event.op !== "INSERT" || event.data.old) {
|
||||
logger.log("Invalid event for auto-add watchers, skipping", "info", "notifications");
|
||||
return;
|
||||
}
|
||||
|
||||
const jobId = event?.data?.new?.id;
|
||||
const shopId = event?.data?.new?.shopid;
|
||||
const roNumber = event?.data?.new?.ro_number || "unknown";
|
||||
|
||||
if (!jobId || !shopId) {
|
||||
throw new Error(`Missing jobId (${jobId}) or shopId (${shopId}) for auto-add watchers`);
|
||||
}
|
||||
|
||||
const hasuraUserRole = event?.session_variables?.["x-hasura-role"];
|
||||
const hasuraUserId = event?.session_variables?.["x-hasura-user-id"];
|
||||
|
||||
try {
|
||||
// Fetch auto-add users and notification followers
|
||||
const autoAddData = await gqlClient.request(queries.GET_AUTOADD_NOTIFICATION_USERS, { shopId });
|
||||
|
||||
// Get users with notifications_autoadd: true
|
||||
const autoAddUsers =
|
||||
autoAddData?.associations?.map((assoc) => ({
|
||||
email: assoc.useremail,
|
||||
associationId: assoc.id
|
||||
})) || [];
|
||||
|
||||
// Get users from notification_followers (array of association IDs)
|
||||
const notificationFollowers = autoAddData?.bodyshops_by_pk?.notification_followers || [];
|
||||
let followerEmails = [];
|
||||
if (notificationFollowers.length > 0) {
|
||||
// Fetch associations for notification_followers
|
||||
const followerAssociations = await gqlClient.request(queries.GET_NOTIFICATION_ASSOCIATIONS, {
|
||||
emails: [], // Filter by association IDs
|
||||
shopid: shopId
|
||||
});
|
||||
followerEmails = followerAssociations.associations
|
||||
.filter((assoc) => notificationFollowers.includes(assoc.id))
|
||||
.map((assoc) => ({
|
||||
email: assoc.useremail,
|
||||
associationId: assoc.id
|
||||
}));
|
||||
}
|
||||
|
||||
// Combine and deduplicate emails (use email as the unique key)
|
||||
const usersToAdd = [...autoAddUsers, ...followerEmails].reduce((acc, user) => {
|
||||
if (!acc.some((u) => u.email === user.email)) {
|
||||
acc.push(user);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
if (isEmpty(usersToAdd)) {
|
||||
logger.log(`No users to auto-add for jobId "${jobId}" (RO: ${roNumber})`, "info", "notifications");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check existing watchers to avoid duplicates
|
||||
const existingWatchersData = await gqlClient.request(queries.GET_JOB_WATCHERS, { jobid: jobId });
|
||||
const existingWatcherEmails = existingWatchersData?.job_watchers?.map((w) => w.user_email) || [];
|
||||
|
||||
// Filter out already existing watchers and optionally the user who created the job
|
||||
const newWatchers = usersToAdd
|
||||
.filter((user) => !existingWatcherEmails.includes(user.email))
|
||||
.filter((user) => {
|
||||
if (FILTER_SELF_FROM_WATCHERS && hasuraUserRole === "user") {
|
||||
// Fetch user email for hasuraUserId to compare
|
||||
const userData = existingWatchersData?.job_watchers?.find((w) => w.user?.authid === hasuraUserId);
|
||||
return userData ? user.email !== userData.user_email : true;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((user) => ({
|
||||
jobid: jobId,
|
||||
user_email: user.email
|
||||
}));
|
||||
|
||||
if (isEmpty(newWatchers)) {
|
||||
logger.log(
|
||||
`No new watchers to add after filtering for jobId "${jobId}" (RO: ${roNumber})`,
|
||||
"info",
|
||||
"notifications"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert new watchers
|
||||
await gqlClient.request(queries.INSERT_JOB_WATCHERS, { watchers: newWatchers });
|
||||
logger.log(
|
||||
`Added ${newWatchers.length} auto-add watchers for jobId "${jobId}" (RO: ${roNumber})`,
|
||||
"info",
|
||||
"notifications",
|
||||
null,
|
||||
{ addedEmails: newWatchers.map((w) => w.user_email) }
|
||||
);
|
||||
} catch (error) {
|
||||
logger.log("Error adding auto-add watchers", "error", "notifications", null, {
|
||||
message: error?.message,
|
||||
stack: error?.stack,
|
||||
jobId,
|
||||
roNumber
|
||||
});
|
||||
throw error; // Re-throw to ensure the error is logged in the handler
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { autoAddWatchers };
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
const scenarioParser = require("./scenarioParser");
|
||||
const { autoAddWatchers } = require("./autoAddWatchers"); // New module
|
||||
|
||||
/**
|
||||
* Processes a notification event by invoking the scenario parser.
|
||||
@@ -185,6 +186,27 @@ const handlePartsDispatchChange = (req, res) => res.status(200).json({ message:
|
||||
*/
|
||||
const handlePartsOrderChange = (req, res) => res.status(200).json({ message: "Parts Order change handled." });
|
||||
|
||||
/**
|
||||
* Handle auto-add watchers for new jobs.
|
||||
*
|
||||
* @param {Object} req - Express request object.
|
||||
* @param {Object} res - Express response object.
|
||||
* @returns {Promise<Object>} JSON response with a success message.
|
||||
*/
|
||||
const handleAutoAddWatchers = async (req, res) => {
|
||||
const { logger } = req;
|
||||
|
||||
// Call autoAddWatchers but don't await it; log any error that occurs.
|
||||
autoAddWatchers(req).catch((error) => {
|
||||
logger.log("auto-add-watchers-error", "error", "notifications", null, {
|
||||
message: error?.message,
|
||||
stack: error?.stack
|
||||
});
|
||||
});
|
||||
|
||||
return res.status(200).json({ message: "Auto-Add Watchers Event Handled." });
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
handleJobsChange,
|
||||
handleBillsChange,
|
||||
@@ -195,5 +217,6 @@ module.exports = {
|
||||
handlePartsOrderChange,
|
||||
handlePaymentsChange,
|
||||
handleTasksChange,
|
||||
handleTimeTicketsChange
|
||||
handleTimeTicketsChange,
|
||||
handleAutoAddWatchers
|
||||
};
|
||||
|
||||
@@ -12,7 +12,8 @@ const {
|
||||
handleNotesChange,
|
||||
handlePaymentsChange,
|
||||
handleDocumentsChange,
|
||||
handleJobLinesChange
|
||||
handleJobLinesChange,
|
||||
handleAutoAddWatchers
|
||||
} = require("../notifications/eventHandlers");
|
||||
|
||||
const router = express.Router();
|
||||
@@ -33,5 +34,6 @@ router.post("/events/handleNotesChange", eventAuthorizationMiddleware, handleNot
|
||||
router.post("/events/handlePaymentsChange", eventAuthorizationMiddleware, handlePaymentsChange);
|
||||
router.post("/events/handleDocumentsChange", eventAuthorizationMiddleware, handleDocumentsChange);
|
||||
router.post("/events/handleJobLinesChange", eventAuthorizationMiddleware, handleJobLinesChange);
|
||||
router.post("/events/handleAutoAdd", eventAuthorizationMiddleware, handleAutoAddWatchers);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user