Compare commits

...

49 Commits

Author SHA1 Message Date
Dave
1ad7468d14 feature/IO-3401-Parts-Rec-Enhanced - Implement 2025-12-23 11:27:14 -05:00
Dave Richer
4a7bb07345 Merged in hotfix/missing-dms-migration (pull request #2738)
hotfix/missing-dms-migration - Add Back DMS_ID
2025-12-19 20:13:11 +00:00
Dave
01fec9fa79 hotfix/missing-dms-migration - Add Back DMS_ID 2025-12-19 15:12:24 -05:00
Dave Richer
2f88d613c3 Merged in release/2025-12-19-mini (pull request #2732)
Release/2025 12 19 mini - IO-3467 IO-3468 IO-3402 IO-3473
2025-12-19 19:14:30 +00:00
Dave Richer
c9467b3982 Merged in feature/IO-3402-Import-Add-Notifiers (pull request #2734)
feature/IO-3402-Import-Add-Notifiers - Fix Normalize
2025-12-19 19:12:04 +00:00
Dave
ca1a456312 feature/IO-3402-Import-Add-Notifiers - Fix Normalize 2025-12-19 14:10:15 -05:00
Dave
ca4c48bd5c release/2025-12-19-mini - Merge 2025-12-19 12:41:23 -05:00
Dave Richer
e5fd5c8bcb Merged in feature/IO-3468-sentry-exceptions (pull request #2731)
Feature/IO-3468 sentry exceptions
2025-12-19 17:39:23 +00:00
Dave Richer
46945a24a7 Merged in feature/IO-3467-report-center-filter-ui (pull request #2730)
IO-3467 Resolve UI on report center filter.
2025-12-19 17:35:47 +00:00
Dave Richer
be746500a6 Merged in feature/IO-3402-Import-Add-Notifiers (pull request #2729)
Feature/IO-3402 Import Add Notifiers
2025-12-19 17:35:12 +00:00
Dave
71c6d9fa94 IO-3473 trim user input 2025-12-19 12:07:30 -05:00
Dave
c010665ea9 feature/IO-3402-Import-Add-Notifiers - Fix 2025-12-18 18:26:02 -05:00
Dave
6d94ce7e5c feature/IO-3468-Senty-Exceptions - Fix unused import 2025-12-18 13:52:55 -05:00
Dave
d6fba12cd9 feature/IO-3402-Import-Add-Notifiers - Fix Auto Notifiers 2025-12-18 13:27:24 -05:00
Patrick Fic
182a8d59ab IO-3468 Add sentry exceptions & minor nul coalesce fixes. 2025-12-16 10:28:00 -08:00
Patrick Fic
f1847ef650 IO-3467 Resolve UI on report center filter. 2025-12-15 08:37:32 -08:00
Allan Carr
6ea1c291e6 Merged in release/2025-12-19 (pull request #2703)
Release/2025 12 19
2025-12-12 02:36:57 +00:00
Allan Carr
05d5c96491 Merged in feature/IO-3462-Project-Mexico-Mod (pull request #2701)
IO-3462 Project Mexico Mod

Approved-by: Dave Richer
2025-12-10 20:18:14 +00:00
Allan Carr
35a566cbe5 IO-3462 Project Mexico Mod
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-12-10 09:52:04 -08:00
Dave Richer
f12e40e4c6 Merged in feature/IO-3461-Fix-EULA (pull request #2698)
feature/IO-3461-Fix-Eula
2025-12-09 22:15:22 +00:00
Dave
bb4e671c83 feature/IO-3461-Fix-Eula 2025-12-09 17:13:59 -05:00
Dave Richer
d1637d2432 Merged in release/2025-12-05 (pull request #2696)
Release/2025 12 05 into master-AIO - IO-3450 IO-3452 IO-3262 - IO-3456 IO-3262
2025-12-06 01:48:37 +00:00
Allan Carr
1c79628613 Merged in feature/IO-3262-Tech-Console-Job-Clock-Out (pull request #2692)
IO-3262 Correction for v_year in Project Mexico

Approved-by: Dave Richer
2025-12-05 19:00:38 +00:00
Allan Carr
521a7084b7 IO-3262 Correction for v_year in Project Mexico
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-12-05 09:48:32 -08:00
Dave Richer
77268d5f5b Merged in feature/IO-3457-job-lifecyle-tags (pull request #2689)
feature/IO-3457-Job-Lifecycle-Tags
2025-12-04 21:23:27 +00:00
Dave
1b3abf17ec feature/IO-3457-Job-Lifecycle-Tags 2025-12-04 16:22:41 -05:00
Dave Richer
3cfd445894 Merged in feature/IO-3456-Broken-Image-Path (pull request #2687)
feature/IO-3456-Broken-Image - Fix issue
2025-12-04 19:22:03 +00:00
Dave
b510eec9aa feature/IO-3456-Broken-Image - Fix issue 2025-12-04 14:20:58 -05:00
Allan Carr
e5eac0933f Merged in feature/IO-3262-Tech-Console-Job-Clock-Out (pull request #2685)
IO-3262 Add email address to Usage Report

Approved-by: Dave Richer
2025-12-03 19:04:08 +00:00
Allan Carr
a3c71fdfc0 IO-3262 Add email address to Usage Report
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-12-03 10:28:20 -08:00
Allan Carr
78750d3d96 Merged in feature/IO-3262-Tech-Console-Job-Clock-Out (pull request #2682)
IO-3262 Tech Console Job Clock Out

Approved-by: Dave Richer
2025-12-02 18:59:41 +00:00
Allan Carr
90edf94fee IO-3262 Tech Console Job Clock Out
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-12-01 12:50:11 -08:00
Allan Carr
065fb72677 Merged in feature/IO-3452-Documents-Adjustments (pull request #2678)
IO-3452 Documents Adjustments

Approved-by: Dave Richer
2025-11-28 15:49:40 +00:00
Allan Carr
ddc6141480 IO-3452 Documents Adjustments
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-11-27 13:15:26 -08:00
Allan Carr
7bc137fa79 Merged in feature/IO-3450-Additional-Crisp-Segments (pull request #2675)
Feature/IO-3450 Additional Crisp Segments

Approved-by: Dave Richer
2025-11-26 16:30:07 +00:00
Allan Carr
dafe9de753 IO-3450 Grammer Correction
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-11-25 18:10:10 -08:00
Allan Carr
78a8474a24 IO-3450 Additional Crisp Segments
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-11-25 17:56:19 -08:00
Dave Richer
123066f1cd Merged in release/2025-11-21 (pull request #2671)
Release/2025 11 21 into Master-AIO - IO-3435 IO-3445 IO-3440 IO-3446
2025-11-21 19:19:15 +00:00
Allan Carr
a153cca3c0 Merged in feature/IO-3440-Payment-By-Date-Excel (pull request #2669)
IO-3440 Payment By Date - Excel
2025-11-21 00:26:54 +00:00
Allan Carr
35c7c32c8e IO-3440 Payment By Date - Excel
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-11-20 16:29:05 -08:00
Allan Carr
6d6b64ebc3 Merged in feature/IO-3446-Kaizen-Datapump-Extension (pull request #2667)
IO-3446 Kaizen Datapump Extension

Approved-by: Dave Richer
2025-11-20 19:53:47 +00:00
Allan Carr
c954695d3c IO-3446 Kaizen Datapump Extension
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-11-19 19:43:55 -08:00
Patrick Fic
338d8e2136 Merged in feature/media-analytics-logging (pull request #2663)
Add unique/dupe columns to media analytics.

Approved-by: Dave Richer
2025-11-19 19:26:00 +00:00
Allan Carr
6674206b4f Merged in feature/IO-3440-Payment-By-Date-Excel (pull request #2665)
IO-3440 Payment By Date - Excel

Approved-by: Dave Richer
2025-11-19 19:16:31 +00:00
Allan Carr
c46ad521d1 Merged in feature/IO-3445-RBAC-BILL-ENTER (pull request #2664)
IO-3445 RBAC Bill:Enter

Approved-by: Dave Richer
2025-11-19 19:13:26 +00:00
Allan Carr
66e5bec4d8 IO-3440 Payment By Date - Excel
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-11-18 17:05:42 -08:00
Allan Carr
0d3161ef84 IO-3445 RBAC Bill:Enter
Signed-off-by: Allan Carr <allan@imexsystems.ca>
2025-11-18 16:47:26 -08:00
Patrick Fic
1cd11bdc18 Add unique/dupe columns to media analytics. 2025-11-17 16:42:39 -08:00
Patrick Fic
9cce2696e2 Merge branch 'master-AIO' into feature/media-analytics-logging 2025-11-17 16:31:04 -08:00
55 changed files with 871 additions and 441 deletions

View File

@@ -138,7 +138,7 @@ export function App({
);
}
if (currentEula && !currentUser.eulaIsAccepted) {
if (!isPartsEntry && currentEula && !currentUser.eulaIsAccepted) {
return <Eula />;
}

View File

@@ -26,6 +26,7 @@ import { CalculateBillTotal } from "../bill-form/bill-form.totals.utility";
import { handleUpload as handleLocalUpload } from "../documents-local-upload/documents-local-upload.utility";
import { handleUpload } from "../documents-upload/documents-upload.utility";
import { handleUpload as handleUploadToImageProxy } from "../documents-upload-imgproxy/documents-upload-imgproxy.utility";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
const mapStateToProps = createStructuredSelector({
billEnterModal: selectBillEnterModal,
@@ -450,7 +451,9 @@ function BillEnterModalContainer({ billEnterModal, toggleModalVisible, bodyshop,
setEnterAgain(false);
}}
>
<BillFormContainer form={form} disableInvNumber={billEnterModal.context.disableInvNumber} />
<RbacWrapper action="bills:enter">
<BillFormContainer form={form} disableInvNumber={billEnterModal.context.disableInvNumber} />
</RbacWrapper>
</Form>
</Modal>
);

View File

@@ -142,17 +142,37 @@ export default function JobLifecycleDashboardComponent({ data, bodyshop, ...card
title={t("job_lifecycle.content.legend_title")}
style={{ marginTop: "10px" }}
>
<div>
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: 8
}}
>
{lifecycleData.summations.map((key) => (
<Tag key={key.status} color={key.color} style={{ width: "13vh", padding: "4px", margin: "4px" }}>
<Tag
key={key.status}
color={key.color}
style={{
// IMPORTANT: let the tag grow with its content
width: "auto",
padding: 0,
margin: 0,
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
boxSizing: "border-box"
}}
>
<div
aria-label={`${key.status} | ${key.roundedPercentage} | ${key.humanReadable}`}
title={`${key.status} | ${key.roundedPercentage} | ${key.humanReadable}`}
style={{
backgroundColor: "var(--tag-wrapper-bg)",
color: "var(--tag-wrapper-text)",
padding: "4px",
textAlign: "center"
padding: "4px 8px",
textAlign: "center",
whiteSpace: "nowrap" // keep it on one line while letting the pill expand
}}
>
{key.status} [{lifecycleData.statusCounts[key.status]}] ({key.roundedPercentage})

View File

@@ -55,7 +55,8 @@ const Eula = ({ currentEula, currentUser, acceptEula }) => {
const useremail = currentUser.email;
try {
const { ...otherFormValues } = formValues;
// eslint-disable-next-line no-unused-vars
const { accepted_terms, ...otherFormValues } = formValues;
// Trim the values of the fields before submitting
const trimmedFormValues = Object.entries(otherFormValues).reduce((acc, [key, value]) => {

View File

@@ -222,17 +222,37 @@ export function JobLifecycleComponent({ bodyshop, job, statuses }) {
</div>
</BlurWrapperComponent>
<Card type="inner" title={t("job_lifecycle.content.legend_title")} style={{ marginTop: "10px" }}>
<div>
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: 8
}}
>
{lifecycleData.durations.summations.map((key) => (
<Tag key={key.status} color={key.color} style={{ width: "13vh", padding: "4px", margin: "4px" }}>
<Tag
key={key.status}
color={key.color}
style={{
// let the tag grow with its content
width: "auto",
padding: 0,
margin: 0,
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
boxSizing: "border-box"
}}
>
<div
aria-label={`${key.status} | ${key.roundedPercentage} | ${key.humanReadable}`}
title={`${key.status} | ${key.roundedPercentage} | ${key.humanReadable}`}
style={{
backgroundColor: "var(--tag-wrapper-bg)",
color: "var(--tag-wrapper-text)",
padding: "4px",
textAlign: "center"
padding: "4px 8px",
textAlign: "center",
whiteSpace: "nowrap" // single line; tag gets wider instead of text escaping
}}
>
{key.status} (

View File

@@ -0,0 +1,105 @@
import { useCallback, useMemo, useState } from "react";
import PropTypes from "prop-types";
import { Popover } from "antd";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import JobPartsQueueCount from "../job-parts-queue-count/job-parts-queue-count.component";
import { useTranslation } from "react-i18next";
const mapStateToProps = createStructuredSelector({
bodyshop: selectBodyshop
});
/**
* Displays "Parts Received" summary (modeled after the Production Board List column),
* and on click shows a popover with the Parts Status grid (existing JobPartsQueueCount UI).
* @param bodyshop
* @param parts
* @param displayMode
* @param popoverPlacement
* @returns {JSX.Element}
* @constructor
*/
export function JobPartsReceived({ bodyshop, parts, displayMode = "full", popoverPlacement = "top" }) {
const [open, setOpen] = useState(false);
const { t } = useTranslation();
const summary = useMemo(() => {
const receivedStatus = bodyshop?.md_order_statuses?.default_received;
if (!Array.isArray(parts) || parts.length === 0 || !receivedStatus) {
return { total: 0, received: 0, percentLabel: t("general.labels.na") };
}
// Keep consistent with JobPartsQueueCount: exclude PAS / PASL from parts math
const { total, received } = parts.reduce(
(acc, val) => {
if (val?.part_type === "PAS" || val?.part_type === "PASL") return acc;
const count = Number(val?.count || 0);
acc.total += count;
if (val?.status === receivedStatus) {
acc.received += count;
}
return acc;
},
{ total: 0, received: 0 }
);
const percentLabel = total > 0 ? `${Math.round((received / total) * 100)}%` : t("general.labels.na");
return { total, received, percentLabel };
}, [parts, bodyshop?.md_order_statuses?.default_received]);
const canOpen = summary.total > 0;
const handleOpenChange = useCallback(
(nextOpen) => {
if (!canOpen) return;
setOpen(nextOpen);
},
[canOpen]
);
const displayText =
displayMode === "compact" ? summary.percentLabel : `${summary.percentLabel} (${summary.received}/${summary.total})`;
// Prevent row/cell click handlers (table selection, drawer selection, etc.)
const stop = (e) => e.stopPropagation();
return (
<Popover
open={open}
onOpenChange={handleOpenChange}
trigger={["click"]}
placement={popoverPlacement}
content={
<div onClick={stop} style={{ minWidth: 260 }}>
<JobPartsQueueCount parts={parts} />
</div>
}
>
<div
onClick={stop}
style={{
width: "100%",
height: "19px",
cursor: canOpen ? "pointer" : "default",
userSelect: "none"
}}
title={canOpen ? t("production.labels.click_for_statuses") : undefined}
>
{displayText}
</div>
</Popover>
);
}
JobPartsReceived.propTypes = {
bodyshop: PropTypes.object,
parts: PropTypes.array,
displayMode: PropTypes.oneOf(["full", "compact"]),
popoverPlacement: PropTypes.string
};
export default connect(mapStateToProps)(JobPartsReceived);

View File

@@ -609,7 +609,7 @@ export function JobsDetailHeaderActions({
<FormDateTimePickerComponent
onBlur={() => {
const start = form.getFieldValue("start");
form.setFieldsValue({ end: start.add(30, "minutes") });
form.setFieldsValue({ end: start?.add(30, "minutes") });
}}
/>
</Form.Item>

View File

@@ -35,16 +35,14 @@ export function JobsDocumentsImgproxyDownloadButton({ galleryImages, identifier,
...galleryImages.other.filter((image) => image.isSelected)
];
function downloadProgress(progressEvent) {
setDownload((currentDownloadState) => {
return {
downloaded: progressEvent.loaded || 0,
speed: (progressEvent.loaded || 0) - ((currentDownloadState && currentDownloadState.downloaded) || 0)
};
});
}
const downloadProgress = ({ loaded }) => {
setDownload((currentDownloadState) => ({
downloaded: loaded ?? 0,
speed: (loaded ?? 0) - (currentDownloadState?.downloaded ?? 0)
}));
};
function standardMediaDownload(bufferData) {
const standardMediaDownload = (bufferData) => {
try {
const a = document.createElement("a");
const url = window.URL.createObjectURL(new Blob([bufferData]));
@@ -55,29 +53,26 @@ export function JobsDocumentsImgproxyDownloadButton({ galleryImages, identifier,
setLoading(false);
setDownload(null);
}
}
};
const handleDownload = async () => {
logImEXEvent("jobs_documents_download");
setLoading(true);
try {
const response = await axios({
const { data } = await axios({
url: "/media/imgproxy/download",
method: "POST",
responseType: "blob",
data: { jobId, documentids: imagesToDownload.map((_) => _.id) },
onDownloadProgress: downloadProgress
});
setLoading(false);
setDownload(null);
// Use the response data (Blob) to trigger download
standardMediaDownload(response.data);
standardMediaDownload(data);
} catch {
// handle error (optional)
} finally {
setLoading(false);
setDownload(null);
// handle error (optional)
}
};

View File

@@ -76,14 +76,14 @@ function JobsDocumentsImgproxyComponent({
<SyncOutlined />
</Button>
<JobsDocumentsGallerySelectAllComponent galleryImages={galleryImages} setGalleryImages={setGalleryImages} />
{!billId && (
<JobsDocumentsGalleryReassign galleryImages={galleryImages} callback={fetchThumbnails || refetch} />
)}
<JobsDocumentsDownloadButton galleryImages={galleryImages} identifier={downloadIdentifier} jobId={jobId} />
<JobsDocumentsDeleteButton
galleryImages={galleryImages}
deletionCallback={billsCallback || fetchThumbnails || refetch}
/>
{!billId && (
<JobsDocumentsGalleryReassign galleryImages={galleryImages} callback={fetchThumbnails || refetch} />
)}
</Space>
</Col>
{!hasMediaAccess && (

View File

@@ -67,7 +67,7 @@ export default function JobsDocumentsImgproxyDeleteButton({ galleryImages, delet
okButtonProps={{ danger: true }}
cancelText={t("general.actions.cancel")}
>
<Button disabled={imagesToDelete.length < 1} loading={loading}>
<Button danger disabled={imagesToDelete.length < 1} loading={loading}>
{t("documents.actions.delete")}
</Button>
</Popconfirm>

View File

@@ -107,8 +107,8 @@ export function JobsDocumentsLocalGallery({
<a href={CreateExplorerLinkForJob({ jobid: job.id })}>
<Button>{t("documents.labels.openinexplorer")}</Button>
</a>
<JobsDocumentsLocalGalleryReassign jobid={job.id} />
<JobsDocumentsLocalGallerySelectAllComponent jobid={job.id} />
<JobsDocumentsLocalGalleryReassign jobid={job.id} />
<JobsLocalGalleryDownloadButton job={job} />
<JobsDocumentsLocalDeleteButton jobid={job.id} />
</Space>

View File

@@ -28,6 +28,8 @@ export function JobsDocumentsLocalDeleteButton({ bodyshop, getJobMedia, allMedia
const [loading, setLoading] = useState(false);
const imagesToDelete = (allMedia?.[jobid] || []).filter((i) => i.isSelected);
const handleDelete = async () => {
logImEXEvent("job_documents_delete");
setLoading(true);
@@ -36,7 +38,7 @@ export function JobsDocumentsLocalDeleteButton({ bodyshop, getJobMedia, allMedia
`${bodyshop.localmediaserverhttp}/jobs/delete`,
{
jobid: jobid,
files: (allMedia?.[jobid] || []).filter((i) => i.isSelected).map((i) => i.filename)
files: imagesToDelete.map((i) => i.filename)
},
{ headers: { ims_token: bodyshop.localmediatoken } }
);
@@ -60,14 +62,17 @@ export function JobsDocumentsLocalDeleteButton({ bodyshop, getJobMedia, allMedia
return (
<Popconfirm
disabled={imagesToDelete.length < 1}
icon={<QuestionCircleOutlined style={{ color: "red" }} />}
onConfirm={handleDelete}
title={t("documents.labels.confirmdelete")}
okText={t("general.actions.delete")}
okButtonProps={{ type: "danger" }}
okButtonProps={{ danger: true }}
cancelText={t("general.actions.cancel")}
>
<Button loading={loading}>{t("documents.actions.delete")}</Button>
<Button danger disabled={imagesToDelete.length < 1} loading={loading}>
{t("documents.actions.delete")}
</Button>
</Popconfirm>
);
}

View File

@@ -1,8 +1,8 @@
import { Button } from "antd";
import { Button, Space } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import cleanAxios from "../../utils/CleanAxios";
import formatBytes from "../../utils/formatbytes";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectAllMedia } from "../../redux/media/media.selectors";
@@ -19,45 +19,63 @@ export default connect(mapStateToProps, mapDispatchToProps)(JobsLocalGalleryDown
export function JobsLocalGalleryDownloadButton({ bodyshop, allMedia, job }) {
const { t } = useTranslation();
const [download, setDownload] = useState(null);
const [loading, setLoading] = useState(false);
const [download, setDownload] = useState(false);
function downloadProgress(progressEvent) {
setDownload((currentDownloadState) => {
return {
downloaded: progressEvent.loaded || 0,
speed: (progressEvent.loaded || 0) - (currentDownloadState?.downloaded || 0)
};
});
}
const imagesToDownload = (allMedia?.[job.id] || []).filter((i) => i.isSelected);
const downloadProgress = ({ loaded }) => {
setDownload((currentDownloadState) => ({
downloaded: loaded || 0,
speed: (loaded || 0) - (currentDownloadState?.downloaded || 0)
}));
};
const standardMediaDownload = (bufferData, filename) => {
try {
const a = document.createElement("a");
const url = window.URL.createObjectURL(new Blob([bufferData]));
a.href = url;
a.download = `${filename}.zip`;
a.click();
} catch {
setLoading(false);
setDownload(null);
}
};
const handleDownload = async () => {
const theDownloadedZip = await cleanAxios.post(
`${bodyshop.localmediaserverhttp}/jobs/download`,
{
jobid: job.id,
files: (allMedia?.[job.id] || []).filter((i) => i.isSelected).map((i) => i.filename)
},
{
headers: { ims_token: bodyshop.localmediatoken },
responseType: "arraybuffer",
onDownloadProgress: downloadProgress
}
);
setDownload(null);
standardMediaDownload(theDownloadedZip.data, job.ro_number);
const { localmediaserverhttp, localmediatoken } = bodyshop;
const { id, ro_number } = job;
setLoading(true);
try {
const response = await cleanAxios.post(
`${localmediaserverhttp}/jobs/download`,
{
jobid: id,
files: imagesToDownload.map((i) => i.filename)
},
{
headers: { ims_token: localmediatoken },
responseType: "arraybuffer",
onDownloadProgress: downloadProgress
}
);
standardMediaDownload(response.data, ro_number);
} catch {
// handle error (optional)
} finally {
setLoading(false);
setDownload(null);
}
};
return (
<Button loading={!!download} onClick={handleDownload}>
{t("documents.actions.download")}
<Button disabled={imagesToDownload < 1} loading={download || loading} onClick={handleDownload}>
<Space>
<span>{t("documents.actions.download")}</span>
{download && <span>{`(${formatBytes(download.downloaded)} @ ${formatBytes(download.speed)} / second)`}</span>}
</Space>
</Button>
);
}
function standardMediaDownload(bufferData, filename) {
const a = document.createElement("a");
const url = window.URL.createObjectURL(new Blob([bufferData]));
a.href = url;
a.download = `${filename}.zip`;
a.click();
}

View File

@@ -16,11 +16,11 @@ import { pageLimit } from "../../utils/config";
import { alphaSort, dateSort } from "../../utils/sorters";
import useLocalStorage from "../../utils/useLocalStorage";
import AlertComponent from "../alert/alert.component";
import JobPartsQueueCount from "../job-parts-queue-count/job-parts-queue-count.component";
import JobRemoveFromPartsQueue from "../job-remove-from-parst-queue/job-remove-from-parts-queue.component";
import OwnerNameDisplay, { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";
import ProductionListColumnComment from "../production-list-columns/production-list-columns.comment.component";
import { logImEXEvent } from "../../firebase/firebase.utils";
import JobPartsReceived from "../job-parts-received/job-parts-received.component";
const mapStateToProps = createStructuredSelector({
bodyshop: selectBodyshop
@@ -235,7 +235,9 @@ export function PartsQueueListComponent({ bodyshop }) {
title: t("jobs.fields.partsstatus"),
dataIndex: "partsstatus",
key: "partsstatus",
render: (text, record) => <JobPartsQueueCount parts={record.joblines_status} />
render: (text, record) => (
<JobPartsReceived parts={record.joblines_status} displayMode="full" popoverPlacement="topLeft" />
)
},
{
title: t("jobs.fields.comment"),

View File

@@ -19,6 +19,7 @@ import JobPartsQueueCount from "../job-parts-queue-count/job-parts-queue-count.c
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import ShareToTeamsButton from "../share-to-teams/share-to-teams.component.jsx";
import { PiMicrosoftTeamsLogo } from "react-icons/pi";
import ProductionListColumnPartsReceived from "../production-list-columns/production-list-columns.partsreceived.component";
const cardColor = (ssbuckets, totalHrs) => {
const bucket = ssbuckets.find((bucket) => bucket.gte <= totalHrs && (!bucket.lt || bucket.lt > totalHrs));
@@ -312,6 +313,20 @@ const TasksToolTip = ({ metadata, cardSettings, t }) =>
</Col>
);
const PartsReceivedComponent = ({ metadata, cardSettings, card }) =>
cardSettings?.partsreceived && (
<Col span={24} style={{ textAlign: "center" }}>
<ProductionListColumnPartsReceived
displayMode="full"
popoverPlacement="topLeft"
record={{
...metadata,
id: card?.id,
refetch: card?.refetch
}}
/>
</Col>
);
export default function ProductionBoardCard({ technician, card, bodyshop, cardSettings }) {
const { t } = useTranslation();
const { metadata } = card;
@@ -411,6 +426,7 @@ export default function ProductionBoardCard({ technician, card, bodyshop, cardSe
<SubletsComponent metadata={metadata} cardSettings={cardSettings} />
<ProductionNoteComponent metadata={metadata} cardSettings={cardSettings} card={card} />
<PartsStatusComponent metadata={metadata} cardSettings={cardSettings} />
<PartsReceivedComponent metadata={metadata} cardSettings={cardSettings} card={card} />
</Row>
);

View File

@@ -18,7 +18,8 @@ const InformationSettings = ({ t }) => (
"partsstatus",
"estimator",
"subtotal",
"tasks"
"tasks",
"partsreceived"
].map((item) => (
<Col xs={24} sm={12} md={8} lg={6} key={item}>
<Form.Item name={item} valuePropName="checked">

View File

@@ -74,6 +74,7 @@ const defaultKanbanSettings = {
cardSize: "small",
model_info: true,
kiosk: false,
partsreceived: false,
totalHrs: true,
totalAmountInProduction: false,
totalLAB: true,

View File

@@ -144,7 +144,7 @@ export function ProductionListEmpAssignment({ insertAuditTrail, bodyshop, record
<Spin spinning={loading}>
{record[type] ? (
<div>
<span>{`${theEmployee.first_name || ""} ${theEmployee.last_name || ""}`}</span>
<span>{`${theEmployee?.first_name || ""} ${theEmployee?.last_name || ""}`}</span>
<DeleteFilled style={iconStyle} onClick={() => handleRemove(type)} />
</div>
) : (

View File

@@ -1,33 +1,5 @@
import { useMemo } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import JobPartsReceived from "../job-parts-received/job-parts-received.component";
const mapStateToProps = createStructuredSelector({
bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
//setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(ProductionListColumnPartsReceived);
export function ProductionListColumnPartsReceived({ bodyshop, record }) {
const amount = useMemo(() => {
const amount = record.joblines_status.reduce(
(acc, val) => {
acc.total += val.count;
acc.received =
val.status === bodyshop.md_order_statuses.default_received ? acc.received + val.count : acc.received;
return acc;
},
{ total: 0, received: 0 }
);
return {
...amount,
percent: amount.total !== 0 ? ((amount.received / amount.total) * 100).toFixed(0) + "%" : "N/A"
};
}, [record, bodyshop.md_order_statuses]);
return `${amount.percent} (${amount.received}/${amount.total})`;
export default function ProductionListColumnPartsReceived({ record }) {
return <JobPartsReceived parts={record.joblines_status} displayMode="full" popoverPlacement="topLeft" />;
}

View File

@@ -143,7 +143,7 @@ export function ReportCenterModalComponent({ reportCenterModal, bodyshop }) {
//TODO: Find a way to filter out / blur on demand.
return (
<div>
<div className="report-center-modal">
<Form onFinish={handleFinish} autoComplete={"off"} layout="vertical" form={form}>
<Input.Search onChange={(e) => setSearch(e.target.value)} value={search} />
<Form.Item name="defaultSorters" hidden />
@@ -163,13 +163,14 @@ export function ReportCenterModalComponent({ reportCenterModal, bodyshop }) {
{Object.keys(grouped)
//.filter((key) => !groupExcludeKeyFilter.includes(key))
.map((key) => (
<Col md={8} sm={12} key={key}>
<Col xs={24} sm={12} md={Object.keys(grouped).length === 1 ? 24 : 8} key={key}>
<Card.Grid
style={{
width: "100%",
height: "100%",
maxHeight: "33vh",
overflowY: "scroll"
overflowY: "scroll",
minWidth: "200px"
}}
>
<Typography.Title level={4}>{t(`reportcenter.labels.groups.${key}`)}</Typography.Title>
@@ -177,7 +178,7 @@ export function ReportCenterModalComponent({ reportCenterModal, bodyshop }) {
<BlurWrapperComponent
featureName={groupExcludeKeyFilter.find((g) => g.key === key).featureName}
>
<ul style={{ listStyleType: "none", columns: "2 auto" }}>
<ul style={{ listStyleType: "none", columns: grouped[key].length > 4 ? "2 auto" : "1", padding: 0, margin: 0 }}>
{grouped[key].map((item) => (
<li key={item.key}>
<Radio key={item.key} value={item.key}>
@@ -188,7 +189,7 @@ export function ReportCenterModalComponent({ reportCenterModal, bodyshop }) {
</ul>
</BlurWrapperComponent>
) : (
<ul style={{ listStyleType: "none", columns: "2 auto" }}>
<ul style={{ listStyleType: "none", columns: grouped[key].length > 4 ? "2 auto" : "1", padding: 0, margin: 0 }}>
{grouped[key].map((item) =>
item.featureNameRestricted ? (
<li key={item.key}>

View File

@@ -11,3 +11,38 @@
}
}
}
// Report center modal fixes for column layout
.report-center-modal {
.ant-form-item .ant-radio-group {
width: 100%;
.ant-card-grid {
padding: 16px;
box-sizing: border-box;
ul {
width: 100%;
li {
margin-bottom: 8px;
break-inside: avoid;
page-break-inside: avoid;
.ant-radio-wrapper {
display: flex;
align-items: flex-start;
width: 100%;
span:not(.ant-radio) {
word-break: break-word;
overflow-wrap: break-word;
hyphens: auto;
flex: 1;
}
}
}
}
}
}
}

View File

@@ -16,6 +16,7 @@ export default function ShopInfoNotificationsAutoadd({ bodyshop }) {
<Text type="secondary">{t("bodyshop.labels.notifications.followers")}</Text>
{employeeOptions.length > 0 ? (
<Form.Item
normalize={(value) => (value || []).filter((id) => typeof id === "string" && id.trim() !== "")}
name="notification_followers"
rules={[
{
@@ -42,11 +43,6 @@ export default function ShopInfoNotificationsAutoadd({ bodyshop }) {
options={employeeOptions}
placeholder={t("bodyshop.fields.notifications.placeholder")}
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>
) : (

View File

@@ -16,7 +16,7 @@ const mapDispatchToProps = () => ({
export function TechHeader({ technician }) {
const { t } = useTranslation();
return (
<Header style={{ textAlign: "center" }}>
<Header style={{ textAlign: "center", height: "auto", overflow: "visible" }}>
<Typography.Title style={{ color: "#fff" }}>
{technician
? t("tech.labels.loggedin", {

View File

@@ -1,5 +1,5 @@
import { useMutation, useQuery } from "@apollo/client";
import { Button, Card, Col, Form, InputNumber, Popover, Row, Select } from "antd";
import { Button, Card, Form, InputNumber, Popover, Select, Space } from "antd";
import axios from "axios";
import { useState } from "react";
import { useTranslation } from "react-i18next";
@@ -124,103 +124,12 @@ export function TechClockOffButton({
cost_center: isShiftTicket ? "timetickets.labels.shift" : technician ? technician.cost_center : null
}}
>
<Row gutter={[16, 16]}>
<Col span={!isShiftTicket ? 8 : 24}>
{!isShiftTicket ? (
<div>
<Form.Item
label={t("timetickets.fields.actualhrs")}
name="actualhrs"
rules={[
{
required: true
//message: t("general.validation.required"),
}
]}
>
<InputNumber min={0} precision={1} />
</Form.Item>
<Form.Item
label={t("timetickets.fields.productivehrs")}
name="productivehrs"
rules={[
{
required: true
//message: t("general.validation.required"),
},
({ getFieldValue }) => ({
validator(rule, value) {
if (!bodyshop.tt_enforce_hours_for_tech_console) {
return Promise.resolve();
}
if (!value || getFieldValue("cost_center") === null || !lineTicketData)
return Promise.resolve();
//Check the cost center,
const totals = CalculateAllocationsTotals(
bodyshop,
lineTicketData.joblines,
lineTicketData.timetickets,
lineTicketData.jobs_by_pk.lbr_adjustments
);
const fieldTypeToCheck =
bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber ? "mod_lbr_ty" : "cost_center";
const costCenterDiff =
Math.round(
totals.find((total) => total[fieldTypeToCheck] === getFieldValue("cost_center"))
?.difference * 10
) / 10;
if (value > costCenterDiff)
return Promise.reject(t("timetickets.validation.hoursenteredmorethanavailable"));
else {
return Promise.resolve();
}
}
})
]}
>
<InputNumber min={0} precision={1} />
</Form.Item>
</div>
) : null}
<Form.Item
name="cost_center"
label={t("timetickets.fields.cost_center")}
rules={[
{
required: true
//message: t("general.validation.required"),
}
]}
>
<Select disabled={isShiftTicket}>
{isShiftTicket ? (
<Select.Option value="timetickets.labels.shift">{t("timetickets.labels.shift")}</Select.Option>
) : (
emps &&
emps.rates.map((item) => (
<Select.Option key={item.cost_center}>
{item.cost_center === "timetickets.labels.shift"
? t(item.cost_center)
: bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber
? t(`joblines.fields.lbr_types.${item.cost_center.toUpperCase()}`)
: item.cost_center}
</Select.Option>
))
)}
</Select>
</Form.Item>
{isShiftTicket ? (
<div></div>
) : (
<Space direction="vertical">
{!isShiftTicket ? (
<div>
<Form.Item
name="status"
label={t("jobs.fields.status")}
initialValue={lineTicketData && lineTicketData.jobs_by_pk.status}
label={t("timetickets.fields.actualhrs")}
name="actualhrs"
rules={[
{
required: true
@@ -228,35 +137,117 @@ export function TechClockOffButton({
}
]}
>
<Select>
{bodyshop.md_ro_statuses.production_statuses.map((item) => (
<Select.Option key={item}></Select.Option>
))}
</Select>
<InputNumber min={0} precision={1} />
</Form.Item>
)}
<Button type="primary" htmlType="submit" loading={loading}>
{t("general.actions.save")}
</Button>
<TechJobClockoutDelete completedCallback={completedCallback} timeTicketId={timeTicketId} />
</Col>
{!isShiftTicket && (
<Col span={16}>
<LaborAllocationContainer
jobid={jobId || null}
loading={queryLoading}
lineTicketData={lineTicketData}
/>
</Col>
<Form.Item
label={t("timetickets.fields.productivehrs")}
name="productivehrs"
rules={[
{
required: true
//message: t("general.validation.required"),
},
({ getFieldValue }) => ({
validator(rule, value) {
if (!bodyshop.tt_enforce_hours_for_tech_console) {
return Promise.resolve();
}
if (!value || getFieldValue("cost_center") === null || !lineTicketData)
return Promise.resolve();
//Check the cost center,
const totals = CalculateAllocationsTotals(
bodyshop,
lineTicketData.joblines,
lineTicketData.timetickets,
lineTicketData.jobs_by_pk.lbr_adjustments
);
const fieldTypeToCheck =
bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber ? "mod_lbr_ty" : "cost_center";
const costCenterDiff =
Math.round(
totals.find((total) => total[fieldTypeToCheck] === getFieldValue("cost_center"))
?.difference * 10
) / 10;
if (value > costCenterDiff)
return Promise.reject(t("timetickets.validation.hoursenteredmorethanavailable"));
else {
return Promise.resolve();
}
}
})
]}
>
<InputNumber min={0} precision={1} />
</Form.Item>
</div>
) : null}
<Form.Item
name="cost_center"
label={t("timetickets.fields.cost_center")}
rules={[
{
required: true
//message: t("general.validation.required"),
}
]}
>
<Select disabled={isShiftTicket}>
{isShiftTicket ? (
<Select.Option value="timetickets.labels.shift">{t("timetickets.labels.shift")}</Select.Option>
) : (
emps &&
emps.rates.map((item) => (
<Select.Option key={item.cost_center}>
{item.cost_center === "timetickets.labels.shift"
? t(item.cost_center)
: bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber
? t(`joblines.fields.lbr_types.${item.cost_center.toUpperCase()}`)
: item.cost_center}
</Select.Option>
))
)}
</Select>
</Form.Item>
{isShiftTicket ? (
<div></div>
) : (
<Form.Item
name="status"
label={t("jobs.fields.status")}
initialValue={lineTicketData && lineTicketData.jobs_by_pk.status}
rules={[
{
required: true
//message: t("general.validation.required"),
}
]}
>
<Select>
{bodyshop.md_ro_statuses.production_statuses.map((item) => (
<Select.Option key={item}></Select.Option>
))}
</Select>
</Form.Item>
)}
</Row>
<Button type="primary" htmlType="submit" loading={loading}>
{t("general.actions.save")}
</Button>
<TechJobClockoutDelete completedCallback={completedCallback} timeTicketId={timeTicketId} />
{!isShiftTicket && (
<LaborAllocationContainer jobid={jobId || null} loading={queryLoading} lineTicketData={lineTicketData} />
)}
</Space>
</Form>
</div>
</Card>
);
return (
<Popover content={overlay} trigger="click">
<Popover
content={<div style={{ maxHeight: "75vh", overflowY: "auto" }}>{overlay}</div>}
trigger="click"
getPopupContainer={() => document.querySelector('#time-ticket-modal')}
>
<Button loading={loading} {...otherBtnProps}>
{t("timetickets.actions.clockout")}
</Button>

View File

@@ -5,7 +5,7 @@ import { getFirestore } from "@firebase/firestore";
import { getMessaging, getToken, onMessage } from "@firebase/messaging";
import { store } from "../redux/store";
//import * as amplitude from '@amplitude/analytics-browser';
import posthog from 'posthog-js'
// import posthog from 'posthog-js'
const config = JSON.parse(import.meta.env.VITE_APP_FIREBASE_CONFIG);
initializeApp(config);
@@ -74,7 +74,6 @@ onMessage(messaging, (payload) => {
export const logImEXEvent = (eventName, additionalParams, stateProp = null) => {
try {
const state = stateProp || store.getState();
const eventParams = {
@@ -99,8 +98,7 @@ export const logImEXEvent = (eventName, additionalParams, stateProp = null) => {
// );
logEvent(analytics, eventName, eventParams);
//amplitude.track(eventName, eventParams);
posthog.capture(eventName, eventParams);
//posthog.capture(eventName, eventParams);
} finally {
//If it fails, just keep going.
}

View File

@@ -50,7 +50,7 @@ import {
} from "./user.actions";
import UserActionTypes from "./user.types";
//import * as amplitude from '@amplitude/analytics-browser';
import posthog from 'posthog-js';
import posthog from "posthog-js";
const fpPromise = FingerprintJS.load();
@@ -269,11 +269,11 @@ export function* signInSuccessSaga({ payload }) {
instanceSeg,
...(isParts
? [
InstanceRenderManager({
imex: "ImexPartsManagement",
rome: "RomePartsManagement"
})
]
InstanceRenderManager({
imex: "ImexPartsManagement",
rome: "RomePartsManagement"
})
]
: [])
];
window.$crisp.push(["set", "session:segments", [segs]]);
@@ -375,17 +375,31 @@ export function* SetAuthLevelFromShopDetails({ payload }) {
const isParts = yield select((state) => state.application.isPartsEntry === true);
const instanceSeg = InstanceRenderManager({ imex: "imex", rome: "rome" });
let featureSegments;
if (payload.features?.allAccess === true) {
featureSegments = ["allAccess"];
} else {
const featureKeys = Object.keys(payload.features).filter(
(key) =>
payload.features[key] === true ||
(typeof payload.features[key] === "string" && !isNaN(Date.parse(payload.features[key])))
);
featureSegments = ["basic", ...featureKeys];
}
const featureSegments =
payload.features?.allAccess === true
? ["allAccess"]
: [
"basic",
...Object.keys(payload.features).filter(
(key) =>
payload.features[key] === true ||
(typeof payload.features[key] === "string" && !isNaN(Date.parse(payload.features[key])))
)
];
const additionalSegments = [
payload.cdk_dealerid && "CDK",
payload.pbs_serialnumber && "PBS",
// payload.rr_dealerid && "Reynolds",
payload.accountingconfig.qbo === true && "QBO",
payload.accountingconfig.qbo === false &&
!payload.cdk_dealerid &&
!payload.pbs_serialnumber &&
// !payload.rr_dealerid &&
"QBD"
].filter(Boolean);
featureSegments.push(...additionalSegments);
const regionSeg = payload.region_config ? `region:${payload.region_config}` : null;
const segments = [instanceSeg, ...(regionSeg ? [regionSeg] : []), ...featureSegments];

View File

@@ -2950,6 +2950,8 @@
"settings": "Error saving board settings: {{error}}"
},
"labels": {
"click_for_statuses": "Click to view parts statuses",
"partsreceived": "Parts Received",
"actual_in": "Actual In",
"addnewprofile": "Add New Profile",
"alert": "Alert",
@@ -3209,6 +3211,7 @@
"parts_not_recieved_vendor": "Parts Not Received by Vendor",
"parts_received_not_scheduled": "Parts Received for Jobs Not Scheduled",
"payments_by_date": "Payments by Date",
"payments_by_date_excel": "Payments by Date - Excel",
"payments_by_date_payment": "Payments by Date and Payment Type",
"payments_by_date_type": "Payments by Date and Customer Type",
"production_by_category": "Production by Category",

View File

@@ -2950,6 +2950,8 @@
"settings": ""
},
"labels": {
"click_for_statuses": "",
"partsreceived": "",
"actual_in": "",
"addnewprofile": "",
"alert": "",
@@ -3209,6 +3211,7 @@
"parts_not_recieved_vendor": "",
"parts_received_not_scheduled": "",
"payments_by_date": "",
"payments_by_date_excel": "",
"payments_by_date_payment": "",
"payments_by_date_type": "",
"production_by_category": "",

View File

@@ -2950,6 +2950,8 @@
"settings": ""
},
"labels": {
"click_for_statuses": "",
"partsreceived": "",
"actual_in": "",
"addnewprofile": "",
"alert": "",
@@ -3209,6 +3211,7 @@
"parts_not_recieved_vendor": "",
"parts_received_not_scheduled": "",
"payments_by_date": "",
"payments_by_date_excel": "",
"payments_by_date_payment": "",
"payments_by_date_type": "",
"production_by_category": "",

View File

@@ -1218,6 +1218,18 @@ export const TemplateList = (type, context) => {
},
group: "customers"
},
payments_by_date_excel: {
title: i18n.t("reportcenter.templates.payments_by_date_excel"),
subject: i18n.t("reportcenter.templates.payments_by_date_excel"),
key: "payments_by_date_excel",
reporttype: "excel",
disabled: false,
rangeFilter: {
object: i18n.t("reportcenter.labels.objects.payments"),
field: i18n.t("payments.fields.date")
},
group: "customers"
},
schedule: {
title: i18n.t("reportcenter.templates.schedule"),
subject: i18n.t("reportcenter.templates.schedule"),

View File

@@ -31,7 +31,8 @@ if (!import.meta.env.DEV) {
"Module specifier, 'fs' does not start",
"Module specifier, 'zlib' does not start with",
"Messaging: This browser doesn't support the API's required to use the Firebase SDK.",
"Failed to update a ServiceWorker for scope"
"Failed to update a ServiceWorker for scope",
"Network Error"
],
integrations: [
// See docs for support of different versions of variation of react router

View File

@@ -24,11 +24,13 @@ const lightningCssTargets = browserslistToTargets(
})
);
const currentDatePST = new Date()
.toLocaleDateString("en-US", { timeZone: "America/Los_Angeles", year: "numeric", month: "2-digit", day: "2-digit" })
.split("/")
.reverse()
.join("-");
const pstFormatter = new Intl.DateTimeFormat("en-CA", {
timeZone: "America/Los_Angeles",
year: "numeric",
month: "2-digit",
day: "2-digit"
});
const currentDatePST = pstFormatter.format(new Date());
const getFormattedTimestamp = () =>
new Date().toLocaleTimeString("en-US", { hour12: true }).replace("AM", "a.m.").replace("PM", "p.m.");

View File

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

View File

@@ -0,0 +1,4 @@
-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."media_analytics" add column "unique_documents" numeric
-- null;

View File

@@ -0,0 +1,2 @@
alter table "public"."media_analytics" add column "unique_documents" numeric
null;

View File

@@ -0,0 +1,4 @@
-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."media_analytics" add column "duplicate_documents" numeric
-- null;

View File

@@ -0,0 +1,2 @@
alter table "public"."media_analytics" add column "duplicate_documents" numeric
null;

View File

@@ -0,0 +1,4 @@
-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."media_analytics_detail" add column "unique_documents" numeric
-- null;

View File

@@ -0,0 +1,2 @@
alter table "public"."media_analytics_detail" add column "unique_documents" numeric
null;

View File

@@ -0,0 +1,4 @@
-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."media_analytics_detail" add column "duplicate_documents" numeric
-- null;

View File

@@ -0,0 +1,2 @@
alter table "public"."media_analytics_detail" add column "duplicate_documents" numeric
null;

View File

@@ -0,0 +1 @@
alter table "public"."media_analytics_detail" rename column "unique_document_count" to "unique_documents";

View File

@@ -0,0 +1 @@
alter table "public"."media_analytics_detail" rename column "unique_documents" to "unique_document_count";

View File

@@ -0,0 +1 @@
alter table "public"."media_analytics_detail" rename column "duplicate_count" to "duplicate_documents";

View File

@@ -0,0 +1 @@
alter table "public"."media_analytics_detail" rename column "duplicate_documents" to "duplicate_count";

View File

@@ -0,0 +1,4 @@
-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."jobs" add column "dms_id" text
-- null;

View File

@@ -0,0 +1,2 @@
alter table "public"."jobs" add column "dms_id" text
null;

View File

@@ -117,44 +117,46 @@ async function processShopData(shopsToProcess, start, end, skipUpload, ignoreDat
imexshopid: shopid,
json: JSON.stringify(carfaxObject, null, 2),
filename: `${shopid}_${moment().format("DDMMYYYY_HHMMss")}.json`,
count: carfaxObject.job.length
count: carfaxObject?.job?.length || 0
};
if (skipUpload) {
fs.writeFileSync(`./logs/${jsonObj.filename}`, jsonObj.json);
uploadToS3(jsonObj, S3_BUCKET_NAME);
} else {
await uploadViaSFTP(jsonObj);
if (jsonObj.count > 0) {
await uploadViaSFTP(jsonObj);
await sendMexicoBillingEmail({
subject: `${shopid.replace(/_/g, "").toUpperCase()}_MexicoRPS_${moment().format("MMDDYYYY")} ROs ${jsonObj.count} Error ${errorCode(jsonObj)}`,
text: `Errors:\n${JSON.stringify(
erroredJobs.map((ej) => ({
jobid: ej.job?.id,
error: ej.error
})),
null,
2
)}\n\nUploaded:\n${JSON.stringify(
{
bodyshopid: bodyshop.id,
imexshopid: shopid,
count: jsonObj.count,
filename: jsonObj.filename,
result: jsonObj.result
},
null,
2
)}`
});
await sendMexicoBillingEmail({
subject: `${shopid.replace(/_/g, "").toUpperCase()}_MexicoRPS_${moment().format("MMDDYYYY")} ROs ${jsonObj.count} Error ${errorCode(jsonObj)}`,
text: `Errors:\n${JSON.stringify(
erroredJobs.map((ej) => ({
jobid: ej.job?.id,
error: ej.error
})),
null,
2
)}\n\nUploaded:\n${JSON.stringify(
{
bodyshopid: bodyshop.id,
imexshopid: shopid,
count: jsonObj.count,
filename: jsonObj.filename,
result: jsonObj.result
},
null,
2
)}`
});
}
}
allJSONResults.push({
jsonObj.count > 0 && allJSONResults.push({
bodyshopid: bodyshop.id,
imexshopid: shopid,
count: jsonObj.count,
filename: jsonObj.filename,
result: jsonObj.result
result: jsonObj.result || "No Upload Result Available"
});
logger.log("CARFAX-RPS-end-shop-extract", "DEBUG", "api", bodyshop.id, {
@@ -234,11 +236,10 @@ const CreateRepairOrderTag = (job, errorCallback) => {
const ret = {
ro_number: crypto.createHash("md5").update(job.id, "utf8").digest("hex"),
v_vin: job.v_vin || "",
v_year: job.v_model_yr
? parseInt(job.v_model_yr.match(/\d/g))
? parseInt(job.v_model_yr.match(/\d/g).join(""), 10)
: ""
: "",
v_year: (() => {
const y = parseInt(job.v_model_yr);
return isNaN(y) ? null : y < 100 ? y + (y >= (new Date().getFullYear() + 1) % 100 ? 1900 : 2000) : y;
})(),
v_make: job.v_makedesc || "",
v_model: job.v_model || "",

View File

@@ -160,40 +160,42 @@ async function processShopData(shopsToProcess, start, end, skipUpload, ignoreDat
imexshopid: shopid,
json: JSON.stringify(carfaxObject, null, 2),
filename: `${shopid}_${moment().format("DDMMYYYY_HHMMss")}.json`,
count: carfaxObject.job.length
count: carfaxObject?.job?.length || 0
};
if (skipUpload) {
fs.writeFileSync(`./logs/${jsonObj.filename}`, jsonObj.json);
uploadToS3(jsonObj);
} else {
await uploadViaSFTP(jsonObj);
if (jsonObj.count > 0) {
await uploadViaSFTP(jsonObj);
await sendMexicoBillingEmail({
subject: `${shopid.replace(/_/g, "").toUpperCase()}_Mexico${InstanceManager({
imex: "IO",
rome: "RO"
})}_${moment().format("MMDDYYYY")} ROs ${jsonObj.count} Error ${errorCode(jsonObj)}`,
text: `Errors:\n${JSON.stringify(
erroredJobs.map((ej) => ({
ro_number: ej.job?.ro_number,
jobid: ej.job?.id,
error: ej.error
})),
null,
2
)}\n\nUploaded:\n${JSON.stringify(
{
bodyshopid: bodyshop.id,
imexshopid: shopid,
count: jsonObj.count,
filename: jsonObj.filename,
result: jsonObj.result
},
null,
2
)}`
});
await sendMexicoBillingEmail({
subject: `${shopid.replace(/_/g, "").toUpperCase()}_Mexico${InstanceManager({
imex: "IO",
rome: "RO"
})}_${moment().format("MMDDYYYY")} ROs ${jsonObj.count} Error ${errorCode(jsonObj)}`,
text: `Errors:\n${JSON.stringify(
erroredJobs.map((ej) => ({
ro_number: ej.job?.ro_number,
jobid: ej.job?.id,
error: ej.error
})),
null,
2
)}\n\nUploaded:\n${JSON.stringify(
{
bodyshopid: bodyshop.id,
imexshopid: shopid,
count: jsonObj.count,
filename: jsonObj.filename,
result: jsonObj.result
},
null,
2
)}`
});
}
}
allJSONResults.push({
@@ -201,7 +203,7 @@ async function processShopData(shopsToProcess, start, end, skipUpload, ignoreDat
imexshopid: shopid,
count: jsonObj.count,
filename: jsonObj.filename,
result: jsonObj.result
result: jsonObj.result || "No Upload Result Available"
});
logger.log("CARFAX-end-shop-extract", "DEBUG", "api", bodyshop.id, {
@@ -286,11 +288,10 @@ const CreateRepairOrderTag = (job, errorCallback) => {
const ret = {
ro_number: crypto.createHash("md5").update(job.ro_number, "utf8").digest("hex"),
v_vin: job.v_vin || "",
v_year: job.v_model_yr
? parseInt(job.v_model_yr.match(/\d/g))
? parseInt(job.v_model_yr.match(/\d/g).join(""), 10)
: ""
: "",
v_year: (() => {
const y = parseInt(job.v_model_yr);
return isNaN(y) ? null : y < 100 ? y + (y >= (new Date().getFullYear() + 1) % 100 ? 1900 : 2000) : y;
})(),
v_make: job.v_make_desc || "",
v_model: job.v_model_desc || "",

View File

@@ -219,8 +219,6 @@ const CreateRepairOrderTag = (job, errorCallback) => {
}
const repairCosts = CreateCosts(job);
const jobline = CreateJobLines(job.joblines);
const timeticket = CreateTimeTickets(job.timetickets);
try {
const ret = {
@@ -290,8 +288,100 @@ const CreateRepairOrderTag = (job, errorCallback) => {
(job.date_exported && moment(job.date_exported).tz(job.bodyshop.timezone).format(DateFormat)) || "",
DateVoid: (job.date_void && moment(job.date_void).tz(job.bodyshop.timezone).format(DateFormat)) || ""
},
JobLineDetails: { jobline },
TimeTicketDetails: { timeticket },
JobLineDetails: (function () {
const joblineSource = Array.isArray(job.joblines) ? job.joblines : job.joblines ? [job.joblines] : [];
if (joblineSource.length === 0) return { jobline: [] };
return {
jobline: joblineSource.map((jl = {}) => ({
line_description: jl.line_desc || jl.line_description || "",
oem_part_no: jl.oem_partno || jl.oem_part_no || "",
alt_part_no: jl.alt_partno || jl.alt_part_no || "",
op_code_desc: jl.op_code_desc || "",
part_type: jl.part_type || "",
part_qty: jl.part_qty ?? jl.quantity ?? 0,
part_price: jl.act_price ?? jl.part_price ?? 0,
labor_type: jl.mod_lbr_ty || jl.labor_type || "",
labor_hours: jl.mod_lb_hrs ?? jl.labor_hours ?? 0,
labor_sale: jl.lbr_amt ?? jl.labor_sale ?? 0
}))
};
})(),
BillsDetails: (function () {
const billsSource = Array.isArray(job.bills) ? job.bills : job.bills ? [job.bills] : [];
if (billsSource.length === 0) return { BillDetails: [] };
return {
BillDetails: billsSource.map(
({
billlines = [],
date = "",
is_credit_memo = false,
invoice_number = "",
isinhouse = false,
vendor = {}
} = {}) => ({
BillLines: {
BillLine: billlines.map((bl = {}) => ({
line_description: bl.line_desc || bl.line_description || "",
part_price: bl.actual_price ?? bl.part_price ?? bl.act_price ?? 0,
actual_cost: bl.actual_cost ?? 0,
cost_center: bl.cost_center || "",
deductedfromlbr: bl.deductedfromlbr || false,
part_qty: bl.quantity ?? bl.part_qty ?? 0,
oem_part_no: bl.oem_partno || bl.oem_part_no || "",
alt_part_no: bl.alt_partno || bl.alt_part_no || ""
}))
},
date,
is_credit_memo,
invoice_number,
isinhouse,
vendorName: vendor.name || ""
})
)
};
})(),
JobNotes: (function () {
const notesSource = Array.isArray(job.notes) ? job.notes : job.notes ? [job.notes] : [];
if (notesSource.length === 0) return { JobNote: [] };
return {
JobNote: notesSource.map((note = {}) => ({
created_at: note.created_at || "",
created_by: note.created_by || "",
critical: note.critical || false,
private: note.private || false,
text: note.text || "",
type: note.type || ""
}))
};
})(),
TimeTicketDetails: (function () {
const ticketSource = Array.isArray(job.timetickets)
? job.timetickets
: job.timetickets
? [job.timetickets]
: [];
if (ticketSource.length === 0) return { timeticket: [] };
return {
timeticket: ticketSource.map((ticket = {}) => ({
date: ticket.date || "",
employee:
ticket.employee && ticket.employee.employee_number
? ticket.employee.employee_number
.trim()
.concat(" - ", ticket.employee.first_name.trim(), " ", ticket.employee.last_name.trim())
.trim()
: "",
productive_hrs: ticket.productivehrs ?? 0,
actual_hrs: ticket.actualhrs ?? 0,
cost_center: ticket.cost_center || "",
flat_rate: ticket.flat_rate || false,
rate: ticket.rate ?? 0,
ticket_cost: ticket.flat_rate
? ticket.rate * (ticket.productivehrs || 0)
: ticket.rate * (ticket.actualhrs || 0)
}))
};
})(),
Sales: {
Labour: {
Aluminum: Dinero(job.job_totals.rates.laa.total).toFormat(DineroFormat),
@@ -636,42 +726,3 @@ const CreateCosts = (job) => {
}, 0)
};
};
const CreateJobLines = (joblines) => {
const repairLines = [];
joblines.forEach((jobline) => {
repairLines.push({
line_description: jobline.line_desc,
oem_part_no: jobline.oem_partno,
alt_part_no: jobline.alt_partno,
op_code_desc: jobline.op_code_desc,
part_type: jobline.part_type,
part_qty: jobline.part_qty,
part_price: jobline.act_price,
labor_type: jobline.mod_lbr_ty,
labor_hours: jobline.mod_lb_hrs,
labor_sale: jobline.lbr_amt
});
});
return repairLines;
};
const CreateTimeTickets = (timetickets) => {
const timeTickets = [];
timetickets.forEach((ticket) => {
timeTickets.push({
date: ticket.date,
employee: ticket.employee.employee_number
.trim()
.concat(" - ", ticket.employee.first_name.trim(), " ", ticket.employee.last_name.trim())
.trim(),
productive_hrs: ticket.productivehrs,
actual_hrs: ticket.actualhrs,
cost_center: ticket.cost_center,
flat_rate: ticket.flat_rate,
rate: ticket.rate,
ticket_cost: ticket.flat_rate ? ticket.rate * ticket.productive_hrs : ticket.rate * ticket.actual_hrs
});
});
return timeTickets;
};

View File

@@ -55,7 +55,9 @@ exports.default = async (req, res) => {
"patrick.fic@convenient-brands.com",
"bradley.rhoades@convenient-brands.com",
"jrome@rometech.com",
"ivana@imexsystems.ca"
"ivana@imexsystems.ca",
"support@imexsystems.ca",
"sarah@rometech.com"
],
subject: `RO Usage Report - ${moment().format("MM/DD/YYYY")}`,
text: `

View File

@@ -1219,7 +1219,7 @@ query ENTEGRAL_EXPORT($bodyshopid: uuid!) {
}`;
exports.KAIZEN_QUERY = `query KAIZEN_EXPORT($start: timestamptz, $bodyshopid: uuid!, $end: timestamptz) {
bodyshops_by_pk(id: $bodyshopid){
bodyshops_by_pk(id: $bodyshopid) {
id
shopname
address1
@@ -1246,15 +1246,24 @@ exports.KAIZEN_QUERY = `query KAIZEN_EXPORT($start: timestamptz, $bodyshopid: uu
bills {
billlines {
actual_cost
actual_price
cost_center
deductedfromlbr
id
line_desc
quantity
}
date
federal_tax_rate
id
is_credit_memo
invoice_number
isinhouse
local_tax_rate
state_tax_rate
vendor {
name
}
}
created_at
clm_no
@@ -1296,7 +1305,7 @@ exports.KAIZEN_QUERY = `query KAIZEN_EXPORT($start: timestamptz, $bodyshopid: uu
joblines(where: {removed: {_eq: false}}) {
act_price
alt_partno
billlines(order_by: {bill: {date: desc_nulls_last}} limit: 1) {
billlines(order_by: {bill: {date: desc_nulls_last}}, limit: 1) {
actual_cost
actual_price
quantity
@@ -1319,8 +1328,8 @@ exports.KAIZEN_QUERY = `query KAIZEN_EXPORT($start: timestamptz, $bodyshopid: uu
mod_lbr_ty
oem_partno
op_code_desc
parts_order_lines(order_by: {parts_order: {order_date: desc_nulls_last}} limit: 1){
parts_order{
parts_order_lines(order_by: {parts_order: {order_date: desc_nulls_last}}, limit: 1) {
parts_order {
id
order_date
}
@@ -1339,6 +1348,14 @@ exports.KAIZEN_QUERY = `query KAIZEN_EXPORT($start: timestamptz, $bodyshopid: uu
jobid
totalliquidcost
}
notes {
created_at
created_by
critical
private
text
type
}
ownr_addr1
ownr_addr2
ownr_city
@@ -2204,16 +2221,18 @@ exports.UPDATE_OLD_TRANSITION = `mutation UPDATE_OLD_TRANSITION($jobid: uuid!, $
exports.INSERT_NEW_TRANSITION = (
includeOldTransition
) => `mutation INSERT_NEW_TRANSITION($newTransition: transitions_insert_input!, ${includeOldTransition ? `$oldTransitionId: uuid!, $duration: numeric` : ""
}) {
) => `mutation INSERT_NEW_TRANSITION($newTransition: transitions_insert_input!, ${
includeOldTransition ? `$oldTransitionId: uuid!, $duration: numeric` : ""
}) {
insert_transitions_one(object: $newTransition) {
id
}
${includeOldTransition
? `update_transitions(where: {id: {_eq: $oldTransitionId}}, _set: {duration: $duration}) {
${
includeOldTransition
? `update_transitions(where: {id: {_eq: $oldTransitionId}}, _set: {duration: $duration}) {
affected_rows
}`
: ""
: ""
}
}`;
@@ -2907,6 +2926,15 @@ 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 = `
query GET_DOCUMENTS_BY_JOB($jobId: uuid!) {
jobs_by_pk(id: $jobId) {
@@ -3152,11 +3180,10 @@ exports.DELETE_PHONE_NUMBER_OPT_OUT = `
}
`;
exports.INSERT_MEDIA_ANALYTICS = `
mutation INSERT_MEDIA_ANALYTICS($mediaObject: media_analytics_insert_input!) {
insert_media_analytics_one(object: $mediaObject) {
id
}
}
`
`;

View File

@@ -77,9 +77,8 @@ const generateResetLink = async (email) => {
*/
const ensureExternalIdUnique = async (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;
};
/**
@@ -134,13 +133,16 @@ const insertUserAssociation = async (uid, email, shopId) => {
/**
* PATCH handler for updating bodyshop fields.
* Allows patching: shopname, address1, address2, city, state, zip_post, country, email, timezone, phone, logo_img_path
* Allows patching: shopname, address1, address2, city, state, zip_post, country, email, timezone, phone
* Also allows updating logo_img_path via a simple logoUrl string, which is expanded to the full object.
* @param req
* @param res
* @returns {Promise<void>}
*/
const patchPartsManagementProvisioning = async (req, res) => {
const { id } = req.params;
// Fields that can be directly patched 1:1
const allowedFields = [
"shopname",
"address1",
@@ -151,31 +153,58 @@ const patchPartsManagementProvisioning = async (req, res) => {
"country",
"email",
"timezone",
"phone",
"logo_img_path"
"phone"
// NOTE: logo_img_path is handled separately via logoUrl
];
const updateFields = {};
// Copy over simple scalar fields if present
for (const field of allowedFields) {
if (req.body[field] !== undefined) {
updateFields[field] = req.body[field];
}
}
// Handle logo update via a simple href string, same behavior as provision route
if (typeof req.body.logo_img_path === "string") {
const trimmed = req.body.logo_img_path.trim();
if (trimmed) {
updateFields.logo_img_path = {
src: trimmed,
width: "",
height: "",
headerMargin: DefaultNewShop.logo_img_path.headerMargin
};
}
}
if (Object.keys(updateFields).length === 0) {
return res.status(400).json({ error: "No valid fields provided for update." });
}
// Check that the bodyshop has an external_shop_id before allowing patch
try {
// Fetch the bodyshop by id
const shopResp = await client.request(
`query GetBodyshop($id: uuid!) { bodyshops_by_pk(id: $id) { id external_shop_id } }`,
`query GetBodyshop($id: uuid!) {
bodyshops_by_pk(id: $id) {
id
external_shop_id
}
}`,
{ id }
);
if (!shopResp.bodyshops_by_pk?.external_shop_id) {
return res.status(400).json({ error: "Cannot patch: bodyshop does not have an external_shop_id." });
}
} catch (err) {
return res.status(500).json({ error: "Failed to validate bodyshop external_shop_id.", detail: err });
return res.status(500).json({
error: "Failed to validate bodyshop external_shop_id.",
detail: err
});
}
try {
const resp = await client.request(UPDATE_BODYSHOP_BY_ID, { id, fields: updateFields });
if (!resp.update_bodyshops_by_pk) {
@@ -195,10 +224,25 @@ const patchPartsManagementProvisioning = async (req, res) => {
*/
const partsManagementProvisioning = async (req, res) => {
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 {
// Ensure email is present and trimmed before checking registration
if (!body.userEmail) {
throw { status: 400, message: "userEmail is required" };
}
await ensureEmailNotRegistered(body.userEmail);
requireFields(body, [
"external_shop_id",
"shopname",
@@ -211,27 +255,69 @@ const partsManagementProvisioning = async (req, res) => {
"phone",
"userEmail"
]);
await ensureExternalIdUnique(body.external_shop_id);
logger.log("admin-create-shop-user", "debug", body.userEmail, null, {
// Trim all top-level string fields
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
}))
: []
};
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,
ioadmin: true
});
const shopInput = {
shopname: body.shopname,
address1: body.address1,
address2: body.address2 || null,
city: body.city,
state: body.state,
zip_post: body.zip_post,
country: body.country,
email: body.email,
external_shop_id: body.external_shop_id,
timezone: body.timezone || DefaultNewShop.timezone,
phone: body.phone,
shopname: trimmedBody.shopname,
address1: trimmedBody.address1,
address2: trimmedBody.address2,
city: trimmedBody.city,
state: trimmedBody.state,
zip_post: trimmedBody.zip_post,
country: trimmedBody.country,
email: trimmedBody.email,
external_shop_id: trimmedBody.external_shop_id,
timezone: trimmedBody.timezone || DefaultNewShop.timezone,
phone: trimmedBody.phone,
logo_img_path: {
src: body.logoUrl,
src: trimmedBody.logoUrl || null, // allow empty logo
width: "",
height: "",
headerMargin: DefaultNewShop.logo_img_path.headerMargin
@@ -256,35 +342,37 @@ const partsManagementProvisioning = async (req, res) => {
appt_alt_transport: DefaultNewShop.appt_alt_transport,
md_jobline_presets: DefaultNewShop.md_jobline_presets,
vendors: {
data: body.vendors.map((v) => ({
data: trimmedBody.vendors.map((v) => ({
name: v.name,
street1: v.street1 || null,
street2: v.street2 || null,
city: v.city || null,
state: v.state || null,
zip: v.zip || null,
country: v.country || null,
email: v.email || null,
discount: v.discount ?? 0,
due_date: v.due_date ?? null,
cost_center: v.cost_center || null,
favorite: v.favorite ?? [],
phone: v.phone || null,
active: v.active ?? true,
dmsid: v.dmsid || null
street1: v.street1,
street2: v.street2,
city: v.city,
state: v.state,
zip: v.zip,
country: v.country,
email: v.email,
discount: v.discount,
due_date: v.due_date,
cost_center: v.cost_center,
favorite: v.favorite,
phone: v.phone,
active: v.active,
dmsid: v.dmsid
}))
}
};
const newShopId = await insertBodyshop(shopInput);
const userRecord = await createFirebaseUser(body.userEmail, body.userPassword);
const userRecord = await createFirebaseUser(trimmedBody.userEmail, trimmedBody.userPassword);
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({
shop: { id: newShopId, shopname: body.shopname },
shop: { id: newShopId, shopname: trimmedBody.shopname },
user: {
id: createdUser.id,
email: createdUser.email,
@@ -292,7 +380,7 @@ const partsManagementProvisioning = async (req, res) => {
}
});
} 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,
detail: err.detail || err
});

View File

@@ -4,11 +4,14 @@
* 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.
*
* 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 { isEmpty } = require("lodash");
const {
GET_BODYSHOP_WATCHERS_BY_ID,
GET_JOB_WATCHERS_MINIMAL,
GET_NOTIFICATION_WATCHERS,
INSERT_JOB_WATCHERS
@@ -26,10 +29,7 @@ const FILTER_SELF_FROM_WATCHERS = process.env?.FILTER_SELF_FROM_WATCHERS !== "fa
*/
const autoAddWatchers = async (req) => {
const { event, trigger } = req.body;
const {
logger,
sessionUtils: { getBodyshopFromRedis }
} = req;
const { logger } = req;
// Validate that this is an INSERT event, bail
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"];
try {
// Fetch bodyshop data from Redis
const bodyshopData = await getBodyshopFromRedis(shopId);
let notificationFollowers = bodyshopData?.notification_followers;
// Fetch bodyshop data directly from DB (avoid Redis staleness)
const bodyshopResponse = await gqlClient.request(GET_BODYSHOP_WATCHERS_BY_ID, { id: shopId });
const bodyshopData = bodyshopResponse?.bodyshops_by_pk;
// Bail if notification_followers is missing or not an array
if (!notificationFollowers || !Array.isArray(notificationFollowers)) {
return;
}
const notificationFollowersRaw = bodyshopData?.notification_followers;
const notificationFollowers = Array.isArray(notificationFollowersRaw)
? [...new Set(notificationFollowersRaw.filter((id) => id))] // de-dupe + remove falsy
: [];
// Execute queries in parallel
const [notificationData, existingWatchersData] = await Promise.all([
gqlClient.request(GET_NOTIFICATION_WATCHERS, {
shopId,
employeeIds: notificationFollowers.filter((id) => id)
employeeIds: notificationFollowers
}),
gqlClient.request(GET_JOB_WATCHERS_MINIMAL, { jobid: jobId })
]);
@@ -73,7 +73,7 @@ const autoAddWatchers = async (req) => {
associationId: assoc.id
})) || [];
// Get users from notification_followers
// Get users from notification_followers (employee IDs -> employee emails)
const followerEmails =
notificationData?.employees
?.filter((e) => e.user_email)
@@ -84,7 +84,7 @@ const autoAddWatchers = async (req) => {
// 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)) {
if (user?.email && !acc.some((u) => u.email === user.email)) {
acc.push(user);
}
return acc;
@@ -123,6 +123,7 @@ const autoAddWatchers = async (req) => {
message: error?.message,
stack: error?.stack,
jobId,
shopId,
roNumber
});
throw error; // Re-throw to ensure the error is logged in the handler

View File

@@ -81,8 +81,8 @@ const alternateTransportChangedBuilder = (data) => {
* @returns {{app: {jobId, jobRoNumber: *, bodyShopId: *, key: string, body: string, variables: Object, recipients: *[]}, email: {jobId, jobRoNumber: *, bodyShopName: *, body: string, recipients: *[]}, fcm: {recipients: *[]}}}
*/
const billPostedBuilder = (data) => {
const facing = data?.data?.isinhouse ? "in-house" : "vendor";
const body = `An ${facing} ${data?.data?.is_credit_memo ? "credit memo" : "bill"} has been posted.`.trim();
const facing = data?.data?.isinhouse ? "An In House" : "A Vendor";
const body = `${facing} ${data?.data?.is_credit_memo ? "credit memo" : "bill"} has been posted.`.trim();
return buildNotification(data, "notifications.job.billPosted", body, {
isInHouse: data?.data?.isinhouse,