Compare commits
68 Commits
feature/IO
...
feature/IO
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6703bc025d | ||
|
|
6f454dd4cb | ||
|
|
1440a60228 | ||
|
|
f2aa3960aa | ||
|
|
06508f3ad8 | ||
|
|
8d4195b596 | ||
|
|
9e190e7fb7 | ||
|
|
5cbf00b0c8 | ||
|
|
655aeb86fc | ||
|
|
225549275d | ||
|
|
f0717b8b36 | ||
|
|
78771ae750 | ||
|
|
0389908398 | ||
|
|
54bee763df | ||
|
|
1117a94930 | ||
|
|
5fbfb992c7 | ||
|
|
87b3b65f3e | ||
|
|
9970190909 | ||
|
|
8eee371a90 | ||
|
|
ba97b1efef | ||
|
|
8d8887c28e | ||
|
|
3b19432974 | ||
|
|
a14b2340b0 | ||
|
|
624f8e77cb | ||
|
|
fb624c817d | ||
|
|
c2b4b66ed1 | ||
|
|
ffec03ab6c | ||
|
|
552163d7b9 | ||
|
|
db1f59578c | ||
|
|
8ec5831ec5 | ||
|
|
0146ac5b7b | ||
|
|
a603e5c0b8 | ||
|
|
338906e288 | ||
|
|
542997b1a7 | ||
|
|
5fce548666 | ||
|
|
80322caad0 | ||
|
|
56472d24d9 | ||
|
|
db5dcc271d | ||
|
|
73ab02225e | ||
|
|
83a1b7690d | ||
|
|
c9e28b1ed2 | ||
|
|
c25c66d00f | ||
|
|
d319ab49d4 | ||
|
|
a069989ea7 | ||
|
|
8e3aa186cb | ||
|
|
01c55d6277 | ||
|
|
3438907d8d | ||
|
|
ae020b651e | ||
|
|
d22988df15 | ||
|
|
8136a56ad2 | ||
|
|
830f6c0eea | ||
|
|
4c1849289a | ||
|
|
c45a4780e3 | ||
|
|
d4adc4c1aa | ||
|
|
d9e71423f5 | ||
|
|
2ab4615642 | ||
|
|
dd5961d419 | ||
|
|
8190958ba3 | ||
|
|
77e009f316 | ||
|
|
2b2738a8d1 | ||
|
|
3d10c9da7f | ||
|
|
e82c77d119 | ||
|
|
855a78be05 | ||
|
|
a29e840797 | ||
|
|
1b30c1ab58 | ||
|
|
80f235f12e | ||
|
|
5b00ded5f6 | ||
|
|
c5b19d8f22 |
24
.platform/hooks/predeploy/00-install-fonts.sh
Normal file
24
.platform/hooks/predeploy/00-install-fonts.sh
Normal file
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Install required packages
|
||||
dnf install -y fontconfig freetype
|
||||
|
||||
# Move to the /tmp directory for temporary download and extraction
|
||||
cd /tmp
|
||||
|
||||
# Download the Montserrat font zip file
|
||||
wget https://images.imex.online/fonts/montserrat.zip -O montserrat.zip
|
||||
|
||||
# Unzip the downloaded font file
|
||||
unzip montserrat.zip -d montserrat
|
||||
|
||||
# Move the font files to the system fonts directory
|
||||
mv montserrat/montserrat/*.ttf /usr/share/fonts
|
||||
|
||||
# Rebuild the font cache
|
||||
fc-cache -fv
|
||||
|
||||
# Clean up
|
||||
rm -rf /tmp/montserrat /tmp/montserrat.zip
|
||||
|
||||
echo "Montserrat fonts installed and cached successfully."
|
||||
@@ -45,7 +45,7 @@ export function ChatPopupComponent({ chatVisible, selectedConversation, toggleCh
|
||||
if (fcmToken) {
|
||||
setpollInterval(0);
|
||||
} else {
|
||||
setpollInterval(60000);
|
||||
setpollInterval(90000);
|
||||
}
|
||||
}, [fcmToken]);
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Card, Table, Tag } from "antd";
|
||||
import LoadingSkeleton from "../../loading-skeleton/loading-skeleton.component";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import dayjs from "../../../utils/day";
|
||||
import DashboardRefreshRequired from "../refresh-required.component";
|
||||
import axios from "axios";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import dayjs from "../../../utils/day";
|
||||
import LoadingSkeleton from "../../loading-skeleton/loading-skeleton.component";
|
||||
import DashboardRefreshRequired from "../refresh-required.component";
|
||||
|
||||
const fortyFiveDaysAgo = () => dayjs().subtract(45, "day").toLocaleString();
|
||||
|
||||
@@ -46,6 +46,11 @@ export default function JobLifecycleDashboardComponent({ data, bodyshop, ...card
|
||||
dataIndex: "humanReadable",
|
||||
key: "humanReadable"
|
||||
},
|
||||
{
|
||||
title: t("job_lifecycle.columns.average_human_readable"),
|
||||
dataIndex: "averageHumanReadable",
|
||||
key: "averageHumanReadable"
|
||||
},
|
||||
{
|
||||
title: t("job_lifecycle.columns.status_count"),
|
||||
key: "statusCount",
|
||||
|
||||
@@ -44,7 +44,7 @@ function LogLevelHierarchy(level) {
|
||||
return "orange";
|
||||
case "INFO":
|
||||
return "blue";
|
||||
case "WARNING":
|
||||
case "WARN":
|
||||
return "yellow";
|
||||
case "ERROR":
|
||||
return "red";
|
||||
|
||||
@@ -2,11 +2,11 @@ import { DatePicker } from "antd";
|
||||
import PropTypes from "prop-types";
|
||||
import React, { useCallback, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import dayjs from "../../utils/day";
|
||||
import { fuzzyMatchDate } from "./formats.js";
|
||||
import { connect } from "react-redux";
|
||||
import { createStructuredSelector } from "reselect";
|
||||
import { selectBodyshop } from "../../redux/user/user.selectors.js";
|
||||
import { connect } from "react-redux";
|
||||
import dayjs from "../../utils/day";
|
||||
import { fuzzyMatchDate } from "./formats.js";
|
||||
|
||||
const mapStateToProps = createStructuredSelector({
|
||||
bodyshop: selectBodyshop
|
||||
@@ -28,9 +28,8 @@ const DateTimePicker = ({
|
||||
|
||||
const handleChange = useCallback(
|
||||
(newDate) => {
|
||||
if (!newDate) return;
|
||||
if (onChange) {
|
||||
onChange(bodyshop?.timezone ? dayjs(newDate).tz(bodyshop.timezone, true) : newDate);
|
||||
onChange(bodyshop?.timezone && newDate ? dayjs(newDate).tz(bodyshop.timezone, true) : newDate);
|
||||
}
|
||||
setIsManualInput(false);
|
||||
},
|
||||
|
||||
@@ -4,12 +4,12 @@ import ScoreboardChart from "../scoreboard-chart/scoreboard-chart.component";
|
||||
import ScoreboardLastDays from "../scoreboard-last-days/scoreboard-last-days.component";
|
||||
import ScoreboardTargetsTable from "../scoreboard-targets-table/scoreboard-targets-table.component";
|
||||
|
||||
import { useApolloClient, useQuery } from "@apollo/client";
|
||||
import { connect } from "react-redux";
|
||||
import { createStructuredSelector } from "reselect";
|
||||
import { GET_BLOCKED_DAYS, QUERY_SCOREBOARD } from "../../graphql/scoreboard.queries";
|
||||
import { selectBodyshop } from "../../redux/user/user.selectors";
|
||||
import dayjs from "../../utils/day";
|
||||
import { useApolloClient, useQuery } from "@apollo/client";
|
||||
import { GET_BLOCKED_DAYS, QUERY_SCOREBOARD } from "../../graphql/scoreboard.queries";
|
||||
|
||||
const mapStateToProps = createStructuredSelector({
|
||||
//currentUser: selectCurrentUser
|
||||
@@ -26,7 +26,7 @@ export function ScoreboardDisplayComponent({ bodyshop }) {
|
||||
start: dayjs().startOf("month"),
|
||||
end: dayjs().endOf("month")
|
||||
},
|
||||
pollInterval: 60000
|
||||
pollInterval: 60000*5
|
||||
});
|
||||
|
||||
const { data } = scoreboardSubscription;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useQuery } from "@apollo/client";
|
||||
import { Col, Row } from "antd";
|
||||
import _ from "lodash";
|
||||
import dayjs from "../../utils/day";
|
||||
import React, { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { connect } from "react-redux";
|
||||
import { createStructuredSelector } from "reselect";
|
||||
import { QUERY_TIME_TICKETS_IN_RANGE_SB } from "../../graphql/timetickets.queries";
|
||||
import { selectBodyshop } from "../../redux/user/user.selectors";
|
||||
import dayjs from "../../utils/day";
|
||||
import AlertComponent from "../alert/alert.component";
|
||||
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
|
||||
import * as Utils from "../scoreboard-targets-table/scoreboard-targets-table.util";
|
||||
@@ -86,7 +86,7 @@ export function ScoreboardTimeTicketsStats({ bodyshop }) {
|
||||
},
|
||||
fetchPolicy: "network-only",
|
||||
nextFetchPolicy: "network-only",
|
||||
pollInterval: 60000,
|
||||
pollInterval: 60000*5,
|
||||
skip: !fixedPeriods
|
||||
});
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useQuery } from "@apollo/client";
|
||||
import { Col, Row } from "antd";
|
||||
import _ from "lodash";
|
||||
import dayjs from "../../utils/day";
|
||||
import queryString from "query-string";
|
||||
import React, { useMemo } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { QUERY_TIME_TICKETS_IN_RANGE_SB } from "../../graphql/timetickets.queries";
|
||||
import dayjs from "../../utils/day";
|
||||
import AlertComponent from "../alert/alert.component";
|
||||
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
|
||||
import * as Utils from "../scoreboard-targets-table/scoreboard-targets-table.util";
|
||||
@@ -68,7 +68,7 @@ export default function ScoreboardTimeTickets() {
|
||||
},
|
||||
fetchPolicy: "network-only",
|
||||
nextFetchPolicy: "network-only",
|
||||
pollInterval: 60000,
|
||||
pollInterval: 60000*5,
|
||||
skip: !fixedPeriods
|
||||
});
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ export function TimeTicketList({
|
||||
extra
|
||||
}) {
|
||||
const [state, setState] = useState({
|
||||
sortedInfo: {},
|
||||
sortedInfo: { columnKey: 'date', order: 'descend' },
|
||||
filteredInfo: { text: "" }
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useMutation, useQuery } from "@apollo/client";
|
||||
import { Button, Form, Modal, notification, Space } from "antd";
|
||||
import { PageHeader } from "@ant-design/pro-layout";
|
||||
import dayjs from "../../utils/day";
|
||||
import { useMutation, useQuery } from "@apollo/client";
|
||||
import { useSplitTreatments } from "@splitsoftware/splitio-react";
|
||||
import { Button, Form, Modal, notification, Space } from "antd";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { connect } from "react-redux";
|
||||
@@ -11,9 +11,9 @@ import { INSERT_NEW_TIME_TICKET, UPDATE_TIME_TICKET } from "../../graphql/timeti
|
||||
import { toggleModalVisible } from "../../redux/modals/modals.actions";
|
||||
import { selectTimeTicket } from "../../redux/modals/modals.selectors";
|
||||
import { selectBodyshop } from "../../redux/user/user.selectors";
|
||||
import TimeTicketModalComponent from "./time-ticket-modal.component";
|
||||
import dayjs from "../../utils/day";
|
||||
import TimeTicketsCommitToggleComponent from "../time-tickets-commit-toggle/time-tickets-commit-toggle.component";
|
||||
import { useSplitTreatments } from "@splitsoftware/splitio-react";
|
||||
import TimeTicketModalComponent from "./time-ticket-modal.component";
|
||||
|
||||
const mapStateToProps = createStructuredSelector({
|
||||
timeTicketModal: selectTimeTicket,
|
||||
@@ -87,7 +87,7 @@ export function TimeTicketModalContainer({ timeTicketModal, toggleModalVisible,
|
||||
if (enterAgain) {
|
||||
//Capture the existing information and repopulate it.
|
||||
|
||||
const prev = form.getFieldsValue(["date", "employeeid"]);
|
||||
const prev = form.getFieldsValue(["date", "employeeid", "flat_rate"]);
|
||||
|
||||
form.resetFields();
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import SocketIO from "socket.io-client";
|
||||
import { auth } from "../../firebase/firebase.utils";
|
||||
import { store } from "../../redux/store";
|
||||
import { setWssStatus } from "../../redux/application/application.actions";
|
||||
import { addAlerts, setWssStatus } from "../../redux/application/application.actions";
|
||||
|
||||
const useSocket = (bodyshop) => {
|
||||
const socketRef = useRef(null);
|
||||
const [clientId, setClientId] = useState(null);
|
||||
@@ -31,6 +32,14 @@ const useSocket = (bodyshop) => {
|
||||
socketRef.current = socketInstance;
|
||||
|
||||
const handleBodyshopMessage = (message) => {
|
||||
if (!message || !message?.type) return;
|
||||
|
||||
switch (message.type) {
|
||||
case "alert-update":
|
||||
store.dispatch(addAlerts(message.payload));
|
||||
break;
|
||||
}
|
||||
|
||||
if (!import.meta.env.DEV) return;
|
||||
console.log(`Received message for bodyshop ${bodyshop.id}:`, message);
|
||||
};
|
||||
@@ -39,22 +48,22 @@ const useSocket = (bodyshop) => {
|
||||
console.log("Socket connected:", socketInstance.id);
|
||||
socketInstance.emit("join-bodyshop-room", bodyshop.id);
|
||||
setClientId(socketInstance.id);
|
||||
store.dispatch(setWssStatus("connected"))
|
||||
store.dispatch(setWssStatus("connected"));
|
||||
};
|
||||
|
||||
const handleReconnect = (attempt) => {
|
||||
console.log(`Socket reconnected after ${attempt} attempts`);
|
||||
store.dispatch(setWssStatus("connected"))
|
||||
store.dispatch(setWssStatus("connected"));
|
||||
};
|
||||
|
||||
const handleConnectionError = (err) => {
|
||||
console.error("Socket connection error:", err);
|
||||
store.dispatch(setWssStatus("error"))
|
||||
store.dispatch(setWssStatus("error"));
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
console.log("Socket disconnected");
|
||||
store.dispatch(setWssStatus("disconnected"))
|
||||
store.dispatch(setWssStatus("disconnected"));
|
||||
};
|
||||
|
||||
socketInstance.on("connect", handleConnect);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { gql } from "@apollo/client";
|
||||
|
||||
export const QUERY_TICKETS_BY_JOBID = gql`
|
||||
query QUERY_TICKETS_BY_JOBID($jobid: uuid!) {
|
||||
timetickets(where: { jobid: { _eq: $jobid } }, order_by: { date: desc_nulls_first }) {
|
||||
timetickets(where: { jobid: { _eq: $jobid } }) {
|
||||
actualhrs
|
||||
cost_center
|
||||
ciecacode
|
||||
@@ -26,7 +26,7 @@ export const QUERY_TICKETS_BY_JOBID = gql`
|
||||
|
||||
export const QUERY_TIME_TICKETS_IN_RANGE = gql`
|
||||
query QUERY_TIME_TICKETS_IN_RANGE($start: date!, $end: date!) {
|
||||
timetickets(where: { date: { _gte: $start, _lte: $end } }, order_by: { date: desc_nulls_first }) {
|
||||
timetickets(where: { date: { _gte: $start, _lte: $end } }) {
|
||||
actualhrs
|
||||
ciecacode
|
||||
clockoff
|
||||
@@ -69,7 +69,6 @@ export const QUERY_TIME_TICKETS_TECHNICIAN_IN_RANGE = gql`
|
||||
) {
|
||||
timetickets(
|
||||
where: { date: { _gte: $start, _lte: $end }, employeeid: { _eq: $employeeid } }
|
||||
order_by: { date: desc_nulls_first }
|
||||
) {
|
||||
actualhrs
|
||||
ciecacode
|
||||
@@ -101,7 +100,6 @@ export const QUERY_TIME_TICKETS_TECHNICIAN_IN_RANGE = gql`
|
||||
}
|
||||
fixedperiod: timetickets(
|
||||
where: { date: { _gte: $fixedStart, _lte: $fixedEnd }, employeeid: { _eq: $employeeid } }
|
||||
order_by: { date: desc_nulls_first }
|
||||
) {
|
||||
actualhrs
|
||||
ciecacode
|
||||
@@ -145,7 +143,6 @@ export const QUERY_TIME_TICKETS_IN_RANGE_SB = gql`
|
||||
) {
|
||||
timetickets(
|
||||
where: { date: { _gte: $start, _lte: $end }, cost_center: { _neq: "timetickets.labels.shift" } }
|
||||
order_by: { date: desc_nulls_first }
|
||||
) {
|
||||
actualhrs
|
||||
ciecacode
|
||||
@@ -180,7 +177,6 @@ export const QUERY_TIME_TICKETS_IN_RANGE_SB = gql`
|
||||
}
|
||||
fixedperiod: timetickets(
|
||||
where: { date: { _gte: $fixedStart, _lte: $fixedEnd }, cost_center: { _neq: "timetickets.labels.shift" } }
|
||||
order_by: { date: desc_nulls_first }
|
||||
) {
|
||||
actualhrs
|
||||
ciecacode
|
||||
@@ -335,7 +331,6 @@ export const UPDATE_TIME_TICKETS = gql`
|
||||
export const QUERY_ACTIVE_TIME_TICKETS = gql`
|
||||
query QUERY_ACTIVE_TIME_TICKETS($employeeId: uuid) {
|
||||
timetickets(
|
||||
order_by: { date: desc_nulls_first }
|
||||
where: {
|
||||
_and: {
|
||||
clockoff: { _is_null: true }
|
||||
|
||||
@@ -71,7 +71,7 @@ export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
|
||||
...logs,
|
||||
{
|
||||
timestamp: new Date(),
|
||||
level: "WARNING",
|
||||
level: "WARN",
|
||||
message: "Reconnected to CDK Export Service"
|
||||
}
|
||||
];
|
||||
@@ -125,7 +125,7 @@ export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
|
||||
>
|
||||
<Select.Option key="DEBUG">DEBUG</Select.Option>
|
||||
<Select.Option key="INFO">INFO</Select.Option>
|
||||
<Select.Option key="WARNING">WARNING</Select.Option>
|
||||
<Select.Option key="WARN">WARN</Select.Option>
|
||||
<Select.Option key="ERROR">ERROR</Select.Option>
|
||||
</Select>
|
||||
<Button onClick={() => setLogs([])}>Clear Logs</Button>
|
||||
|
||||
@@ -90,7 +90,7 @@ export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader, inse
|
||||
...logs,
|
||||
{
|
||||
timestamp: new Date(),
|
||||
level: "WARNING",
|
||||
level: "warn",
|
||||
message: "Reconnected to CDK Export Service"
|
||||
}
|
||||
];
|
||||
@@ -175,7 +175,7 @@ export function DmsContainer({ bodyshop, setBreadcrumbs, setSelectedHeader, inse
|
||||
>
|
||||
<Select.Option key="DEBUG">DEBUG</Select.Option>
|
||||
<Select.Option key="INFO">INFO</Select.Option>
|
||||
<Select.Option key="WARNING">WARNING</Select.Option>
|
||||
<Select.Option key="WARN">WARN</Select.Option>
|
||||
<Select.Option key="ERROR">ERROR</Select.Option>
|
||||
</Select>
|
||||
<Button onClick={() => setLogs([])}>Clear Logs</Button>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FloatButton, Layout, Spin } from "antd";
|
||||
import { FloatButton, Layout, notification, Spin } from "antd";
|
||||
// import preval from "preval.macro";
|
||||
import React, { lazy, Suspense, useContext, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -21,11 +21,12 @@ import ShopSubStatusComponent from "../../components/shop-sub-status/shop-sub-st
|
||||
import { requestForToken } from "../../firebase/firebase.utils";
|
||||
import SocketContext from "../../contexts/SocketIO/socketContext.jsx";
|
||||
import { selectBodyshop, selectInstanceConflict } from "../../redux/user/user.selectors";
|
||||
|
||||
import UpdateAlert from "../../components/update-alert/update-alert.component";
|
||||
import InstanceRenderManager from "../../utils/instanceRenderMgr.js";
|
||||
import "./manage.page.styles.scss";
|
||||
import WssStatusDisplayComponent from "../../components/wss-status-display/wss-status-display.component.jsx";
|
||||
import { selectAlerts } from "../../redux/application/application.selectors.js";
|
||||
import { addAlerts } from "../../redux/application/application.actions.js";
|
||||
|
||||
const JobsPage = lazy(() => import("../jobs/jobs.page"));
|
||||
|
||||
@@ -104,16 +105,80 @@ const { Content, Footer } = Layout;
|
||||
|
||||
const mapStateToProps = createStructuredSelector({
|
||||
conflict: selectInstanceConflict,
|
||||
bodyshop: selectBodyshop
|
||||
bodyshop: selectBodyshop,
|
||||
alerts: selectAlerts
|
||||
});
|
||||
|
||||
const mapDispatchToProps = (dispatch) => ({});
|
||||
const ALERT_FILE_URL = InstanceRenderManager({
|
||||
imex: "https://images.imex.online/alerts/alerts-imex.json",
|
||||
rome: "https://images.imex.online/alerts/alerts-rome.json"
|
||||
});
|
||||
|
||||
export function Manage({ conflict, bodyshop }) {
|
||||
const mapDispatchToProps = (dispatch) => ({
|
||||
setAlerts: (alerts) => dispatch(addAlerts(alerts))
|
||||
});
|
||||
|
||||
export function Manage({ conflict, bodyshop, alerts, setAlerts }) {
|
||||
const { t } = useTranslation();
|
||||
const [chatVisible] = useState(false);
|
||||
const { socket, clientId } = useContext(SocketContext);
|
||||
|
||||
// State to track displayed alerts
|
||||
const [displayedAlertIds, setDisplayedAlertIds] = useState([]);
|
||||
|
||||
// Fetch displayed alerts from localStorage on mount
|
||||
useEffect(() => {
|
||||
const displayedAlerts = JSON.parse(localStorage.getItem("displayedAlerts") || "[]");
|
||||
setDisplayedAlertIds(displayedAlerts);
|
||||
}, []);
|
||||
|
||||
// Fetch alerts from the JSON file and dispatch to Redux store
|
||||
useEffect(() => {
|
||||
const fetchAlerts = async () => {
|
||||
try {
|
||||
const response = await fetch(ALERT_FILE_URL);
|
||||
const fetchedAlerts = await response.json();
|
||||
setAlerts(fetchedAlerts);
|
||||
} catch (error) {
|
||||
console.error("Error fetching alerts:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchAlerts();
|
||||
}, []);
|
||||
|
||||
// Use useEffect to watch for new alerts
|
||||
useEffect(() => {
|
||||
if (alerts && Object.keys(alerts).length > 0) {
|
||||
// Convert the alerts object into an array
|
||||
const alertArray = Object.values(alerts);
|
||||
|
||||
// Filter out alerts that have already been dismissed
|
||||
const newAlerts = alertArray.filter((alert) => !displayedAlertIds.includes(alert.id));
|
||||
|
||||
newAlerts.forEach((alert) => {
|
||||
// Display the notification
|
||||
notification.open({
|
||||
key: "notification-alerts-" + alert.id,
|
||||
message: alert.message,
|
||||
description: alert.description,
|
||||
type: alert.type || "info",
|
||||
duration: 0,
|
||||
placement: "bottomRight",
|
||||
closable: true,
|
||||
onClose: () => {
|
||||
// When the notification is closed, update displayed alerts state and localStorage
|
||||
setDisplayedAlertIds((prevIds) => {
|
||||
const updatedIds = [...prevIds, alert.id];
|
||||
localStorage.setItem("displayedAlerts", JSON.stringify(updatedIds));
|
||||
return updatedIds;
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}, [alerts, displayedAlertIds]);
|
||||
|
||||
useEffect(() => {
|
||||
const widgetId = InstanceRenderManager({
|
||||
imex: "IABVNO4scRKY11XBQkNr",
|
||||
|
||||
@@ -67,6 +67,12 @@ export const setUpdateAvailable = (isUpdateAvailable) => ({
|
||||
type: ApplicationActionTypes.SET_UPDATE_AVAILABLE,
|
||||
payload: isUpdateAvailable
|
||||
});
|
||||
|
||||
export const addAlerts = (alerts) => ({
|
||||
type: ApplicationActionTypes.ADD_ALERTS,
|
||||
payload: alerts
|
||||
});
|
||||
|
||||
export const setWssStatus = (status) => ({
|
||||
type: ApplicationActionTypes.SET_WSS_STATUS,
|
||||
payload: status
|
||||
|
||||
@@ -15,7 +15,8 @@ const INITIAL_STATE = {
|
||||
error: null
|
||||
},
|
||||
jobReadOnly: false,
|
||||
partnerVersion: null
|
||||
partnerVersion: null,
|
||||
alerts: {}
|
||||
};
|
||||
|
||||
const applicationReducer = (state = INITIAL_STATE, action) => {
|
||||
@@ -91,6 +92,18 @@ const applicationReducer = (state = INITIAL_STATE, action) => {
|
||||
case ApplicationActionTypes.SET_WSS_STATUS: {
|
||||
return { ...state, wssStatus: action.payload };
|
||||
}
|
||||
|
||||
case ApplicationActionTypes.ADD_ALERTS: {
|
||||
const newAlertsMap = { ...state.alerts };
|
||||
|
||||
action.payload.alerts.forEach((alert) => {
|
||||
newAlertsMap[alert.id] = alert;
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
alerts: newAlertsMap
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -23,3 +23,4 @@ export const selectOnline = createSelector([selectApplication], (application) =>
|
||||
export const selectProblemJobs = createSelector([selectApplication], (application) => application.problemJobs);
|
||||
export const selectUpdateAvailable = createSelector([selectApplication], (application) => application.updateAvailable);
|
||||
export const selectWssStatus = createSelector([selectApplication], (application) => application.wssStatus);
|
||||
export const selectAlerts = createSelector([selectApplication], (application) => application.alerts);
|
||||
|
||||
@@ -13,6 +13,7 @@ const ApplicationActionTypes = {
|
||||
INSERT_AUDIT_TRAIL: "INSERT_AUDIT_TRAIL",
|
||||
SET_PROBLEM_JOBS: "SET_PROBLEM_JOBS",
|
||||
SET_UPDATE_AVAILABLE: "SET_UPDATE_AVAILABLE",
|
||||
SET_WSS_STATUS: "SET_WSS_STATUS"
|
||||
SET_WSS_STATUS: "SET_WSS_STATUS",
|
||||
ADD_ALERTS: "ADD_ALERTS"
|
||||
};
|
||||
export default ApplicationActionTypes;
|
||||
|
||||
@@ -1338,6 +1338,8 @@
|
||||
},
|
||||
"job_lifecycle": {
|
||||
"columns": {
|
||||
"average_human_readable": "Average Human Readable",
|
||||
"average_value": "Average Value",
|
||||
"duration": "Duration",
|
||||
"end": "End",
|
||||
"human_readable": "Human Readable",
|
||||
|
||||
@@ -1338,6 +1338,8 @@
|
||||
},
|
||||
"job_lifecycle": {
|
||||
"columns": {
|
||||
"average_human_readable": "",
|
||||
"average_value": "",
|
||||
"duration": "",
|
||||
"end": "",
|
||||
"human_readable": "",
|
||||
|
||||
@@ -1338,6 +1338,8 @@
|
||||
},
|
||||
"job_lifecycle": {
|
||||
"columns": {
|
||||
"average_human_readable": "",
|
||||
"average_value": "",
|
||||
"duration": "",
|
||||
"end": "",
|
||||
"human_readable": "",
|
||||
|
||||
@@ -167,6 +167,28 @@ services:
|
||||
# volumes:
|
||||
# - redis-insight-data:/db
|
||||
|
||||
# ##Optional Container for SFTP/SSH Server for testing
|
||||
# ssh-sftp-server:
|
||||
# image: atmoz/sftp:alpine # Using an image with SFTP support
|
||||
# container_name: ssh-sftp-server
|
||||
# hostname: ssh-sftp-server
|
||||
# networks:
|
||||
# - redis-cluster-net
|
||||
# ports:
|
||||
# - "2222:22" # Expose port 22 for SSH/SFTP (mapped to 2222 on the host)
|
||||
# volumes:
|
||||
# - ./certs/id_rsa.pub:/home/user/.ssh/keys/id_rsa.pub:ro # Mount the SSH public key
|
||||
# - ./upload:/home/user/upload # Mount a local directory for SFTP uploads
|
||||
# environment:
|
||||
# - SFTP_USERS=user:password:1000::upload
|
||||
# command: >
|
||||
# /bin/sh -c "
|
||||
# chmod -R 007 /home/user/upload &&
|
||||
# echo 'Match User user' >> /etc/ssh/sshd_config &&
|
||||
# sed -i -e 's#ForceCommand internal-sftp#ForceCommand internal-sftp -d /upload#' /etc/ssh/sshd_config &&
|
||||
# /usr/sbin/sshd -D
|
||||
# "
|
||||
|
||||
networks:
|
||||
redis-cluster-net:
|
||||
driver: bridge
|
||||
|
||||
@@ -69,7 +69,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
jobline:
|
||||
job:
|
||||
@@ -180,7 +179,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -387,7 +385,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -504,7 +501,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bill:
|
||||
job:
|
||||
@@ -671,7 +667,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
_and:
|
||||
- job:
|
||||
@@ -1285,7 +1280,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
courtesycar:
|
||||
bodyshop:
|
||||
@@ -1526,7 +1520,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -1786,7 +1779,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -1920,7 +1912,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
_or:
|
||||
- job:
|
||||
@@ -2105,7 +2096,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
employee_team:
|
||||
bodyshop:
|
||||
@@ -2268,7 +2258,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
employee:
|
||||
bodyshop:
|
||||
@@ -2449,7 +2438,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -2696,7 +2684,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -2808,7 +2795,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
conversation:
|
||||
bodyshop:
|
||||
@@ -3123,7 +3109,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
job:
|
||||
bodyshop:
|
||||
@@ -4232,7 +4217,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -4248,41 +4232,41 @@
|
||||
enable_manual: false
|
||||
update:
|
||||
columns:
|
||||
- clm_no
|
||||
- v_make_desc
|
||||
- date_next_contact
|
||||
- status
|
||||
- employee_csr
|
||||
- employee_prep
|
||||
- clm_total
|
||||
- suspended
|
||||
- employee_body
|
||||
- ro_number
|
||||
- actual_in
|
||||
- ownr_co_nm
|
||||
- v_model_yr
|
||||
- comment
|
||||
- job_totals
|
||||
- v_vin
|
||||
- ownr_fn
|
||||
- scheduled_completion
|
||||
- special_coverage_policy
|
||||
- v_color
|
||||
- ca_gst_registrant
|
||||
- scheduled_delivery
|
||||
- actual_delivery
|
||||
- actual_completion
|
||||
- kanbanparent
|
||||
- est_ct_fn
|
||||
- alt_transport
|
||||
- v_model_desc
|
||||
- clm_no
|
||||
- v_make_desc
|
||||
- date_next_contact
|
||||
- status
|
||||
- employee_csr
|
||||
- actual_in
|
||||
- v_model_yr
|
||||
- comment
|
||||
- job_totals
|
||||
- ownr_fn
|
||||
- v_color
|
||||
- ca_gst_registrant
|
||||
- employee_refinish
|
||||
- ownr_ph1
|
||||
- date_last_contacted
|
||||
- alt_transport
|
||||
- inproduction
|
||||
- est_ct_ln
|
||||
- production_vars
|
||||
- category
|
||||
- v_model_desc
|
||||
- date_invoiced
|
||||
- est_co_nm
|
||||
- ownr_ln
|
||||
@@ -4295,6 +4279,12 @@
|
||||
- name: event-secret
|
||||
value_from_env: EVENT_SECRET
|
||||
request_transform:
|
||||
body:
|
||||
action: transform
|
||||
template: |-
|
||||
{
|
||||
"data": {{$body?.event?.data?.new}}
|
||||
}
|
||||
method: POST
|
||||
query_params: {}
|
||||
template_engine: Kriti
|
||||
@@ -4496,7 +4486,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
conversation:
|
||||
bodyshop:
|
||||
@@ -4670,7 +4659,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
job:
|
||||
bodyshop:
|
||||
@@ -4805,7 +4793,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -5110,7 +5097,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
parts_order:
|
||||
job:
|
||||
@@ -5243,7 +5229,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
job:
|
||||
bodyshop:
|
||||
@@ -5419,7 +5404,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
job:
|
||||
bodyshop:
|
||||
@@ -5559,7 +5543,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -5670,7 +5653,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
_or:
|
||||
- parentjob_rel:
|
||||
@@ -5760,7 +5742,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
job:
|
||||
bodyshop:
|
||||
@@ -6045,7 +6026,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -6541,7 +6521,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
@@ -6698,7 +6677,6 @@
|
||||
delete_permissions:
|
||||
- role: user
|
||||
permission:
|
||||
backend_only: false
|
||||
filter:
|
||||
bodyshop:
|
||||
associations:
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Could not auto-generate a down migration.
|
||||
-- Please write an appropriate down migration for the SQL below:
|
||||
-- CREATE INDEX idx_timetickets_date ON timetickets (date );
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX idx_timetickets_date ON timetickets (date );
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Could not auto-generate a down migration.
|
||||
-- Please write an appropriate down migration for the SQL below:
|
||||
-- CREATE INDEX idx_jobs_ownr_fn ON jobs USING gin (ownr_fn gin_trgm_ops);
|
||||
-- CREATE INDEX idx_jobs_ownr_ln ON jobs USING gin (ownr_ln gin_trgm_ops);
|
||||
-- CREATE INDEX idx_jobs_ownr_co_nm ON jobs USING gin (ownr_co_nm gin_trgm_ops);
|
||||
-- CREATE INDEX idx_jobs_clm_no ON jobs USING gin (clm_no gin_trgm_ops);
|
||||
-- CREATE INDEX idx_jobs_v_make_desc ON jobs USING gin (v_make_desc gin_trgm_ops);
|
||||
-- CREATE INDEX idx_jobs_v_model_desc ON jobs USING gin (v_model_desc gin_trgm_ops);
|
||||
-- CREATE INDEX idx_jobs_plate_no ON jobs USING gin (plate_no gin_trgm_ops);
|
||||
7
hasura/migrations/1730517308367_run_sql_migration/up.sql
Normal file
7
hasura/migrations/1730517308367_run_sql_migration/up.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
CREATE INDEX idx_jobs_ownr_fn ON jobs USING gin (ownr_fn gin_trgm_ops);
|
||||
CREATE INDEX idx_jobs_ownr_ln ON jobs USING gin (ownr_ln gin_trgm_ops);
|
||||
CREATE INDEX idx_jobs_ownr_co_nm ON jobs USING gin (ownr_co_nm gin_trgm_ops);
|
||||
CREATE INDEX idx_jobs_clm_no ON jobs USING gin (clm_no gin_trgm_ops);
|
||||
CREATE INDEX idx_jobs_v_make_desc ON jobs USING gin (v_make_desc gin_trgm_ops);
|
||||
CREATE INDEX idx_jobs_v_model_desc ON jobs USING gin (v_model_desc gin_trgm_ops);
|
||||
CREATE INDEX idx_jobs_plate_no ON jobs USING gin (plate_no gin_trgm_ops);
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Could not auto-generate a down migration.
|
||||
-- Please write an appropriate down migration for the SQL below:
|
||||
-- CREATE INDEX idx_exportlog_createdat_desc ON exportlog (created_at desc);
|
||||
1
hasura/migrations/1730518121867_run_sql_migration/up.sql
Normal file
1
hasura/migrations/1730518121867_run_sql_migration/up.sql
Normal file
@@ -0,0 +1 @@
|
||||
CREATE INDEX idx_exportlog_createdat_desc ON exportlog (created_at desc);
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Could not auto-generate a down migration.
|
||||
-- Please write an appropriate down migration for the SQL below:
|
||||
-- CREATE index idx_messages_unread_agg ON messages (read, isoutbound)
|
||||
-- WHERE read = false AND isoutbound = false;
|
||||
2
hasura/migrations/1730521661838_run_sql_migration/up.sql
Normal file
2
hasura/migrations/1730521661838_run_sql_migration/up.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
CREATE index idx_messages_unread_agg ON messages (read, isoutbound)
|
||||
WHERE read = false AND isoutbound = false;
|
||||
@@ -611,7 +611,7 @@ async function InsertFailedExportLog(socket, error) {
|
||||
bodyshopid: socket.JobData.bodyshop.id,
|
||||
jobid: socket.JobData.id,
|
||||
successful: false,
|
||||
message: [error],
|
||||
message: JSON.stringify(error),
|
||||
useremail: socket.user.email
|
||||
}
|
||||
});
|
||||
|
||||
@@ -167,7 +167,7 @@ async function QueryVendorRecord(oauthClient, qbo_realmId, req, bill) {
|
||||
|
||||
async function InsertVendorRecord(oauthClient, qbo_realmId, req, bill) {
|
||||
const Vendor = {
|
||||
DisplayName: bill.vendor.name
|
||||
DisplayName: StandardizeName(bill.vendor.name)
|
||||
};
|
||||
try {
|
||||
const result = await oauthClient.makeApiCall({
|
||||
|
||||
@@ -10,7 +10,7 @@ function urlBuilder(realmId, object, query = null) {
|
||||
}
|
||||
|
||||
function StandardizeName(str) {
|
||||
return str.replace(new RegExp(/'/g), "\\'");
|
||||
return str.replace(new RegExp(/'/g), "\\'").trim();
|
||||
}
|
||||
|
||||
exports.urlBuilder = urlBuilder;
|
||||
|
||||
76
server/alerts/alertcheck.js
Normal file
76
server/alerts/alertcheck.js
Normal file
@@ -0,0 +1,76 @@
|
||||
const axios = require("axios");
|
||||
const _ = require("lodash");
|
||||
const { default: InstanceMgr } = require("../utils/instanceMgr"); // For deep object comparison
|
||||
|
||||
// Constants
|
||||
const ALERTS_REDIS_KEY = "alerts_data"; // The key under which we'll store alerts in Redis
|
||||
const GLOBAL_SOCKET_ID = "global"; // Use 'global' as a socketId to store global data
|
||||
|
||||
const ALERT_FILE_URL = InstanceMgr({
|
||||
imex: "https://images.imex.online/alerts/alerts-imex.json",
|
||||
rome: "https://images.imex.online/alerts/alerts-rome.json"
|
||||
});
|
||||
|
||||
const alertCheck = async (req, res) => {
|
||||
// Access Redis helper functions
|
||||
const { ioRedis, logger } = req;
|
||||
const { getSessionData, setSessionData } = req.sessionUtils;
|
||||
|
||||
try {
|
||||
// Get the JSON Alert file from the server
|
||||
const response = await axios.get(ALERT_FILE_URL);
|
||||
const currentAlerts = response.data;
|
||||
// Retrieve stored alerts from Redis using a global socketId
|
||||
const storedAlerts = await getSessionData(GLOBAL_SOCKET_ID, ALERTS_REDIS_KEY);
|
||||
if (!storedAlerts) {
|
||||
// Alerts not in Redis, store them
|
||||
await setSessionData(GLOBAL_SOCKET_ID, ALERTS_REDIS_KEY, currentAlerts);
|
||||
logger.logger.debug("Alerts added to Redis for the first time.");
|
||||
|
||||
// Emit to clients
|
||||
if (ioRedis) {
|
||||
ioRedis.emit("bodyshop-message", {
|
||||
type: "alert-update",
|
||||
payload: currentAlerts
|
||||
});
|
||||
logger.logger.debug("Alerts emitted to clients for the first time.");
|
||||
} else {
|
||||
logger.log("Socket.IO instance not found. (1)", "error");
|
||||
}
|
||||
|
||||
return res.status(200).send("Alerts added to Redis and emitted to clients.");
|
||||
} else {
|
||||
// Alerts are in Redis, compare them
|
||||
if (!_.isEqual(currentAlerts, storedAlerts)) {
|
||||
// Alerts are different, update Redis and emit to clients
|
||||
await setSessionData(GLOBAL_SOCKET_ID, ALERTS_REDIS_KEY, currentAlerts);
|
||||
logger.logger.debug("Alerts updated in Redis.");
|
||||
|
||||
// Emit the new alerts to all connected clients
|
||||
if (ioRedis) {
|
||||
ioRedis.emit("bodyshop-message", {
|
||||
type: "alert-update",
|
||||
payload: currentAlerts
|
||||
});
|
||||
logger.logger.debug("Alerts emitted to clients after update.");
|
||||
} else {
|
||||
logger.log("Socket.IO instance not found. (2)", "error");
|
||||
}
|
||||
|
||||
return res.status(200).send("Alerts updated in Redis and emitted to clients.");
|
||||
} else {
|
||||
return res.status(200).send("No changes in alerts.");
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.log("Error in alertCheck:", "error", null, null, {
|
||||
error: {
|
||||
message: error.message,
|
||||
stack: error.stack
|
||||
}
|
||||
});
|
||||
return res.status(500).send("Internal server error.");
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { alertCheck };
|
||||
@@ -995,7 +995,7 @@ async function InsertFailedExportLog(socket, error) {
|
||||
bodyshopid: socket.JobData.bodyshop.id,
|
||||
jobid: socket.JobData.id,
|
||||
successful: false,
|
||||
message: [error],
|
||||
message: JSON.stringify(error),
|
||||
useremail: socket.user.email
|
||||
}
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@ function CheckCdkResponseForError(socket, soapResponse) {
|
||||
//The response was null, this might be ok, it might not.
|
||||
CdkBase.createLogEvent(
|
||||
socket,
|
||||
"WARNING",
|
||||
"warn",
|
||||
`Warning detected in CDK Response - it appears to be null. Stack: ${new Error().stack}`
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -13,6 +13,7 @@ let Client = require("ssh2-sftp-client");
|
||||
|
||||
const client = require("../graphql-client/graphql-client").client;
|
||||
const { sendServerEmail } = require("../email/sendemail");
|
||||
|
||||
const AHDineroFormat = "0.00";
|
||||
const AhDateFormat = "MMDDYYYY";
|
||||
|
||||
@@ -26,170 +27,177 @@ const ftpSetup = {
|
||||
password: process.env.AUTOHOUSE_PASSWORD,
|
||||
debug: (message, ...data) => logger.log(message, "DEBUG", "api", null, data),
|
||||
algorithms: {
|
||||
serverHostKey: ["ssh-rsa", "ssh-dss"]
|
||||
serverHostKey: ["ssh-rsa", "ssh-dss", "rsa-sha2-256", "rsa-sha2-512", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384"]
|
||||
}
|
||||
};
|
||||
|
||||
const allxmlsToUpload = [];
|
||||
const allErrors = [];
|
||||
|
||||
exports.default = async (req, res) => {
|
||||
// Only process if in production environment.
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
res.sendStatus(403);
|
||||
return;
|
||||
}
|
||||
|
||||
//Query for the List of Bodyshop Clients.
|
||||
logger.log("autohouse-start", "DEBUG", "api", null, null);
|
||||
const { bodyshops } = await client.request(queries.GET_AUTOHOUSE_SHOPS);
|
||||
|
||||
const specificShopIds = req.body.bodyshopIds; // ['uuid]
|
||||
const { start, end, skipUpload } = req.body; //YYYY-MM-DD
|
||||
// Only process if the appropriate token is provided.
|
||||
if (req.headers["x-imex-auth"] !== process.env.AUTOHOUSE_AUTH_TOKEN) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
}
|
||||
const allxmlsToUpload = [];
|
||||
const allErrors = [];
|
||||
|
||||
// Send immediate response and continue processing.
|
||||
res.status(200).send();
|
||||
|
||||
try {
|
||||
for (const bodyshop of specificShopIds ? bodyshops.filter((b) => specificShopIds.includes(b.id)) : bodyshops) {
|
||||
logger.log("autohouse-start", "DEBUG", "api", null, null);
|
||||
const { bodyshops } = await client.request(queries.GET_AUTOHOUSE_SHOPS); //Query for the List of Bodyshop Clients.
|
||||
const specificShopIds = req.body.bodyshopIds; // ['uuid];
|
||||
const { start, end, skipUpload } = req.body; //YYYY-MM-DD
|
||||
|
||||
const batchSize = 10;
|
||||
|
||||
const shopsToProcess =
|
||||
specificShopIds?.length > 0 ? bodyshops.filter((shop) => specificShopIds.includes(shop.id)) : bodyshops;
|
||||
logger.log("autohouse-shopsToProcess-generated", "DEBUG", "api", null, null);
|
||||
|
||||
if (shopsToProcess.length === 0) {
|
||||
logger.log("autohouse-shopsToProcess-empty", "DEBUG", "api", null, null);
|
||||
return;
|
||||
}
|
||||
const batchPromises = [];
|
||||
for (let i = 0; i < shopsToProcess.length; i += batchSize) {
|
||||
const batch = shopsToProcess.slice(i, i + batchSize);
|
||||
const batchPromise = (async () => {
|
||||
await processBatch(batch, start, end);
|
||||
|
||||
if (skipUpload) {
|
||||
for (const xmlObj of allxmlsToUpload) {
|
||||
fs.writeFileSync(`./logs/${xmlObj.filename}`, xmlObj.xml);
|
||||
}
|
||||
} else {
|
||||
await uploadViaSFTP(allxmlsToUpload);
|
||||
}
|
||||
})();
|
||||
batchPromises.push(batchPromise);
|
||||
}
|
||||
await Promise.all(batchPromises);
|
||||
await sendServerEmail({
|
||||
subject: `Autohouse Report ${moment().format("MM-DD-YY")}`,
|
||||
text: `Errors:\n${JSON.stringify(allErrors, null, 2)}\n\nUploaded:\n${JSON.stringify(
|
||||
allxmlsToUpload.map((x) => ({ filename: x.filename, count: x.count, result: x.result })),
|
||||
null,
|
||||
2
|
||||
)}`
|
||||
});
|
||||
|
||||
logger.log("autohouse-end", "DEBUG", "api", null, null);
|
||||
} catch (error) {
|
||||
logger.log("autohouse-error", "ERROR", "api", null, { error: error.message, stack: error.stack });
|
||||
}
|
||||
};
|
||||
|
||||
async function processBatch(batch, start, end) {
|
||||
for (const bodyshop of batch) {
|
||||
const erroredJobs = [];
|
||||
try {
|
||||
logger.log("autohouse-start-shop-extract", "DEBUG", "api", bodyshop.id, {
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
const erroredJobs = [];
|
||||
try {
|
||||
const { jobs, bodyshops_by_pk } = await client.request(queries.AUTOHOUSE_QUERY, {
|
||||
bodyshopid: bodyshop.id,
|
||||
start: start ? moment(start).startOf("day") : moment().subtract(5, "days").startOf("day"),
|
||||
...(end && { end: moment(end).endOf("day") })
|
||||
});
|
||||
|
||||
const autoHouseObject = {
|
||||
AutoHouseExport: {
|
||||
RepairOrder: jobs.map((j) =>
|
||||
CreateRepairOrderTag({ ...j, bodyshop: bodyshops_by_pk }, function ({ job, error }) {
|
||||
erroredJobs.push({ job: job, error: error.toString() });
|
||||
})
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
if (erroredJobs.length > 0) {
|
||||
logger.log("autohouse-failed-jobs", "ERROR", "api", bodyshop.id, {
|
||||
count: erroredJobs.length,
|
||||
jobs: JSON.stringify(erroredJobs.map((j) => j.job.ro_number))
|
||||
});
|
||||
}
|
||||
|
||||
var ret = builder
|
||||
.create(
|
||||
{
|
||||
// version: "1.0",
|
||||
// encoding: "UTF-8",
|
||||
//keepNullNodes: true,
|
||||
},
|
||||
autoHouseObject
|
||||
)
|
||||
.end({ allowEmptyTags: true });
|
||||
|
||||
allxmlsToUpload.push({
|
||||
count: autoHouseObject.AutoHouseExport.RepairOrder.length,
|
||||
xml: ret,
|
||||
filename: `IM_${bodyshop.autohouseid}_${moment().format("DDMMYYYY_HHMMss")}.xml`
|
||||
});
|
||||
|
||||
logger.log("autohouse-end-shop-extract", "DEBUG", "api", bodyshop.id, {
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
} catch (error) {
|
||||
//Error at the shop level.
|
||||
logger.log("autohouse-error-shop", "ERROR", "api", bodyshop.id, {
|
||||
...error
|
||||
});
|
||||
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
autuhouseid: bodyshop.autuhouseid,
|
||||
fatal: true,
|
||||
errors: [error.toString()]
|
||||
});
|
||||
} finally {
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
autohouseid: bodyshop.autohouseid,
|
||||
errors: erroredJobs.map((ej) => ({
|
||||
ro_number: ej.job?.ro_number,
|
||||
jobid: ej.job?.id,
|
||||
error: ej.error
|
||||
}))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (skipUpload) {
|
||||
for (const xmlObj of allxmlsToUpload) {
|
||||
fs.writeFileSync(`./logs/${xmlObj.filename}`, xmlObj.xml);
|
||||
}
|
||||
|
||||
res.json(allxmlsToUpload);
|
||||
sendServerEmail({
|
||||
subject: `Autohouse Report ${moment().format("MM-DD-YY")}`,
|
||||
text: `Errors: ${allErrors.map((e) => JSON.stringify(e, null, 2))}
|
||||
Uploaded: ${JSON.stringify(
|
||||
allxmlsToUpload.map((x) => ({ filename: x.filename, count: x.count })),
|
||||
null,
|
||||
2
|
||||
)}
|
||||
`
|
||||
const { jobs, bodyshops_by_pk } = await client.request(queries.AUTOHOUSE_QUERY, {
|
||||
bodyshopid: bodyshop.id,
|
||||
start: start ? moment(start).startOf("day") : moment().subtract(5, "days").startOf("day"),
|
||||
...(end && { end: moment(end).endOf("day") })
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let sftp = new Client();
|
||||
sftp.on("error", (errors) =>
|
||||
logger.log("autohouse-sftp-error", "ERROR", "api", null, {
|
||||
...errors
|
||||
})
|
||||
);
|
||||
try {
|
||||
//Connect to the FTP and upload all.
|
||||
const autoHouseObject = {
|
||||
AutoHouseExport: {
|
||||
RepairOrder: jobs.map((j) =>
|
||||
CreateRepairOrderTag({ ...j, bodyshop: bodyshops_by_pk }, function ({ job, error }) {
|
||||
erroredJobs.push({ job: job, error: error.toString() });
|
||||
})
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
await sftp.connect(ftpSetup);
|
||||
|
||||
for (const xmlObj of allxmlsToUpload) {
|
||||
logger.log("autohouse-sftp-upload", "DEBUG", "api", null, {
|
||||
filename: xmlObj.filename
|
||||
});
|
||||
|
||||
const uploadResult = await sftp.put(Buffer.from(xmlObj.xml), `/${xmlObj.filename}`);
|
||||
logger.log("autohouse-sftp-upload-result", "DEBUG", "api", null, {
|
||||
uploadResult
|
||||
if (erroredJobs.length > 0) {
|
||||
logger.log("autohouse-failed-jobs", "ERROR", "api", bodyshop.id, {
|
||||
count: erroredJobs.length,
|
||||
jobs: JSON.stringify(erroredJobs.map((j) => j.job.ro_number))
|
||||
});
|
||||
}
|
||||
|
||||
//***TODO Change filing naming when creating the cron job. IM_ShopInternalName_DDMMYYYY_HHMMSS.xml
|
||||
const ret = builder.create({}, autoHouseObject).end({ allowEmptyTags: true });
|
||||
|
||||
allxmlsToUpload.push({
|
||||
count: autoHouseObject.AutoHouseExport.RepairOrder.length,
|
||||
xml: ret,
|
||||
filename: `IM_${bodyshop.autohouseid}_${moment().format("DDMMYYYY_HHMMss")}.xml`
|
||||
});
|
||||
|
||||
logger.log("autohouse-end-shop-extract", "DEBUG", "api", bodyshop.id, {
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
} catch (error) {
|
||||
logger.log("autohouse-sftp-error", "ERROR", "api", null, {
|
||||
...error
|
||||
//Error at the shop level.
|
||||
logger.log("autohouse-error-shop", "ERROR", "api", bodyshop.id, { error: error.message, stack: error.stack });
|
||||
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
autuhouseid: bodyshop.autuhouseid,
|
||||
fatal: true,
|
||||
errors: [error.toString()]
|
||||
});
|
||||
} finally {
|
||||
sftp.end();
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
autuhouseid: bodyshop.autuhouseid,
|
||||
errors: erroredJobs.map((ej) => ({
|
||||
ro_number: ej.job?.ro_number,
|
||||
jobid: ej.job?.id,
|
||||
error: ej.error
|
||||
}))
|
||||
});
|
||||
}
|
||||
sendServerEmail({
|
||||
subject: `Autohouse Report ${moment().format("MM-DD-YY")}`,
|
||||
text: `Errors: ${allErrors.map((e) => JSON.stringify(e, null, 2))}
|
||||
Uploaded: ${JSON.stringify(
|
||||
allxmlsToUpload.map((x) => ({ filename: x.filename, count: x.count })),
|
||||
null,
|
||||
2
|
||||
)}
|
||||
`
|
||||
});
|
||||
res.sendStatus(200);
|
||||
} catch (error) {
|
||||
res.status(200).json(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function uploadViaSFTP(allxmlsToUpload) {
|
||||
const sftp = new Client();
|
||||
sftp.on("error", (errors) =>
|
||||
logger.log("autohouse-sftp-connection-error", "ERROR", "api", null, { error: errors.message, stack: errors.stack })
|
||||
);
|
||||
try {
|
||||
//Connect to the FTP and upload all.
|
||||
await sftp.connect(ftpSetup);
|
||||
|
||||
for (const xmlObj of allxmlsToUpload) {
|
||||
try {
|
||||
logger.log("autohouse-sftp-upload", "DEBUG", "api", null, { filename: xmlObj.filename });
|
||||
xmlObj.result = await sftp.put(Buffer.from(xmlObj.xml), `${xmlObj.filename}`);
|
||||
logger.log("autohouse-sftp-upload-result", "DEBUG", "api", null, {
|
||||
filename: xmlObj.filename,
|
||||
result: xmlObj.result
|
||||
});
|
||||
} catch (error) {
|
||||
logger.log("autohouse-sftp-upload-error", "ERROR", "api", null, {
|
||||
filename: xmlObj.filename,
|
||||
error: error.message,
|
||||
stack: error.stack
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.log("autohouse-sftp-error", "ERROR", "api", null, { error: error.message, stack: error.stack });
|
||||
throw error;
|
||||
} finally {
|
||||
sftp.end();
|
||||
}
|
||||
}
|
||||
|
||||
const CreateRepairOrderTag = (job, errorCallback) => {
|
||||
//Level 2
|
||||
@@ -287,8 +295,8 @@ const CreateRepairOrderTag = (job, errorCallback) => {
|
||||
InsuranceCo: job.ins_co_nm || "",
|
||||
CompanyName: job.ins_co_nm || "",
|
||||
Address: job.ins_addr1 || "",
|
||||
City: job.ins_addr1 || "",
|
||||
State: job.ins_city || "",
|
||||
City: job.ins_city || "",
|
||||
State: job.ins_st || "",
|
||||
Zip: job.ins_zip || "",
|
||||
Phone: job.ins_ph1 || "",
|
||||
Fax: job.ins_fax || "",
|
||||
|
||||
@@ -22,135 +22,129 @@ const ftpSetup = {
|
||||
serverHostKey: ["ssh-rsa", "ssh-dss", "rsa-sha2-256", "rsa-sha2-512", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384"]
|
||||
}
|
||||
};
|
||||
|
||||
const allcsvsToUpload = [];
|
||||
const allErrors = [];
|
||||
|
||||
exports.default = async (req, res) => {
|
||||
// Only process if in production environment.
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
res.sendStatus(403);
|
||||
return;
|
||||
}
|
||||
|
||||
// Only process if the appropriate token is provided.
|
||||
if (req.headers["x-imex-auth"] !== process.env.AUTOHOUSE_AUTH_TOKEN) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
}
|
||||
//Query for the List of Bodyshop Clients.
|
||||
logger.log("chatter-start", "DEBUG", "api", null, null);
|
||||
const { bodyshops } = await client.request(queries.GET_CHATTER_SHOPS);
|
||||
const specificShopIds = req.body.bodyshopIds; // ['uuid]
|
||||
const { start, end, skipUpload } = req.body; //YYYY-MM-DD
|
||||
|
||||
const allcsvsToUpload = [];
|
||||
const allErrors = [];
|
||||
// Send immediate response and continue processing.
|
||||
res.status(200).send();
|
||||
|
||||
try {
|
||||
for (const bodyshop of specificShopIds ? bodyshops.filter((b) => specificShopIds.includes(b.id)) : bodyshops) {
|
||||
logger.log("chatter-start-shop-extract", "DEBUG", "api", bodyshop.id, {
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
try {
|
||||
const { jobs, bodyshops_by_pk } = await client.request(queries.CHATTER_QUERY, {
|
||||
bodyshopid: bodyshop.id,
|
||||
start: start ? moment(start).startOf("day") : moment().subtract(1, "days").startOf("day"),
|
||||
...(end && { end: moment(end).endOf("day") })
|
||||
});
|
||||
logger.log("chatter-start", "DEBUG", "api", null, null);
|
||||
const { bodyshops } = await client.request(queries.GET_CHATTER_SHOPS); //Query for the List of Bodyshop Clients.
|
||||
const specificShopIds = req.body.bodyshopIds; // ['uuid];
|
||||
const { start, end, skipUpload } = req.body; //YYYY-MM-DD
|
||||
|
||||
const chatterObject = jobs.map((j) => {
|
||||
return {
|
||||
poc_trigger_code: bodyshops_by_pk.chatterid,
|
||||
firstname: j.ownr_co_nm ? null : j.ownr_fn,
|
||||
lastname: j.ownr_co_nm ? j.ownr_co_nm : j.ownr_ln,
|
||||
transaction_id: j.ro_number,
|
||||
email: j.ownr_ea,
|
||||
phone_number: j.ownr_ph1
|
||||
};
|
||||
});
|
||||
const batchSize = 10;
|
||||
|
||||
const ret = converter.json2csv(chatterObject, { emptyFieldValue: "" });
|
||||
const shopsToProcess =
|
||||
specificShopIds?.length > 0 ? bodyshops.filter((shop) => specificShopIds.includes(shop.id)) : bodyshops;
|
||||
logger.log("chatter-shopsToProcess-generated", "DEBUG", "api", null, null);
|
||||
|
||||
allcsvsToUpload.push({
|
||||
count: chatterObject.length,
|
||||
csv: ret,
|
||||
filename: `${bodyshop.shopname}_solicitation_${moment().format("YYYYMMDD")}.csv`
|
||||
});
|
||||
|
||||
logger.log("chatter-end-shop-extract", "DEBUG", "api", bodyshop.id, {
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
} catch (error) {
|
||||
//Error at the shop level.
|
||||
logger.log("chatter-error-shop", "ERROR", "api", bodyshop.id, {
|
||||
...error
|
||||
});
|
||||
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
shopname: bodyshop.shopname,
|
||||
fatal: true,
|
||||
errors: [error.toString()]
|
||||
});
|
||||
} finally {
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (skipUpload) {
|
||||
for (const csvObj of allcsvsToUpload) {
|
||||
fs.writeFile(`./logs/${csvObj.filename}`, csvObj.csv);
|
||||
}
|
||||
|
||||
sendServerEmail({
|
||||
subject: `Chatter Report ${moment().format("MM-DD-YY")}`,
|
||||
text: `Errors: ${allErrors.map((e) => JSON.stringify(e, null, 2))}
|
||||
Uploaded: ${JSON.stringify(
|
||||
allcsvsToUpload.map((x) => ({ filename: x.filename, count: x.count })),
|
||||
null,
|
||||
2
|
||||
)}
|
||||
`
|
||||
});
|
||||
res.json(allcsvsToUpload);
|
||||
if (shopsToProcess.length === 0) {
|
||||
logger.log("chatter-shopsToProcess-empty", "DEBUG", "api", null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
const sftp = new Client();
|
||||
sftp.on("error", (errors) => logger.log("chatter-sftp-error", "ERROR", "api", null, { ...errors }));
|
||||
try {
|
||||
//Get the private key from AWS Secrets Manager.
|
||||
ftpSetup.privateKey = await getPrivateKey();
|
||||
|
||||
//Connect to the FTP and upload all.
|
||||
await sftp.connect(ftpSetup);
|
||||
|
||||
for (const csvObj of allcsvsToUpload) {
|
||||
logger.log("chatter-sftp-upload", "DEBUG", "api", null, { filename: csvObj.filename });
|
||||
|
||||
const uploadResult = await sftp.put(Buffer.from(csvObj.xml), `/${csvObj.filename}`);
|
||||
logger.log("chatter-sftp-upload-result", "DEBUG", "api", null, { uploadResult });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.log("chatter-sftp-error", "ERROR", "api", null, { ...error });
|
||||
} finally {
|
||||
sftp.end();
|
||||
const batchPromises = [];
|
||||
for (let i = 0; i < shopsToProcess.length; i += batchSize) {
|
||||
const batch = shopsToProcess.slice(i, i + batchSize);
|
||||
const batchPromise = (async () => {
|
||||
await processBatch(batch, start, end);
|
||||
if (skipUpload) {
|
||||
for (const csvObj of allcsvsToUpload) {
|
||||
await fs.promises.writeFile(`./logs/${csvObj.filename}`, csvObj.csv);
|
||||
}
|
||||
} else {
|
||||
await uploadViaSFTP(allcsvsToUpload);
|
||||
}
|
||||
})();
|
||||
batchPromises.push(batchPromise);
|
||||
}
|
||||
sendServerEmail({
|
||||
await Promise.all(batchPromises);
|
||||
await sendServerEmail({
|
||||
subject: `Chatter Report ${moment().format("MM-DD-YY")}`,
|
||||
text: `Errors: ${allErrors.map((e) => JSON.stringify(e, null, 2))}
|
||||
Uploaded: ${JSON.stringify(
|
||||
allcsvsToUpload.map((x) => ({ filename: x.filename, count: x.count })),
|
||||
text: `Errors:\n${JSON.stringify(allErrors, null, 2)}\n\nUploaded:\n${JSON.stringify(
|
||||
allcsvsToUpload.map((x) => ({ filename: x.filename, count: x.count, result: x.result })),
|
||||
null,
|
||||
2
|
||||
)}`
|
||||
});
|
||||
res.sendStatus(200);
|
||||
|
||||
logger.log("chatter-end", "DEBUG", "api", null, null);
|
||||
} catch (error) {
|
||||
res.status(200).json(error);
|
||||
logger.log("chatter-error", "ERROR", "api", null, { error: error.message, stack: error.stack });
|
||||
}
|
||||
};
|
||||
|
||||
async function processBatch(batch, start, end) {
|
||||
for (const bodyshop of batch) {
|
||||
try {
|
||||
logger.log("chatter-start-shop-extract", "DEBUG", "api", bodyshop.id, {
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
|
||||
const { jobs, bodyshops_by_pk } = await client.request(queries.CHATTER_QUERY, {
|
||||
bodyshopid: bodyshop.id,
|
||||
start: start ? moment(start).startOf("day") : moment().subtract(1, "days").startOf("day"),
|
||||
...(end && { end: moment(end).endOf("day") })
|
||||
});
|
||||
|
||||
const chatterObject = jobs.map((j) => {
|
||||
return {
|
||||
poc_trigger_code: bodyshops_by_pk.chatterid,
|
||||
firstname: j.ownr_co_nm ? null : j.ownr_fn,
|
||||
lastname: j.ownr_co_nm ? j.ownr_co_nm : j.ownr_ln,
|
||||
transaction_id: j.ro_number,
|
||||
email: j.ownr_ea,
|
||||
phone_number: j.ownr_ph1
|
||||
};
|
||||
});
|
||||
|
||||
const ret = converter.json2csv(chatterObject, { emptyFieldValue: "" });
|
||||
|
||||
allcsvsToUpload.push({
|
||||
count: chatterObject.length,
|
||||
csv: ret,
|
||||
filename: `${bodyshop.shopname}_solicitation_${moment().format("YYYYMMDD")}.csv`
|
||||
});
|
||||
|
||||
logger.log("chatter-end-shop-extract", "DEBUG", "api", bodyshop.id, {
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
} catch (error) {
|
||||
//Error at the shop level.
|
||||
logger.log("chatter-error-shop", "ERROR", "api", bodyshop.id, { error: error.message, stack: error.stack });
|
||||
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
shopname: bodyshop.shopname,
|
||||
fatal: true,
|
||||
errors: [error.toString()]
|
||||
});
|
||||
} finally {
|
||||
allErrors.push({
|
||||
bodyshopid: bodyshop.id,
|
||||
imexshopid: bodyshop.imexshopid,
|
||||
shopname: bodyshop.shopname
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function getPrivateKey() {
|
||||
// Connect to AWS Secrets Manager
|
||||
const client = new SecretsManagerClient({ region: "ca-central-1" });
|
||||
@@ -160,9 +154,47 @@ async function getPrivateKey() {
|
||||
try {
|
||||
const { SecretString, SecretBinary } = await client.send(command);
|
||||
if (SecretString || SecretBinary) logger.log("chatter-retrieved-private-key", "DEBUG", "api", null, null);
|
||||
return SecretString || Buffer.from(SecretBinary, "base64").toString("ascii");
|
||||
const chatterPrivateKey = SecretString ? SecretString : Buffer.from(SecretBinary, "base64").toString("ascii");
|
||||
return chatterPrivateKey;
|
||||
} catch (error) {
|
||||
logger.log("chatter-get-private-key", "ERROR", "api", null, error);
|
||||
throw err;
|
||||
logger.log("chatter-get-private-key", "ERROR", "api", null, { error: error.message, stack: error.stack });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadViaSFTP(allcsvsToUpload) {
|
||||
const sftp = new Client();
|
||||
sftp.on("error", (errors) =>
|
||||
logger.log("chatter-sftp-connection-error", "ERROR", "api", null, { error: errors.message, stack: errors.stack })
|
||||
);
|
||||
try {
|
||||
//Get the private key from AWS Secrets Manager.
|
||||
const privateKey = await getPrivateKey();
|
||||
|
||||
//Connect to the FTP and upload all.
|
||||
await sftp.connect({ ...ftpSetup, privateKey });
|
||||
|
||||
for (const csvObj of allcsvsToUpload) {
|
||||
try {
|
||||
logger.log("chatter-sftp-upload", "DEBUG", "api", null, { filename: csvObj.filename });
|
||||
csvObj.result = await sftp.put(Buffer.from(csvObj.csv), `${csvObj.filename}`);
|
||||
logger.log("chatter-sftp-upload-result", "DEBUG", "api", null, {
|
||||
filename: csvObj.filename,
|
||||
result: csvObj.result
|
||||
});
|
||||
} catch (error) {
|
||||
logger.log("chatter-sftp-upload-error", "ERROR", "api", null, {
|
||||
filename: csvObj.filename,
|
||||
error: error.message,
|
||||
stack: error.stack
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.log("chatter-sftp-error", "ERROR", "api", null, { error: error.message, stack: error.stack });
|
||||
throw error;
|
||||
} finally {
|
||||
sftp.end();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,16 +78,20 @@ const jobLifecycle = async (req, res) => {
|
||||
Object.keys(flatGroupedAllDurations).forEach((status) => {
|
||||
const value = flatGroupedAllDurations[status].reduce((acc, curr) => acc + curr.value, 0);
|
||||
const humanReadable = durationToHumanReadable(moment.duration(value));
|
||||
const percentage = (value / finalTotal) * 100;
|
||||
const percentage = finalTotal > 0 ? (value / finalTotal) * 100 : 0;
|
||||
const color = getLifecycleStatusColor(status);
|
||||
const roundedPercentage = `${Math.round(percentage)}%`;
|
||||
const averageValue = _.size(jobIDs) > 0 ? value / jobIDs.length : 0;
|
||||
const averageHumanReadable = durationToHumanReadable(moment.duration(averageValue));
|
||||
finalSummations.push({
|
||||
status,
|
||||
value,
|
||||
humanReadable,
|
||||
percentage,
|
||||
color,
|
||||
roundedPercentage
|
||||
roundedPercentage,
|
||||
averageValue,
|
||||
averageHumanReadable
|
||||
});
|
||||
});
|
||||
|
||||
@@ -100,7 +104,12 @@ const jobLifecycle = async (req, res) => {
|
||||
totalStatuses: finalSummations.length,
|
||||
total: finalTotal,
|
||||
statusCounts: finalStatusCounts,
|
||||
humanReadable: durationToHumanReadable(moment.duration(finalTotal))
|
||||
humanReadable: durationToHumanReadable(moment.duration(finalTotal)),
|
||||
averageValue: _.size(jobIDs) > 0 ? finalTotal / jobIDs.length : 0,
|
||||
averageHumanReadable:
|
||||
_.size(jobIDs) > 0
|
||||
? durationToHumanReadable(moment.duration(finalTotal / jobIDs.length))
|
||||
: durationToHumanReadable(moment.duration(0))
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -2,8 +2,16 @@ const { isObject } = require("lodash");
|
||||
|
||||
const jobUpdated = async (req, res) => {
|
||||
const { ioRedis, logger, ioHelpers } = req;
|
||||
// Old Way
|
||||
if (req?.body?.event?.data?.new || isObject(req?.body?.event?.data?.new)) {
|
||||
const updatedJob = req.body.event.data.new;
|
||||
const bodyshopID = updatedJob.shopid;
|
||||
ioRedis.to(ioHelpers.getBodyshopRoom(bodyshopID)).emit("production-job-updated", updatedJob);
|
||||
return res.json({ message: "Job updated and event emitted" });
|
||||
}
|
||||
|
||||
if (!req?.body?.event?.data?.new || !isObject(req?.body?.event?.data?.new)) {
|
||||
// New way
|
||||
if (!req?.body?.data || !isObject(req.body.data)) {
|
||||
logger.log("job-update-error", "ERROR", req.user?.email, null, {
|
||||
message: `Malformed Job Update request sent from Hasura`,
|
||||
body: req?.body
|
||||
@@ -15,12 +23,14 @@ const jobUpdated = async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
logger.log("job-update", "DEBUG", req.user?.email, null, {
|
||||
message: `Job updated event received from Hasura`,
|
||||
jobid: req?.body?.event?.data?.new?.id
|
||||
});
|
||||
// Uncomment for further testing
|
||||
// You can also test this using SocketIOAdmin
|
||||
// logger.log("job-update", "DEBUG", req.user?.email, null, {
|
||||
// message: `Job updated event received from Hasura`,
|
||||
// jobid: req?.body?.event?.data?.new?.id
|
||||
// });
|
||||
|
||||
const updatedJob = req.body.event.data.new;
|
||||
const updatedJob = req.body.data;
|
||||
const bodyshopID = updatedJob.shopid;
|
||||
|
||||
// Emit the job-updated event only to the room corresponding to the bodyshop
|
||||
|
||||
@@ -59,7 +59,7 @@ exports.mixdataUpload = async (req, res) => {
|
||||
res.status(500).json(error);
|
||||
logger.log("job-mixdata-upload-error", "ERROR", null, null, {
|
||||
error: error.message,
|
||||
...error
|
||||
stack: error.stack
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -12,6 +12,7 @@ const validateFirebaseIdTokenMiddleware = require("../middleware/validateFirebas
|
||||
const withUserGraphQLClientMiddleware = require("../middleware/withUserGraphQLClientMiddleware");
|
||||
const { taskAssignedEmail, tasksRemindEmail } = require("../email/tasksEmails");
|
||||
const { canvastest } = require("../render/canvas-handler");
|
||||
const { alertCheck } = require("../alerts/alertcheck");
|
||||
|
||||
//Test route to ensure Express is responding.
|
||||
router.get("/test", async function (req, res) {
|
||||
@@ -53,4 +54,7 @@ router.post("/taskHandler", validateFirebaseIdTokenMiddleware, taskHandler.taskH
|
||||
// Canvas Test
|
||||
router.post("/canvastest", validateFirebaseIdTokenMiddleware, canvastest);
|
||||
|
||||
// Alert Check
|
||||
router.post("/alertcheck", eventAuthorizationMiddleware, alertCheck);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -10,6 +10,18 @@ const WinstonCloudWatch = require("winston-cloudwatch");
|
||||
const { isString, isEmpty } = require("lodash");
|
||||
const { networkInterfaces, hostname } = require("node:os");
|
||||
|
||||
const LOG_LEVELS = {
|
||||
error: { level: 0, name: "error" },
|
||||
warn: { level: 1, name: "warn" },
|
||||
info: { level: 2, name: "info" },
|
||||
http: { level: 3, name: "http" },
|
||||
verbose: { level: 4, name: "verbose" },
|
||||
debug: { level: 5, name: "debug" },
|
||||
silly: { level: 6, name: "silly" }
|
||||
};
|
||||
|
||||
const normalizeLevel = (level) => (level ? level.toLowerCase() : LOG_LEVELS.debug.name);
|
||||
|
||||
const createLogger = () => {
|
||||
try {
|
||||
const isLocal = isString(process.env?.LOCALSTACK_HOSTNAME) && !isEmpty(process.env?.LOCALSTACK_HOSTNAME);
|
||||
@@ -114,7 +126,7 @@ const createLogger = () => {
|
||||
|
||||
const log = (message, type, user, record, meta) => {
|
||||
winstonLogger.log({
|
||||
level: type.toLowerCase(),
|
||||
level: normalizeLevel(type),
|
||||
message,
|
||||
user,
|
||||
record,
|
||||
@@ -131,7 +143,8 @@ const createLogger = () => {
|
||||
console.error("Error setting up enhanced Logger, defaulting to console.: " + e?.message || "");
|
||||
return {
|
||||
log: console.log,
|
||||
logger: console.log
|
||||
logger: console.log,
|
||||
LOG_LEVELS
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -212,7 +212,7 @@ function LogLevelHierarchy(level) {
|
||||
return 4;
|
||||
case "INFO":
|
||||
return 3;
|
||||
case "WARNING":
|
||||
case "WARN":
|
||||
return 2;
|
||||
case "ERROR":
|
||||
return 1;
|
||||
|
||||
2
upload/.gitignore
vendored
Normal file
2
upload/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*
|
||||
!.gitignore
|
||||
Reference in New Issue
Block a user