Simplify available jobs page IO-454

This commit is contained in:
Patrick Fic
2021-02-01 14:14:54 -08:00
parent 0d484677e0
commit 7e4faec0ff
14 changed files with 441 additions and 757 deletions

View File

@@ -0,0 +1,93 @@
import { GET_JOB_LINES_BY_PK } from "../../graphql/jobs-lines.queries";
import gql from "graphql-tag";
import _ from "lodash";
export const GetSupplementDelta = async (client, jobId, newLines) => {
console.log("-----Begin Supplement-----");
const {
data: { joblines: existingLinesFromDb },
} = await client.query({
query: GET_JOB_LINES_BY_PK,
variables: { id: jobId },
});
const existingLines = _.cloneDeep(existingLinesFromDb);
const linesToInsert = [];
const linesToUpdate = [];
newLines.forEach((newLine) => {
const matchingIndex = existingLines.findIndex(
(eL) => eL.unq_seq === newLine.unq_seq
);
if (matchingIndex >= 0) {
//Found a relevant matching line. Add it to lines to update.
linesToUpdate.push({
id: existingLines[matchingIndex].id,
newData: newLine,
});
//Splice out item we found for performance.
existingLines.splice(matchingIndex, 1);
} else {
//Didn't find a match. Must be a new line.
linesToInsert.push(newLine);
}
});
//Wahtever is left in the existing lines, are lines that should be removed.
const insertQueries = linesToInsert.reduce((acc, value, idx) => {
return acc + generateInsertQuery(value, idx, jobId);
}, "");
const updateQueries = linesToUpdate.reduce((acc, value, idx) => {
return acc + generateUpdateQuery(value, idx);
}, "");
const removeQueries = existingLines.reduce((acc, value, idx) => {
return acc + generateRemoveQuery(value, idx);
}, "");
return new Promise((resolve, reject) => {
resolve(gql`
mutation SUPPLEMENT_EST_LINES{
${insertQueries + updateQueries + removeQueries}
}
`);
});
};
const generateInsertQuery = (lineToInsert, index, jobId) => {
return `
insert_joblines${index}: insert_joblines(objects: ${JSON.stringify({
...lineToInsert,
jobid: jobId,
}).replace(/"(\w+)"\s*:/g, "$1:")}) {
returning {
id
}
}`;
};
const generateUpdateQuery = (lineToUpdate, index) => {
return `
update_joblines${index}: update_joblines(where: { id: { _eq: "${
lineToUpdate.id
}" } }, _set: ${JSON.stringify(lineToUpdate.newData).replace(
/"(\w+)"\s*:/g,
"$1:"
)}) {
returning {
id
}
}`;
};
const generateRemoveQuery = (lineToRemove, index) => {
return `
update_joblines_r${index}: update_joblines(where: {id: {_eq: "${lineToRemove.id}"}}, _set: {removed: true}) {
returning{
id
}
}`;
};

View File

