Compare commits

..

1 Commits

Author SHA1 Message Date
Dave
71c6d9fa94 IO-3473 trim user input 2025-12-19 12:07:30 -05:00
5 changed files with 114 additions and 71 deletions

View File

@@ -16,7 +16,6 @@ export default function ShopInfoNotificationsAutoadd({ bodyshop }) {
<Text type="secondary">{t("bodyshop.labels.notifications.followers")}</Text> <Text type="secondary">{t("bodyshop.labels.notifications.followers")}</Text>
{employeeOptions.length > 0 ? ( {employeeOptions.length > 0 ? (
<Form.Item <Form.Item
normalize={(value) => (value || []).filter((id) => typeof id === "string" && id.trim() !== "")}
name="notification_followers" name="notification_followers"
rules={[ rules={[
{ {
@@ -43,6 +42,11 @@ export default function ShopInfoNotificationsAutoadd({ bodyshop }) {
options={employeeOptions} options={employeeOptions}
placeholder={t("bodyshop.fields.notifications.placeholder")} placeholder={t("bodyshop.fields.notifications.placeholder")}
showEmail={true} showEmail={true}
onChange={(value) => {
// Filter out null or invalid values before passing to Form
const cleanedValue = value?.filter((id) => id != null && typeof id === "string" && id.trim() !== "");
return cleanedValue;
}}
/> />
</Form.Item> </Form.Item>
) : ( ) : (

View File

@@ -1156,11 +1156,7 @@
enable_manual: false enable_manual: false
update: update:
columns: columns:
- imexshopid
- timezone
- shopname - shopname
- notification_followers
- state
- md_order_statuses - md_order_statuses
retry_conf: retry_conf:
interval_sec: 10 interval_sec: 10
@@ -3702,7 +3698,6 @@
- deliverchecklist - deliverchecklist
- depreciation_taxes - depreciation_taxes
- dms_allocation - dms_allocation
- dms_id
- driveable - driveable
- employee_body - employee_body
- employee_csr - employee_csr
@@ -3980,7 +3975,6 @@
- deliverchecklist - deliverchecklist
- depreciation_taxes - depreciation_taxes
- dms_allocation - dms_allocation
- dms_id
- driveable - driveable
- employee_body - employee_body
- employee_csr - employee_csr
@@ -4270,7 +4264,6 @@
- deliverchecklist - deliverchecklist
- depreciation_taxes - depreciation_taxes
- dms_allocation - dms_allocation
- dms_id
- driveable - driveable
- employee_body - employee_body
- employee_csr - employee_csr

View File

@@ -2926,15 +2926,6 @@ exports.GET_BODYSHOP_BY_ID = `
} }
`; `;
exports.GET_BODYSHOP_WATCHERS_BY_ID = `
query GET_BODYSHOP_BY_ID($id: uuid!) {
bodyshops_by_pk(id: $id) {
id
notification_followers
}
}
`;
exports.GET_DOCUMENTS_BY_JOB = ` exports.GET_DOCUMENTS_BY_JOB = `
query GET_DOCUMENTS_BY_JOB($jobId: uuid!) { query GET_DOCUMENTS_BY_JOB($jobId: uuid!) {
jobs_by_pk(id: $jobId) { jobs_by_pk(id: $jobId) {

View File

@@ -77,9 +77,8 @@ const generateResetLink = async (email) => {
*/ */
const ensureExternalIdUnique = async (externalId) => { const ensureExternalIdUnique = async (externalId) => {
const resp = await client.request(CHECK_EXTERNAL_SHOP_ID, { key: externalId }); const resp = await client.request(CHECK_EXTERNAL_SHOP_ID, { key: externalId });
if (resp.bodyshops.length) {
throw { status: 400, message: `external_shop_id '${externalId}' is already in use.` }; return !!resp.bodyshops.length;
}
}; };
/** /**
@@ -225,10 +224,25 @@ const patchPartsManagementProvisioning = async (req, res) => {
*/ */
const partsManagementProvisioning = async (req, res) => { const partsManagementProvisioning = async (req, res) => {
const { logger } = req; const { logger } = req;
const body = { ...req.body, userEmail: req.body.userEmail?.toLowerCase() };
// Trim and normalize email early
const body = {
...req.body,
userEmail: req.body.userEmail?.trim().toLowerCase()
};
const trim = (value) => (typeof value === "string" ? value.trim() : value);
const trimIfString = (value) =>
value !== null && value !== undefined && typeof value === "string" ? value.trim() : value;
try { try {
// Ensure email is present and trimmed before checking registration
if (!body.userEmail) {
throw { status: 400, message: "userEmail is required" };
}
await ensureEmailNotRegistered(body.userEmail); await ensureEmailNotRegistered(body.userEmail);
requireFields(body, [ requireFields(body, [
"external_shop_id", "external_shop_id",
"shopname", "shopname",
@@ -242,28 +256,68 @@ const partsManagementProvisioning = async (req, res) => {
"userEmail" "userEmail"
]); ]);
// TODO add in check for early access // Trim all top-level string fields
await ensureExternalIdUnique(body.external_shop_id); const trimmedBody = {
...body,
external_shop_id: trim(body.external_shop_id),
shopname: trim(body.shopname),
address1: trim(body.address1),
address2: trimIfString(body.address2),
city: trim(body.city),
state: trim(body.state),
zip_post: trim(body.zip_post),
country: trim(body.country),
email: trim(body.email),
phone: trim(body.phone),
timezone: trimIfString(body.timezone),
logoUrl: trimIfString(body.logoUrl),
userPassword: body.userPassword, // passwords should NOT be trimmed (preserves intentional spaces if any, though rare)
vendors: Array.isArray(body.vendors)
? body.vendors.map((v) => ({
name: trim(v.name),
street1: trimIfString(v.street1),
street2: trimIfString(v.street2),
city: trimIfString(v.city),
state: trimIfString(v.state),
zip: trimIfString(v.zip),
country: trimIfString(v.country),
email: trimIfString(v.email),
cost_center: trimIfString(v.cost_center),
phone: trimIfString(v.phone),
dmsid: trimIfString(v.dmsid),
discount: v.discount ?? 0,
due_date: v.due_date ?? null,
favorite: v.favorite ?? [],
active: v.active ?? true
}))
: []
};
logger.log("admin-create-shop-user", "debug", body.userEmail, null, { const duplicateCheck = await ensureExternalIdUnique(trimmedBody.external_shop_id);
if (duplicateCheck) {
throw { status: 400, message: `external_shop_id '${trimmedBody.external_shop_id}' is already in use.` };
}
logger.log("admin-create-shop-user", "debug", trimmedBody.userEmail, null, {
request: req.body, request: req.body,
ioadmin: true ioadmin: true
}); });
const shopInput = { const shopInput = {
shopname: body.shopname, shopname: trimmedBody.shopname,
address1: body.address1, address1: trimmedBody.address1,
address2: body.address2 || null, address2: trimmedBody.address2,
city: body.city, city: trimmedBody.city,
state: body.state, state: trimmedBody.state,
zip_post: body.zip_post, zip_post: trimmedBody.zip_post,
country: body.country, country: trimmedBody.country,
email: body.email, email: trimmedBody.email,
external_shop_id: body.external_shop_id, external_shop_id: trimmedBody.external_shop_id,
timezone: body.timezone || DefaultNewShop.timezone, timezone: trimmedBody.timezone || DefaultNewShop.timezone,
phone: body.phone, phone: trimmedBody.phone,
logo_img_path: { logo_img_path: {
src: body.logoUrl, src: trimmedBody.logoUrl || null, // allow empty logo
width: "", width: "",
height: "", height: "",
headerMargin: DefaultNewShop.logo_img_path.headerMargin headerMargin: DefaultNewShop.logo_img_path.headerMargin
@@ -288,35 +342,37 @@ const partsManagementProvisioning = async (req, res) => {
appt_alt_transport: DefaultNewShop.appt_alt_transport, appt_alt_transport: DefaultNewShop.appt_alt_transport,
md_jobline_presets: DefaultNewShop.md_jobline_presets, md_jobline_presets: DefaultNewShop.md_jobline_presets,
vendors: { vendors: {
data: body.vendors.map((v) => ({ data: trimmedBody.vendors.map((v) => ({
name: v.name, name: v.name,
street1: v.street1 || null, street1: v.street1,
street2: v.street2 || null, street2: v.street2,
city: v.city || null, city: v.city,
state: v.state || null, state: v.state,
zip: v.zip || null, zip: v.zip,
country: v.country || null, country: v.country,
email: v.email || null, email: v.email,
discount: v.discount ?? 0, discount: v.discount,
due_date: v.due_date ?? null, due_date: v.due_date,
cost_center: v.cost_center || null, cost_center: v.cost_center,
favorite: v.favorite ?? [], favorite: v.favorite,
phone: v.phone || null, phone: v.phone,
active: v.active ?? true, active: v.active,
dmsid: v.dmsid || null dmsid: v.dmsid
})) }))
} }
}; };
const newShopId = await insertBodyshop(shopInput); const newShopId = await insertBodyshop(shopInput);
const userRecord = await createFirebaseUser(body.userEmail, body.userPassword); const userRecord = await createFirebaseUser(trimmedBody.userEmail, trimmedBody.userPassword);
let resetLink = null; let resetLink = null;
if (!body.userPassword) resetLink = await generateResetLink(body.userEmail); if (!trimmedBody.userPassword) {
resetLink = await generateResetLink(trimmedBody.userEmail);
}
const createdUser = await insertUserAssociation(userRecord.uid, body.userEmail, newShopId); const createdUser = await insertUserAssociation(userRecord.uid, trimmedBody.userEmail, newShopId);
return res.status(200).json({ return res.status(200).json({
shop: { id: newShopId, shopname: body.shopname }, shop: { id: newShopId, shopname: trimmedBody.shopname },
user: { user: {
id: createdUser.id, id: createdUser.id,
email: createdUser.email, email: createdUser.email,
@@ -324,7 +380,7 @@ const partsManagementProvisioning = async (req, res) => {
} }
}); });
} catch (err) { } catch (err) {
logger.log("admin-create-shop-user-error", "error", body.userEmail, null, { logger.log("admin-create-shop-user-error", "error", body.userEmail || "unknown", null, {
message: err.message, message: err.message,
detail: err.detail || err detail: err.detail || err
}); });

View File

@@ -4,14 +4,11 @@
* This module handles automatically adding watchers to new jobs based on the notifications_autoadd * 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. * 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. * It ensures users are not added twice and logs the process.
*
* NOTE: Bodyshop notification_followers is fetched directly from the DB (Hasura) to avoid stale Redis cache.
*/ */
const { client: gqlClient } = require("../graphql-client/graphql-client"); const { client: gqlClient } = require("../graphql-client/graphql-client");
const { isEmpty } = require("lodash"); const { isEmpty } = require("lodash");
const { const {
GET_BODYSHOP_WATCHERS_BY_ID,
GET_JOB_WATCHERS_MINIMAL, GET_JOB_WATCHERS_MINIMAL,
GET_NOTIFICATION_WATCHERS, GET_NOTIFICATION_WATCHERS,
INSERT_JOB_WATCHERS INSERT_JOB_WATCHERS
@@ -29,7 +26,10 @@ const FILTER_SELF_FROM_WATCHERS = process.env?.FILTER_SELF_FROM_WATCHERS !== "fa
*/ */
const autoAddWatchers = async (req) => { const autoAddWatchers = async (req) => {
const { event, trigger } = req.body; const { event, trigger } = req.body;
const { logger } = req; const {
logger,
sessionUtils: { getBodyshopFromRedis }
} = req;
// Validate that this is an INSERT event, bail // Validate that this is an INSERT event, bail
if (trigger?.name !== "notifications_jobs_autoadd" || event.op !== "INSERT" || event.data.old) { if (trigger?.name !== "notifications_jobs_autoadd" || event.op !== "INSERT" || event.data.old) {
@@ -48,20 +48,20 @@ const autoAddWatchers = async (req) => {
const hasuraUserId = event?.session_variables?.["x-hasura-user-id"]; const hasuraUserId = event?.session_variables?.["x-hasura-user-id"];
try { try {
// Fetch bodyshop data directly from DB (avoid Redis staleness) // Fetch bodyshop data from Redis
const bodyshopResponse = await gqlClient.request(GET_BODYSHOP_WATCHERS_BY_ID, { id: shopId }); const bodyshopData = await getBodyshopFromRedis(shopId);
const bodyshopData = bodyshopResponse?.bodyshops_by_pk; let notificationFollowers = bodyshopData?.notification_followers;
const notificationFollowersRaw = bodyshopData?.notification_followers; // Bail if notification_followers is missing or not an array
const notificationFollowers = Array.isArray(notificationFollowersRaw) if (!notificationFollowers || !Array.isArray(notificationFollowers)) {
? [...new Set(notificationFollowersRaw.filter((id) => id))] // de-dupe + remove falsy return;
: []; }
// Execute queries in parallel // Execute queries in parallel
const [notificationData, existingWatchersData] = await Promise.all([ const [notificationData, existingWatchersData] = await Promise.all([
gqlClient.request(GET_NOTIFICATION_WATCHERS, { gqlClient.request(GET_NOTIFICATION_WATCHERS, {
shopId, shopId,
employeeIds: notificationFollowers employeeIds: notificationFollowers.filter((id) => id)
}), }),
gqlClient.request(GET_JOB_WATCHERS_MINIMAL, { jobid: jobId }) gqlClient.request(GET_JOB_WATCHERS_MINIMAL, { jobid: jobId })
]); ]);
@@ -73,7 +73,7 @@ const autoAddWatchers = async (req) => {
associationId: assoc.id associationId: assoc.id
})) || []; })) || [];
// Get users from notification_followers (employee IDs -> employee emails) // Get users from notification_followers
const followerEmails = const followerEmails =
notificationData?.employees notificationData?.employees
?.filter((e) => e.user_email) ?.filter((e) => e.user_email)
@@ -84,7 +84,7 @@ const autoAddWatchers = async (req) => {
// Combine and deduplicate emails (use email as the unique key) // Combine and deduplicate emails (use email as the unique key)
const usersToAdd = [...autoAddUsers, ...followerEmails].reduce((acc, user) => { const usersToAdd = [...autoAddUsers, ...followerEmails].reduce((acc, user) => {
if (user?.email && !acc.some((u) => u.email === user.email)) { if (!acc.some((u) => u.email === user.email)) {
acc.push(user); acc.push(user);
} }
return acc; return acc;
@@ -123,7 +123,6 @@ const autoAddWatchers = async (req) => {
message: error?.message, message: error?.message,
stack: error?.stack, stack: error?.stack,
jobId, jobId,
shopId,
roNumber roNumber
}); });
throw error; // Re-throw to ensure the error is logged in the handler throw error; // Re-throw to ensure the error is logged in the handler