@@ -0,0 +1,225 @@
const headerFields = [
//AD1
"ins_co_id",
"ins_co_nm",
"ins_addr1",
"ins_addr2",
"ins_city",
"ins_st",
"ins_zip",
"ins_ctry",
"ins_ea",
"policy_no",
"ded_amt",
"ded_status",
"asgn_no",
"asgn_date",
"asgn_type",
"clm_no",
"clm_ofc_id",
"clm_ofc_nm",
"clm_addr1",
"clm_addr2",
"clm_city",
"clm_st",
"clm_zip",
"clm_ctry",
"clm_ph1",
"clm_ph1x",
"clm_ph2",
"clm_ph2x",
"clm_fax",
"clm_faxx",
"clm_ct_ln",
"clm_ct_fn",
"clm_title",
"clm_ct_ph",
"clm_ct_phx",
"clm_ea",
"payee_nms",
"pay_type",
"pay_date",
"pay_chknm",
"pay_amt",
"agt_co_id",
"agt_co_nm",
"agt_addr1",
"agt_addr2",
"agt_city",
"agt_st",
"agt_zip",
"agt_ctry",
"agt_ph1",
"agt_ph1x",
"agt_ph2",
"agt_ph2x",
"agt_fax",
"agt_faxx",
"agt_ct_ln",
"agt_ct_fn",
"agt_ct_ph",
"agt_ct_phx",
"agt_ea",
"agt_lic_no",
"loss_date",
"loss_type",
"loss_desc",
"theft_ind",
"cat_no",
"tlos_ind",
"cust_pr",
"insd_ln",
"insd_fn",
"insd_title",
"insd_co_nm",
"insd_addr1",
"insd_addr2",
"insd_city",
"insd_st",
"insd_zip",
"insd_ctry",
"insd_ph1",
"insd_ph1x",
"insd_ph2",
"insd_ph2x",
"insd_fax",
"insd_faxx",
"insd_ea",
"ownr_ln",
"ownr_fn",
"ownr_title",
"ownr_co_nm",
"ownr_addr1",
"ownr_addr2",
"ownr_city",
"ownr_st",
"ownr_zip",
"ownr_ctry",
"ownr_ph1",
"ownr_ph1x",
"ownr_ph2",
"ownr_ph2x",
"ownr_fax",
"ownr_faxx",
"ownr_ea",
"ins_ph1",
"ins_ph1x",
"ins_ph2",
"ins_ph2x",
"ins_fax",
"ins_faxx",
"ins_ct_ln",
"ins_ct_fn",
"ins_title",
"ins_ct_ph",
"ins_ct_phx",
"loss_cat",
//ad2
"clmt_ln",
"clmt_fn",
"clmt_title",
"clmt_co_nm",
"clmt_addr1",
"clmt_addr2",
"clmt_city",
"clmt_st",
"clmt_zip",
"clmt_ctry",
"clmt_ph1",
"clmt_ph1x",
"clmt_ph2",
"clmt_ph2x",
"clmt_fax",
"clmt_faxx",
"clmt_ea",
"est_co_id",
"est_co_nm",
"est_addr1",
"est_addr2",
"est_city",
"est_st",
"est_zip",
"est_ctry",
"est_ph1",
"est_ph1x",
"est_ph2",
"est_ph2x",
"est_fax",
"est_faxx",
"est_ct_ln",
"est_ct_fn",
"est_ea",
"est_lic_no",
"est_fileno",
"insp_ct_ln",
"insp_ct_fn",
"insp_addr1",
"insp_addr2",
"insp_city",
"insp_st",
"insp_zip",
"insp_ctry",
"insp_ph1",
"insp_ph1x",
"insp_ph2",
"insp_ph2x",
"insp_fax",
"insp_faxx",
"insp_ea",
"insp_code",
"insp_desc",
"insp_date",
"insp_time",
"rf_co_id",
"rf_co_nm",
"rf_addr1",
"rf_addr2",
"rf_city",
"rf_st",
"rf_zip",
"rf_ctry",
"rf_ph1",
"rf_ph1x",
"rf_ph2",
"rf_ph2x",
"rf_fax",
"rf_faxx",
"rf_ct_ln",
"rf_ct_fn",
"rf_ea",
"rf_tax_id",
"rf_lic_no",
"rf_bar_no",
"ro_in_date",
"ro_in_time",
"tar_date",
"tar_time",
"ro_cmpdate",
"ro_cmptime",
"date_out",
"time_out",
"rf_estimtr",
"mktg_type",
"mktg_src",
"loc_nm",
"loc_addr1",
"loc_addr2",
"loc_city",
"loc_st",
"loc_zip",
"loc_ctry",
"loc_ph1",
"loc_ph1x",
"loc_ph2",
"loc_ph2x",
"loc_fax",
"loc_faxx",
"loc_ct_ln",
"loc_ct_fn",
"loc_title",
"loc_ph",
"loc_phx",
"loc_ea"
];
export default headerFields;

View File

@@ -0,0 +1,233 @@
import {
DeleteFilled,
DownloadOutlined,
PlusCircleFilled,
SyncOutlined,
} from "@ant-design/icons";
import { useMutation } from "@apollo/react-hooks";
import { Button, Input, notification, Space, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import {
DELETE_ALL_AVAILABLE_JOBS,
DELETE_AVAILABLE_JOB,
} from "../../graphql/available-jobs.queries";
import CurrencyFormatter from "../../utils/CurrencyFormatter";
import { TimeAgoFormatter } from "../../utils/DateFormatter";
import { alphaSort } from "../../utils/sorters";
export default function JobsAvailableComponent({
loading,
data,
refetch,
addJobAsNew,
addJobAsSupp,
}) {
const [deleteAllAvailableJobs] = useMutation(DELETE_ALL_AVAILABLE_JOBS);
const [deleteJob] = useMutation(DELETE_AVAILABLE_JOB);
const { t } = useTranslation();
const [searchText, setSearchText] = useState("");
const [state, setState] = useState({
sortedInfo: {},
filteredInfo: { text: "" },
});
const handleTableChange = (pagination, filters, sorter) => {
setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
};
const columns = [
{
title: t("jobs.fields.cieca_id"),
dataIndex: "cieca_id",
key: "cieca_id",
sorter: (a, b) => alphaSort(a, b),
sortOrder:
state.sortedInfo.columnKey === "cieca_id" && state.sortedInfo.order,
},
{
title: t("jobs.fields.ro_number"),
dataIndex: "job_id",
key: "job_id",
//width: "8%",
// onFilter: (value, record) => record.ro_number.includes(value),
// filteredValue: state.filteredInfo.text || null,
sorter: (a, b) => alphaSort(a, b),
sortOrder:
state.sortedInfo.columnKey === "cieca_id" && state.sortedInfo.order,
render: (text, record) =>
record.job ? (
<Link to={`/manage/jobs/${record.job.id}`}>
{(record.job && record.job_ro_number) || t("general.labels.na")}
</Link>
) : (
<div>
{(record.job && record.job_ro_number) || t("general.labels.na")}
</div>
),
},
{
title: t("jobs.fields.owner"),
dataIndex: "ownr_name",
key: "ownr_name",
ellipsis: true,
sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
sortOrder:
state.sortedInfo.columnKey === "ownr_name" && state.sortedInfo.order,
},
{
title: t("jobs.fields.vehicle"),
dataIndex: "vehicle_info",
key: "vehicle_info",
sorter: (a, b) => alphaSort(a.vehicle_info, b.vehicle_info),
sortOrder:
state.sortedInfo.columnKey === "vehicle_info" && state.sortedInfo.order,
},
{
title: t("jobs.fields.clm_no"),
dataIndex: "clm_no",
key: "clm_no",
sorter: (a, b) => alphaSort(a.clm_no, b.clm_no),
sortOrder:
state.sortedInfo.columnKey === "clm_no" && state.sortedInfo.order,
},
{
title: t("jobs.fields.ins_co_nm"),
dataIndex: "ins_co_nm",
key: "ins_co_nm",
sorter: (a, b) => alphaSort(a.ins_co_nm, b.ins_co_nm),
sortOrder:
state.sortedInfo.columnKey === "ins_co_nm" && state.sortedInfo.order,
},
{
title: t("jobs.fields.clm_total"),
dataIndex: "clm_amt",
key: "clm_amt",
sorter: (a, b) => a.clm_amt - b.clm_amt,
sortOrder:
state.sortedInfo.columnKey === "clm_amt" && state.sortedInfo.order,
render: (text, record) => (
<CurrencyFormatter>{record.clm_amt}</CurrencyFormatter>
),
},
{
title: t("jobs.fields.uploaded_by"),
dataIndex: "uploaded_by",
key: "uploaded_by",
sorter: (a, b) => alphaSort(a.uploaded_by, b.uploaded_by),
sortOrder:
state.sortedInfo.columnKey === "uploaded_by" && state.sortedInfo.order,
},
{
title: t("jobs.fields.updated_at"),
dataIndex: "updated_at",
key: "updated_at",
sorter: (a, b) => new Date(a.updated_at) - new Date(b.updated_at),
sortOrder:
state.sortedInfo.columnKey === "updated_at" && state.sortedInfo.order,
render: (text, record) => (
<TimeAgoFormatter>{record.updated_at}</TimeAgoFormatter>
),
},
{
title: t("general.labels.actions"),
key: "actions",
render: (text, record) => (
<Space>
<Button
onClick={() => {
deleteJob({ variables: { id: record.id } }).then((r) => {
notification["success"]({
message: t("jobs.successes.deleted"),
});
refetch();
});
}}
>
<DeleteFilled />
</Button>
<Button
onClick={() => addJobAsNew(record)}
disabled={record.issupplement}
>
<PlusCircleFilled />
</Button>
<Button onClick={() => addJobAsSupp(record)}>
<DownloadOutlined />
</Button>
</Space>
),
},
];
const availableJobs = data
? searchText
? data.available_jobs.filter(
(j) =>
(j.ownr_name || "")
.toLowerCase()
.includes(searchText.toLowerCase()) ||
(j.vehicle_info || "")
.toLowerCase()
.includes(searchText.toLowerCase()) ||
(j.clm_no || "").toLowerCase().includes(searchText.toLowerCase())
)
: data.available_jobs
: [];
return (
<Table
loading={loading}
title={() => {
return (
<div className="imex-table-header">
<Space>
<strong>{t("jobs.labels.availablejobs")}</strong>
<Button
onClick={() => {
refetch();
}}
>
<SyncOutlined />
</Button>
<Button
onClick={() => {
deleteAllAvailableJobs()
.then((r) => {
notification["success"]({
message: t("jobs.successes.all_deleted", {
count: r.data.delete_available_jobs.affected_rows,
}),
});
refetch();
})
.catch((r) => {
notification["error"]({
message: t("jobs.errors.deleted") + " " + r.message,
});
});
}}
>
{t("general.actions.deleteall")}
</Button>
</Space>
<div className="imex-table-header__search">
<Input.Search
placeholder={t("general.labels.search")}
onChange={(e) => {
setSearchText(e.currentTarget.value);
}}
/>
</div>
</div>
);
}}
size="small"
pagination={{ position: "top" }}
columns={columns}
rowKey="id"
dataSource={availableJobs}
onChange={handleTableChange}
/>
);
}

View File

@@ -0,0 +1,315 @@
import {
useApolloClient,
useLazyQuery,
useMutation,
useQuery
} from "@apollo/react-hooks";
import { notification } from "antd";
import Axios from "axios";
import Dinero from "dinero.js";
import gql from "graphql-tag";
import _ from "lodash";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useHistory } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import {
DELETE_AVAILABLE_JOB,
QUERY_AVAILABLE_JOBS,
QUERY_AVAILABLE_NEW_JOBS_EST_DATA_BY_PK
} from "../../graphql/available-jobs.queries";
import { INSERT_NEW_JOB, UPDATE_JOB } from "../../graphql/jobs.queries";
import { SEARCH_VEHICLE_BY_VIN } from "../../graphql/vehicles.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import JobsFindModalContainer from "../jobs-find-modal/jobs-find-modal.container";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import OwnerFindModalContainer from "../owner-find-modal/owner-find-modal.container";
import { GetSupplementDelta } from "./jobs-available-supplement.estlines.util";
import HeaderFields from "./jobs-available-supplement.headerfields";
import JobsAvailableTableComponent from "./jobs-available-table.component";
const mapStateToProps = createStructuredSelector({
bodyshop: selectBodyshop,
});
export function JobsAvailableContainer({ bodyshop }) {
const { loading, error, data, refetch } = useQuery(QUERY_AVAILABLE_JOBS, {
fetchPolicy: "network-only",
});
const history = useHistory();
const { t } = useTranslation();
const [ownerModalVisible, setOwnerModalVisible] = useState(false);
const [jobModalVisible, setJobModalVisible] = useState(false);
const [selectedJob, setSelectedJob] = useState(null);
const [selectedOwner, setSelectedOwner] = useState(null);
const [insertLoading, setInsertLoading] = useState(false);
const [deleteJob] = useMutation(DELETE_AVAILABLE_JOB);
const [updateJob] = useMutation(UPDATE_JOB);
const [insertNewJob] = useMutation(INSERT_NEW_JOB);
const client = useApolloClient();
const estDataLazyLoad = useLazyQuery(QUERY_AVAILABLE_NEW_JOBS_EST_DATA_BY_PK);
const [loadEstData, estData] = estDataLazyLoad;
const importOptionsState = useState({ overrideHeaders: false });
const importOptions = importOptionsState[0];
const modalSearchState = useState("");
const onOwnerFindModalOk = async () => {
logImEXEvent("job_import_new");
setOwnerModalVisible(false);
setInsertLoading(true);
if (
!(
estData.data &&
estData.data.available_jobs_by_pk &&
estData.data.available_jobs_by_pk.est_data
)
) {
//We don't have the right data. Error!
setInsertLoading(false);
notification["error"]({
message: t("jobs.errors.creating", { error: "No job data present." }),
});
return;
}
const newTotals = (
await Axios.post("/job/totals", {
job: {
...estData.data.available_jobs_by_pk.est_data,
joblines: estData.data.available_jobs_by_pk.est_data.joblines.data,
},
})
).data;
let existingVehicles;
if (estData.data.available_jobs_by_pk.est_data.vehicle) {
//There's vehicle data, need to double check the VIN.
existingVehicles = await client.query({
query: SEARCH_VEHICLE_BY_VIN,
variables: {
vin: estData.data.available_jobs_by_pk.est_data.vehicle.data.v_vin,
},
});
}
const newJob = {
...estData.data.available_jobs_by_pk.est_data,
clm_total: Dinero(newTotals.totals.total_repairs).toFormat("0.00"),
owner_owing: Dinero(newTotals.totals.custPayable.total).toFormat("0.00"),
job_totals: newTotals,
queued_for_parts: true,
...(existingVehicles && existingVehicles.data.vehicles.length > 0
? { vehicleid: existingVehicles.data.vehicles[0].id, vehicle: null }
: {}),
};
insertNewJob({
variables: {
job: selectedOwner
? Object.assign(
{},
newJob,
{ owner: null },
{ ownerid: selectedOwner }
)
: newJob,
},
})
.then((r) => {
notification["success"]({
message: t("jobs.successes.created"),
onClick: () => {
history.push(`/manage/jobs/${r.data.insert_jobs.returning[0].id}`);
},
});
//Job has been inserted. Clean up the available jobs record.
deleteJob({
variables: { id: estData.data.available_jobs_by_pk.id },
}).then((r) => {
refetch();
setInsertLoading(false);
});
})
.catch((r) => {
//error while inserting
notification["error"]({
message: t("jobs.errors.creating", { error: r.message }),
});
refetch();
setInsertLoading(false);
});
};
const onJobFindModalOk = async () => {
logImEXEvent("job_import_supplement");
setJobModalVisible(false);
setInsertLoading(true);
if (
!(
estData.data &&
estData.data.available_jobs_by_pk &&
estData.data.available_jobs_by_pk.est_data
)
) {
//We don't have the right data. Error!
setInsertLoading(false);
notification["error"]({
message: t("jobs.errors.creating", { error: "No job data present." }),
});
} else {
//create upsert job
let supp = _.cloneDeep(estData.data.available_jobs_by_pk.est_data);
delete supp.owner;
delete supp.vehicle;
if (importOptions.overrideHeaders) {
HeaderFields.forEach((item) => delete supp[item]);
}
const newTotals = (
await Axios.post("/job/totals", {
job: {
...estData.data.available_jobs_by_pk.est_data,
joblines: estData.data.available_jobs_by_pk.est_data.joblines.data,
},
})
).data;
let suppDelta = await GetSupplementDelta(
client,
selectedJob,
estData.data.available_jobs_by_pk.est_data.joblines.data
);
delete supp.joblines;
await client.mutate({
mutation: gql`
${suppDelta}
`,
});
updateJob({
variables: {
jobId: selectedJob,
job: {
...supp,
clm_total: Dinero(newTotals.totals.total_repairs).toFormat("0.00"),
owner_owing: Dinero(newTotals.totals.custPayable.total).toFormat(
"0.00"
),
job_totals: newTotals,
queued_for_parts: true,
},
},
})
.then((r) => {
notification["success"]({
message: t("jobs.successes.supplemented"),
onClick: () => {
history.push(
`/manage/jobs/${r.data.update_jobs.returning[0].id}`
);
},
});
//Job has been inserted. Clean up the available jobs record.
deleteJob({
variables: { id: estData.data.available_jobs_by_pk.id },
}).then((r) => {
refetch();
setInsertLoading(false);
});
})
.catch((r) => {
//error while inserting
notification["error"]({
message: t("jobs.errors.creating", { error: r.message }),
});
refetch();
setInsertLoading(false);
});
}
};
const owner =
estData.data &&
estData.data.available_jobs_by_pk &&
estData.data.available_jobs_by_pk.est_data &&
estData.data.available_jobs_by_pk.est_data.owner &&
estData.data.available_jobs_by_pk.est_data.owner.data &&
!estData.data.available_jobs_by_pk.issupplement
? estData.data.available_jobs_by_pk.est_data.owner.data
: null;
const onOwnerModalCancel = () => {
setOwnerModalVisible(false);
setSelectedOwner(null);
};
const onJobModalCancel = () => {
setJobModalVisible(false);
modalSearchState[1]("");
setSelectedJob(null);
};
const addJobAsNew = (record) => {
loadEstData({ variables: { id: record.id } });
setOwnerModalVisible(true);
};
const addJobAsSupp = (record) => {
loadEstData({ variables: { id: record.id } });
modalSearchState[1](record.clm_no);
setJobModalVisible(true);
};
if (error) return <AlertComponent type="error" message={error.message} />;
return (
<LoadingSpinner
loading={insertLoading}
message={t("jobs.labels.creating_new_job")}
>
<OwnerFindModalContainer
loading={estData.loading}
error={estData.error}
owner={owner}
selectedOwner={selectedOwner}
setSelectedOwner={setSelectedOwner}
visible={ownerModalVisible}
onOk={onOwnerFindModalOk}
onCancel={onOwnerModalCancel}
/>
<JobsFindModalContainer
loading={estData.loading}
error={estData.error}
selectedJob={selectedJob}
setSelectedJob={setSelectedJob}
importOptionsState={importOptionsState}
visible={jobModalVisible}
onOk={onJobFindModalOk}
onCancel={onJobModalCancel}
modalSearchState={modalSearchState}
/>
<JobsAvailableTableComponent
loading={loading}
data={data}
refetch={refetch}
addJobAsNew={addJobAsNew}
addJobAsSupp={addJobAsSupp}
/>
</LoadingSpinner>
);
}
export default connect(mapStateToProps, null)(JobsAvailableContainer);