From d4aa83fd7a56581487b7a8f69f458a363be486e6 Mon Sep 17 00:00:00 2001 From: Dan Gowans Date: Tue, 18 Mar 2025 13:40:03 -0400 Subject: [PATCH] legacy import --- app.js | 5 - app.ts | 7 - bin/www.js | 4 + bin/www.ts | 5 + bin/wwwProcess.js | 5 + bin/wwwProcess.ts | 6 + data/config.defaultValues.d.ts | 2 + data/config.defaultValues.js | 2 + data/config.defaultValues.ts | 2 + database/addCommittalType.d.ts | 6 + database/addCommittalType.js | 16 + database/addCommittalType.ts | 42 + database/addContract.d.ts | 2 + database/addContract.js | 5 +- database/addContract.ts | 7 +- database/addContractInterment.d.ts | 2 + database/addContractInterment.ts | 2 + database/addFee.d.ts | 6 +- database/addFee.js | 2 +- database/addFee.ts | 12 +- database/addFuneralHome.d.ts | 1 + database/addFuneralHome.js | 6 +- database/addFuneralHome.ts | 6 +- database/addIntermentContainerType.d.ts | 1 + database/addIntermentContainerType.js | 6 +- database/addIntermentContainerType.ts | 6 +- database/addRecord.d.ts | 2 +- database/addRecord.js | 1 - database/addRecord.ts | 2 - database/getBurialSite.js | 4 +- database/getBurialSite.ts | 4 +- database/getCemetery.d.ts | 1 + database/getCemetery.js | 12 +- database/getCemetery.ts | 23 +- database/getCommittalTypes.js | 2 +- database/getCommittalTypes.ts | 2 +- database/getContract.js | 2 +- database/getContract.ts | 2 +- database/getContractInterments.js | 1 + database/getContractInterments.ts | 1 + database/getFuneralHome.d.ts | 1 + database/getFuneralHome.js | 14 +- database/getFuneralHome.ts | 23 +- database/getFuneralHomes.js | 2 +- database/getFuneralHomes.ts | 2 +- database/getIntermentContainerTypes.js | 2 +- database/getIntermentContainerTypes.ts | 2 +- database/initializeDatabase.js | 41 +- database/initializeDatabase.ts | 43 +- database/updateContractInterment.d.ts | 2 + database/updateContractInterment.js | 4 +- database/updateContractInterment.ts | 6 + database/updateFee.js | 2 +- database/updateFee.ts | 4 +- helpers/functions.cache.js | 4 +- helpers/functions.cache.ts | 4 +- package.json | 3 +- public/html/contract-addInterment.html | 12 + public/html/contract-editInterment.html | 12 + public/javascripts/contract.editInterments.js | 41 + public/javascripts/contract.editInterments.ts | 56 + temp/legacy.importFromCSV.js | 977 ---------- temp/legacy.importFromCSV.ts | 1663 ----------------- temp/legacy.importFromCsv.data.d.ts | 3 - temp/legacy.importFromCsv.data.js | 120 -- temp/legacy.importFromCsv.data.ts | 129 -- temp/legacy.importFromCsv.ids.d.ts | 20 - temp/legacy.importFromCsv.ids.js | 89 - temp/legacy.importFromCsv.ids.ts | 171 -- .../data.burialSiteTypes.d.ts | 1 + .../data.burialSiteTypes.js | 35 + .../data.burialSiteTypes.ts | 45 + temp/legacyImportFromCsv/data.cemeteries.d.ts | 1 + temp/legacyImportFromCsv/data.cemeteries.js | 51 + temp/legacyImportFromCsv/data.cemeteries.ts | 67 + .../data.committalTypes.d.ts | 1 + .../data.committalTypes.js | 16 + .../data.committalTypes.ts | 31 + .../data.deathAgePeriods.d.ts | 1 + .../data.deathAgePeriods.js | 16 + .../data.deathAgePeriods.ts | 17 + temp/legacyImportFromCsv/data.fees.d.ts | 1 + temp/legacyImportFromCsv/data.fees.js | 37 + temp/legacyImportFromCsv/data.fees.ts | 61 + .../data.funeralHomes.d.ts | 2 + temp/legacyImportFromCsv/data.funeralHomes.js | 106 ++ temp/legacyImportFromCsv/data.funeralHomes.ts | 124 ++ temp/legacyImportFromCsv/data.ids.d.ts | 12 + temp/legacyImportFromCsv/data.ids.js | 30 + temp/legacyImportFromCsv/data.ids.ts | 74 + .../data.intermentContainerTypes.d.ts | 1 + .../data.intermentContainerTypes.js | 16 + .../data.intermentContainerTypes.ts | 31 + .../index.d.ts} | 0 temp/legacyImportFromCsv/index.js | 818 ++++++++ temp/legacyImportFromCsv/index.ts | 1409 ++++++++++++++ types/configTypes.d.ts | 1 + types/configTypes.ts | 1 + types/recordTypes.d.ts | 6 + types/recordTypes.ts | 8 +- views/contract-edit.ejs | 23 +- views/contract-view.ejs | 9 + views/workOrder-view.ejs | 187 +- 103 files changed, 3561 insertions(+), 3355 deletions(-) create mode 100644 database/addCommittalType.d.ts create mode 100644 database/addCommittalType.js create mode 100644 database/addCommittalType.ts delete mode 100644 temp/legacy.importFromCSV.js delete mode 100644 temp/legacy.importFromCSV.ts delete mode 100644 temp/legacy.importFromCsv.data.d.ts delete mode 100644 temp/legacy.importFromCsv.data.js delete mode 100644 temp/legacy.importFromCsv.data.ts delete mode 100644 temp/legacy.importFromCsv.ids.d.ts delete mode 100644 temp/legacy.importFromCsv.ids.js delete mode 100644 temp/legacy.importFromCsv.ids.ts create mode 100644 temp/legacyImportFromCsv/data.burialSiteTypes.d.ts create mode 100644 temp/legacyImportFromCsv/data.burialSiteTypes.js create mode 100644 temp/legacyImportFromCsv/data.burialSiteTypes.ts create mode 100644 temp/legacyImportFromCsv/data.cemeteries.d.ts create mode 100644 temp/legacyImportFromCsv/data.cemeteries.js create mode 100644 temp/legacyImportFromCsv/data.cemeteries.ts create mode 100644 temp/legacyImportFromCsv/data.committalTypes.d.ts create mode 100644 temp/legacyImportFromCsv/data.committalTypes.js create mode 100644 temp/legacyImportFromCsv/data.committalTypes.ts create mode 100644 temp/legacyImportFromCsv/data.deathAgePeriods.d.ts create mode 100644 temp/legacyImportFromCsv/data.deathAgePeriods.js create mode 100644 temp/legacyImportFromCsv/data.deathAgePeriods.ts create mode 100644 temp/legacyImportFromCsv/data.fees.d.ts create mode 100644 temp/legacyImportFromCsv/data.fees.js create mode 100644 temp/legacyImportFromCsv/data.fees.ts create mode 100644 temp/legacyImportFromCsv/data.funeralHomes.d.ts create mode 100644 temp/legacyImportFromCsv/data.funeralHomes.js create mode 100644 temp/legacyImportFromCsv/data.funeralHomes.ts create mode 100644 temp/legacyImportFromCsv/data.ids.d.ts create mode 100644 temp/legacyImportFromCsv/data.ids.js create mode 100644 temp/legacyImportFromCsv/data.ids.ts create mode 100644 temp/legacyImportFromCsv/data.intermentContainerTypes.d.ts create mode 100644 temp/legacyImportFromCsv/data.intermentContainerTypes.js create mode 100644 temp/legacyImportFromCsv/data.intermentContainerTypes.ts rename temp/{legacy.importFromCSV.d.ts => legacyImportFromCsv/index.d.ts} (100%) create mode 100644 temp/legacyImportFromCsv/index.js create mode 100644 temp/legacyImportFromCsv/index.ts diff --git a/app.js b/app.js index cf2905da..8afe6683 100644 --- a/app.js +++ b/app.js @@ -9,7 +9,6 @@ import rateLimit from 'express-rate-limit'; import session from 'express-session'; import createError from 'http-errors'; import FileStore from 'session-file-store'; -import { initializeDatabase } from './database/initializeDatabase.js'; import { DEBUG_NAMESPACE } from './debug.config.js'; import * as permissionHandlers from './handlers/permissions.js'; import * as configFunctions from './helpers/config.helpers.js'; @@ -29,10 +28,6 @@ import routerReports from './routes/reports.js'; import routerWorkOrders from './routes/workOrders.js'; import { version } from './version.js'; const debug = Debug(`${DEBUG_NAMESPACE}:app:${process.pid}`); -/* - * INITIALIZE THE DATABASE - */ -await initializeDatabase(); /* * INITIALIZE APP */ diff --git a/app.ts b/app.ts index bed9a32d..535a2060 100644 --- a/app.ts +++ b/app.ts @@ -11,7 +11,6 @@ import session from 'express-session' import createError from 'http-errors' import FileStore from 'session-file-store' -import { initializeDatabase } from './database/initializeDatabase.js' import { DEBUG_NAMESPACE } from './debug.config.js' import * as permissionHandlers from './handlers/permissions.js' import * as configFunctions from './helpers/config.helpers.js' @@ -33,12 +32,6 @@ import { version } from './version.js' const debug = Debug(`${DEBUG_NAMESPACE}:app:${process.pid}`) -/* - * INITIALIZE THE DATABASE - */ - -await initializeDatabase() - /* * INITIALIZE APP */ diff --git a/bin/www.js b/bin/www.js index 7b84d712..dc131992 100644 --- a/bin/www.js +++ b/bin/www.js @@ -6,9 +6,12 @@ import ntfyPublish from '@cityssm/ntfy-publish'; import { secondsToMillis } from '@cityssm/to-millis'; import Debug from 'debug'; import exitHook from 'exit-hook'; +import { initializeDatabase } from '../database/initializeDatabase.js'; import { DEBUG_NAMESPACE } from '../debug.config.js'; import { getConfigProperty } from '../helpers/config.helpers.js'; const debug = Debug(`${DEBUG_NAMESPACE}:www:${process.pid}`); +// INITIALIZE THE DATABASE +await initializeDatabase(); const directoryName = path.dirname(fileURLToPath(import.meta.url)); const processCount = Math.min(getConfigProperty('application.maximumProcesses'), os.cpus().length); process.title = `${getConfigProperty('application.applicationName')} (Primary)`; @@ -26,6 +29,7 @@ for (let index = 0; index < processCount; index += 1) { } cluster.on('message', (worker, message) => { for (const [pid, activeWorker] of activeWorkers.entries()) { + // eslint-disable-next-line sonarjs/different-types-comparison, @typescript-eslint/no-unnecessary-condition if (activeWorker === undefined || pid === message.pid) { continue; } diff --git a/bin/www.ts b/bin/www.ts index ade1101f..4d90f3b1 100644 --- a/bin/www.ts +++ b/bin/www.ts @@ -8,12 +8,16 @@ import { secondsToMillis } from '@cityssm/to-millis' import Debug from 'debug' import exitHook from 'exit-hook' +import { initializeDatabase } from '../database/initializeDatabase.js' import { DEBUG_NAMESPACE } from '../debug.config.js' import { getConfigProperty } from '../helpers/config.helpers.js' import type { WorkerMessage } from '../types/applicationTypes.js' const debug = Debug(`${DEBUG_NAMESPACE}:www:${process.pid}`) +// INITIALIZE THE DATABASE +await initializeDatabase() + const directoryName = path.dirname(fileURLToPath(import.meta.url)) const processCount = Math.min( @@ -42,6 +46,7 @@ for (let index = 0; index < processCount; index += 1) { cluster.on('message', (worker, message: WorkerMessage) => { for (const [pid, activeWorker] of activeWorkers.entries()) { + // eslint-disable-next-line sonarjs/different-types-comparison, @typescript-eslint/no-unnecessary-condition if (activeWorker === undefined || pid === message.pid) { continue } diff --git a/bin/wwwProcess.js b/bin/wwwProcess.js index 70fc4b88..deb4d513 100644 --- a/bin/wwwProcess.js +++ b/bin/wwwProcess.js @@ -4,9 +4,14 @@ import http from 'node:http'; import Debug from 'debug'; import exitHook from 'exit-hook'; import { app } from '../app.js'; +import { initializeDatabase } from '../database/initializeDatabase.js'; import { DEBUG_NAMESPACE } from '../debug.config.js'; import { getConfigProperty } from '../helpers/config.helpers.js'; const debug = Debug(`${DEBUG_NAMESPACE}:wwwProcess:${process.pid}`); +if (process.send === undefined) { + // INITIALIZE THE DATABASE + await initializeDatabase(); +} function onError(error) { if (error.syscall !== 'listen') { throw error; diff --git a/bin/wwwProcess.ts b/bin/wwwProcess.ts index 9bbb9111..ff6fcf1c 100644 --- a/bin/wwwProcess.ts +++ b/bin/wwwProcess.ts @@ -7,11 +7,17 @@ import Debug from 'debug' import exitHook from 'exit-hook' import { app } from '../app.js' +import { initializeDatabase } from '../database/initializeDatabase.js' import { DEBUG_NAMESPACE } from '../debug.config.js' import { getConfigProperty } from '../helpers/config.helpers.js' const debug = Debug(`${DEBUG_NAMESPACE}:wwwProcess:${process.pid}`) +if (process.send === undefined) { + // INITIALIZE THE DATABASE + await initializeDatabase() +} + interface ServerError extends Error { syscall: string code: string diff --git a/data/config.defaultValues.d.ts b/data/config.defaultValues.d.ts index e02a1d60..7697af44 100644 --- a/data/config.defaultValues.d.ts +++ b/data/config.defaultValues.d.ts @@ -28,6 +28,8 @@ export declare const configDefaultValues: { 'settings.provinceDefault': string; 'settings.burialSites.burialSiteNameSegments': ConfigBurialSiteNameSegments; 'settings.contracts.burialSiteIdIsRequired': boolean; + 'settings.contracts.contractEndDateIsRequired': boolean; + 'settings.contracts.deathAgePeriods': string[]; 'settings.contracts.prints': string[]; 'settings.fees.taxPercentageDefault': number; 'settings.workOrders.workOrderNumberLength': number; diff --git a/data/config.defaultValues.js b/data/config.defaultValues.js index a6d88a17..ca27293d 100644 --- a/data/config.defaultValues.js +++ b/data/config.defaultValues.js @@ -38,6 +38,8 @@ export const configDefaultValues = { } }, 'settings.contracts.burialSiteIdIsRequired': true, + 'settings.contracts.contractEndDateIsRequired': false, + 'settings.contracts.deathAgePeriods': ['Years', 'Months', 'Days', 'Stillborn'], 'settings.contracts.prints': ['screen/contract'], 'settings.fees.taxPercentageDefault': 0, 'settings.workOrders.workOrderNumberLength': 6, diff --git a/data/config.defaultValues.ts b/data/config.defaultValues.ts index 71415c3b..3f7940e5 100644 --- a/data/config.defaultValues.ts +++ b/data/config.defaultValues.ts @@ -57,6 +57,8 @@ export const configDefaultValues = { 'settings.contracts.burialSiteIdIsRequired': true, + 'settings.contracts.contractEndDateIsRequired': false, + 'settings.contracts.deathAgePeriods': ['Years', 'Months', 'Days', 'Stillborn'], 'settings.contracts.prints': ['screen/contract'], 'settings.fees.taxPercentageDefault': 0, diff --git a/database/addCommittalType.d.ts b/database/addCommittalType.d.ts new file mode 100644 index 00000000..04ac7e4d --- /dev/null +++ b/database/addCommittalType.d.ts @@ -0,0 +1,6 @@ +export interface AddForm { + committalType: string; + committalTypeKey?: string; + orderNumber?: number; +} +export default function addCommittalType(addForm: AddForm, user: User): Promise; diff --git a/database/addCommittalType.js b/database/addCommittalType.js new file mode 100644 index 00000000..eb757ebb --- /dev/null +++ b/database/addCommittalType.js @@ -0,0 +1,16 @@ +import { clearCacheByTableName } from '../helpers/functions.cache.js'; +import { acquireConnection } from './pool.js'; +export default async function addCommittalType(addForm, user) { + const database = await acquireConnection(); + const rightNowMillis = Date.now(); + const result = database + .prepare(`insert into CommittalTypes ( + committalType, committalTypeKey, orderNumber, + recordCreate_userName, recordCreate_timeMillis, + recordUpdate_userName, recordUpdate_timeMillis) + values (?, ?, ?, ?, ?, ?, ?)`) + .run(addForm.committalType, addForm.committalTypeKey ?? '', addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); + database.release(); + clearCacheByTableName('CommittalTypes'); + return result.lastInsertRowid; +} diff --git a/database/addCommittalType.ts b/database/addCommittalType.ts new file mode 100644 index 00000000..70a194fe --- /dev/null +++ b/database/addCommittalType.ts @@ -0,0 +1,42 @@ +import { clearCacheByTableName } from '../helpers/functions.cache.js' + +import { acquireConnection } from './pool.js' + +export interface AddForm { + committalType: string + committalTypeKey?: string + orderNumber?: number +} + +export default async function addCommittalType( + addForm: AddForm, + user: User +): Promise { + const database = await acquireConnection() + + const rightNowMillis = Date.now() + + const result = database + .prepare( + `insert into CommittalTypes ( + committalType, committalTypeKey, orderNumber, + recordCreate_userName, recordCreate_timeMillis, + recordUpdate_userName, recordUpdate_timeMillis) + values (?, ?, ?, ?, ?, ?, ?)` + ) + .run( + addForm.committalType, + addForm.committalTypeKey ?? '', + addForm.orderNumber ?? -1, + user.userName, + rightNowMillis, + user.userName, + rightNowMillis + ) + + database.release() + + clearCacheByTableName('CommittalTypes') + + return result.lastInsertRowid as number +} diff --git a/database/addContract.d.ts b/database/addContract.d.ts index 7600d93e..91e81fe5 100644 --- a/database/addContract.d.ts +++ b/database/addContract.d.ts @@ -31,6 +31,8 @@ export interface AddContractForm { birthPlace?: string; deathDateString?: DateString | ''; deathPlace?: string; + deathAge?: string; + deathAgePeriod?: string; intermentContainerTypeId?: string | number; } export default function addContract(addForm: AddContractForm, user: User, connectedDatabase?: PoolConnection): Promise; diff --git a/database/addContract.js b/database/addContract.js index f6a7109f..4f3a0e37 100644 --- a/database/addContract.js +++ b/database/addContract.js @@ -52,15 +52,16 @@ export default async function addContract(addForm, user, connectedDatabase) { deceasedCity, deceasedProvince, deceasedPostalCode, birthDate, deathDate, birthPlace, deathPlace, + deathAge, deathAgePeriod, intermentContainerTypeId, recordCreate_userName, recordCreate_timeMillis, recordUpdate_userName, recordUpdate_timeMillis) - values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) + values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) .run(contractId, 1, addForm.deceasedName ?? '', addForm.deceasedAddress1 ?? '', addForm.deceasedAddress2 ?? '', addForm.deceasedCity ?? '', addForm.deceasedProvince ?? '', addForm.deceasedPostalCode ?? '', addForm.birthDateString === '' ? undefined : dateStringToInteger(addForm.birthDateString), addForm.deathDateString === '' ? undefined - : dateStringToInteger(addForm.deathDateString), addForm.birthPlace ?? '', addForm.deathPlace ?? '', addForm.intermentContainerTypeId === '' + : dateStringToInteger(addForm.deathDateString), addForm.birthPlace ?? '', addForm.deathPlace ?? '', addForm.deathAge ?? undefined, addForm.deathAgePeriod ?? '', addForm.intermentContainerTypeId === '' ? undefined : addForm.intermentContainerTypeId, user.userName, rightNowMillis, user.userName, rightNowMillis); } diff --git a/database/addContract.ts b/database/addContract.ts index 2900d06d..eabfacf4 100644 --- a/database/addContract.ts +++ b/database/addContract.ts @@ -46,6 +46,8 @@ export interface AddContractForm { birthPlace?: string deathDateString?: DateString | '' deathPlace?: string + deathAge?: string + deathAgePeriod?: string intermentContainerTypeId?: string | number } @@ -148,10 +150,11 @@ export default async function addContract( deceasedCity, deceasedProvince, deceasedPostalCode, birthDate, deathDate, birthPlace, deathPlace, + deathAge, deathAgePeriod, intermentContainerTypeId, recordCreate_userName, recordCreate_timeMillis, recordUpdate_userName, recordUpdate_timeMillis) - values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` ) .run( @@ -171,6 +174,8 @@ export default async function addContract( : dateStringToInteger(addForm.deathDateString as DateString), addForm.birthPlace ?? '', addForm.deathPlace ?? '', + addForm.deathAge ?? undefined, + addForm.deathAgePeriod ?? '', addForm.intermentContainerTypeId === '' ? undefined : addForm.intermentContainerTypeId, diff --git a/database/addContractInterment.d.ts b/database/addContractInterment.d.ts index d0a2355e..2db3c5d2 100644 --- a/database/addContractInterment.d.ts +++ b/database/addContractInterment.d.ts @@ -11,6 +11,8 @@ export interface AddForm { birthPlace: string; deathDateString: DateString | ''; deathPlace: string; + deathAge: string; + deathAgePeriod: string; intermentContainerTypeId: string | number; } export default function addContractInterment(contractForm: AddForm, user: User): Promise; diff --git a/database/addContractInterment.ts b/database/addContractInterment.ts index 5e4b6d1b..15c86832 100644 --- a/database/addContractInterment.ts +++ b/database/addContractInterment.ts @@ -14,6 +14,8 @@ export interface AddForm { birthPlace: string deathDateString: DateString | '' deathPlace: string + deathAge: string + deathAgePeriod: string intermentContainerTypeId: string | number } diff --git a/database/addFee.d.ts b/database/addFee.d.ts index eee8c6b3..8cad91e2 100644 --- a/database/addFee.d.ts +++ b/database/addFee.d.ts @@ -1,10 +1,10 @@ export interface AddFeeForm { - feeCategoryId: string; + feeCategoryId: string | number; feeName: string; feeDescription: string; feeAccount: string; - contractTypeId: string; - burialSiteTypeId: string; + contractTypeId: string | number; + burialSiteTypeId: string | number; feeAmount?: string; feeFunction?: string; taxAmount?: string; diff --git a/database/addFee.js b/database/addFee.js index ebdba8fd..fc3b86df 100644 --- a/database/addFee.js +++ b/database/addFee.js @@ -14,7 +14,7 @@ export default async function addFee(feeForm, user) { recordCreate_userName, recordCreate_timeMillis, recordUpdate_userName, recordUpdate_timeMillis) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) - .run(feeForm.feeCategoryId, feeForm.feeName, feeForm.feeDescription, feeForm.feeAccount, feeForm.contractTypeId === '' ? undefined : feeForm.contractTypeId, feeForm.burialSiteTypeId === '' ? undefined : feeForm.burialSiteTypeId, feeForm.feeAmount ?? undefined, feeForm.feeFunction ?? undefined, feeForm.taxAmount ?? undefined, feeForm.taxPercentage ?? undefined, (feeForm.includeQuantity ?? '') === '' ? 0 : 1, feeForm.quantityUnit, (feeForm.isRequired ?? '') === '' ? 0 : 1, feeForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); + .run(feeForm.feeCategoryId, feeForm.feeName, feeForm.feeDescription, feeForm.feeAccount, feeForm.contractTypeId === '' ? undefined : feeForm.contractTypeId, feeForm.burialSiteTypeId === '' ? undefined : feeForm.burialSiteTypeId, feeForm.feeAmount === '' ? undefined : feeForm.feeAmount, feeForm.feeFunction ?? undefined, feeForm.taxAmount === '' ? undefined : feeForm.taxAmount, feeForm.taxPercentage === '' ? undefined : feeForm.taxPercentage, (feeForm.includeQuantity ?? '') === '' ? 0 : 1, feeForm.quantityUnit, (feeForm.isRequired ?? '') === '' ? 0 : 1, feeForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); database.release(); return result.lastInsertRowid; } diff --git a/database/addFee.ts b/database/addFee.ts index 954adb43..8328755b 100644 --- a/database/addFee.ts +++ b/database/addFee.ts @@ -1,12 +1,12 @@ import { acquireConnection } from './pool.js' export interface AddFeeForm { - feeCategoryId: string + feeCategoryId: string | number feeName: string feeDescription: string feeAccount: string - contractTypeId: string - burialSiteTypeId: string + contractTypeId: string | number + burialSiteTypeId: string | number feeAmount?: string feeFunction?: string taxAmount?: string @@ -46,10 +46,10 @@ export default async function addFee( feeForm.feeAccount, feeForm.contractTypeId === '' ? undefined : feeForm.contractTypeId, feeForm.burialSiteTypeId === '' ? undefined : feeForm.burialSiteTypeId, - feeForm.feeAmount ?? undefined, + feeForm.feeAmount === '' ? undefined : feeForm.feeAmount, feeForm.feeFunction ?? undefined, - feeForm.taxAmount ?? undefined, - feeForm.taxPercentage ?? undefined, + feeForm.taxAmount === '' ? undefined : feeForm.taxAmount, + feeForm.taxPercentage === '' ? undefined : feeForm.taxPercentage, (feeForm.includeQuantity ?? '') === '' ? 0 : 1, feeForm.quantityUnit, (feeForm.isRequired ?? '') === '' ? 0 : 1, diff --git a/database/addFuneralHome.d.ts b/database/addFuneralHome.d.ts index 46e3a817..7edc71be 100644 --- a/database/addFuneralHome.d.ts +++ b/database/addFuneralHome.d.ts @@ -1,5 +1,6 @@ export interface AddForm { funeralHomeName: string; + funeralHomeKey: string; funeralHomeAddress1: string; funeralHomeAddress2: string; funeralHomeCity: string; diff --git a/database/addFuneralHome.js b/database/addFuneralHome.js index e83bf842..57ed93e2 100644 --- a/database/addFuneralHome.js +++ b/database/addFuneralHome.js @@ -4,12 +4,12 @@ export default async function addFuneralHome(addForm, user) { const rightNowMillis = Date.now(); const result = database .prepare(`insert into FuneralHomes ( - funeralHomeName, funeralHomeAddress1, funeralHomeAddress2, + funeralHomeName, funeralHomeKey, funeralHomeAddress1, funeralHomeAddress2, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber, recordCreate_userName, recordCreate_timeMillis, recordUpdate_userName, recordUpdate_timeMillis) - values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) - .run(addForm.funeralHomeName, addForm.funeralHomeAddress1, addForm.funeralHomeAddress2, addForm.funeralHomeCity, addForm.funeralHomeProvince, addForm.funeralHomePostalCode, addForm.funeralHomePhoneNumber, user.userName, rightNowMillis, user.userName, rightNowMillis); + values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) + .run(addForm.funeralHomeName, addForm.funeralHomeKey, addForm.funeralHomeAddress1, addForm.funeralHomeAddress2, addForm.funeralHomeCity, addForm.funeralHomeProvince, addForm.funeralHomePostalCode, addForm.funeralHomePhoneNumber, user.userName, rightNowMillis, user.userName, rightNowMillis); database.release(); return result.lastInsertRowid; } diff --git a/database/addFuneralHome.ts b/database/addFuneralHome.ts index f96ea474..037c5e4d 100644 --- a/database/addFuneralHome.ts +++ b/database/addFuneralHome.ts @@ -2,6 +2,7 @@ import { acquireConnection } from './pool.js' export interface AddForm { funeralHomeName: string + funeralHomeKey: string funeralHomeAddress1: string funeralHomeAddress2: string funeralHomeCity: string @@ -21,14 +22,15 @@ export default async function addFuneralHome( const result = database .prepare( `insert into FuneralHomes ( - funeralHomeName, funeralHomeAddress1, funeralHomeAddress2, + funeralHomeName, funeralHomeKey, funeralHomeAddress1, funeralHomeAddress2, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber, recordCreate_userName, recordCreate_timeMillis, recordUpdate_userName, recordUpdate_timeMillis) - values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` ) .run( addForm.funeralHomeName, + addForm.funeralHomeKey, addForm.funeralHomeAddress1, addForm.funeralHomeAddress2, addForm.funeralHomeCity, diff --git a/database/addIntermentContainerType.d.ts b/database/addIntermentContainerType.d.ts index 399e41bf..77414dad 100644 --- a/database/addIntermentContainerType.d.ts +++ b/database/addIntermentContainerType.d.ts @@ -1,5 +1,6 @@ export interface AddForm { intermentContainerType: string; + intermentContainerTypeKey?: string; isCremationType?: string; orderNumber?: number; } diff --git a/database/addIntermentContainerType.js b/database/addIntermentContainerType.js index bfec6eb2..dd7a88bc 100644 --- a/database/addIntermentContainerType.js +++ b/database/addIntermentContainerType.js @@ -5,11 +5,11 @@ export default async function addIntermentContainerType(addForm, user) { const rightNowMillis = Date.now(); const result = database .prepare(`insert into IntermentContainerTypes ( - intermentContainerType, isCremationType, orderNumber, + intermentContainerType, intermentContainerTypeKey, isCremationType, orderNumber, recordCreate_userName, recordCreate_timeMillis, recordUpdate_userName, recordUpdate_timeMillis) - values (?, ?, ?, ?, ?, ?, ?)`) - .run(addForm.intermentContainerType, addForm.isCremationType === undefined ? 0 : 1, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); + values (?, ?, ?, ?, ?, ?, ?, ?)`) + .run(addForm.intermentContainerType, addForm.intermentContainerTypeKey ?? '', addForm.isCremationType === undefined ? 0 : 1, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); database.release(); clearCacheByTableName('IntermentContainerTypes'); return result.lastInsertRowid; diff --git a/database/addIntermentContainerType.ts b/database/addIntermentContainerType.ts index 83852760..40a424b3 100644 --- a/database/addIntermentContainerType.ts +++ b/database/addIntermentContainerType.ts @@ -4,6 +4,7 @@ import { acquireConnection } from './pool.js' export interface AddForm { intermentContainerType: string + intermentContainerTypeKey?: string isCremationType?: string orderNumber?: number } @@ -19,13 +20,14 @@ export default async function addIntermentContainerType( const result = database .prepare( `insert into IntermentContainerTypes ( - intermentContainerType, isCremationType, orderNumber, + intermentContainerType, intermentContainerTypeKey, isCremationType, orderNumber, recordCreate_userName, recordCreate_timeMillis, recordUpdate_userName, recordUpdate_timeMillis) - values (?, ?, ?, ?, ?, ?, ?)` + values (?, ?, ?, ?, ?, ?, ?, ?)` ) .run( addForm.intermentContainerType, + addForm.intermentContainerTypeKey ?? '', addForm.isCremationType === undefined ? 0 : 1, addForm.orderNumber ?? -1, user.userName, diff --git a/database/addRecord.d.ts b/database/addRecord.d.ts index cf62d577..887976a7 100644 --- a/database/addRecord.d.ts +++ b/database/addRecord.d.ts @@ -1,3 +1,3 @@ -type RecordTable = 'BurialSiteStatuses' | 'BurialSiteTypes' | 'CommittalTypes' | 'WorkOrderMilestoneTypes' | 'WorkOrderTypes'; +type RecordTable = 'BurialSiteStatuses' | 'BurialSiteTypes' | 'WorkOrderMilestoneTypes' | 'WorkOrderTypes'; export default function addRecord(recordTable: RecordTable, recordName: string, orderNumber: number | string, user: User): Promise; export {}; diff --git a/database/addRecord.js b/database/addRecord.js index 4d00e72e..4e45c5f3 100644 --- a/database/addRecord.js +++ b/database/addRecord.js @@ -3,7 +3,6 @@ import { acquireConnection } from './pool.js'; const recordNameColumns = new Map(); recordNameColumns.set('BurialSiteStatuses', 'burialSiteStatus'); recordNameColumns.set('BurialSiteTypes', 'burialSiteType'); -recordNameColumns.set('CommittalTypes', 'committalType'); recordNameColumns.set('WorkOrderMilestoneTypes', 'workOrderMilestoneType'); recordNameColumns.set('WorkOrderTypes', 'workOrderType'); export default async function addRecord(recordTable, recordName, orderNumber, user) { diff --git a/database/addRecord.ts b/database/addRecord.ts index 4e35c2be..d38b0a25 100644 --- a/database/addRecord.ts +++ b/database/addRecord.ts @@ -5,14 +5,12 @@ import { acquireConnection } from './pool.js' type RecordTable = | 'BurialSiteStatuses' | 'BurialSiteTypes' - | 'CommittalTypes' | 'WorkOrderMilestoneTypes' | 'WorkOrderTypes' const recordNameColumns = new Map() recordNameColumns.set('BurialSiteStatuses', 'burialSiteStatus') recordNameColumns.set('BurialSiteTypes', 'burialSiteType') -recordNameColumns.set('CommittalTypes', 'committalType') recordNameColumns.set('WorkOrderMilestoneTypes', 'workOrderMilestoneType') recordNameColumns.set('WorkOrderTypes', 'workOrderType') diff --git a/database/getBurialSite.js b/database/getBurialSite.js index cd9ae014..51def221 100644 --- a/database/getBurialSite.js +++ b/database/getBurialSite.js @@ -1,6 +1,6 @@ import getBurialSiteComments from './getBurialSiteComments.js'; -import getBurialSiteInterments from './getContracts.js'; import getBurialSiteFields from './getBurialSiteFields.js'; +import getContracts from './getContracts.js'; import { acquireConnection } from './pool.js'; const baseSQL = `select l.burialSiteId, l.burialSiteTypeId, t.burialSiteType, @@ -24,7 +24,7 @@ async function _getBurialSite(sql, burialSiteIdOrLotName) { const database = await acquireConnection(); const burialSite = database.prepare(sql).get(burialSiteIdOrLotName); if (burialSite !== undefined) { - const contracts = await getBurialSiteInterments({ + const contracts = await getContracts({ burialSiteId: burialSite.burialSiteId }, { includeInterments: true, diff --git a/database/getBurialSite.ts b/database/getBurialSite.ts index 7a00df95..21b70ed7 100644 --- a/database/getBurialSite.ts +++ b/database/getBurialSite.ts @@ -1,8 +1,8 @@ import type { BurialSite } from '../types/recordTypes.js' import getBurialSiteComments from './getBurialSiteComments.js' -import getBurialSiteInterments from './getContracts.js' import getBurialSiteFields from './getBurialSiteFields.js' +import getContracts from './getContracts.js' import { acquireConnection } from './pool.js' const baseSQL = `select l.burialSiteId, @@ -33,7 +33,7 @@ async function _getBurialSite( const burialSite = database.prepare(sql).get(burialSiteIdOrLotName) as BurialSite | undefined if (burialSite !== undefined) { - const contracts = await getBurialSiteInterments( + const contracts = await getContracts( { burialSiteId: burialSite.burialSiteId }, diff --git a/database/getCemetery.d.ts b/database/getCemetery.d.ts index 7abca40c..02c99c31 100644 --- a/database/getCemetery.d.ts +++ b/database/getCemetery.d.ts @@ -1,3 +1,4 @@ import type { PoolConnection } from 'better-sqlite-pool'; import type { Cemetery } from '../types/recordTypes.js'; export default function getCemetery(cemeteryId: number | string, connectedDatabase?: PoolConnection): Promise; +export declare function getCemeteryByKey(cemeteryKey: string, connectedDatabase?: PoolConnection): Promise; diff --git a/database/getCemetery.js b/database/getCemetery.js index 15a8f7c9..8b9dd47b 100644 --- a/database/getCemetery.js +++ b/database/getCemetery.js @@ -1,5 +1,5 @@ import { acquireConnection } from './pool.js'; -export default async function getCemetery(cemeteryId, connectedDatabase) { +async function _getCemetery(keyColumn, cemeteryIdOrKey, connectedDatabase) { const database = connectedDatabase ?? (await acquireConnection()); const cemetery = database .prepare(`select m.cemeteryId, m.cemeteryName, m.cemeteryKey, m.cemeteryDescription, @@ -12,7 +12,7 @@ export default async function getCemetery(cemeteryId, connectedDatabase) { count(l.burialSiteId) as burialSiteCount from Cemeteries m left join BurialSites l on m.cemeteryId = l.cemeteryId and l.recordDelete_timeMillis is null - where m.cemeteryId = ? + where m.${keyColumn} = ? and m.recordDelete_timeMillis is null group by m.cemeteryId, m.cemeteryName, m.cemeteryDescription, m.cemeteryLatitude, m.cemeteryLongitude, m.cemeterySvg, @@ -21,9 +21,15 @@ export default async function getCemetery(cemeteryId, connectedDatabase) { m.recordCreate_userName, m.recordCreate_timeMillis, m.recordUpdate_userName, m.recordUpdate_timeMillis, m.recordDelete_userName, m.recordDelete_timeMillis`) - .get(cemeteryId); + .get(cemeteryIdOrKey); if (connectedDatabase === undefined) { database.release(); } return cemetery; } +export default async function getCemetery(cemeteryId, connectedDatabase) { + return await _getCemetery('cemeteryId', cemeteryId, connectedDatabase); +} +export async function getCemeteryByKey(cemeteryKey, connectedDatabase) { + return await _getCemetery('cemeteryKey', cemeteryKey, connectedDatabase); +} diff --git a/database/getCemetery.ts b/database/getCemetery.ts index 96f3903f..d3248c34 100644 --- a/database/getCemetery.ts +++ b/database/getCemetery.ts @@ -4,8 +4,9 @@ import type { Cemetery } from '../types/recordTypes.js' import { acquireConnection } from './pool.js' -export default async function getCemetery( - cemeteryId: number | string, +async function _getCemetery( + keyColumn: 'cemeteryId' | 'cemeteryKey', + cemeteryIdOrKey: number | string, connectedDatabase?: PoolConnection ): Promise { const database = connectedDatabase ?? (await acquireConnection()) @@ -22,7 +23,7 @@ export default async function getCemetery( count(l.burialSiteId) as burialSiteCount from Cemeteries m left join BurialSites l on m.cemeteryId = l.cemeteryId and l.recordDelete_timeMillis is null - where m.cemeteryId = ? + where m.${keyColumn} = ? and m.recordDelete_timeMillis is null group by m.cemeteryId, m.cemeteryName, m.cemeteryDescription, m.cemeteryLatitude, m.cemeteryLongitude, m.cemeterySvg, @@ -32,7 +33,7 @@ export default async function getCemetery( m.recordUpdate_userName, m.recordUpdate_timeMillis, m.recordDelete_userName, m.recordDelete_timeMillis` ) - .get(cemeteryId) as Cemetery | undefined + .get(cemeteryIdOrKey) as Cemetery | undefined if (connectedDatabase === undefined) { database.release() @@ -40,3 +41,17 @@ export default async function getCemetery( return cemetery } + +export default async function getCemetery( + cemeteryId: number | string, + connectedDatabase?: PoolConnection +): Promise { + return await _getCemetery('cemeteryId', cemeteryId, connectedDatabase) +} + +export async function getCemeteryByKey( + cemeteryKey: string, + connectedDatabase?: PoolConnection +): Promise { + return await _getCemetery('cemeteryKey', cemeteryKey, connectedDatabase) +} diff --git a/database/getCommittalTypes.js b/database/getCommittalTypes.js index dbab67b2..831a6ba7 100644 --- a/database/getCommittalTypes.js +++ b/database/getCommittalTypes.js @@ -3,7 +3,7 @@ import { updateRecordOrderNumber } from './updateRecordOrderNumber.js'; export default async function getCommittalTypes() { const database = await acquireConnection(); const committalTypes = database - .prepare(`select committalTypeId, committalType, orderNumber + .prepare(`select committalTypeId, committalTypeKey, committalType, orderNumber from CommittalTypes where recordDelete_timeMillis is null order by orderNumber, committalType, committalTypeId`) diff --git a/database/getCommittalTypes.ts b/database/getCommittalTypes.ts index 0783edc8..497b6b85 100644 --- a/database/getCommittalTypes.ts +++ b/database/getCommittalTypes.ts @@ -8,7 +8,7 @@ export default async function getCommittalTypes(): Promise { const committalTypes = database .prepare( - `select committalTypeId, committalType, orderNumber + `select committalTypeId, committalTypeKey, committalType, orderNumber from CommittalTypes where recordDelete_timeMillis is null order by orderNumber, committalType, committalTypeId` diff --git a/database/getContract.js b/database/getContract.js index ffcfa9d2..d9e9fd78 100644 --- a/database/getContract.js +++ b/database/getContract.js @@ -20,7 +20,7 @@ export default async function getContract(contractId, connectedDatabase) { o.purchaserName, o.purchaserAddress1, o.purchaserAddress2, o.purchaserCity, o.purchaserProvince, o.purchaserPostalCode, o.purchaserPhoneNumber, o.purchaserEmail, o.purchaserRelationship, - o.funeralHomeId, o.funeralDirectorName, + o.funeralHomeId, o.funeralDirectorName, f.funeralHomeKey, f.funeralHomeName, f.funeralHomeAddress1, f.funeralHomeAddress2, f.funeralHomeCity, f.funeralHomeProvince, f.funeralHomePostalCode, o.funeralDate, userFn_dateIntegerToString(o.funeralDate) as funeralDateString, diff --git a/database/getContract.ts b/database/getContract.ts index f274c2cc..ae60c0c7 100644 --- a/database/getContract.ts +++ b/database/getContract.ts @@ -31,7 +31,7 @@ export default async function getContract( o.purchaserName, o.purchaserAddress1, o.purchaserAddress2, o.purchaserCity, o.purchaserProvince, o.purchaserPostalCode, o.purchaserPhoneNumber, o.purchaserEmail, o.purchaserRelationship, - o.funeralHomeId, o.funeralDirectorName, + o.funeralHomeId, o.funeralDirectorName, f.funeralHomeKey, f.funeralHomeName, f.funeralHomeAddress1, f.funeralHomeAddress2, f.funeralHomeCity, f.funeralHomeProvince, f.funeralHomePostalCode, o.funeralDate, userFn_dateIntegerToString(o.funeralDate) as funeralDateString, diff --git a/database/getContractInterments.js b/database/getContractInterments.js index 1f3c5f9c..437b1748 100644 --- a/database/getContractInterments.js +++ b/database/getContractInterments.js @@ -12,6 +12,7 @@ export default async function getContractInterments(contractId, connectedDatabas o.birthPlace, o.deathDate, userFn_dateIntegerToString(o.deathDate) as deathDateString, o.deathPlace, + o.deathAge, o.deathAgePeriod, o.intermentContainerTypeId, t.intermentContainerType, t.isCremationType diff --git a/database/getContractInterments.ts b/database/getContractInterments.ts index aeecad88..c70c8ce8 100644 --- a/database/getContractInterments.ts +++ b/database/getContractInterments.ts @@ -25,6 +25,7 @@ export default async function getContractInterments( o.birthPlace, o.deathDate, userFn_dateIntegerToString(o.deathDate) as deathDateString, o.deathPlace, + o.deathAge, o.deathAgePeriod, o.intermentContainerTypeId, t.intermentContainerType, t.isCremationType diff --git a/database/getFuneralHome.d.ts b/database/getFuneralHome.d.ts index c33ac8e5..dc0a4338 100644 --- a/database/getFuneralHome.d.ts +++ b/database/getFuneralHome.d.ts @@ -1,2 +1,3 @@ import type { FuneralHome } from '../types/recordTypes.js'; export default function getFuneralHome(funeralHomeId: number | string): Promise; +export declare function getFuneralHomeByKey(funeralHomeKey: string): Promise; diff --git a/database/getFuneralHome.js b/database/getFuneralHome.js index dbde71eb..7e9f1b34 100644 --- a/database/getFuneralHome.js +++ b/database/getFuneralHome.js @@ -1,15 +1,21 @@ import { acquireConnection } from './pool.js'; -export default async function getFuneralHome(funeralHomeId) { +async function _getFuneralHome(keyColumn, funeralHomeIdOrKey) { const database = await acquireConnection(); const funeralHome = database - .prepare(`select funeralHomeId, funeralHomeName, + .prepare(`select funeralHomeId, funeralHomeKey, funeralHomeName, funeralHomeAddress1, funeralHomeAddress2, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber from FuneralHomes f where f.recordDelete_timeMillis is null - and f.funeralHomeId = ? + and f.${keyColumn} = ? order by f.funeralHomeName, f.funeralHomeId`) - .get(funeralHomeId); + .get(funeralHomeIdOrKey); database.release(); return funeralHome; } +export default async function getFuneralHome(funeralHomeId) { + return await _getFuneralHome('funeralHomeId', funeralHomeId); +} +export async function getFuneralHomeByKey(funeralHomeKey) { + return await _getFuneralHome('funeralHomeKey', funeralHomeKey); +} diff --git a/database/getFuneralHome.ts b/database/getFuneralHome.ts index 2e2eef24..8d13543a 100644 --- a/database/getFuneralHome.ts +++ b/database/getFuneralHome.ts @@ -2,24 +2,37 @@ import type { Cemetery, FuneralHome } from '../types/recordTypes.js' import { acquireConnection } from './pool.js' -export default async function getFuneralHome( - funeralHomeId: number | string +async function _getFuneralHome( + keyColumn: 'funeralHomeId' | 'funeralHomeKey', + funeralHomeIdOrKey: number | string ): Promise { const database = await acquireConnection() const funeralHome = database .prepare( - `select funeralHomeId, funeralHomeName, + `select funeralHomeId, funeralHomeKey, funeralHomeName, funeralHomeAddress1, funeralHomeAddress2, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber from FuneralHomes f where f.recordDelete_timeMillis is null - and f.funeralHomeId = ? + and f.${keyColumn} = ? order by f.funeralHomeName, f.funeralHomeId` ) - .get(funeralHomeId) as Cemetery | undefined + .get(funeralHomeIdOrKey) as Cemetery | undefined database.release() return funeralHome } + +export default async function getFuneralHome( + funeralHomeId: number | string +): Promise { + return await _getFuneralHome('funeralHomeId', funeralHomeId) +} + +export async function getFuneralHomeByKey( + funeralHomeKey: string +): Promise { + return await _getFuneralHome('funeralHomeKey', funeralHomeKey) +} diff --git a/database/getFuneralHomes.js b/database/getFuneralHomes.js index e61010b4..bbf04587 100644 --- a/database/getFuneralHomes.js +++ b/database/getFuneralHomes.js @@ -2,7 +2,7 @@ import { acquireConnection } from './pool.js'; export default async function getFuneralHomes() { const database = await acquireConnection(); const funeralHomes = database - .prepare(`select funeralHomeId, funeralHomeName, + .prepare(`select funeralHomeId, funeralHomeKey, funeralHomeName, funeralHomeAddress1, funeralHomeAddress2, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber from FuneralHomes f diff --git a/database/getFuneralHomes.ts b/database/getFuneralHomes.ts index e505551d..4139a1c6 100644 --- a/database/getFuneralHomes.ts +++ b/database/getFuneralHomes.ts @@ -7,7 +7,7 @@ export default async function getFuneralHomes(): Promise { const funeralHomes = database .prepare( - `select funeralHomeId, funeralHomeName, + `select funeralHomeId, funeralHomeKey, funeralHomeName, funeralHomeAddress1, funeralHomeAddress2, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber from FuneralHomes f diff --git a/database/getIntermentContainerTypes.js b/database/getIntermentContainerTypes.js index 9d7e66bc..9130e87b 100644 --- a/database/getIntermentContainerTypes.js +++ b/database/getIntermentContainerTypes.js @@ -3,7 +3,7 @@ import { updateRecordOrderNumber } from './updateRecordOrderNumber.js'; export default async function getIntermentContainerTypes() { const database = await acquireConnection(); const containerTypes = database - .prepare(`select intermentContainerTypeId, intermentContainerType, isCremationType, orderNumber + .prepare(`select intermentContainerTypeId, intermentContainerType, intermentContainerTypeKey, isCremationType, orderNumber from IntermentContainerTypes where recordDelete_timeMillis is null order by isCremationType, orderNumber, intermentContainerType, intermentContainerTypeId`) diff --git a/database/getIntermentContainerTypes.ts b/database/getIntermentContainerTypes.ts index d0237419..8347037d 100644 --- a/database/getIntermentContainerTypes.ts +++ b/database/getIntermentContainerTypes.ts @@ -10,7 +10,7 @@ export default async function getIntermentContainerTypes(): Promise< const containerTypes = database .prepare( - `select intermentContainerTypeId, intermentContainerType, isCremationType, orderNumber + `select intermentContainerTypeId, intermentContainerType, intermentContainerTypeKey, isCremationType, orderNumber from IntermentContainerTypes where recordDelete_timeMillis is null order by isCremationType, orderNumber, intermentContainerType, intermentContainerTypeId` diff --git a/database/initializeDatabase.js b/database/initializeDatabase.js index e78cfd34..13a591a2 100644 --- a/database/initializeDatabase.js +++ b/database/initializeDatabase.js @@ -4,6 +4,7 @@ import sqlite from 'better-sqlite3'; import Debug from 'debug'; import { DEBUG_NAMESPACE } from '../debug.config.js'; import { sunriseDB as databasePath } from '../helpers/database.helpers.js'; +import addCommittalType from './addCommittalType.js'; import addContractType from './addContractType.js'; import addFeeCategory from './addFeeCategory.js'; import addIntermentContainerType from './addIntermentContainerType.js'; @@ -121,6 +122,7 @@ const createStatements = [ `create table if not exists FuneralHomes ( funeralHomeId integer not null primary key autoincrement, funeralHomeName varchar(200) not null, + funeralHomeKey varchar(20) not null default '', funeralHomeAddress1 varchar(50), funeralHomeAddress2 varchar(50), funeralHomeCity varchar(20), @@ -165,6 +167,7 @@ const createStatements = [ on ContractTypePrints (contractTypeId, orderNumber, printEJS)`, `create table if not exists CommittalTypes ( committalTypeId integer not null primary key autoincrement, + committalTypeKey varchar(20) not null default '', committalType varchar(100) not null, orderNumber smallint not null default 0, ${recordColumns})`, @@ -222,6 +225,7 @@ const createStatements = [ `create table if not exists IntermentContainerTypes ( intermentContainerTypeId integer not null primary key autoincrement, intermentContainerType varchar(100) not null, + intermentContainerTypeKey varchar(20) not null default '', isCremationType bit not null default 0, orderNumber smallint not null default 0, ${recordColumns})`, @@ -245,6 +249,8 @@ const createStatements = [ deathDate integer, deathPlace varchar(100), + deathAge integer, + deathAgePeriod varchar(10), intermentContainerTypeId integer, @@ -393,7 +399,7 @@ export async function initializeDatabase() { return true; } async function initializeData() { - debug("Initializing data..."); + debug('Initializing data...'); await addRecord('BurialSiteTypes', 'Casket Grave', 1, initializingUser); await addRecord('BurialSiteTypes', 'Columbarium', 2, initializingUser); await addRecord('BurialSiteTypes', 'Mausoleum', 2, initializingUser); @@ -420,31 +426,54 @@ async function initializeData() { // Interment Container Types await addIntermentContainerType({ intermentContainerType: 'No Shell', + intermentContainerTypeKey: 'NS', orderNumber: 1 }, initializingUser); await addIntermentContainerType({ intermentContainerType: 'Concrete Liner', + intermentContainerTypeKey: 'CL', orderNumber: 2 }, initializingUser); await addIntermentContainerType({ intermentContainerType: 'Unpainted Vault', + intermentContainerTypeKey: 'UV', orderNumber: 3 }, initializingUser); await addIntermentContainerType({ intermentContainerType: 'Concrete Vault', + intermentContainerTypeKey: 'CV', orderNumber: 4 }, initializingUser); - await addIntermentContainerType({ intermentContainerType: 'Wooden Shell', orderNumber: 5 }, initializingUser); - await addIntermentContainerType({ intermentContainerType: 'Steel Vault', orderNumber: 6 }, initializingUser); + await addIntermentContainerType({ + intermentContainerType: 'Wooden Shell', + intermentContainerTypeKey: 'WS', + orderNumber: 5 + }, initializingUser); + await addIntermentContainerType({ intermentContainerType: 'Steel Vault', + intermentContainerTypeKey: 'SV', + orderNumber: 6 }, initializingUser); await addIntermentContainerType({ intermentContainerType: 'Urn', + intermentContainerTypeKey: 'U', isCremationType: '1', orderNumber: 7 }, initializingUser); // Committal Types - await addRecord('CommittalTypes', 'Graveside', 1, initializingUser); - await addRecord('CommittalTypes', 'Chapel', 2, initializingUser); - await addRecord('CommittalTypes', 'Church', 3, initializingUser); + await addCommittalType({ + committalType: 'Graveside', + committalTypeKey: 'GS', + orderNumber: 1 + }, initializingUser); + await addCommittalType({ + committalType: 'Chapel', + committalTypeKey: 'CS', + orderNumber: 2 + }, initializingUser); + await addCommittalType({ + committalType: 'Church', + committalTypeKey: 'CH', + orderNumber: 3 + }, initializingUser); /* * Fee Categories */ diff --git a/database/initializeDatabase.ts b/database/initializeDatabase.ts index 404934b9..1aa71a5a 100644 --- a/database/initializeDatabase.ts +++ b/database/initializeDatabase.ts @@ -7,6 +7,7 @@ import Debug from 'debug' import { DEBUG_NAMESPACE } from '../debug.config.js' import { sunriseDB as databasePath } from '../helpers/database.helpers.js' +import addCommittalType from './addCommittalType.js' import addContractType from './addContractType.js' import addFeeCategory from './addFeeCategory.js' import addIntermentContainerType from './addIntermentContainerType.js' @@ -143,6 +144,7 @@ const createStatements = [ `create table if not exists FuneralHomes ( funeralHomeId integer not null primary key autoincrement, funeralHomeName varchar(200) not null, + funeralHomeKey varchar(20) not null default '', funeralHomeAddress1 varchar(50), funeralHomeAddress2 varchar(50), funeralHomeCity varchar(20), @@ -195,6 +197,7 @@ const createStatements = [ `create table if not exists CommittalTypes ( committalTypeId integer not null primary key autoincrement, + committalTypeKey varchar(20) not null default '', committalType varchar(100) not null, orderNumber smallint not null default 0, ${recordColumns})`, @@ -259,6 +262,7 @@ const createStatements = [ `create table if not exists IntermentContainerTypes ( intermentContainerTypeId integer not null primary key autoincrement, intermentContainerType varchar(100) not null, + intermentContainerTypeKey varchar(20) not null default '', isCremationType bit not null default 0, orderNumber smallint not null default 0, ${recordColumns})`, @@ -284,6 +288,8 @@ const createStatements = [ deathDate integer, deathPlace varchar(100), + deathAge integer, + deathAgePeriod varchar(10), intermentContainerTypeId integer, @@ -461,7 +467,7 @@ export async function initializeDatabase(): Promise { } async function initializeData(): Promise { - debug("Initializing data...") + debug('Initializing data...') await addRecord('BurialSiteTypes', 'Casket Grave', 1, initializingUser) await addRecord('BurialSiteTypes', 'Columbarium', 2, initializingUser) @@ -506,6 +512,7 @@ async function initializeData(): Promise { await addIntermentContainerType( { intermentContainerType: 'No Shell', + intermentContainerTypeKey: 'NS', orderNumber: 1 }, initializingUser @@ -514,6 +521,7 @@ async function initializeData(): Promise { await addIntermentContainerType( { intermentContainerType: 'Concrete Liner', + intermentContainerTypeKey: 'CL', orderNumber: 2 }, initializingUser @@ -522,6 +530,7 @@ async function initializeData(): Promise { await addIntermentContainerType( { intermentContainerType: 'Unpainted Vault', + intermentContainerTypeKey: 'UV', orderNumber: 3 }, initializingUser @@ -530,24 +539,32 @@ async function initializeData(): Promise { await addIntermentContainerType( { intermentContainerType: 'Concrete Vault', + intermentContainerTypeKey: 'CV', orderNumber: 4 }, initializingUser ) await addIntermentContainerType( - { intermentContainerType: 'Wooden Shell', orderNumber: 5 }, + { + intermentContainerType: 'Wooden Shell', + intermentContainerTypeKey: 'WS', + orderNumber: 5 + }, initializingUser ) await addIntermentContainerType( - { intermentContainerType: 'Steel Vault', orderNumber: 6 }, + { intermentContainerType: 'Steel Vault', + intermentContainerTypeKey: 'SV', + orderNumber: 6 }, initializingUser ) await addIntermentContainerType( { intermentContainerType: 'Urn', + intermentContainerTypeKey: 'U', isCremationType: '1', orderNumber: 7 }, @@ -556,9 +573,23 @@ async function initializeData(): Promise { // Committal Types - await addRecord('CommittalTypes', 'Graveside', 1, initializingUser) - await addRecord('CommittalTypes', 'Chapel', 2, initializingUser) - await addRecord('CommittalTypes', 'Church', 3, initializingUser) + await addCommittalType({ + committalType: 'Graveside', + committalTypeKey: 'GS', + orderNumber: 1 + }, initializingUser) + + await addCommittalType({ + committalType: 'Chapel', + committalTypeKey: 'CS', + orderNumber: 2 + }, initializingUser) + + await addCommittalType({ + committalType: 'Church', + committalTypeKey: 'CH', + orderNumber: 3 + }, initializingUser) /* * Fee Categories diff --git a/database/updateContractInterment.d.ts b/database/updateContractInterment.d.ts index ef9b3de6..e7dc694e 100644 --- a/database/updateContractInterment.d.ts +++ b/database/updateContractInterment.d.ts @@ -12,6 +12,8 @@ export interface UpdateForm { birthPlace: string; deathDateString: DateString | ''; deathPlace: string; + deathAge: string; + deathAgePeriod: string; intermentContainerTypeId: string | number; } export default function updateContractInterment(contractForm: UpdateForm, user: User): Promise; diff --git a/database/updateContractInterment.js b/database/updateContractInterment.js index 497180ef..bb314d83 100644 --- a/database/updateContractInterment.js +++ b/database/updateContractInterment.js @@ -14,6 +14,8 @@ export default async function updateContractInterment(contractForm, user) { birthPlace = ?, deathDate = ?, deathPlace = ?, + deathAge = ?, + deathAgePeriod = ?, intermentContainerTypeId = ?, recordUpdate_userName = ?, recordUpdate_timeMillis = ? @@ -24,7 +26,7 @@ export default async function updateContractInterment(contractForm, user) { ? undefined : dateStringToInteger(contractForm.birthDateString), contractForm.birthPlace, contractForm.deathDateString === '' ? undefined - : dateStringToInteger(contractForm.deathDateString), contractForm.deathPlace, contractForm.intermentContainerTypeId === '' + : dateStringToInteger(contractForm.deathDateString), contractForm.deathPlace, contractForm.deathAge, contractForm.deathAgePeriod, contractForm.intermentContainerTypeId === '' ? undefined : contractForm.intermentContainerTypeId, user.userName, Date.now(), contractForm.contractId, contractForm.intermentNumber); database.release(); diff --git a/database/updateContractInterment.ts b/database/updateContractInterment.ts index 38bce77b..a52f9580 100644 --- a/database/updateContractInterment.ts +++ b/database/updateContractInterment.ts @@ -15,6 +15,8 @@ export interface UpdateForm { birthPlace: string deathDateString: DateString | '' deathPlace: string + deathAge: string + deathAgePeriod: string intermentContainerTypeId: string | number } @@ -37,6 +39,8 @@ export default async function updateContractInterment( birthPlace = ?, deathDate = ?, deathPlace = ?, + deathAge = ?, + deathAgePeriod = ?, intermentContainerTypeId = ?, recordUpdate_userName = ?, recordUpdate_timeMillis = ? @@ -59,6 +63,8 @@ export default async function updateContractInterment( ? undefined : dateStringToInteger(contractForm.deathDateString), contractForm.deathPlace, + contractForm.deathAge, + contractForm.deathAgePeriod, contractForm.intermentContainerTypeId === '' ? undefined : contractForm.intermentContainerTypeId, diff --git a/database/updateFee.js b/database/updateFee.js index 2ca39bd8..4b47a76b 100644 --- a/database/updateFee.js +++ b/database/updateFee.js @@ -22,7 +22,7 @@ export default async function updateFee(feeForm, user) { and feeId = ?`) .run(feeForm.feeCategoryId, feeForm.feeName, feeForm.feeDescription, feeForm.feeAccount, feeForm.contractTypeId === '' ? undefined : feeForm.contractTypeId, feeForm.burialSiteTypeId === '' ? undefined : feeForm.burialSiteTypeId, feeForm.feeAmount === undefined || feeForm.feeAmount === '' ? 0 - : feeForm.feeAmount, feeForm.feeFunction ?? undefined, feeForm.taxAmount ?? undefined, feeForm.taxPercentage ?? undefined, feeForm.includeQuantity === '' ? 0 : 1, feeForm.quantityUnit, feeForm.isRequired === '' ? 0 : 1, user.userName, Date.now(), feeForm.feeId); + : feeForm.feeAmount, feeForm.feeFunction ?? undefined, feeForm.taxAmount === '' ? undefined : feeForm.taxAmount, feeForm.taxPercentage === '' ? undefined : feeForm.taxPercentage, feeForm.includeQuantity === '' ? 0 : 1, feeForm.quantityUnit, feeForm.isRequired === '' ? 0 : 1, user.userName, Date.now(), feeForm.feeId); database.release(); return result.changes > 0; } diff --git a/database/updateFee.ts b/database/updateFee.ts index d68ebfa9..959e833f 100644 --- a/database/updateFee.ts +++ b/database/updateFee.ts @@ -55,8 +55,8 @@ export default async function updateFee( ? 0 : feeForm.feeAmount, feeForm.feeFunction ?? undefined, - feeForm.taxAmount ?? undefined, - feeForm.taxPercentage ?? undefined, + feeForm.taxAmount === '' ? undefined : feeForm.taxAmount, + feeForm.taxPercentage === '' ? undefined : feeForm.taxPercentage, feeForm.includeQuantity === '' ? 0 : 1, feeForm.quantityUnit, feeForm.isRequired === '' ? 0 : 1, diff --git a/helpers/functions.cache.js b/helpers/functions.cache.js index 52def610..09a6748f 100644 --- a/helpers/functions.cache.js +++ b/helpers/functions.cache.js @@ -243,7 +243,9 @@ export function clearCacheByTableName(tableName, relayMessage = true) { } } } - catch { } + catch { + // ignore + } } process.on('message', (message) => { if (message.messageType === 'clearCache' && message.pid !== process.pid) { diff --git a/helpers/functions.cache.ts b/helpers/functions.cache.ts index f98950fb..02e20ac2 100644 --- a/helpers/functions.cache.ts +++ b/helpers/functions.cache.ts @@ -418,7 +418,9 @@ export function clearCacheByTableName( process.send(workerMessage) } } - } catch {} + } catch { + // ignore + } } process.on('message', (message: WorkerMessage) => { diff --git a/package.json b/package.json index 39977882..b5edde54 100644 --- a/package.json +++ b/package.json @@ -18,8 +18,7 @@ "test": "cross-env NODE_ENV=dev DEBUG=sunrise:* TEST_DATABASES=true mocha --timeout 30000 --exit", "test:startup": "cross-env NODE_ENV=dev DEBUG=sunrise:* TEST_DATABASES=true STARTUP_TEST=true node ./bin/www.js", "coverage": "cross-env NODE_ENV=dev DEBUG=sunrise:* TEST_DATABASES=true c8 --reporter=lcov --reporter=text --reporter=text-summary mocha --timeout 30000 --exit", - "temp:legacy:importFromCsv": "cross-env NODE_ENV=dev DEBUG=sunrise:* TEST_DATABASES=true node ./temp/legacy.importFromCsv.js", - "temp:so:exportMaps": "node ./temp/so.exportMaps.js" + "temp:legacyImportFromCsv": "cross-env NODE_ENV=dev DEBUG=sunrise:* TEST_DATABASES=true node ./temp/legacyImportFromCsv/index.js" }, "repository": { "type": "git", diff --git a/public/html/contract-addInterment.html b/public/html/contract-addInterment.html index 7541cf76..58e2b614 100644 --- a/public/html/contract-addInterment.html +++ b/public/html/contract-addInterment.html @@ -174,6 +174,18 @@ + +
+
+ +
+
+
+ +
+
+
diff --git a/public/html/contract-editInterment.html b/public/html/contract-editInterment.html index 6b779e4f..235d7172 100644 --- a/public/html/contract-editInterment.html +++ b/public/html/contract-editInterment.html @@ -181,6 +181,18 @@
+ +
+
+ +
+
+
+ +
+
+
diff --git a/public/javascripts/contract.editInterments.js b/public/javascripts/contract.editInterments.js index 8bae23eb..9e24b66f 100644 --- a/public/javascripts/contract.editInterments.js +++ b/public/javascripts/contract.editInterments.js @@ -4,6 +4,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); const contractId = document.querySelector('#contract--contractId').value; let contractInterments = exports.contractInterments; delete exports.contractInterments; + const deathAgePeriods = exports.deathAgePeriods; + delete exports.deathAgePeriods; const intermentContainerTypes = exports.intermentContainerTypes; delete exports.intermentContainerTypes; function openEditContractInterment(clickEvent) { @@ -66,6 +68,28 @@ Object.defineProperty(exports, "__esModule", { value: true }); modalElement .querySelector('#contractIntermentEdit--deathPlace') ?.setAttribute('value', contractInterment.deathPlace ?? ''); + modalElement + .querySelector('#contractIntermentEdit--deathAge') + ?.setAttribute('value', contractInterment.deathAge?.toString() ?? ''); + const deathAgePeriodElement = modalElement.querySelector('#contractIntermentEdit--deathAgePeriod'); + let deathAgePeriodIsFound = false; + for (const deathAgePeriod of deathAgePeriods) { + const optionElement = document.createElement('option'); + optionElement.value = deathAgePeriod; + optionElement.text = deathAgePeriod; + if (deathAgePeriod === contractInterment.deathAgePeriod) { + optionElement.selected = true; + deathAgePeriodIsFound = true; + } + deathAgePeriodElement.append(optionElement); + } + if (!deathAgePeriodIsFound) { + const optionElement = document.createElement('option'); + optionElement.value = contractInterment.deathAgePeriod ?? ''; + optionElement.text = contractInterment.deathAgePeriod ?? '(Not Set)'; + optionElement.selected = true; + deathAgePeriodElement.append(optionElement); + } const containerTypeElement = modalElement.querySelector('#contractIntermentEdit--intermentContainerTypeId'); let containerTypeIsFound = false; for (const containerType of intermentContainerTypes) { @@ -131,6 +155,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); } }); } + // eslint-disable-next-line complexity function renderContractInterments() { const containerElement = document.querySelector('#container--contractInterments'); if (contractInterments.length === 0) { @@ -180,6 +205,15 @@ Object.defineProperty(exports, "__esModule", { value: true }); ${cityssm.escapeHTML(interment.deathPlace ?? '(No Death Place)')}
+
+
+ Age: +
+
+ ${cityssm.escapeHTML(interment.deathAge === undefined ? '(No Age)' : interment.deathAge.toString())} + ${cityssm.escapeHTML(interment.deathAgePeriod ?? '')} +
+
Container: @@ -229,6 +263,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); modalElement .querySelector('#contractIntermentAdd--contractId') ?.setAttribute('value', contractId); + const deathAgePeriodElement = modalElement.querySelector('#contractIntermentAdd--deathAgePeriod'); + for (const deathAgePeriod of deathAgePeriods) { + const optionElement = document.createElement('option'); + optionElement.value = deathAgePeriod; + optionElement.text = deathAgePeriod; + deathAgePeriodElement.append(optionElement); + } const containerTypeElement = modalElement.querySelector('#contractIntermentAdd--intermentContainerTypeId'); for (const containerType of intermentContainerTypes) { const optionElement = document.createElement('option'); diff --git a/public/javascripts/contract.editInterments.ts b/public/javascripts/contract.editInterments.ts index 6b5d0248..25f1df64 100644 --- a/public/javascripts/contract.editInterments.ts +++ b/public/javascripts/contract.editInterments.ts @@ -17,6 +17,9 @@ declare const exports: Record let contractInterments = exports.contractInterments as ContractInterment[] delete exports.contractInterments + const deathAgePeriods = exports.deathAgePeriods as string[] + delete exports.deathAgePeriods + const intermentContainerTypes = exports.intermentContainerTypes as IntermentContainerType[] delete exports.intermentContainerTypes @@ -112,6 +115,37 @@ declare const exports: Record .querySelector('#contractIntermentEdit--deathPlace') ?.setAttribute('value', contractInterment.deathPlace ?? '') + modalElement + .querySelector('#contractIntermentEdit--deathAge') + ?.setAttribute('value', contractInterment.deathAge?.toString() ?? '') + + const deathAgePeriodElement = modalElement.querySelector( + '#contractIntermentEdit--deathAgePeriod' + ) as HTMLSelectElement + + let deathAgePeriodIsFound = false + + for (const deathAgePeriod of deathAgePeriods) { + const optionElement = document.createElement('option') + optionElement.value = deathAgePeriod + optionElement.text = deathAgePeriod + + if (deathAgePeriod === contractInterment.deathAgePeriod) { + optionElement.selected = true + deathAgePeriodIsFound = true + } + + deathAgePeriodElement.append(optionElement) + } + + if (!deathAgePeriodIsFound) { + const optionElement = document.createElement('option') + optionElement.value = contractInterment.deathAgePeriod ?? '' + optionElement.text = contractInterment.deathAgePeriod ?? '(Not Set)' + optionElement.selected = true + deathAgePeriodElement.append(optionElement) + } + const containerTypeElement = modalElement.querySelector( '#contractIntermentEdit--intermentContainerTypeId' ) as HTMLSelectElement @@ -211,6 +245,7 @@ declare const exports: Record }) } + // eslint-disable-next-line complexity function renderContractInterments(): void { const containerElement = document.querySelector( '#container--contractInterments' @@ -269,6 +304,15 @@ declare const exports: Record ${cityssm.escapeHTML(interment.deathPlace ?? '(No Death Place)')}
+
+
+ Age: +
+
+ ${cityssm.escapeHTML(interment.deathAge === undefined ? '(No Age)' : interment.deathAge.toString())} + ${cityssm.escapeHTML(interment.deathAgePeriod ?? '')} +
+
Container: @@ -335,6 +379,18 @@ declare const exports: Record .querySelector('#contractIntermentAdd--contractId') ?.setAttribute('value', contractId) + const deathAgePeriodElement = modalElement.querySelector( + '#contractIntermentAdd--deathAgePeriod' + ) as HTMLSelectElement + + for (const deathAgePeriod of deathAgePeriods) { + const optionElement = document.createElement('option') + optionElement.value = deathAgePeriod + optionElement.text = deathAgePeriod + + deathAgePeriodElement.append(optionElement) + } + const containerTypeElement = modalElement.querySelector( '#contractIntermentAdd--intermentContainerTypeId' ) as HTMLSelectElement diff --git a/temp/legacy.importFromCSV.js b/temp/legacy.importFromCSV.js deleted file mode 100644 index 905788fb..00000000 --- a/temp/legacy.importFromCSV.js +++ /dev/null @@ -1,977 +0,0 @@ -/* eslint-disable max-lines */ -import fs from 'node:fs'; -import { dateIntegerToString, dateToString } from '@cityssm/utils-datetime'; -import sqlite from 'better-sqlite3'; -import papa from 'papaparse'; -import { sunriseDB as databasePath } from '../helpers/database.helpers.js'; -import addBurialSite from '../database/addBurialSite.js'; -import addContract from '../database/addContract.js'; -import addContractComment from '../database/addContractComment.js'; -import addContractFee from '../database/addContractFee.js'; -import addContractOccupant from '../database/addContractOccupant.js'; -import addContractTransaction from '../database/addContractTransaction.js'; -import addCemetery from '../database/addCemetery.js'; -import addOrUpdateContractField from '../database/addOrUpdateContractField.js'; -import addWorkOrder from '../database/addWorkOrder.js'; -import addWorkOrderBurialSite from '../database/addWorkOrderBurialSite.js'; -import addWorkOrderContract from '../database/addWorkOrderContract.js'; -import addWorkOrderMilestone from '../database/addWorkOrderMilestone.js'; -import closeWorkOrder from '../database/closeWorkOrder.js'; -import getBurialSite from '../database/getBurialSite.js'; -import getContracts from '../database/getContracts.js'; -import getCemeteryFromDatabase from '../database/getCemetery.js'; -import getWorkOrder, { getWorkOrderByWorkOrderNumber } from '../database/getWorkOrder.js'; -import reopenWorkOrder from '../database/reopenWorkOrder.js'; -import { updateBurialSiteStatus } from '../database/updateBurialSite.js'; -import * as importData from './legacy.importFromCsv.data.js'; -import * as importIds from './legacy.importFromCsv.ids.js'; -const user = { - userName: 'import.unix', - userProperties: { - canUpdate: true, - isAdmin: false, - apiKey: '' - } -}; -function purgeTables() { - console.time('purgeTables'); - const tablesToPurge = [ - 'WorkOrderMilestones', - 'WorkOrderComments', - 'WorkOrderBurialSites', - 'WorkOrderContracts', - 'WorkOrders', - 'ContractTransactions', - 'ContractFees', - 'ContractFields', - 'ContractComments', - 'ContractInterments', - 'Contracts', - 'BurialSiteFields', - 'BurialSiteComments', - 'BurialSites' - ]; - const database = sqlite(databasePath); - for (const tableName of tablesToPurge) { - database.prepare(`delete from ${tableName}`).run(); - database - .prepare('delete from sqlite_sequence where name = ?') - .run(tableName); - } - database.close(); - console.timeEnd('purgeTables'); -} -function purgeConfigTables() { - console.time('purgeConfigTables'); - const database = sqlite(databasePath); - database.prepare('delete from Cemeteries').run(); - database.prepare("delete from sqlite_sequence where name in ('Cemeteries')").run(); - database.close(); - console.timeEnd('purgeConfigTables'); -} -function getCemeteryByDescription(cemeteryDescription) { - const database = sqlite(databasePath, { - readonly: true - }); - const cemetery = database - .prepare('select * from Cemeteries where cemeteryDescription = ?') - .get(cemeteryDescription); - database.close(); - return cemetery; -} -function formatDateString(year, month, day) { - const formattedYear = `0000${year}`.slice(-4); - const formattedMonth = `00${month}`.slice(-2); - const formattedDay = `00${day}`.slice(-2); - return `${formattedYear}-${formattedMonth}-${formattedDay}`; -} -function formatTimeString(hour, minute) { - const formattedHour = `00${hour}`.slice(-2); - const formattedMinute = `00${minute}`.slice(-2); - return `${formattedHour}:${formattedMinute}`; -} -const cemeteryToCemeteryName = { - '00': 'Crematorium', - GC: 'New Greenwood - Columbarium', - HC: 'Holy Sepulchre - Columbarium', - HS: 'Holy Sepulchre', - MA: 'Holy Sepulchre - Mausoleum', - NG: 'New Greenwood', - NW: 'Niche Wall', - OG: 'Old Greenwood', - PG: 'Pine Grove', - UG: 'New Greenwood - Urn Garden', - WK: 'West Korah' -}; -const cemeteryCache = new Map(); -async function getCemetery(dataRow) { - const mapCacheKey = dataRow.cemetery; - /* - if (masterRow.CM_CEMETERY === "HS" && - (masterRow.CM_BLOCK === "F" || masterRow.CM_BLOCK === "G" || masterRow.CM_BLOCK === "H" || masterRow.CM_BLOCK === "J")) { - mapCacheKey += "-" + masterRow.CM_BLOCK; - } - */ - if (cemeteryCache.has(mapCacheKey)) { - return cemeteryCache.get(mapCacheKey); - } - let cemetery = getCemeteryByDescription(mapCacheKey); - if (cemetery === undefined) { - console.log(`Creating cemetery: ${dataRow.cemetery}`); - const cemeteryId = await addCemetery({ - cemeteryName: cemeteryToCemeteryName[dataRow.cemetery] ?? dataRow.cemetery, - cemeteryDescription: dataRow.cemetery, - cemeterySvg: '', - cemeteryLatitude: '', - cemeteryLongitude: '', - cemeteryAddress1: '', - cemeteryAddress2: '', - cemeteryCity: 'Sault Ste. Marie', - cemeteryProvince: 'ON', - cemeteryPostalCode: '', - cemeteryPhoneNumber: '' - }, user); - cemetery = (await getCemeteryFromDatabase(cemeteryId)); - } - cemeteryCache.set(mapCacheKey, cemetery); - return cemetery; -} -async function importFromMasterCSV() { - console.time('importFromMasterCSV'); - let masterRow; - const rawData = fs.readFileSync('./temp/CMMASTER.csv').toString(); - const cmmaster = papa.parse(rawData, { - delimiter: ',', - header: true, - skipEmptyLines: true - }); - for (const parseError of cmmaster.errors) { - console.log(parseError); - } - try { - for (masterRow of cmmaster.data) { - const cemetery = await getCemetery({ - cemetery: masterRow.CM_CEMETERY - }); - const burialSiteTypeId = importIds.getburialSiteTypeId({ - cemetery: masterRow.CM_CEMETERY - }); - let burialSiteId; - if (masterRow.CM_CEMETERY !== '00') { - burialSiteId = await addBurialSite({ - burialSiteName, - burialSiteTypeId, - burialSiteStatusId: importIds.availableBurialSiteStatusId, - cemeteryId: cemetery.cemeteryId, - cemeterySvgId: '', - burialSiteLatitude: '', - burialSiteLongitude: '' - }, user); - } - let preneedcontractStartDateString; - let preneedcontractId; - if (masterRow.CM_PRENEED_OWNER !== '' || masterRow.CM_STATUS === 'P') { - preneedcontractStartDateString = formatDateString(masterRow.CM_PURCHASE_YR, masterRow.CM_PURCHASE_MON, masterRow.CM_PURCHASE_DAY); - let contractEndDateString = ''; - if (masterRow.CM_INTERMENT_YR !== '' && - masterRow.CM_INTERMENT_YR !== '0') { - contractEndDateString = formatDateString(masterRow.CM_INTERMENT_YR, masterRow.CM_INTERMENT_MON, masterRow.CM_INTERMENT_DAY); - } - // if purchase date unavailable - if (preneedcontractStartDateString === '0000-00-00' && - contractEndDateString !== '') { - preneedcontractStartDateString = contractEndDateString; - } - // if end date unavailable - if (preneedcontractStartDateString === '0000-00-00' && - masterRow.CM_DEATH_YR !== '' && - masterRow.CM_DEATH_YR !== '0') { - preneedcontractStartDateString = formatDateString(masterRow.CM_DEATH_YR, masterRow.CM_DEATH_MON, masterRow.CM_DEATH_DAY); - // if death took place, and there's no preneed end date - if (contractEndDateString === '0000-00-00' || - contractEndDateString === '') { - contractEndDateString = preneedcontractStartDateString; - } - } - if (preneedcontractStartDateString === '' || - preneedcontractStartDateString === '0000-00-00') { - preneedcontractStartDateString = '0001-01-01'; - } - preneedcontractId = await addContract({ - contractTypeId: importIds.preneedContractType.contractTypeId, - burialSiteId: burialSiteId ?? '', - contractStartDateString: preneedcontractStartDateString, - contractEndDateString, - contractTypeFieldIds: '' - }, user); - const occupantPostalCode = `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim(); - await addContractOccupant({ - contractId: preneedcontractId, - lotOccupantTypeId: importIds.preneedOwnerLotOccupantTypeId, - occupantName: masterRow.CM_PRENEED_OWNER, - occupantFamilyName: '', - occupantAddress1: masterRow.CM_ADDRESS, - occupantAddress2: '', - occupantCity: masterRow.CM_CITY, - occupantProvince: masterRow.CM_PROV, - occupantPostalCode, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, user); - if (masterRow.CM_REMARK1 !== '') { - await addContractComment({ - contractId: preneedcontractId, - contractCommentDateString: preneedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK1 - }, user); - } - if (masterRow.CM_REMARK2 !== '') { - await addContractComment({ - contractId: preneedcontractId, - contractCommentDateString: preneedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK2 - }, user); - } - if (masterRow.CM_WORK_ORDER.trim() !== '') { - await addContractComment({ - contractId: preneedcontractId, - contractCommentDateString: preneedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: `Imported Contract #${masterRow.CM_WORK_ORDER}` - }, user); - } - if (contractEndDateString === '') { - await updateBurialSiteStatus(burialSiteId ?? '', importIds.reservedburialSiteStatusId, user); - } - } - let deceasedcontractStartDateString; - let deceasedcontractId; - if (masterRow.CM_DECEASED_NAME !== '') { - deceasedcontractStartDateString = formatDateString(masterRow.CM_INTERMENT_YR, masterRow.CM_INTERMENT_MON, masterRow.CM_INTERMENT_DAY); - // if interment date unavailable - if (deceasedcontractStartDateString === '0000-00-00' && - masterRow.CM_DEATH_YR !== '' && - masterRow.CM_DEATH_YR !== '0') { - deceasedcontractStartDateString = formatDateString(masterRow.CM_DEATH_YR, masterRow.CM_DEATH_MON, masterRow.CM_DEATH_DAY); - } - if (deceasedcontractStartDateString === '' || - deceasedcontractStartDateString === '0000-00-00') { - deceasedcontractStartDateString = '0001-01-01'; - } - const deceasedcontractEndDateString = burialSiteId - ? '' - : deceasedcontractStartDateString; - const contractType = burialSiteId - ? importIds.deceasedContractType - : importIds.cremationContractType; - deceasedcontractId = await addContract({ - contractTypeId: contractType.contractTypeId, - burialSiteId: burialSiteId ?? '', - contractStartDateString: deceasedcontractStartDateString, - contractEndDateString: deceasedcontractEndDateString, - contractTypeFieldIds: '' - }, user); - const deceasedPostalCode = `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim(); - await addContractOccupant({ - contractId: deceasedcontractId, - lotOccupantTypeId: importIds.deceasedLotOccupantTypeId, - occupantName: masterRow.CM_DECEASED_NAME, - occupantFamilyName: '', - occupantAddress1: masterRow.CM_ADDRESS, - occupantAddress2: '', - occupantCity: masterRow.CM_CITY, - occupantProvince: masterRow.CM_PROV, - occupantPostalCode: deceasedPostalCode, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, user); - if (masterRow.CM_DEATH_YR !== '') { - const contractFieldValue = formatDateString(masterRow.CM_DEATH_YR, masterRow.CM_DEATH_MON, masterRow.CM_DEATH_DAY); - await addOrUpdateContractField({ - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Death Date').contractTypeFieldId, - contractFieldValue - }, user); - } - if (masterRow.CM_AGE !== '') { - await addOrUpdateContractField({ - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Death Age').contractTypeFieldId, - contractFieldValue: masterRow.CM_AGE - }, user); - } - if (masterRow.CM_PERIOD !== '') { - const period = importData.getDeathAgePeriod(masterRow.CM_PERIOD); - await addOrUpdateContractField({ - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Death Age Period').contractTypeFieldId, - contractFieldValue: period - }, user); - } - if (masterRow.CM_FUNERAL_HOME !== '') { - const funeralHomeOccupant = importData.getFuneralHomeLotOccupancyOccupantData(masterRow.CM_FUNERAL_HOME); - await addContractOccupant({ - contractId: deceasedcontractId, - lotOccupantTypeId: funeralHomeOccupant.lotOccupantTypeId ?? '', - occupantName: funeralHomeOccupant.occupantName ?? '', - occupantFamilyName: '', - occupantAddress1: funeralHomeOccupant.occupantAddress1 ?? '', - occupantAddress2: funeralHomeOccupant.occupantAddress2 ?? '', - occupantCity: funeralHomeOccupant.occupantCity ?? '', - occupantProvince: funeralHomeOccupant.occupantProvince ?? '', - occupantPostalCode: funeralHomeOccupant.occupantPostalCode ?? '', - occupantPhoneNumber: funeralHomeOccupant.occupantPhoneNumber ?? '', - occupantEmailAddress: funeralHomeOccupant.occupantEmailAddress ?? '' - }, user); - /* - addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: allContractTypeFields.find( - (contractTypeField) => { - return contractTypeField.contractTypeField === "Funeral Home"; - } - ).contractTypeFieldId, - contractFieldValue: masterRow.CM_FUNERAL_HOME - }, - user - ); - */ - } - if (masterRow.CM_FUNERAL_YR !== '') { - const contractFieldValue = formatDateString(masterRow.CM_FUNERAL_YR, masterRow.CM_FUNERAL_MON, masterRow.CM_FUNERAL_DAY); - await addOrUpdateContractField({ - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Funeral Date').contractTypeFieldId, - contractFieldValue - }, user); - } - if (contractType.contractType !== 'Cremation') { - if (masterRow.CM_CONTAINER_TYPE !== '') { - await addOrUpdateContractField({ - contractId: deceasedcontractId, - contractTypeFieldId: contractType.contractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Container Type').contractTypeFieldId, - contractFieldValue: masterRow.CM_CONTAINER_TYPE - }, user); - } - if (masterRow.CM_COMMITTAL_TYPE !== '') { - let commitalType = masterRow.CM_COMMITTAL_TYPE; - if (commitalType === 'GS') { - commitalType = 'Graveside'; - } - await addOrUpdateContractField({ - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Committal Type').contractTypeFieldId, - contractFieldValue: commitalType - }, user); - } - } - if (masterRow.CM_REMARK1 !== '') { - await addContractComment({ - contractId: deceasedcontractId, - contractCommentDateString: deceasedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK1 - }, user); - } - if (masterRow.CM_REMARK2 !== '') { - await addContractComment({ - contractId: deceasedcontractId, - contractCommentDateString: deceasedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK2 - }, user); - } - if (masterRow.CM_WORK_ORDER.trim() !== '') { - await addContractComment({ - contractId: deceasedcontractId, - contractCommentDateString: deceasedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: `Imported Contract #${masterRow.CM_WORK_ORDER}` - }, user); - } - await updateBurialSiteStatus(burialSiteId ?? '', importIds.takenburialSiteStatusId, user); - if (masterRow.CM_PRENEED_OWNER !== '') { - await addContractOccupant({ - contractId: deceasedcontractId, - lotOccupantTypeId: importIds.preneedOwnerLotOccupantTypeId, - occupantName: masterRow.CM_PRENEED_OWNER, - occupantFamilyName: '', - occupantAddress1: '', - occupantAddress2: '', - occupantCity: '', - occupantProvince: '', - occupantPostalCode: '', - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, user); - } - } - } - } - catch (error) { - console.error(error); - console.log(masterRow); - } - console.timeEnd('importFromMasterCSV'); -} -async function importFromPrepaidCSV() { - console.time('importFromPrepaidCSV'); - let prepaidRow; - const rawData = fs.readFileSync('./temp/CMPRPAID.csv').toString(); - const cmprpaid = papa.parse(rawData, { - delimiter: ',', - header: true, - skipEmptyLines: true - }); - for (const parseError of cmprpaid.errors) { - console.log(parseError); - } - try { - for (prepaidRow of cmprpaid.data) { - if (!prepaidRow.CMPP_PREPAID_FOR_NAME) { - continue; - } - let cemetery = prepaidRow.CMPP_CEMETERY; - if (cemetery === '.m') { - cemetery = 'HC'; - } - let lot; - if (cemetery !== '') { - const map = await getCemetery({ - cemetery - }); - const burialSiteName = importData.buildLotName({ - cemetery, - block: prepaidRow.CMPP_BLOCK, - range1: prepaidRow.CMPP_RANGE1, - range2: prepaidRow.CMPP_RANGE2, - lot1: prepaidRow.CMPP_LOT1, - lot2: prepaidRow.CMPP_LOT2, - grave1: prepaidRow.CMPP_GRAVE1, - grave2: prepaidRow.CMPP_GRAVE2, - interment: prepaidRow.CMPP_INTERMENT - }); - lot = await getBurialSiteByLotName(burialSiteName); - if (!lot) { - const burialSiteTypeId = importIds.getburialSiteTypeId({ - cemetery - }); - const burialSiteId = await addBurialSite({ - burialSiteName, - burialSiteTypeId, - burialSiteStatusId: importIds.reservedburialSiteStatusId, - cemeteryId: map.cemeteryId ?? '', - mapKey: burialSiteName.includes(',') ? burialSiteName.split(',')[0] : burialSiteName, - burialSiteLatitude: '', - burialSiteLongitude: '' - }, user); - lot = await getBurialSite(burialSiteId); - } - } - if (lot && - lot.burialSiteStatusId === importIds.availableburialSiteStatusId) { - await updateBurialSiteStatus(lot.burialSiteId, importIds.reservedburialSiteStatusId, user); - } - const contractStartDateString = formatDateString(prepaidRow.CMPP_PURCH_YR, prepaidRow.CMPP_PURCH_MON, prepaidRow.CMPP_PURCH_DAY); - let contractId; - if (lot) { - const possibleLotOccupancies = await getContracts({ - burialSiteId: lot.burialSiteId, - contractTypeId: importIds.preneedContractType.contractTypeId, - deceasedName: prepaidRow.CMPP_PREPAID_FOR_NAME, - contractStartDateString - }, { - includeOccupants: false, - includeFees: false, - includeTransactions: false, - limit: -1, - offset: 0 - }); - if (possibleLotOccupancies.lotOccupancies.length > 0) { - contractId = - possibleLotOccupancies.lotOccupancies[0].contractId; - } - } - contractId ||= await addContract({ - burialSiteId: lot ? lot.burialSiteId : '', - contractTypeId: importIds.preneedContractType.contractTypeId, - contractStartDateString, - contractEndDateString: '' - }, user); - await addContractOccupant({ - contractId, - lotOccupantTypeId: importIds.preneedOwnerLotOccupantTypeId, - occupantName: prepaidRow.CMPP_PREPAID_FOR_NAME, - occupantFamilyName: '', - occupantAddress1: prepaidRow.CMPP_ADDRESS, - occupantAddress2: '', - occupantCity: prepaidRow.CMPP_CITY, - occupantProvince: prepaidRow.CMPP_PROV.slice(0, 2), - occupantPostalCode: `${prepaidRow.CMPP_POSTAL1} ${prepaidRow.CMPP_POSTAL2}`, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, user); - if (prepaidRow.CMPP_ARRANGED_BY_NAME) { - await addContractOccupant({ - contractId, - lotOccupantTypeId: importIds.purchaserLotOccupantTypeId, - occupantName: prepaidRow.CMPP_ARRANGED_BY_NAME, - occupantFamilyName: '', - occupantAddress1: '', - occupantAddress2: '', - occupantCity: '', - occupantProvince: '', - occupantPostalCode: '', - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, user); - } - if (prepaidRow.CMPP_FEE_GRAV_SD !== '0.0') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_GRAV_SD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_GRAV_SD, - taxAmount: prepaidRow.CMPP_GST_GRAV_SD - }, user); - } - if (prepaidRow.CMPP_FEE_GRAV_DD !== '0.0') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_GRAV_DD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_GRAV_DD, - taxAmount: prepaidRow.CMPP_GST_GRAV_DD - }, user); - } - if (prepaidRow.CMPP_FEE_CHAP_SD !== '0.0') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_CHAP_SD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_CHAP_SD, - taxAmount: prepaidRow.CMPP_GST_CHAP_SD - }, user); - } - if (prepaidRow.CMPP_FEE_CHAP_DD !== '0.0') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_CHAP_DD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_CHAP_DD, - taxAmount: prepaidRow.CMPP_GST_CHAP_DD - }, user); - } - if (prepaidRow.CMPP_FEE_ENTOMBMENT !== '0.0') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_ENTOMBMENT'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_ENTOMBMENT, - taxAmount: prepaidRow.CMPP_GST_ENTOMBMENT - }, user); - } - if (prepaidRow.CMPP_FEE_CREM !== '0.0') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_CREM'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_CREM, - taxAmount: prepaidRow.CMPP_GST_CREM - }, user); - } - if (prepaidRow.CMPP_FEE_NICHE !== '0.0') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_NICHE'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_NICHE, - taxAmount: prepaidRow.CMPP_GST_NICHE - }, user); - } - if (prepaidRow.CMPP_FEE_DISINTERMENT !== '0.0' && - prepaidRow.CMPP_FEE_DISINTERMENT !== '20202.02') { - await addContractFee({ - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_DISINTERMENT'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_DISINTERMENT, - taxAmount: prepaidRow.CMPP_GST_DISINTERMENT - }, user); - } - const transactionAmount = Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_SD) + - Number.parseFloat(prepaidRow.CMPP_GST_GRAV_SD) + - Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_DD) + - Number.parseFloat(prepaidRow.CMPP_GST_GRAV_DD) + - Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_SD) + - Number.parseFloat(prepaidRow.CMPP_GST_CHAP_SD) + - Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_DD) + - Number.parseFloat(prepaidRow.CMPP_GST_CHAP_DD) + - Number.parseFloat(prepaidRow.CMPP_FEE_ENTOMBMENT) + - Number.parseFloat(prepaidRow.CMPP_GST_ENTOMBMENT) + - Number.parseFloat(prepaidRow.CMPP_FEE_CREM) + - Number.parseFloat(prepaidRow.CMPP_GST_CREM) + - Number.parseFloat(prepaidRow.CMPP_FEE_NICHE) + - Number.parseFloat(prepaidRow.CMPP_GST_NICHE) + - Number.parseFloat(prepaidRow.CMPP_FEE_DISINTERMENT === '20202.02' - ? '0' - : prepaidRow.CMPP_FEE_DISINTERMENT) + - Number.parseFloat(prepaidRow.CMPP_GST_DISINTERMENT === '20202.02' - ? '0' - : prepaidRow.CMPP_GST_DISINTERMENT); - await addContractTransaction({ - contractId, - externalReceiptNumber: '', - transactionAmount, - transactionDateString: contractStartDateString, - transactionNote: `Order Number: ${prepaidRow.CMPP_ORDER_NO}` - }, user); - if (prepaidRow.CMPP_REMARK1) { - await addContractComment({ - contractId, - contractCommentDateString: contractStartDateString, - contractComment: prepaidRow.CMPP_REMARK1 - }, user); - } - if (prepaidRow.CMPP_REMARK2) { - await addContractComment({ - contractId, - contractCommentDateString: contractStartDateString, - contractComment: prepaidRow.CMPP_REMARK2 - }, user); - } - } - } - catch (error) { - console.error(error); - console.log(prepaidRow); - } - console.timeEnd('importFromPrepaidCSV'); -} -async function importFromWorkOrderCSV() { - console.time('importFromWorkOrderCSV'); - let workOrderRow; - const rawData = fs.readFileSync('./temp/CMWKORDR.csv').toString(); - const cmwkordr = papa.parse(rawData, { - delimiter: ',', - header: true, - skipEmptyLines: true - }); - for (const parseError of cmwkordr.errors) { - console.log(parseError); - } - const currentDateString = dateToString(new Date()); - try { - for (workOrderRow of cmwkordr.data) { - const workOrderNumber = `000000${workOrderRow.WO_WORK_ORDER}`.slice(-6); - let workOrder = await getWorkOrderByWorkOrderNumber(workOrderNumber); - const workOrderOpenDateString = dateIntegerToString(Number.parseInt(workOrderRow.WO_INITIATION_DATE, 10)); - if (workOrder) { - if (workOrder.workOrderCloseDate) { - await reopenWorkOrder(workOrder.workOrderId, user); - delete workOrder.workOrderCloseDate; - delete workOrder.workOrderCloseDateString; - } - } - else { - const workOrderId = await addWorkOrder({ - workOrderNumber, - workOrderTypeId: importIds.workOrderTypeId, - workOrderDescription: `${workOrderRow.WO_REMARK1} ${workOrderRow.WO_REMARK2} ${workOrderRow.WO_REMARK3}`.trim(), - workOrderOpenDateString - }, user); - workOrder = await getWorkOrder(workOrderId, { - includeLotsAndLotOccupancies: true, - includeComments: true, - includeMilestones: true - }); - } - let lot; - if (workOrderRow.WO_CEMETERY !== '00') { - const burialSiteName = importData.buildLotName({ - cemetery: workOrderRow.WO_CEMETERY, - block: workOrderRow.WO_BLOCK, - range1: workOrderRow.WO_RANGE1, - range2: workOrderRow.WO_RANGE2, - lot1: workOrderRow.WO_LOT1, - lot2: workOrderRow.WO_LOT2, - grave1: workOrderRow.WO_GRAVE1, - grave2: workOrderRow.WO_GRAVE2, - interment: workOrderRow.WO_INTERMENT - }); - lot = await getBurialSiteByLotName(burialSiteName); - if (lot) { - await updateBurialSiteStatus(lot.burialSiteId, importIds.takenburialSiteStatusId, user); - } - else { - const map = await getCemetery({ cemetery: workOrderRow.WO_CEMETERY }); - const burialSiteTypeId = importIds.getburialSiteTypeId({ - cemetery: workOrderRow.WO_CEMETERY - }); - const burialSiteId = await addBurialSite({ - cemeteryId: map.cemeteryId, - burialSiteName, - mapKey: burialSiteName.includes(',') ? burialSiteName.split(',')[0] : burialSiteName, - burialSiteStatusId: importIds.takenburialSiteStatusId, - burialSiteTypeId, - burialSiteLatitude: '', - burialSiteLongitude: '' - }, user); - lot = await getBurialSite(burialSiteId); - } - const workOrderContainsLot = workOrder.workOrderLots.find((possibleLot) => (possibleLot.burialSiteId = lot.burialSiteId)); - if (!workOrderContainsLot) { - await addWorkOrderBurialSite({ - workOrderId: workOrder.workOrderId, - burialSiteId: lot.burialSiteId - }, user); - workOrder.workOrderLots.push(lot); - } - } - let contractStartDateString = workOrderOpenDateString; - if (workOrderRow.WO_INTERMENT_YR) { - contractStartDateString = formatDateString(workOrderRow.WO_INTERMENT_YR, workOrderRow.WO_INTERMENT_MON, workOrderRow.WO_INTERMENT_DAY); - } - const contractType = lot - ? importIds.deceasedContractType - : importIds.cremationContractType; - const contractId = await addContract({ - burialSiteId: lot ? lot.burialSiteId : '', - contractTypeId: contractType.contractTypeId, - contractStartDateString, - contractEndDateString: '' - }, user); - await addContractOccupant({ - contractId, - lotOccupantTypeId: importIds.deceasedLotOccupantTypeId, - occupantName: workOrderRow.WO_DECEASED_NAME, - occupantFamilyName: '', - occupantAddress1: workOrderRow.WO_ADDRESS, - occupantAddress2: '', - occupantCity: workOrderRow.WO_CITY, - occupantProvince: workOrderRow.WO_PROV.slice(0, 2), - occupantPostalCode: `${workOrderRow.WO_POST1} ${workOrderRow.WO_POST2}`, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, user); - if (workOrderRow.WO_DEATH_YR !== '') { - const contractFieldValue = formatDateString(workOrderRow.WO_DEATH_YR, workOrderRow.WO_DEATH_MON, workOrderRow.WO_DEATH_DAY); - await addOrUpdateContractField({ - contractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Death Date').contractTypeFieldId, - contractFieldValue - }, user); - } - if (workOrderRow.WO_DEATH_PLACE !== '') { - await addOrUpdateContractField({ - contractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Death Place').contractTypeFieldId, - contractFieldValue: workOrderRow.WO_DEATH_PLACE - }, user); - } - if (workOrderRow.WO_AGE !== '') { - await addOrUpdateContractField({ - contractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Death Age').contractTypeFieldId, - contractFieldValue: workOrderRow.WO_AGE - }, user); - } - if (workOrderRow.WO_PERIOD !== '') { - const period = importData.getDeathAgePeriod(workOrderRow.WO_PERIOD); - await addOrUpdateContractField({ - contractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Death Age Period').contractTypeFieldId, - contractFieldValue: period - }, user); - } - if (workOrderRow.WO_FUNERAL_HOME !== '') { - const funeralHomeOccupant = importData.getFuneralHomeLotOccupancyOccupantData(workOrderRow.WO_FUNERAL_HOME); - await addContractOccupant({ - contractId, - lotOccupantTypeId: funeralHomeOccupant.lotOccupantTypeId, - occupantName: funeralHomeOccupant.occupantName, - occupantFamilyName: '', - occupantAddress1: funeralHomeOccupant.occupantAddress1, - occupantAddress2: funeralHomeOccupant.occupantAddress2, - occupantCity: funeralHomeOccupant.occupantCity, - occupantProvince: funeralHomeOccupant.occupantProvince, - occupantPostalCode: funeralHomeOccupant.occupantPostalCode, - occupantPhoneNumber: funeralHomeOccupant.occupantPhoneNumber, - occupantEmailAddress: funeralHomeOccupant.occupantEmailAddress - }, user); - /* - addOrUpdateContractField( - { - contractId: contractId, - contractTypeFieldId: allContractTypeFields.find((contractTypeField) => { - return contractTypeField.contractTypeField === "Funeral Home"; - }).contractTypeFieldId, - contractFieldValue: workOrderRow.WO_FUNERAL_HOME - }, - user - ); - */ - } - if (workOrderRow.WO_FUNERAL_YR !== '') { - const contractFieldValue = formatDateString(workOrderRow.WO_FUNERAL_YR, workOrderRow.WO_FUNERAL_MON, workOrderRow.WO_FUNERAL_DAY); - await addOrUpdateContractField({ - contractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Funeral Date').contractTypeFieldId, - contractFieldValue - }, user); - } - if (contractType.contractType !== 'Cremation') { - if (workOrderRow.WO_CONTAINER_TYPE !== '') { - await addOrUpdateContractField({ - contractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Container Type').contractTypeFieldId, - contractFieldValue: workOrderRow.WO_CONTAINER_TYPE - }, user); - } - if (workOrderRow.WO_COMMITTAL_TYPE !== '') { - let commitalType = workOrderRow.WO_COMMITTAL_TYPE; - if (commitalType === 'GS') { - commitalType = 'Graveside'; - } - await addOrUpdateContractField({ - contractId, - contractTypeFieldId: contractType.ContractTypeFields.find((contractTypeField) => contractTypeField.contractTypeField === 'Committal Type').contractTypeFieldId, - contractFieldValue: commitalType - }, user); - } - } - await addWorkOrderContract({ - workOrderId: workOrder.workOrderId, - contractId - }, user); - // Milestones - let hasIncompleteMilestones = !workOrderRow.WO_CONFIRMATION_IN; - let maxMilestoneCompletionDateString = workOrderOpenDateString; - if (importIds.acknowledgedWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone({ - workOrderId: workOrder.workOrderId, - workOrderMilestoneTypeId: importIds.acknowledgedWorkOrderMilestoneTypeId, - workOrderMilestoneDateString: workOrderOpenDateString, - workOrderMilestoneDescription: '', - workOrderMilestoneCompletionDateString: workOrderRow.WO_CONFIRMATION_IN - ? workOrderOpenDateString - : undefined, - workOrderMilestoneCompletionTimeString: workOrderRow.WO_CONFIRMATION_IN ? '00:00' : undefined - }, user); - } - if (workOrderRow.WO_DEATH_YR) { - const workOrderMilestoneDateString = formatDateString(workOrderRow.WO_DEATH_YR, workOrderRow.WO_DEATH_MON, workOrderRow.WO_DEATH_DAY); - if (importIds.deathWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone({ - workOrderId: workOrder.workOrderId, - workOrderMilestoneTypeId: importIds.deathWorkOrderMilestoneTypeId, - workOrderMilestoneDateString, - workOrderMilestoneDescription: `Death Place: ${workOrderRow.WO_DEATH_PLACE}`, - workOrderMilestoneCompletionDateString: workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneDateString - : undefined, - workOrderMilestoneCompletionTimeString: workOrderMilestoneDateString < currentDateString - ? '00:00' - : undefined - }, user); - } - if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { - maxMilestoneCompletionDateString = workOrderMilestoneDateString; - } - if (workOrderMilestoneDateString >= currentDateString) { - hasIncompleteMilestones = true; - } - } - if (workOrderRow.WO_FUNERAL_YR) { - const workOrderMilestoneDateString = formatDateString(workOrderRow.WO_FUNERAL_YR, workOrderRow.WO_FUNERAL_MON, workOrderRow.WO_FUNERAL_DAY); - let funeralHour = Number.parseInt(workOrderRow.WO_FUNERAL_HR, 10); - if (funeralHour <= 6) { - funeralHour += 12; - } - const workOrderMilestoneTimeString = formatTimeString(funeralHour.toString(), workOrderRow.WO_FUNERAL_MIN); - if (importIds.funeralWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone({ - workOrderId: workOrder.workOrderId, - workOrderMilestoneTypeId: importIds.funeralWorkOrderMilestoneTypeId, - workOrderMilestoneDateString, - workOrderMilestoneTimeString, - workOrderMilestoneDescription: `Funeral Home: ${workOrderRow.WO_FUNERAL_HOME}`, - workOrderMilestoneCompletionDateString: workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneDateString - : undefined, - workOrderMilestoneCompletionTimeString: workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneTimeString - : undefined - }, user); - } - if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { - maxMilestoneCompletionDateString = workOrderMilestoneDateString; - } - if (workOrderMilestoneDateString >= currentDateString) { - hasIncompleteMilestones = true; - } - } - if (workOrderRow.WO_CREMATION === 'Y' && - importIds.cremationWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone({ - workOrderId: workOrder.workOrderId, - workOrderMilestoneTypeId: importIds.cremationWorkOrderMilestoneTypeId, - workOrderMilestoneDateString: maxMilestoneCompletionDateString, - workOrderMilestoneDescription: '', - workOrderMilestoneCompletionDateString: maxMilestoneCompletionDateString < currentDateString - ? maxMilestoneCompletionDateString - : undefined, - workOrderMilestoneCompletionTimeString: maxMilestoneCompletionDateString < currentDateString - ? '00:00' - : undefined - }, user); - } - if (workOrderRow.WO_INTERMENT_YR) { - const workOrderMilestoneDateString = formatDateString(workOrderRow.WO_INTERMENT_YR, workOrderRow.WO_INTERMENT_MON, workOrderRow.WO_INTERMENT_DAY); - if (importIds.intermentWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone({ - workOrderId: workOrder.workOrderId, - workOrderMilestoneTypeId: importIds.intermentWorkOrderMilestoneTypeId, - workOrderMilestoneDateString, - workOrderMilestoneDescription: `Depth: ${workOrderRow.WO_DEPTH}`, - workOrderMilestoneCompletionDateString: workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneDateString - : undefined, - workOrderMilestoneCompletionTimeString: workOrderMilestoneDateString < currentDateString - ? '23:59' - : undefined - }, user); - } - if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { - maxMilestoneCompletionDateString = workOrderMilestoneDateString; - } - if (workOrderMilestoneDateString >= currentDateString) { - hasIncompleteMilestones = true; - } - } - if (!hasIncompleteMilestones) { - await closeWorkOrder({ - workOrderId: workOrder.workOrderId, - workOrderCloseDateString: maxMilestoneCompletionDateString - }, user); - } - } - } - catch (error) { - console.error(error); - console.log(workOrderRow); - } - console.timeEnd('importFromWorkOrderCSV'); -} -console.log(`Started ${new Date().toLocaleString()}`); -console.time('importFromCsv'); -purgeTables(); -// purgeConfigTables(); -await importFromMasterCSV(); -await importFromPrepaidCSV(); -await importFromWorkOrderCSV(); -console.timeEnd('importFromCsv'); -console.log(`Finished ${new Date().toLocaleString()}`); diff --git a/temp/legacy.importFromCSV.ts b/temp/legacy.importFromCSV.ts deleted file mode 100644 index bc4ad9bc..00000000 --- a/temp/legacy.importFromCSV.ts +++ /dev/null @@ -1,1663 +0,0 @@ -/* eslint-disable max-lines */ - -import fs from 'node:fs' - -import { - type DateString, - type TimeString, - dateIntegerToString, - dateToString -} from '@cityssm/utils-datetime' -import sqlite from 'better-sqlite3' -import papa from 'papaparse' - -import { sunriseDB as databasePath } from '../helpers/database.helpers.js' -import addBurialSite from '../database/addBurialSite.js' -import addContract from '../database/addContract.js' -import addContractComment from '../database/addContractComment.js' -import addContractFee from '../database/addContractFee.js' -import addContractOccupant from '../database/addContractOccupant.js' -import addContractTransaction from '../database/addContractTransaction.js' -import addCemetery from '../database/addCemetery.js' -import addOrUpdateContractField from '../database/addOrUpdateContractField.js' -import addWorkOrder from '../database/addWorkOrder.js' -import addWorkOrderBurialSite from '../database/addWorkOrderBurialSite.js' -import addWorkOrderContract from '../database/addWorkOrderContract.js' -import addWorkOrderMilestone from '../database/addWorkOrderMilestone.js' -import closeWorkOrder from '../database/closeWorkOrder.js' -import getBurialSite, { - getBurialSiteByBurialSiteName -} from '../database/getBurialSite.js' -import getContracts from '../database/getContracts.js' -import getCemeteryFromDatabase from '../database/getCemetery.js' -import getWorkOrder, { - getWorkOrderByWorkOrderNumber -} from '../database/getWorkOrder.js' -import reopenWorkOrder from '../database/reopenWorkOrder.js' -import { updateBurialSiteStatus } from '../database/updateBurialSite.js' -import type * as recordTypes from '../types/recordTypes.js' - -import * as importData from './legacy.importFromCsv.data.js' -import * as importIds from './legacy.importFromCsv.ids.js' - -interface MasterRecord { - CM_SYSREC: string - CM_CEMETERY: string - CM_BLOCK: string - CM_RANGE1: string - CM_RANGE2: string - CM_LOT1: string - CM_LOT2: string - CM_GRAVE1: string - CM_GRAVE2: string - CM_INTERMENT: string - CM_PRENEED_OWNER: string - CM_PRENEED_OWNER_SEQ: string - CM_DECEASED_NAME: string - CM_DECEASED_NAME_SEQ: string - CM_ADDRESS: string - CM_CITY: string - CM_PROV: string - CM_POST1: string - CM_POST2: string - CM_PRENEED_ORDER: string - CM_PURCHASE_YR: string - CM_PURCHASE_MON: string - CM_PURCHASE_DAY: string - CM_NO_GRAVES: string - CM_DEATH_YR: string - CM_DEATH_MON: string - CM_DEATH_DAY: string - CM_WORK_ORDER: string - CM_INTERMENT_YR: string - CM_INTERMENT_MON: string - CM_INTERMENT_DAY: string - CM_AGE: string - CM_CONTAINER_TYPE: string - CM_COMMITTAL_TYPE: string - CM_CREMATION: string - CM_FUNERAL_HOME: string - CM_FUNERAL_YR: string - CM_FUNERAL_MON: string - CM_FUNERAL_DAY: string - CM_RESIDENT_TYPE: string - CM_REMARK1: string - CM_REMARK2: string - CM_STATUS: string - CM_PERIOD: string - CM_LAST_CHG_DATE: string - CM_DEPTH: string -} - -interface PrepaidRecord { - CMPP_SYSREC: string - CMPP_PREPAID_FOR_NAME: string - CMPP_PREPAID_FOR_SEQ: string - CMPP_ADDRESS: string - CMPP_CITY: string - CMPP_PROV: string - CMPP_POSTAL1: string - CMPP_POSTAL2: string - CMPP_ARRANGED_BY_NAME: string - CMPP_ARRANGED_BY_SEQ: string - CMPP_CEMETERY: string - CMPP_BLOCK: string - CMPP_RANGE1: string - CMPP_RANGE2: string - CMPP_LOT1: string - CMPP_LOT2: string - CMPP_GRAVE1: string - CMPP_GRAVE2: string - CMPP_INTERMENT: string - CMPP_ORDER_NO: string - CMPP_PURCH_YR: string - CMPP_PURCH_MON: string - CMPP_PURCH_DAY: string - CMPP_FEE_GRAV_SD: string - CMPP_GST_GRAV_SD: string - CMPP_FEE_GRAV_DD: string - CMPP_GST_GRAV_DD: string - CMPP_FEE_CHAP_SD: string - CMPP_GST_CHAP_SD: string - CMPP_FEE_CHAP_DD: string - CMPP_GST_CHAP_DD: string - CMPP_FEE_ENTOMBMENT: string - CMPP_GST_ENTOMBMENT: string - CMPP_FEE_CREM: string - CMPP_GST_CREM: string - CMPP_FEE_NICHE: string - CMPP_GST_NICHE: string - CMPP_FEE_DISINTERMENT: string - CMPP_GST_DISINTERMENT: string - CMPP_REMARK1: string - CMPP_REMARK2: string -} - -interface WorkOrderRecord { - WO_SYSREC: string - WO_DECEASED_NAME: string - WO_DECEASED_SEQ: string - WO_CEMETERY: string - WO_BLOCK: string - WO_RANGE1: string - WO_RANGE2: string - WO_LOT1: string - WO_LOT2: string - WO_GRAVE1: string - WO_GRAVE2: string - WO_INTERMENT: string - WO_ADDRESS: string - WO_CITY: string - WO_PROV: string - WO_POST1: string - WO_POST2: string - WO_DEATH_YR: string - WO_DEATH_MON: string - WO_DEATH_DAY: string - WO_AGE: string - WO_FUNERAL_HOME: string - WO_FUNERAL_YR: string - WO_FUNERAL_MON: string - WO_FUNERAL_DAY: string - WO_FUNERAL_HR: string - WO_FUNERAL_MIN: string - WO_INTERMENT_YR: string - WO_INTERMENT_MON: string - WO_INTERMENT_DAY: string - WO_COST: string - WO_COMMITTAL_TYPE: string - WO_CONTAINER_TYPE: string - WO_CREMATION: string - WO_CONFIRMATION_IN: string - WO_COMPLETION_YR: string - WO_COMPLETION_MON: string - WO_COMPLETION_DAY: string - WO_INITIATION_DATE: string - WO_WORK_ORDER: string - WO_REMARK1: string - WO_REMARK2: string - WO_REMARK3: string - WO_PERIOD: string - WO_RESIDENT_TYPE: string - WO_DEPTH: string - WO_DEATH_PLACE: string -} - -const user: User = { - userName: 'import.unix', - userProperties: { - canUpdate: true, - isAdmin: false, - apiKey: '' - } -} - -function purgeTables(): void { - console.time('purgeTables') - - const tablesToPurge = [ - 'WorkOrderMilestones', - 'WorkOrderComments', - 'WorkOrderBurialSites', - 'WorkOrderContracts', - 'WorkOrders', - 'ContractTransactions', - 'ContractFees', - 'ContractFields', - 'ContractComments', - 'ContractInterments', - 'Contracts', - 'BurialSiteFields', - 'BurialSiteComments', - 'BurialSites' - ] - - const database = sqlite(databasePath) - - for (const tableName of tablesToPurge) { - database.prepare(`delete from ${tableName}`).run() - database - .prepare('delete from sqlite_sequence where name = ?') - .run(tableName) - } - - database.close() - - console.timeEnd('purgeTables') -} - -function purgeConfigTables(): void { - console.time('purgeConfigTables') - - const database = sqlite(databasePath) - database.prepare('delete from Cemeteries').run() - database.prepare("delete from sqlite_sequence where name in ('Cemeteries')").run() - database.close() - - console.timeEnd('purgeConfigTables') -} - -function getCemeteryByDescription( - cemeteryDescription: string -): recordTypes.Cemetery | undefined { - const database = sqlite(databasePath, { - readonly: true - }) - - const cemetery = database - .prepare('select * from Cemeteries where cemeteryDescription = ?') - .get(cemeteryDescription) as recordTypes.Cemetery - - database.close() - - return cemetery -} - -function formatDateString( - year: string, - month: string, - day: string -): DateString { - const formattedYear = `0000${year}`.slice(-4) - const formattedMonth = `00${month}`.slice(-2) - const formattedDay = `00${day}`.slice(-2) - - return `${formattedYear}-${formattedMonth}-${formattedDay}` as DateString -} - -function formatTimeString(hour: string, minute: string): TimeString { - const formattedHour = `00${hour}`.slice(-2) - const formattedMinute = `00${minute}`.slice(-2) - - return `${formattedHour}:${formattedMinute}` as TimeString -} - -const cemeteryToCemeteryName = { - '00': 'Crematorium', - GC: 'New Greenwood - Columbarium', - HC: 'Holy Sepulchre - Columbarium', - HS: 'Holy Sepulchre', - MA: 'Holy Sepulchre - Mausoleum', - NG: 'New Greenwood', - NW: 'Niche Wall', - OG: 'Old Greenwood', - PG: 'Pine Grove', - UG: 'New Greenwood - Urn Garden', - WK: 'West Korah' -} - -const cemeteryCache = new Map() - -async function getCemetery(dataRow: { - cemetery: string -}): Promise { - const mapCacheKey = dataRow.cemetery - - /* - if (masterRow.CM_CEMETERY === "HS" && - (masterRow.CM_BLOCK === "F" || masterRow.CM_BLOCK === "G" || masterRow.CM_BLOCK === "H" || masterRow.CM_BLOCK === "J")) { - mapCacheKey += "-" + masterRow.CM_BLOCK; - } - */ - - if (cemeteryCache.has(mapCacheKey)) { - return cemeteryCache.get(mapCacheKey)! - } - - let cemetery = getCemeteryByDescription(mapCacheKey) - - if (cemetery === undefined) { - console.log(`Creating cemetery: ${dataRow.cemetery}`) - - const cemeteryId = await addCemetery( - { - cemeteryName: - cemeteryToCemeteryName[dataRow.cemetery] ?? dataRow.cemetery, - cemeteryDescription: dataRow.cemetery, - cemeterySvg: '', - cemeteryLatitude: '', - cemeteryLongitude: '', - cemeteryAddress1: '', - cemeteryAddress2: '', - cemeteryCity: 'Sault Ste. Marie', - cemeteryProvince: 'ON', - cemeteryPostalCode: '', - cemeteryPhoneNumber: '' - }, - user - ) - - cemetery = (await getCemeteryFromDatabase(cemeteryId)) as recordTypes.Cemetery - } - - cemeteryCache.set(mapCacheKey, cemetery) - - return cemetery -} - -async function importFromMasterCSV(): Promise { - console.time('importFromMasterCSV') - - let masterRow: MasterRecord - - const rawData = fs.readFileSync('./temp/CMMASTER.csv').toString() - - const cmmaster: papa.ParseResult = papa.parse(rawData, { - delimiter: ',', - header: true, - skipEmptyLines: true - }) - - for (const parseError of cmmaster.errors) { - console.log(parseError) - } - - try { - for (masterRow of cmmaster.data) { - const cemetery = await getCemetery({ - cemetery: masterRow.CM_CEMETERY - })! - - const burialSiteTypeId = importIds.getburialSiteTypeId({ - cemetery: masterRow.CM_CEMETERY - })! - - let burialSiteId: number | undefined - - if (masterRow.CM_CEMETERY !== '00') { - burialSiteId = await addBurialSite( - { - burialSiteName, - burialSiteTypeId, - burialSiteStatusId: importIds.availableBurialSiteStatusId, - cemeteryId: cemetery.cemeteryId!, - cemeterySvgId: '', - burialSiteLatitude: '', - burialSiteLongitude: '' - }, - user - ) - } - - let preneedcontractStartDateString: string - let preneedcontractId: number - - if (masterRow.CM_PRENEED_OWNER !== '' || masterRow.CM_STATUS === 'P') { - preneedcontractStartDateString = formatDateString( - masterRow.CM_PURCHASE_YR, - masterRow.CM_PURCHASE_MON, - masterRow.CM_PURCHASE_DAY - ) - - let contractEndDateString = '' - - if ( - masterRow.CM_INTERMENT_YR !== '' && - masterRow.CM_INTERMENT_YR !== '0' - ) { - contractEndDateString = formatDateString( - masterRow.CM_INTERMENT_YR, - masterRow.CM_INTERMENT_MON, - masterRow.CM_INTERMENT_DAY - ) - } - - // if purchase date unavailable - if ( - preneedcontractStartDateString === '0000-00-00' && - contractEndDateString !== '' - ) { - preneedcontractStartDateString = contractEndDateString - } - - // if end date unavailable - if ( - preneedcontractStartDateString === '0000-00-00' && - masterRow.CM_DEATH_YR !== '' && - masterRow.CM_DEATH_YR !== '0' - ) { - preneedcontractStartDateString = formatDateString( - masterRow.CM_DEATH_YR, - masterRow.CM_DEATH_MON, - masterRow.CM_DEATH_DAY - ) - - // if death took place, and there's no preneed end date - if ( - contractEndDateString === '0000-00-00' || - contractEndDateString === '' - ) { - contractEndDateString = preneedcontractStartDateString - } - } - - if ( - preneedcontractStartDateString === '' || - preneedcontractStartDateString === '0000-00-00' - ) { - preneedcontractStartDateString = '0001-01-01' - } - - preneedcontractId = await addContract( - { - contractTypeId: importIds.preneedContractType.contractTypeId, - burialSiteId: burialSiteId ?? '', - contractStartDateString: preneedcontractStartDateString, - contractEndDateString, - contractTypeFieldIds: '' - }, - user - ) - - const occupantPostalCode = - `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim() - - await addContractOccupant( - { - contractId: preneedcontractId, - lotOccupantTypeId: importIds.preneedOwnerLotOccupantTypeId, - occupantName: masterRow.CM_PRENEED_OWNER, - occupantFamilyName: '', - occupantAddress1: masterRow.CM_ADDRESS, - occupantAddress2: '', - occupantCity: masterRow.CM_CITY, - occupantProvince: masterRow.CM_PROV, - occupantPostalCode, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, - user - ) - - if (masterRow.CM_REMARK1 !== '') { - await addContractComment( - { - contractId: preneedcontractId, - contractCommentDateString: - preneedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK1 - }, - user - ) - } - - if (masterRow.CM_REMARK2 !== '') { - await addContractComment( - { - contractId: preneedcontractId, - contractCommentDateString: - preneedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK2 - }, - user - ) - } - - if (masterRow.CM_WORK_ORDER.trim() !== '') { - await addContractComment( - { - contractId: preneedcontractId, - contractCommentDateString: - preneedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: `Imported Contract #${masterRow.CM_WORK_ORDER}` - }, - user - ) - } - - if (contractEndDateString === '') { - await updateBurialSiteStatus( - burialSiteId ?? '', - importIds.reservedburialSiteStatusId, - user - ) - } - } - - let deceasedcontractStartDateString: string - let deceasedcontractId: number - - if (masterRow.CM_DECEASED_NAME !== '') { - deceasedcontractStartDateString = formatDateString( - masterRow.CM_INTERMENT_YR, - masterRow.CM_INTERMENT_MON, - masterRow.CM_INTERMENT_DAY - ) - - // if interment date unavailable - if ( - deceasedcontractStartDateString === '0000-00-00' && - masterRow.CM_DEATH_YR !== '' && - masterRow.CM_DEATH_YR !== '0' - ) { - deceasedcontractStartDateString = formatDateString( - masterRow.CM_DEATH_YR, - masterRow.CM_DEATH_MON, - masterRow.CM_DEATH_DAY - ) - } - - if ( - deceasedcontractStartDateString === '' || - deceasedcontractStartDateString === '0000-00-00' - ) { - deceasedcontractStartDateString = '0001-01-01' - } - - const deceasedcontractEndDateString = burialSiteId - ? '' - : deceasedcontractStartDateString - - const contractType = burialSiteId - ? importIds.deceasedContractType - : importIds.cremationContractType - - deceasedcontractId = await addContract( - { - contractTypeId: contractType.contractTypeId, - burialSiteId: burialSiteId ?? '', - contractStartDateString: deceasedcontractStartDateString, - contractEndDateString: deceasedcontractEndDateString, - contractTypeFieldIds: '' - }, - user - ) - - const deceasedPostalCode = - `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim() - - await addContractOccupant( - { - contractId: deceasedcontractId, - lotOccupantTypeId: importIds.deceasedLotOccupantTypeId, - occupantName: masterRow.CM_DECEASED_NAME, - occupantFamilyName: '', - occupantAddress1: masterRow.CM_ADDRESS, - occupantAddress2: '', - occupantCity: masterRow.CM_CITY, - occupantProvince: masterRow.CM_PROV, - occupantPostalCode: deceasedPostalCode, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, - user - ) - - if (masterRow.CM_DEATH_YR !== '') { - const contractFieldValue = formatDateString( - masterRow.CM_DEATH_YR, - masterRow.CM_DEATH_MON, - masterRow.CM_DEATH_DAY - ) - - await addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Death Date' - )!.contractTypeFieldId!, - contractFieldValue - }, - user - ) - } - - if (masterRow.CM_AGE !== '') { - await addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Death Age' - )!.contractTypeFieldId!, - contractFieldValue: masterRow.CM_AGE - }, - user - ) - } - - if (masterRow.CM_PERIOD !== '') { - const period = importData.getDeathAgePeriod(masterRow.CM_PERIOD) - - await addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Death Age Period' - )!.contractTypeFieldId!, - contractFieldValue: period - }, - user - ) - } - - if (masterRow.CM_FUNERAL_HOME !== '') { - const funeralHomeOccupant = - importData.getFuneralHomeLotOccupancyOccupantData( - masterRow.CM_FUNERAL_HOME - ) - - await addContractOccupant( - { - contractId: deceasedcontractId, - lotOccupantTypeId: funeralHomeOccupant.lotOccupantTypeId ?? '', - occupantName: funeralHomeOccupant.occupantName ?? '', - occupantFamilyName: '', - occupantAddress1: funeralHomeOccupant.occupantAddress1 ?? '', - occupantAddress2: funeralHomeOccupant.occupantAddress2 ?? '', - occupantCity: funeralHomeOccupant.occupantCity ?? '', - occupantProvince: funeralHomeOccupant.occupantProvince ?? '', - occupantPostalCode: funeralHomeOccupant.occupantPostalCode ?? '', - occupantPhoneNumber: - funeralHomeOccupant.occupantPhoneNumber ?? '', - occupantEmailAddress: - funeralHomeOccupant.occupantEmailAddress ?? '' - }, - user - ) - - /* - addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: allContractTypeFields.find( - (contractTypeField) => { - return contractTypeField.contractTypeField === "Funeral Home"; - } - ).contractTypeFieldId, - contractFieldValue: masterRow.CM_FUNERAL_HOME - }, - user - ); - */ - } - - if (masterRow.CM_FUNERAL_YR !== '') { - const contractFieldValue = formatDateString( - masterRow.CM_FUNERAL_YR, - masterRow.CM_FUNERAL_MON, - masterRow.CM_FUNERAL_DAY - ) - - await addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Funeral Date' - )!.contractTypeFieldId!, - contractFieldValue - }, - user - ) - } - - if (contractType.contractType !== 'Cremation') { - if (masterRow.CM_CONTAINER_TYPE !== '') { - await addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: contractType.contractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Container Type' - )!.contractTypeFieldId!, - contractFieldValue: masterRow.CM_CONTAINER_TYPE - }, - user - ) - } - - if (masterRow.CM_COMMITTAL_TYPE !== '') { - let commitalType = masterRow.CM_COMMITTAL_TYPE - - if (commitalType === 'GS') { - commitalType = 'Graveside' - } - - await addOrUpdateContractField( - { - contractId: deceasedcontractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Committal Type' - )!.contractTypeFieldId!, - contractFieldValue: commitalType - }, - user - ) - } - } - - if (masterRow.CM_REMARK1 !== '') { - await addContractComment( - { - contractId: deceasedcontractId, - contractCommentDateString: - deceasedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK1 - }, - user - ) - } - - if (masterRow.CM_REMARK2 !== '') { - await addContractComment( - { - contractId: deceasedcontractId, - contractCommentDateString: - deceasedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: masterRow.CM_REMARK2 - }, - user - ) - } - - if (masterRow.CM_WORK_ORDER.trim() !== '') { - await addContractComment( - { - contractId: deceasedcontractId, - contractCommentDateString: - deceasedcontractStartDateString, - contractCommentTimeString: '00:00', - contractComment: `Imported Contract #${masterRow.CM_WORK_ORDER}` - }, - user - ) - } - - await updateBurialSiteStatus( - burialSiteId ?? '', - importIds.takenburialSiteStatusId, - user - ) - - if (masterRow.CM_PRENEED_OWNER !== '') { - await addContractOccupant( - { - contractId: deceasedcontractId, - lotOccupantTypeId: importIds.preneedOwnerLotOccupantTypeId, - occupantName: masterRow.CM_PRENEED_OWNER, - occupantFamilyName: '', - occupantAddress1: '', - occupantAddress2: '', - occupantCity: '', - occupantProvince: '', - occupantPostalCode: '', - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, - user - ) - } - } - } - } catch (error) { - console.error(error) - console.log(masterRow) - } - - console.timeEnd('importFromMasterCSV') -} - -async function importFromPrepaidCSV(): Promise { - console.time('importFromPrepaidCSV') - - let prepaidRow: PrepaidRecord - - const rawData = fs.readFileSync('./temp/CMPRPAID.csv').toString() - - const cmprpaid: papa.ParseResult = papa.parse(rawData, { - delimiter: ',', - header: true, - skipEmptyLines: true - }) - - for (const parseError of cmprpaid.errors) { - console.log(parseError) - } - - try { - for (prepaidRow of cmprpaid.data) { - if (!prepaidRow.CMPP_PREPAID_FOR_NAME) { - continue - } - - let cemetery = prepaidRow.CMPP_CEMETERY - - if (cemetery === '.m') { - cemetery = 'HC' - } - - let lot: recordTypes.Lot | undefined - - if (cemetery !== '') { - const map = await getCemetery({ - cemetery - }) - - const burialSiteName = importData.buildLotName({ - cemetery, - block: prepaidRow.CMPP_BLOCK, - range1: prepaidRow.CMPP_RANGE1, - range2: prepaidRow.CMPP_RANGE2, - lot1: prepaidRow.CMPP_LOT1, - lot2: prepaidRow.CMPP_LOT2, - grave1: prepaidRow.CMPP_GRAVE1, - grave2: prepaidRow.CMPP_GRAVE2, - interment: prepaidRow.CMPP_INTERMENT - }) - - lot = await getBurialSiteByLotName(burialSiteName) - - if (!lot) { - const burialSiteTypeId = importIds.getburialSiteTypeId({ - cemetery - }) - - const burialSiteId = await addBurialSite( - { - burialSiteName, - burialSiteTypeId, - burialSiteStatusId: importIds.reservedburialSiteStatusId, - cemeteryId: map.cemeteryId ?? '', - mapKey: burialSiteName.includes(',') ? burialSiteName.split(',')[0] : burialSiteName, - burialSiteLatitude: '', - burialSiteLongitude: '' - }, - user - ) - - lot = await getBurialSite(burialSiteId) - } - } - - if ( - lot && - lot.burialSiteStatusId === importIds.availableburialSiteStatusId - ) { - await updateBurialSiteStatus( - lot.burialSiteId, - importIds.reservedburialSiteStatusId, - user - ) - } - - const contractStartDateString = formatDateString( - prepaidRow.CMPP_PURCH_YR, - prepaidRow.CMPP_PURCH_MON, - prepaidRow.CMPP_PURCH_DAY - ) - - let contractId: number - - if (lot) { - const possibleLotOccupancies = await getContracts( - { - burialSiteId: lot.burialSiteId, - contractTypeId: importIds.preneedContractType.contractTypeId, - deceasedName: prepaidRow.CMPP_PREPAID_FOR_NAME, - contractStartDateString - }, - { - includeOccupants: false, - includeFees: false, - includeTransactions: false, - limit: -1, - offset: 0 - } - ) - - if (possibleLotOccupancies.lotOccupancies.length > 0) { - contractId = - possibleLotOccupancies.lotOccupancies[0].contractId! - } - } - - contractId ||= await addContract( - { - burialSiteId: lot ? lot.burialSiteId : '', - contractTypeId: importIds.preneedContractType.contractTypeId, - contractStartDateString, - contractEndDateString: '' - }, - user - ) - - await addContractOccupant( - { - contractId, - lotOccupantTypeId: importIds.preneedOwnerLotOccupantTypeId, - occupantName: prepaidRow.CMPP_PREPAID_FOR_NAME, - occupantFamilyName: '', - occupantAddress1: prepaidRow.CMPP_ADDRESS, - occupantAddress2: '', - occupantCity: prepaidRow.CMPP_CITY, - occupantProvince: prepaidRow.CMPP_PROV.slice(0, 2), - occupantPostalCode: `${prepaidRow.CMPP_POSTAL1} ${prepaidRow.CMPP_POSTAL2}`, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, - user - ) - - if (prepaidRow.CMPP_ARRANGED_BY_NAME) { - await addContractOccupant( - { - contractId, - lotOccupantTypeId: importIds.purchaserLotOccupantTypeId, - occupantName: prepaidRow.CMPP_ARRANGED_BY_NAME, - occupantFamilyName: '', - occupantAddress1: '', - occupantAddress2: '', - occupantCity: '', - occupantProvince: '', - occupantPostalCode: '', - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, - user - ) - } - - if (prepaidRow.CMPP_FEE_GRAV_SD !== '0.0') { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_GRAV_SD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_GRAV_SD, - taxAmount: prepaidRow.CMPP_GST_GRAV_SD - }, - user - ) - } - - if (prepaidRow.CMPP_FEE_GRAV_DD !== '0.0') { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_GRAV_DD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_GRAV_DD, - taxAmount: prepaidRow.CMPP_GST_GRAV_DD - }, - user - ) - } - - if (prepaidRow.CMPP_FEE_CHAP_SD !== '0.0') { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_CHAP_SD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_CHAP_SD, - taxAmount: prepaidRow.CMPP_GST_CHAP_SD - }, - user - ) - } - - if (prepaidRow.CMPP_FEE_CHAP_DD !== '0.0') { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_CHAP_DD'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_CHAP_DD, - taxAmount: prepaidRow.CMPP_GST_CHAP_DD - }, - user - ) - } - - if (prepaidRow.CMPP_FEE_ENTOMBMENT !== '0.0') { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_ENTOMBMENT'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_ENTOMBMENT, - taxAmount: prepaidRow.CMPP_GST_ENTOMBMENT - }, - user - ) - } - - if (prepaidRow.CMPP_FEE_CREM !== '0.0') { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_CREM'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_CREM, - taxAmount: prepaidRow.CMPP_GST_CREM - }, - user - ) - } - - if (prepaidRow.CMPP_FEE_NICHE !== '0.0') { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_NICHE'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_NICHE, - taxAmount: prepaidRow.CMPP_GST_NICHE - }, - user - ) - } - - if ( - prepaidRow.CMPP_FEE_DISINTERMENT !== '0.0' && - prepaidRow.CMPP_FEE_DISINTERMENT !== '20202.02' - ) { - await addContractFee( - { - contractId, - feeId: importIds.getFeeIdByFeeDescription('CMPP_FEE_DISINTERMENT'), - quantity: 1, - feeAmount: prepaidRow.CMPP_FEE_DISINTERMENT, - taxAmount: prepaidRow.CMPP_GST_DISINTERMENT - }, - user - ) - } - - const transactionAmount = - Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_SD) + - Number.parseFloat(prepaidRow.CMPP_GST_GRAV_SD) + - Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_DD) + - Number.parseFloat(prepaidRow.CMPP_GST_GRAV_DD) + - Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_SD) + - Number.parseFloat(prepaidRow.CMPP_GST_CHAP_SD) + - Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_DD) + - Number.parseFloat(prepaidRow.CMPP_GST_CHAP_DD) + - Number.parseFloat(prepaidRow.CMPP_FEE_ENTOMBMENT) + - Number.parseFloat(prepaidRow.CMPP_GST_ENTOMBMENT) + - Number.parseFloat(prepaidRow.CMPP_FEE_CREM) + - Number.parseFloat(prepaidRow.CMPP_GST_CREM) + - Number.parseFloat(prepaidRow.CMPP_FEE_NICHE) + - Number.parseFloat(prepaidRow.CMPP_GST_NICHE) + - Number.parseFloat( - prepaidRow.CMPP_FEE_DISINTERMENT === '20202.02' - ? '0' - : prepaidRow.CMPP_FEE_DISINTERMENT - ) + - Number.parseFloat( - prepaidRow.CMPP_GST_DISINTERMENT === '20202.02' - ? '0' - : prepaidRow.CMPP_GST_DISINTERMENT - ) - - await addContractTransaction( - { - contractId, - externalReceiptNumber: '', - transactionAmount, - transactionDateString: contractStartDateString, - transactionNote: `Order Number: ${prepaidRow.CMPP_ORDER_NO}` - }, - user - ) - - if (prepaidRow.CMPP_REMARK1) { - await addContractComment( - { - contractId, - contractCommentDateString: contractStartDateString, - contractComment: prepaidRow.CMPP_REMARK1 - }, - user - ) - } - - if (prepaidRow.CMPP_REMARK2) { - await addContractComment( - { - contractId, - contractCommentDateString: contractStartDateString, - contractComment: prepaidRow.CMPP_REMARK2 - }, - user - ) - } - } - } catch (error) { - console.error(error) - console.log(prepaidRow) - } - - console.timeEnd('importFromPrepaidCSV') -} - -async function importFromWorkOrderCSV(): Promise { - console.time('importFromWorkOrderCSV') - - let workOrderRow: WorkOrderRecord - - const rawData = fs.readFileSync('./temp/CMWKORDR.csv').toString() - - const cmwkordr: papa.ParseResult = papa.parse(rawData, { - delimiter: ',', - header: true, - skipEmptyLines: true - }) - - for (const parseError of cmwkordr.errors) { - console.log(parseError) - } - - const currentDateString = dateToString(new Date()) - - try { - for (workOrderRow of cmwkordr.data) { - const workOrderNumber = `000000${workOrderRow.WO_WORK_ORDER}`.slice(-6) - - let workOrder = await getWorkOrderByWorkOrderNumber(workOrderNumber) - - const workOrderOpenDateString = dateIntegerToString( - Number.parseInt(workOrderRow.WO_INITIATION_DATE, 10) - ) - - if (workOrder) { - if (workOrder.workOrderCloseDate) { - await reopenWorkOrder(workOrder.workOrderId!, user) - delete workOrder.workOrderCloseDate - delete workOrder.workOrderCloseDateString - } - } else { - const workOrderId = await addWorkOrder( - { - workOrderNumber, - workOrderTypeId: importIds.workOrderTypeId, - workOrderDescription: - `${workOrderRow.WO_REMARK1} ${workOrderRow.WO_REMARK2} ${workOrderRow.WO_REMARK3}`.trim(), - workOrderOpenDateString - }, - user - ) - - workOrder = await getWorkOrder(workOrderId, { - includeLotsAndLotOccupancies: true, - includeComments: true, - includeMilestones: true - }) - } - - let lot: recordTypes.Lot - - if (workOrderRow.WO_CEMETERY !== '00') { - const burialSiteName = importData.buildLotName({ - cemetery: workOrderRow.WO_CEMETERY, - block: workOrderRow.WO_BLOCK, - range1: workOrderRow.WO_RANGE1, - range2: workOrderRow.WO_RANGE2, - lot1: workOrderRow.WO_LOT1, - lot2: workOrderRow.WO_LOT2, - grave1: workOrderRow.WO_GRAVE1, - grave2: workOrderRow.WO_GRAVE2, - interment: workOrderRow.WO_INTERMENT - }) - - lot = await getBurialSiteByLotName(burialSiteName) - - if (lot) { - await updateBurialSiteStatus( - lot.burialSiteId, - importIds.takenburialSiteStatusId, - user - ) - } else { - const map = await getCemetery({ cemetery: workOrderRow.WO_CEMETERY }) - - const burialSiteTypeId = importIds.getburialSiteTypeId({ - cemetery: workOrderRow.WO_CEMETERY - }) - - const burialSiteId = await addBurialSite( - { - cemeteryId: map.cemeteryId!, - burialSiteName, - mapKey: burialSiteName.includes(',') ? burialSiteName.split(',')[0] : burialSiteName, - burialSiteStatusId: importIds.takenburialSiteStatusId, - burialSiteTypeId, - burialSiteLatitude: '', - burialSiteLongitude: '' - }, - user - ) - - lot = await getBurialSite(burialSiteId) - } - - const workOrderContainsLot = workOrder.workOrderLots!.find( - (possibleLot) => (possibleLot.burialSiteId = lot.burialSiteId) - ) - - if (!workOrderContainsLot) { - await addWorkOrderBurialSite( - { - workOrderId: workOrder.workOrderId!, - burialSiteId: lot.burialSiteId - }, - user - ) - - workOrder.workOrderLots!.push(lot) - } - } - - let contractStartDateString = workOrderOpenDateString - - if (workOrderRow.WO_INTERMENT_YR) { - contractStartDateString = formatDateString( - workOrderRow.WO_INTERMENT_YR, - workOrderRow.WO_INTERMENT_MON, - workOrderRow.WO_INTERMENT_DAY - ) - } - - const contractType = lot - ? importIds.deceasedContractType - : importIds.cremationContractType - - const contractId = await addContract( - { - burialSiteId: lot ? lot.burialSiteId : '', - contractTypeId: contractType.contractTypeId, - contractStartDateString, - contractEndDateString: '' - }, - user - ) - - await addContractOccupant( - { - contractId, - lotOccupantTypeId: importIds.deceasedLotOccupantTypeId, - occupantName: workOrderRow.WO_DECEASED_NAME, - occupantFamilyName: '', - occupantAddress1: workOrderRow.WO_ADDRESS, - occupantAddress2: '', - occupantCity: workOrderRow.WO_CITY, - occupantProvince: workOrderRow.WO_PROV.slice(0, 2), - occupantPostalCode: `${workOrderRow.WO_POST1} ${workOrderRow.WO_POST2}`, - occupantPhoneNumber: '', - occupantEmailAddress: '' - }, - user - ) - - if (workOrderRow.WO_DEATH_YR !== '') { - const contractFieldValue = formatDateString( - workOrderRow.WO_DEATH_YR, - workOrderRow.WO_DEATH_MON, - workOrderRow.WO_DEATH_DAY - ) - - await addOrUpdateContractField( - { - contractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Death Date' - )!.contractTypeFieldId!, - contractFieldValue - }, - user - ) - } - - if (workOrderRow.WO_DEATH_PLACE !== '') { - await addOrUpdateContractField( - { - contractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Death Place' - )!.contractTypeFieldId!, - contractFieldValue: workOrderRow.WO_DEATH_PLACE - }, - user - ) - } - - if (workOrderRow.WO_AGE !== '') { - await addOrUpdateContractField( - { - contractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Death Age' - )!.contractTypeFieldId!, - contractFieldValue: workOrderRow.WO_AGE - }, - user - ) - } - - if (workOrderRow.WO_PERIOD !== '') { - const period = importData.getDeathAgePeriod(workOrderRow.WO_PERIOD) - - await addOrUpdateContractField( - { - contractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Death Age Period' - )!.contractTypeFieldId!, - contractFieldValue: period - }, - user - ) - } - - if (workOrderRow.WO_FUNERAL_HOME !== '') { - const funeralHomeOccupant = - importData.getFuneralHomeLotOccupancyOccupantData( - workOrderRow.WO_FUNERAL_HOME - ) - - await addContractOccupant( - { - contractId, - lotOccupantTypeId: funeralHomeOccupant.lotOccupantTypeId!, - occupantName: funeralHomeOccupant.occupantName!, - occupantFamilyName: '', - occupantAddress1: funeralHomeOccupant.occupantAddress1!, - occupantAddress2: funeralHomeOccupant.occupantAddress2!, - occupantCity: funeralHomeOccupant.occupantCity!, - occupantProvince: funeralHomeOccupant.occupantProvince!, - occupantPostalCode: funeralHomeOccupant.occupantPostalCode!, - occupantPhoneNumber: funeralHomeOccupant.occupantPhoneNumber!, - occupantEmailAddress: funeralHomeOccupant.occupantEmailAddress! - }, - user - ) - - /* - addOrUpdateContractField( - { - contractId: contractId, - contractTypeFieldId: allContractTypeFields.find((contractTypeField) => { - return contractTypeField.contractTypeField === "Funeral Home"; - }).contractTypeFieldId, - contractFieldValue: workOrderRow.WO_FUNERAL_HOME - }, - user - ); - */ - } - - if (workOrderRow.WO_FUNERAL_YR !== '') { - const contractFieldValue = formatDateString( - workOrderRow.WO_FUNERAL_YR, - workOrderRow.WO_FUNERAL_MON, - workOrderRow.WO_FUNERAL_DAY - ) - - await addOrUpdateContractField( - { - contractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Funeral Date' - )!.contractTypeFieldId!, - contractFieldValue - }, - user - ) - } - - if (contractType.contractType !== 'Cremation') { - if (workOrderRow.WO_CONTAINER_TYPE !== '') { - await addOrUpdateContractField( - { - contractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Container Type' - )!.contractTypeFieldId!, - contractFieldValue: workOrderRow.WO_CONTAINER_TYPE - }, - user - ) - } - - if (workOrderRow.WO_COMMITTAL_TYPE !== '') { - let commitalType = workOrderRow.WO_COMMITTAL_TYPE - - if (commitalType === 'GS') { - commitalType = 'Graveside' - } - - await addOrUpdateContractField( - { - contractId, - contractTypeFieldId: contractType.ContractTypeFields!.find( - (contractTypeField) => - contractTypeField.contractTypeField === 'Committal Type' - )!.contractTypeFieldId!, - contractFieldValue: commitalType - }, - user - ) - } - } - - await addWorkOrderContract( - { - workOrderId: workOrder.workOrderId!, - contractId - }, - user - ) - - // Milestones - - let hasIncompleteMilestones = !workOrderRow.WO_CONFIRMATION_IN - let maxMilestoneCompletionDateString = workOrderOpenDateString - - if (importIds.acknowledgedWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone( - { - workOrderId: workOrder.workOrderId!, - workOrderMilestoneTypeId: - importIds.acknowledgedWorkOrderMilestoneTypeId, - workOrderMilestoneDateString: workOrderOpenDateString, - workOrderMilestoneDescription: '', - workOrderMilestoneCompletionDateString: - workOrderRow.WO_CONFIRMATION_IN - ? workOrderOpenDateString - : undefined, - workOrderMilestoneCompletionTimeString: - workOrderRow.WO_CONFIRMATION_IN ? '00:00' : undefined - }, - user - ) - } - - if (workOrderRow.WO_DEATH_YR) { - const workOrderMilestoneDateString = formatDateString( - workOrderRow.WO_DEATH_YR, - workOrderRow.WO_DEATH_MON, - workOrderRow.WO_DEATH_DAY - ) - - if (importIds.deathWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone( - { - workOrderId: workOrder.workOrderId!, - workOrderMilestoneTypeId: importIds.deathWorkOrderMilestoneTypeId, - workOrderMilestoneDateString, - workOrderMilestoneDescription: `Death Place: ${workOrderRow.WO_DEATH_PLACE}`, - workOrderMilestoneCompletionDateString: - workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneDateString - : undefined, - workOrderMilestoneCompletionTimeString: - workOrderMilestoneDateString < currentDateString - ? '00:00' - : undefined - }, - user - ) - } - - if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { - maxMilestoneCompletionDateString = workOrderMilestoneDateString - } - - if (workOrderMilestoneDateString >= currentDateString) { - hasIncompleteMilestones = true - } - } - - if (workOrderRow.WO_FUNERAL_YR) { - const workOrderMilestoneDateString = formatDateString( - workOrderRow.WO_FUNERAL_YR, - workOrderRow.WO_FUNERAL_MON, - workOrderRow.WO_FUNERAL_DAY - ) - - let funeralHour = Number.parseInt(workOrderRow.WO_FUNERAL_HR, 10) - if (funeralHour <= 6) { - funeralHour += 12 - } - - const workOrderMilestoneTimeString = formatTimeString( - funeralHour.toString(), - workOrderRow.WO_FUNERAL_MIN - ) - - if (importIds.funeralWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone( - { - workOrderId: workOrder.workOrderId!, - workOrderMilestoneTypeId: - importIds.funeralWorkOrderMilestoneTypeId, - workOrderMilestoneDateString, - workOrderMilestoneTimeString, - workOrderMilestoneDescription: `Funeral Home: ${workOrderRow.WO_FUNERAL_HOME}`, - workOrderMilestoneCompletionDateString: - workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneDateString - : undefined, - workOrderMilestoneCompletionTimeString: - workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneTimeString - : undefined - }, - user - ) - } - - if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { - maxMilestoneCompletionDateString = workOrderMilestoneDateString - } - - if (workOrderMilestoneDateString >= currentDateString) { - hasIncompleteMilestones = true - } - } - - if ( - workOrderRow.WO_CREMATION === 'Y' && - importIds.cremationWorkOrderMilestoneTypeId - ) { - await addWorkOrderMilestone( - { - workOrderId: workOrder.workOrderId!, - workOrderMilestoneTypeId: - importIds.cremationWorkOrderMilestoneTypeId, - workOrderMilestoneDateString: maxMilestoneCompletionDateString, - workOrderMilestoneDescription: '', - workOrderMilestoneCompletionDateString: - maxMilestoneCompletionDateString < currentDateString - ? maxMilestoneCompletionDateString - : undefined, - workOrderMilestoneCompletionTimeString: - maxMilestoneCompletionDateString < currentDateString - ? '00:00' - : undefined - }, - user - ) - } - - if (workOrderRow.WO_INTERMENT_YR) { - const workOrderMilestoneDateString = formatDateString( - workOrderRow.WO_INTERMENT_YR, - workOrderRow.WO_INTERMENT_MON, - workOrderRow.WO_INTERMENT_DAY - ) - - if (importIds.intermentWorkOrderMilestoneTypeId) { - await addWorkOrderMilestone( - { - workOrderId: workOrder.workOrderId!, - workOrderMilestoneTypeId: - importIds.intermentWorkOrderMilestoneTypeId, - workOrderMilestoneDateString, - workOrderMilestoneDescription: `Depth: ${workOrderRow.WO_DEPTH}`, - workOrderMilestoneCompletionDateString: - workOrderMilestoneDateString < currentDateString - ? workOrderMilestoneDateString - : undefined, - workOrderMilestoneCompletionTimeString: - workOrderMilestoneDateString < currentDateString - ? '23:59' - : undefined - }, - user - ) - } - - if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { - maxMilestoneCompletionDateString = workOrderMilestoneDateString - } - - if (workOrderMilestoneDateString >= currentDateString) { - hasIncompleteMilestones = true - } - } - - if (!hasIncompleteMilestones) { - await closeWorkOrder( - { - workOrderId: workOrder.workOrderId!, - workOrderCloseDateString: maxMilestoneCompletionDateString - }, - user - ) - } - } - } catch (error) { - console.error(error) - console.log(workOrderRow) - } - - console.timeEnd('importFromWorkOrderCSV') -} - -console.log(`Started ${new Date().toLocaleString()}`) -console.time('importFromCsv') - -purgeTables() -// purgeConfigTables(); -await importFromMasterCSV() -await importFromPrepaidCSV() -await importFromWorkOrderCSV() - -console.timeEnd('importFromCsv') -console.log(`Finished ${new Date().toLocaleString()}`) diff --git a/temp/legacy.importFromCsv.data.d.ts b/temp/legacy.importFromCsv.data.d.ts deleted file mode 100644 index 2b5afdea..00000000 --- a/temp/legacy.importFromCsv.data.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { LotOccupancyOccupant } from '../types/recordTypes.js'; -export declare function getFuneralHomeLotOccupancyOccupantData(funeralHomeKey: string): LotOccupancyOccupant; -export declare function getDeathAgePeriod(legacyDeathAgePeriod: string): string; diff --git a/temp/legacy.importFromCsv.data.js b/temp/legacy.importFromCsv.data.js deleted file mode 100644 index b396f64d..00000000 --- a/temp/legacy.importFromCsv.data.js +++ /dev/null @@ -1,120 +0,0 @@ -// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair -/* eslint-disable @cspell/spellchecker */ -import * as importIds from './legacy.importFromCsv.ids.js'; -export function getFuneralHomeLotOccupancyOccupantData(funeralHomeKey) { - switch (funeralHomeKey) { - case 'AR': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Arthur Funeral Home', - occupantAddress1: '492 Wellington Street East', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6A 2L9', - occupantPhoneNumber: '705-759-2522', - occupantEmailAddress: '' - }; - } - case 'BG': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Beggs Funeral Home', - occupantAddress1: '175 Main Street', - occupantAddress2: 'P.O. Box 280', - occupantCity: 'Thessalon', - occupantProvince: 'ON', - occupantPostalCode: 'P0R 1L0', - occupantPhoneNumber: '705-842-2520', - occupantEmailAddress: 'bfh@beggsfh.ca' - }; - } - case 'BK': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Barton and Kiteley', - occupantAddress1: '', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: '', - occupantPhoneNumber: '', - occupantEmailAddress: '' - }; - } - case 'DA': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Damignani Burial, Cremation and Transfer Service', - occupantAddress1: '215 St. James Street', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6A 1P7', - occupantPhoneNumber: '705-759-8456', - occupantEmailAddress: '' - }; - } - case 'GL': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Gilmartin P.M. Funeral Home', - occupantAddress1: '140 Churchill Avenue', - occupantAddress2: '', - occupantCity: 'Wawa', - occupantProvince: 'ON', - occupantPostalCode: 'P0S 1K0', - occupantPhoneNumber: '705-856-7340', - occupantEmailAddress: '' - }; - } - case 'NO': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Northwood Funeral Home', - occupantAddress1: '942 Great Northern Road', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6B 0B6', - occupantPhoneNumber: '705-945-7758', - occupantEmailAddress: '' - }; - } - case 'OS': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: "O'Sullivan Funeral Home", - occupantAddress1: '215 St. James Street', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6A 1P7', - occupantPhoneNumber: '705-759-8456', - occupantEmailAddress: '' - }; - } - } - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: funeralHomeKey, - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON' - }; -} -export function getDeathAgePeriod(legacyDeathAgePeriod) { - switch (legacyDeathAgePeriod.toLowerCase()) { - case 'yrs': { - return 'Years'; - } - case 'mts': { - return 'Months'; - } - case 'dys': { - return 'Days'; - } - default: { - return legacyDeathAgePeriod; - } - } -} diff --git a/temp/legacy.importFromCsv.data.ts b/temp/legacy.importFromCsv.data.ts deleted file mode 100644 index 90f6b72e..00000000 --- a/temp/legacy.importFromCsv.data.ts +++ /dev/null @@ -1,129 +0,0 @@ -// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair -/* eslint-disable @cspell/spellchecker */ - -import type { LotOccupancyOccupant } from '../types/recordTypes.js' - -import * as importIds from './legacy.importFromCsv.ids.js' - -export function getFuneralHomeLotOccupancyOccupantData( - funeralHomeKey: string -): LotOccupancyOccupant { - switch (funeralHomeKey) { - case 'AR': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Arthur Funeral Home', - occupantAddress1: '492 Wellington Street East', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6A 2L9', - occupantPhoneNumber: '705-759-2522', - occupantEmailAddress: '' - } - } - case 'BG': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Beggs Funeral Home', - occupantAddress1: '175 Main Street', - occupantAddress2: 'P.O. Box 280', - occupantCity: 'Thessalon', - occupantProvince: 'ON', - occupantPostalCode: 'P0R 1L0', - occupantPhoneNumber: '705-842-2520', - occupantEmailAddress: 'bfh@beggsfh.ca' - } - } - case 'BK': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Barton and Kiteley', - occupantAddress1: '', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: '', - occupantPhoneNumber: '', - occupantEmailAddress: '' - } - } - case 'DA': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Damignani Burial, Cremation and Transfer Service', - occupantAddress1: '215 St. James Street', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6A 1P7', - occupantPhoneNumber: '705-759-8456', - occupantEmailAddress: '' - } - } - case 'GL': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Gilmartin P.M. Funeral Home', - occupantAddress1: '140 Churchill Avenue', - occupantAddress2: '', - occupantCity: 'Wawa', - occupantProvince: 'ON', - occupantPostalCode: 'P0S 1K0', - occupantPhoneNumber: '705-856-7340', - occupantEmailAddress: '' - } - } - case 'NO': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: 'Northwood Funeral Home', - occupantAddress1: '942 Great Northern Road', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6B 0B6', - occupantPhoneNumber: '705-945-7758', - occupantEmailAddress: '' - } - } - case 'OS': { - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: "O'Sullivan Funeral Home", - occupantAddress1: '215 St. James Street', - occupantAddress2: '', - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON', - occupantPostalCode: 'P6A 1P7', - occupantPhoneNumber: '705-759-8456', - occupantEmailAddress: '' - } - } - } - - return { - lotOccupantTypeId: importIds.funeralDirectorLotOccupantTypeId, - occupantName: funeralHomeKey, - occupantCity: 'Sault Ste. Marie', - occupantProvince: 'ON' - } -} - -export function getDeathAgePeriod(legacyDeathAgePeriod: string): string { - switch (legacyDeathAgePeriod.toLowerCase()) { - case 'yrs': { - return 'Years' - } - case 'mts': { - return 'Months' - } - case 'dys': { - return 'Days' - } - - default: { - return legacyDeathAgePeriod - } - } -} diff --git a/temp/legacy.importFromCsv.ids.d.ts b/temp/legacy.importFromCsv.ids.d.ts deleted file mode 100644 index ff9675b6..00000000 --- a/temp/legacy.importFromCsv.ids.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -export declare function getFeeIdByFeeDescription(feeDescription: string): number; -export declare const preneedOwnerLotOccupantTypeId: any; -export declare const funeralDirectorLotOccupantTypeId: any; -export declare const deceasedLotOccupantTypeId: any; -export declare const purchaserLotOccupantTypeId: any; -export declare const availableburialSiteStatusId: any; -export declare const reservedburialSiteStatusId: any; -export declare const takenburialSiteStatusId: any; -export declare function getburialSiteTypeId(dataRow: { - cemetery: string; -}): number; -export declare const preneedContractType: import("../types/recordTypes.js").ContractType; -export declare const deceasedContractType: import("../types/recordTypes.js").ContractType; -export declare const cremationContractType: import("../types/recordTypes.js").ContractType; -export declare const acknowledgedWorkOrderMilestoneTypeId: number | undefined; -export declare const deathWorkOrderMilestoneTypeId: number | undefined; -export declare const funeralWorkOrderMilestoneTypeId: number | undefined; -export declare const cremationWorkOrderMilestoneTypeId: number | undefined; -export declare const intermentWorkOrderMilestoneTypeId: number | undefined; -export declare const workOrderTypeId = 1; diff --git a/temp/legacy.importFromCsv.ids.js b/temp/legacy.importFromCsv.ids.js deleted file mode 100644 index 0fcfc4d0..00000000 --- a/temp/legacy.importFromCsv.ids.js +++ /dev/null @@ -1,89 +0,0 @@ -// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair -/* eslint-disable unicorn/no-await-expression-member */ -import sqlite from 'better-sqlite3'; -import { sunriseDB as databasePath } from '../data/databasePaths.js'; -import * as cacheFunctions from '../helpers/functions.cache.js'; -/* - * Fee IDs - */ -const feeCache = new Map(); -export function getFeeIdByFeeDescription(feeDescription) { - if (feeCache.keys.length === 0) { - const database = sqlite(databasePath, { - readonly: true - }); - const records = database - .prepare("select feeId, feeDescription from Fees where feeDescription like 'CMPP_FEE_%'") - .all(); - for (const record of records) { - feeCache.set(record.feeDescription, record.feeId); - } - database.close(); - } - return feeCache.get(feeDescription); -} -/* - * Lot Occupant Type IDs - */ -export const preneedOwnerLotOccupantTypeId = (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType('Preneed Owner')) - .lotOccupantTypeId; -export const funeralDirectorLotOccupantTypeId = (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType('Funeral Director')).lotOccupantTypeId; -export const deceasedLotOccupantTypeId = (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType('Deceased')) - .lotOccupantTypeId; -export const purchaserLotOccupantTypeId = (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType('Purchaser')) - .lotOccupantTypeId; -/* - * Lot Status IDs - */ -export const availableburialSiteStatusId = (await cacheFunctions.getBurialSiteStatusByLotStatus('Available')).burialSiteStatusId; -export const reservedburialSiteStatusId = (await cacheFunctions.getBurialSiteStatusByLotStatus('Reserved')).burialSiteStatusId; -export const takenburialSiteStatusId = (await cacheFunctions.getBurialSiteStatusByLotStatus('Taken')).burialSiteStatusId; -/* - * Lot Type IDs - */ -const casketburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Casket Grave')).burialSiteTypeId; -const columbariumburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Columbarium')).burialSiteTypeId; -const crematoriumburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Crematorium')).burialSiteTypeId; -const mausoleumburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Mausoleum')).burialSiteTypeId; -const nicheWallburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Niche Wall')).burialSiteTypeId; -const urnGardenburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Urn Garden')).burialSiteTypeId; -export function getburialSiteTypeId(dataRow) { - switch (dataRow.cemetery) { - case '00': { - return crematoriumburialSiteTypeId; - } - case 'GC': - case 'HC': { - return columbariumburialSiteTypeId; - } - case 'MA': { - return mausoleumburialSiteTypeId; - } - case 'MN': - case 'NW': { - return nicheWallburialSiteTypeId; - } - case 'UG': { - return urnGardenburialSiteTypeId; - } - } - return casketburialSiteTypeId; -} -/* - * Occupancy Type IDs - */ -export const preneedContractType = (await cacheFunctions.getContractTypeByContractType('Preneed')); -export const deceasedContractType = (await cacheFunctions.getContractTypeByContractType('Interment')); -export const cremationContractType = (await cacheFunctions.getContractTypeByContractType('Cremation')); -/* - * Work Order Milestone Type IDs - */ -export const acknowledgedWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Acknowledged'))?.workOrderMilestoneTypeId; -export const deathWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Death'))?.workOrderMilestoneTypeId; -export const funeralWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Funeral'))?.workOrderMilestoneTypeId; -export const cremationWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Cremation'))?.workOrderMilestoneTypeId; -export const intermentWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Interment'))?.workOrderMilestoneTypeId; -/* - * Work Order Type IDs - */ -export const workOrderTypeId = 1; diff --git a/temp/legacy.importFromCsv.ids.ts b/temp/legacy.importFromCsv.ids.ts deleted file mode 100644 index 755ec4be..00000000 --- a/temp/legacy.importFromCsv.ids.ts +++ /dev/null @@ -1,171 +0,0 @@ -// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair -/* eslint-disable unicorn/no-await-expression-member */ - -import sqlite from 'better-sqlite3' - -import { sunriseDB as databasePath } from '../data/databasePaths.js' -import * as cacheFunctions from '../helpers/functions.cache.js' - -/* - * Fee IDs - */ - -const feeCache = new Map() - -export function getFeeIdByFeeDescription(feeDescription: string): number { - if (feeCache.keys.length === 0) { - const database = sqlite(databasePath, { - readonly: true - }) - - const records = database - .prepare( - "select feeId, feeDescription from Fees where feeDescription like 'CMPP_FEE_%'" - ) - .all() as Array<{ - feeId: number - feeDescription: string - }> - - for (const record of records) { - feeCache.set(record.feeDescription, record.feeId) - } - - database.close() - } - - return feeCache.get(feeDescription)! -} - -/* - * Lot Occupant Type IDs - */ - -export const preneedOwnerLotOccupantTypeId = - (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType('Preneed Owner'))! - .lotOccupantTypeId - -export const funeralDirectorLotOccupantTypeId = - (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType( - 'Funeral Director' - ))!.lotOccupantTypeId - -export const deceasedLotOccupantTypeId = - (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType('Deceased'))! - .lotOccupantTypeId - -export const purchaserLotOccupantTypeId = - (await cacheFunctions.getBurialSiteOccupantTypeByLotOccupantType('Purchaser'))! - .lotOccupantTypeId - -/* - * Lot Status IDs - */ - -export const availableburialSiteStatusId = - (await cacheFunctions.getBurialSiteStatusByLotStatus('Available'))!.burialSiteStatusId -export const reservedburialSiteStatusId = - (await cacheFunctions.getBurialSiteStatusByLotStatus('Reserved'))!.burialSiteStatusId -export const takenburialSiteStatusId = (await cacheFunctions.getBurialSiteStatusByLotStatus( - 'Taken' -))!.burialSiteStatusId - -/* - * Lot Type IDs - */ - -const casketburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType( - 'Casket Grave' -))!.burialSiteTypeId -const columbariumburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType( - 'Columbarium' -))!.burialSiteTypeId -const crematoriumburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType( - 'Crematorium' -))!.burialSiteTypeId -const mausoleumburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType( - 'Mausoleum' -))!.burialSiteTypeId -const nicheWallburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType( - 'Niche Wall' -))!.burialSiteTypeId -const urnGardenburialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType( - 'Urn Garden' -))!.burialSiteTypeId - -export function getburialSiteTypeId(dataRow: { cemetery: string }): number { - switch (dataRow.cemetery) { - case '00': { - return crematoriumburialSiteTypeId - } - case 'GC': - case 'HC': { - return columbariumburialSiteTypeId - } - case 'MA': { - return mausoleumburialSiteTypeId - } - case 'MN': - case 'NW': { - return nicheWallburialSiteTypeId - } - case 'UG': { - return urnGardenburialSiteTypeId - } - } - - return casketburialSiteTypeId -} - -/* - * Occupancy Type IDs - */ - -export const preneedContractType = - (await cacheFunctions.getContractTypeByContractType('Preneed'))! - -export const deceasedContractType = - (await cacheFunctions.getContractTypeByContractType('Interment'))! - -export const cremationContractType = - (await cacheFunctions.getContractTypeByContractType('Cremation'))! - -/* - * Work Order Milestone Type IDs - */ - -export const acknowledgedWorkOrderMilestoneTypeId = ( - await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( - 'Acknowledged' - ) -)?.workOrderMilestoneTypeId - -export const deathWorkOrderMilestoneTypeId = ( - await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( - 'Death' - ) -)?.workOrderMilestoneTypeId - -export const funeralWorkOrderMilestoneTypeId = ( - await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( - 'Funeral' - ) -)?.workOrderMilestoneTypeId - -export const cremationWorkOrderMilestoneTypeId = ( - await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( - 'Cremation' - ) -)?.workOrderMilestoneTypeId - -export const intermentWorkOrderMilestoneTypeId = ( - await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( - 'Interment' - ) -)?.workOrderMilestoneTypeId - -/* - * Work Order Type IDs - */ - -export const workOrderTypeId = 1 diff --git a/temp/legacyImportFromCsv/data.burialSiteTypes.d.ts b/temp/legacyImportFromCsv/data.burialSiteTypes.d.ts new file mode 100644 index 00000000..2a656596 --- /dev/null +++ b/temp/legacyImportFromCsv/data.burialSiteTypes.d.ts @@ -0,0 +1 @@ +export declare function getBurialSiteTypeId(cemeteryKey: string): number; diff --git a/temp/legacyImportFromCsv/data.burialSiteTypes.js b/temp/legacyImportFromCsv/data.burialSiteTypes.js new file mode 100644 index 00000000..8d008c10 --- /dev/null +++ b/temp/legacyImportFromCsv/data.burialSiteTypes.js @@ -0,0 +1,35 @@ +import * as cacheFunctions from '../../helpers/functions.cache.js'; +const casketBurialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Casket Grave')) + .burialSiteTypeId; +const columbariumBurialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Columbarium')) + .burialSiteTypeId; +const cremationBurialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Crematorium')) + .burialSiteTypeId; +const mausoleumBurialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Mausoleum')) + .burialSiteTypeId; +const nicheWallBurialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Niche Wall')) + .burialSiteTypeId; +const urnGardenBurialSiteTypeId = (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Urn Garden')) + .burialSiteTypeId; +export function getBurialSiteTypeId(cemeteryKey) { + switch (cemeteryKey) { + case '00': { + return cremationBurialSiteTypeId; + } + case 'GC': + case 'HC': { + return columbariumBurialSiteTypeId; + } + case 'MA': { + return mausoleumBurialSiteTypeId; + } + case 'MN': + case 'NW': { + return nicheWallBurialSiteTypeId; + } + case 'UG': { + return urnGardenBurialSiteTypeId; + } + } + return casketBurialSiteTypeId; +} diff --git a/temp/legacyImportFromCsv/data.burialSiteTypes.ts b/temp/legacyImportFromCsv/data.burialSiteTypes.ts new file mode 100644 index 00000000..d20d114f --- /dev/null +++ b/temp/legacyImportFromCsv/data.burialSiteTypes.ts @@ -0,0 +1,45 @@ +import * as cacheFunctions from '../../helpers/functions.cache.js' + +const casketBurialSiteTypeId = + (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Casket Grave'))! + .burialSiteTypeId + +const columbariumBurialSiteTypeId = + (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Columbarium'))! + .burialSiteTypeId +const cremationBurialSiteTypeId = + (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Crematorium'))! + .burialSiteTypeId +const mausoleumBurialSiteTypeId = + (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Mausoleum'))! + .burialSiteTypeId +const nicheWallBurialSiteTypeId = + (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Niche Wall'))! + .burialSiteTypeId +const urnGardenBurialSiteTypeId = + (await cacheFunctions.getBurialSiteTypesByBurialSiteType('Urn Garden'))! + .burialSiteTypeId + +export function getBurialSiteTypeId(cemeteryKey: string): number { + switch (cemeteryKey) { + case '00': { + return cremationBurialSiteTypeId + } + case 'GC': + case 'HC': { + return columbariumBurialSiteTypeId + } + case 'MA': { + return mausoleumBurialSiteTypeId + } + case 'MN': + case 'NW': { + return nicheWallBurialSiteTypeId + } + case 'UG': { + return urnGardenBurialSiteTypeId + } + } + + return casketBurialSiteTypeId +} \ No newline at end of file diff --git a/temp/legacyImportFromCsv/data.cemeteries.d.ts b/temp/legacyImportFromCsv/data.cemeteries.d.ts new file mode 100644 index 00000000..ccf2cce7 --- /dev/null +++ b/temp/legacyImportFromCsv/data.cemeteries.d.ts @@ -0,0 +1 @@ +export declare function getCemeteryIdByKey(cemeteryKey: string, user: User): Promise; diff --git a/temp/legacyImportFromCsv/data.cemeteries.js b/temp/legacyImportFromCsv/data.cemeteries.js new file mode 100644 index 00000000..056be487 --- /dev/null +++ b/temp/legacyImportFromCsv/data.cemeteries.js @@ -0,0 +1,51 @@ +// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair +/* eslint-disable no-console */ +import addCemetery from '../../database/addCemetery.js'; +import { getCemeteryByKey } from '../../database/getCemetery.js'; +const cemeteryToCemeteryName = { + '00': 'Crematorium', + GC: 'New Greenwood - Columbarium', + HC: 'Holy Sepulchre - Columbarium', + HS: 'Holy Sepulchre', + MA: 'Holy Sepulchre - Mausoleum', + MN: 'Mausoleum Niche', + NG: 'New Greenwood', + NW: 'Niche Wall', + OG: 'Old Greenwood', + PG: 'Pine Grove', + UG: 'New Greenwood - Urn Garden', + WK: 'West Korah', + WS: 'West Section' +}; +const cemeteryCache = new Map(); +export async function getCemeteryIdByKey(cemeteryKey, user) { + /* + if (masterRow.CM_CEMETERY === "HS" && + (masterRow.CM_BLOCK === "F" || masterRow.CM_BLOCK === "G" || masterRow.CM_BLOCK === "H" || masterRow.CM_BLOCK === "J")) { + mapCacheKey += "-" + masterRow.CM_BLOCK; + } + */ + if (cemeteryCache.has(cemeteryKey)) { + return cemeteryCache.get(cemeteryKey); + } + const cemetery = await getCemeteryByKey(cemeteryKey); + if (cemetery === undefined) { + console.log(`Creating cemetery: ${cemeteryKey}`); + const cemeteryId = await addCemetery({ + cemeteryName: cemeteryToCemeteryName[cemeteryKey] ?? cemeteryKey, + cemeteryKey, + cemeteryDescription: '', + cemeterySvg: '', + cemeteryLatitude: '', + cemeteryLongitude: '', + cemeteryAddress1: '', + cemeteryAddress2: '', + cemeteryCity: 'Sault Ste. Marie', + cemeteryProvince: 'ON', + cemeteryPostalCode: '', + cemeteryPhoneNumber: '' + }, user); + cemeteryCache.set(cemeteryKey, cemeteryId); + } + return cemeteryCache.get(cemeteryKey); +} diff --git a/temp/legacyImportFromCsv/data.cemeteries.ts b/temp/legacyImportFromCsv/data.cemeteries.ts new file mode 100644 index 00000000..01c250e9 --- /dev/null +++ b/temp/legacyImportFromCsv/data.cemeteries.ts @@ -0,0 +1,67 @@ +// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair +/* eslint-disable no-console */ + +import addCemetery from '../../database/addCemetery.js' +import { getCemeteryByKey } from '../../database/getCemetery.js' + +const cemeteryToCemeteryName = { + '00': 'Crematorium', + GC: 'New Greenwood - Columbarium', + HC: 'Holy Sepulchre - Columbarium', + HS: 'Holy Sepulchre', + MA: 'Holy Sepulchre - Mausoleum', + MN: 'Mausoleum Niche', + NG: 'New Greenwood', + NW: 'Niche Wall', + OG: 'Old Greenwood', + PG: 'Pine Grove', + UG: 'New Greenwood - Urn Garden', + WK: 'West Korah', + WS: 'West Section' +} + +const cemeteryCache = new Map() + +export async function getCemeteryIdByKey( + cemeteryKey: string, + user: User +): Promise { + /* + if (masterRow.CM_CEMETERY === "HS" && + (masterRow.CM_BLOCK === "F" || masterRow.CM_BLOCK === "G" || masterRow.CM_BLOCK === "H" || masterRow.CM_BLOCK === "J")) { + mapCacheKey += "-" + masterRow.CM_BLOCK; + } + */ + + if (cemeteryCache.has(cemeteryKey)) { + return cemeteryCache.get(cemeteryKey) as number + } + + const cemetery = await getCemeteryByKey(cemeteryKey) + + if (cemetery === undefined) { + console.log(`Creating cemetery: ${cemeteryKey}`) + + const cemeteryId = await addCemetery( + { + cemeteryName: cemeteryToCemeteryName[cemeteryKey] ?? cemeteryKey, + cemeteryKey, + cemeteryDescription: '', + cemeterySvg: '', + cemeteryLatitude: '', + cemeteryLongitude: '', + cemeteryAddress1: '', + cemeteryAddress2: '', + cemeteryCity: 'Sault Ste. Marie', + cemeteryProvince: 'ON', + cemeteryPostalCode: '', + cemeteryPhoneNumber: '' + }, + user + ) + + cemeteryCache.set(cemeteryKey, cemeteryId) + } + + return cemeteryCache.get(cemeteryKey) as number +} diff --git a/temp/legacyImportFromCsv/data.committalTypes.d.ts b/temp/legacyImportFromCsv/data.committalTypes.d.ts new file mode 100644 index 00000000..24595eee --- /dev/null +++ b/temp/legacyImportFromCsv/data.committalTypes.d.ts @@ -0,0 +1 @@ +export declare function getCommittalTypeIdByKey(committalTypeKey: string, user: User): Promise; diff --git a/temp/legacyImportFromCsv/data.committalTypes.js b/temp/legacyImportFromCsv/data.committalTypes.js new file mode 100644 index 00000000..d1fd0120 --- /dev/null +++ b/temp/legacyImportFromCsv/data.committalTypes.js @@ -0,0 +1,16 @@ +import addCommittalType from "../../database/addCommittalType.js"; +import getCommittalTypes from "../../database/getCommittalTypes.js"; +let committalTypes = await getCommittalTypes(); +export async function getCommittalTypeIdByKey(committalTypeKey, user) { + const committalType = committalTypes.find((committalType) => committalType.committalTypeKey === + committalTypeKey); + if (committalType === undefined) { + const committalTypeId = await addCommittalType({ + committalTypeKey, + committalType: committalTypeKey + }, user); + committalTypes = await getCommittalTypes(); + return committalTypeId; + } + return committalType.committalTypeId; +} diff --git a/temp/legacyImportFromCsv/data.committalTypes.ts b/temp/legacyImportFromCsv/data.committalTypes.ts new file mode 100644 index 00000000..79ac9dc7 --- /dev/null +++ b/temp/legacyImportFromCsv/data.committalTypes.ts @@ -0,0 +1,31 @@ +import addCommittalType from "../../database/addCommittalType.js"; +import getCommittalTypes from "../../database/getCommittalTypes.js"; + +let committalTypes = await getCommittalTypes() + +export async function getCommittalTypeIdByKey( + committalTypeKey: string, + user: User +): Promise { + const committalType = committalTypes.find( + (committalType) => + committalType.committalTypeKey === + committalTypeKey + ) + + if (committalType === undefined) { + const committalTypeId = await addCommittalType( + { + committalTypeKey, + committalType: committalTypeKey + }, + user + ) + + committalTypes = await getCommittalTypes() + + return committalTypeId + } + + return committalType.committalTypeId +} \ No newline at end of file diff --git a/temp/legacyImportFromCsv/data.deathAgePeriods.d.ts b/temp/legacyImportFromCsv/data.deathAgePeriods.d.ts new file mode 100644 index 00000000..93623bea --- /dev/null +++ b/temp/legacyImportFromCsv/data.deathAgePeriods.d.ts @@ -0,0 +1 @@ +export declare function getDeathAgePeriod(legacyDeathAgePeriod: string): string; diff --git a/temp/legacyImportFromCsv/data.deathAgePeriods.js b/temp/legacyImportFromCsv/data.deathAgePeriods.js new file mode 100644 index 00000000..dc827efe --- /dev/null +++ b/temp/legacyImportFromCsv/data.deathAgePeriods.js @@ -0,0 +1,16 @@ +export function getDeathAgePeriod(legacyDeathAgePeriod) { + switch (legacyDeathAgePeriod.toLowerCase()) { + case 'yrs': { + return 'Years'; + } + case 'mts': { + return 'Months'; + } + case 'dys': { + return 'Days'; + } + default: { + return legacyDeathAgePeriod; + } + } +} diff --git a/temp/legacyImportFromCsv/data.deathAgePeriods.ts b/temp/legacyImportFromCsv/data.deathAgePeriods.ts new file mode 100644 index 00000000..f203a4d9 --- /dev/null +++ b/temp/legacyImportFromCsv/data.deathAgePeriods.ts @@ -0,0 +1,17 @@ +export function getDeathAgePeriod(legacyDeathAgePeriod: string): string { + switch (legacyDeathAgePeriod.toLowerCase()) { + case 'yrs': { + return 'Years' + } + case 'mts': { + return 'Months' + } + case 'dys': { + return 'Days' + } + + default: { + return legacyDeathAgePeriod + } + } +} diff --git a/temp/legacyImportFromCsv/data.fees.d.ts b/temp/legacyImportFromCsv/data.fees.d.ts new file mode 100644 index 00000000..1fc59af0 --- /dev/null +++ b/temp/legacyImportFromCsv/data.fees.d.ts @@ -0,0 +1 @@ +export declare function getFeeIdByFeeDescription(feeDescription: string, user: User): Promise; diff --git a/temp/legacyImportFromCsv/data.fees.js b/temp/legacyImportFromCsv/data.fees.js new file mode 100644 index 00000000..98a020f0 --- /dev/null +++ b/temp/legacyImportFromCsv/data.fees.js @@ -0,0 +1,37 @@ +import sqlite from 'better-sqlite3'; +import addFee from '../../database/addFee.js'; +import { sunriseDB as databasePath } from '../../helpers/database.helpers.js'; +let feeCategoryId = 0; +const feeCache = new Map(); +export async function getFeeIdByFeeDescription(feeDescription, user) { + if (feeCache.keys.length === 0) { + const database = sqlite(databasePath, { + readonly: true + }); + const records = database + .prepare(`select feeId, feeCategoryId, feeDescription + from Fees + where feeDescription like 'CMPP_FEE_%'`) + .all(); + for (const record of records) { + if (feeCategoryId === 0) { + feeCategoryId = record.feeCategoryId; + } + feeCache.set(record.feeDescription, record.feeId); + } + database.close(); + } + let feeId = feeCache.get(feeDescription); + if (feeId === undefined) { + feeId = await addFee({ + feeName: feeDescription.slice(9), + feeDescription, + feeCategoryId, + feeAccount: '', + contractTypeId: '', + burialSiteTypeId: '' + }, user); + feeCache.set(feeDescription, feeId); + } + return feeId; +} diff --git a/temp/legacyImportFromCsv/data.fees.ts b/temp/legacyImportFromCsv/data.fees.ts new file mode 100644 index 00000000..bc23d459 --- /dev/null +++ b/temp/legacyImportFromCsv/data.fees.ts @@ -0,0 +1,61 @@ +import sqlite from 'better-sqlite3' + +import addFee from '../../database/addFee.js' +import { sunriseDB as databasePath } from '../../helpers/database.helpers.js' + +let feeCategoryId = 0 + +const feeCache = new Map() + +export async function getFeeIdByFeeDescription( + feeDescription: string, + user: User +): Promise { + if (feeCache.keys.length === 0) { + const database = sqlite(databasePath, { + readonly: true + }) + + const records = database + .prepare( + `select feeId, feeCategoryId, feeDescription + from Fees + where feeDescription like 'CMPP_FEE_%'` + ) + .all() as Array<{ + feeId: number + feeCategoryId: number + feeDescription: string + }> + + for (const record of records) { + if (feeCategoryId === 0) { + feeCategoryId = record.feeCategoryId + } + + feeCache.set(record.feeDescription, record.feeId) + } + + database.close() + } + + let feeId = feeCache.get(feeDescription) + + if (feeId === undefined) { + feeId = await addFee( + { + feeName: feeDescription.slice(9), + feeDescription, + feeCategoryId, + feeAccount: '', + contractTypeId: '', + burialSiteTypeId: '' + }, + user + ) + + feeCache.set(feeDescription, feeId) + } + + return feeId +} diff --git a/temp/legacyImportFromCsv/data.funeralHomes.d.ts b/temp/legacyImportFromCsv/data.funeralHomes.d.ts new file mode 100644 index 00000000..795e5910 --- /dev/null +++ b/temp/legacyImportFromCsv/data.funeralHomes.d.ts @@ -0,0 +1,2 @@ +export declare function initializeFuneralHomes(user: User): Promise; +export declare function getFuneralHomeIdByKey(funeralHomeKey: string, user: User): Promise; diff --git a/temp/legacyImportFromCsv/data.funeralHomes.js b/temp/legacyImportFromCsv/data.funeralHomes.js new file mode 100644 index 00000000..a0c7de77 --- /dev/null +++ b/temp/legacyImportFromCsv/data.funeralHomes.js @@ -0,0 +1,106 @@ +import addFuneralHome from "../../database/addFuneralHome.js"; +const funeralHomes = [ + { + funeralHomeKey: 'AR', + funeralHomeName: 'Arthur Funeral Home', + funeralHomeAddress1: '492 Wellington Street East', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6A 2L9', + funeralHomePhoneNumber: '705-759-2522' + }, + { + funeralHomeKey: 'BG', + funeralHomeName: 'Beggs Funeral Home', + funeralHomeAddress1: '175 Main Street', + funeralHomeAddress2: 'P.O. Box 280', + funeralHomeCity: 'Thessalon', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P0R 1L0', + funeralHomePhoneNumber: '705-842-2520' + }, + { + funeralHomeKey: 'BK', + funeralHomeName: 'Barton and Kiteley', + funeralHomeAddress1: '', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: '', + funeralHomePhoneNumber: '' + }, + { + funeralHomeKey: 'DA', + funeralHomeName: 'Damignani Burial, Cremation and Transfer Service', + funeralHomeAddress1: '215 St. James Street', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6A 1P7', + funeralHomePhoneNumber: '705-759-8456' + }, + { + funeralHomeKey: 'GL', + funeralHomeName: 'Gilmartin P.M. Funeral Home', + funeralHomeAddress1: '140 Churchill Avenue', + funeralHomeAddress2: '', + funeralHomeCity: 'Wawa', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P0S 1K0', + funeralHomePhoneNumber: '705-856-7340' + }, + { + funeralHomeKey: 'NO', + funeralHomeName: 'Northwood Funeral Home', + funeralHomeAddress1: '942 Great Northern Road', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6B 0B6', + funeralHomePhoneNumber: '705-945-7758' + }, + { + funeralHomeKey: 'OS', + funeralHomeName: "O'Sullivan Funeral Home", + funeralHomeAddress1: '215 St. James Street', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6A 1P7', + funeralHomePhoneNumber: '705-759-8456' + } +]; +const funeralHomeKeyToId = new Map(); +export async function initializeFuneralHomes(user) { + for (const funeralHome of funeralHomes) { + const funeralHomeId = await addFuneralHome({ + funeralHomeName: funeralHome.funeralHomeName ?? '', + funeralHomeKey: funeralHome.funeralHomeKey ?? '', + funeralHomeAddress1: funeralHome.funeralHomeAddress1 ?? '', + funeralHomeAddress2: funeralHome.funeralHomeAddress2 ?? '', + funeralHomeCity: funeralHome.funeralHomeCity ?? '', + funeralHomeProvince: funeralHome.funeralHomeProvince ?? '', + funeralHomePostalCode: funeralHome.funeralHomePostalCode ?? '', + funeralHomePhoneNumber: funeralHome.funeralHomePhoneNumber ?? '' + }, user); + funeralHomeKeyToId.set(funeralHome.funeralHomeKey ?? '', funeralHomeId); + } +} +export async function getFuneralHomeIdByKey(funeralHomeKey, user) { + if (funeralHomeKeyToId.has(funeralHomeKey)) { + return funeralHomeKeyToId.get(funeralHomeKey); + } + const funeralHomeId = await addFuneralHome({ + funeralHomeName: funeralHomeKey, + funeralHomeKey, + funeralHomeAddress1: '', + funeralHomeAddress2: '', + funeralHomeCity: '', + funeralHomeProvince: '', + funeralHomePostalCode: '', + funeralHomePhoneNumber: '' + }, user); + funeralHomeKeyToId.set(funeralHomeKey, funeralHomeId); + return funeralHomeId; +} diff --git a/temp/legacyImportFromCsv/data.funeralHomes.ts b/temp/legacyImportFromCsv/data.funeralHomes.ts new file mode 100644 index 00000000..bb3d0a0f --- /dev/null +++ b/temp/legacyImportFromCsv/data.funeralHomes.ts @@ -0,0 +1,124 @@ +import addFuneralHome from "../../database/addFuneralHome.js" +import type { FuneralHome } from "../../types/recordTypes.js" + +const funeralHomes: FuneralHome[] = [ + { + funeralHomeKey: 'AR', + funeralHomeName: 'Arthur Funeral Home', + funeralHomeAddress1: '492 Wellington Street East', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6A 2L9', + funeralHomePhoneNumber: '705-759-2522' + }, + { + funeralHomeKey: 'BG', + funeralHomeName: 'Beggs Funeral Home', + funeralHomeAddress1: '175 Main Street', + funeralHomeAddress2: 'P.O. Box 280', + funeralHomeCity: 'Thessalon', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P0R 1L0', + funeralHomePhoneNumber: '705-842-2520' + }, + { + funeralHomeKey: 'BK', + funeralHomeName: 'Barton and Kiteley', + funeralHomeAddress1: '', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: '', + funeralHomePhoneNumber: '' + }, + { + funeralHomeKey: 'DA', + funeralHomeName: 'Damignani Burial, Cremation and Transfer Service', + funeralHomeAddress1: '215 St. James Street', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6A 1P7', + funeralHomePhoneNumber: '705-759-8456' + }, + { + funeralHomeKey: 'GL', + funeralHomeName: 'Gilmartin P.M. Funeral Home', + funeralHomeAddress1: '140 Churchill Avenue', + funeralHomeAddress2: '', + funeralHomeCity: 'Wawa', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P0S 1K0', + funeralHomePhoneNumber: '705-856-7340' + }, + { + funeralHomeKey: 'NO', + funeralHomeName: 'Northwood Funeral Home', + funeralHomeAddress1: '942 Great Northern Road', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6B 0B6', + funeralHomePhoneNumber: '705-945-7758' + }, + { + funeralHomeKey: 'OS', + funeralHomeName: "O'Sullivan Funeral Home", + funeralHomeAddress1: '215 St. James Street', + funeralHomeAddress2: '', + funeralHomeCity: 'Sault Ste. Marie', + funeralHomeProvince: 'ON', + funeralHomePostalCode: 'P6A 1P7', + funeralHomePhoneNumber: '705-759-8456' + } +] + +const funeralHomeKeyToId = new Map() + +export async function initializeFuneralHomes(user: User): Promise { + for (const funeralHome of funeralHomes) { + const funeralHomeId = await addFuneralHome( + { + funeralHomeName: funeralHome.funeralHomeName ?? '', + funeralHomeKey: funeralHome.funeralHomeKey ?? '', + funeralHomeAddress1: funeralHome.funeralHomeAddress1 ?? '', + funeralHomeAddress2: funeralHome.funeralHomeAddress2 ?? '', + funeralHomeCity: funeralHome.funeralHomeCity ?? '', + funeralHomeProvince: funeralHome.funeralHomeProvince ?? '', + funeralHomePostalCode: funeralHome.funeralHomePostalCode ?? '', + funeralHomePhoneNumber: funeralHome.funeralHomePhoneNumber ?? '' + }, + user + ) + + funeralHomeKeyToId.set(funeralHome.funeralHomeKey ?? '', funeralHomeId) + } +} + +export async function getFuneralHomeIdByKey( + funeralHomeKey: string, + user: User +): Promise { + if (funeralHomeKeyToId.has(funeralHomeKey)) { + return funeralHomeKeyToId.get(funeralHomeKey) as number + } + + const funeralHomeId = await addFuneralHome( + { + funeralHomeName: funeralHomeKey, + funeralHomeKey, + funeralHomeAddress1: '', + funeralHomeAddress2: '', + funeralHomeCity: '', + funeralHomeProvince: '', + funeralHomePostalCode: '', + funeralHomePhoneNumber: '' + }, + user + ) + + funeralHomeKeyToId.set(funeralHomeKey, funeralHomeId) + + return funeralHomeId +} \ No newline at end of file diff --git a/temp/legacyImportFromCsv/data.ids.d.ts b/temp/legacyImportFromCsv/data.ids.d.ts new file mode 100644 index 00000000..d48eea59 --- /dev/null +++ b/temp/legacyImportFromCsv/data.ids.d.ts @@ -0,0 +1,12 @@ +export declare const availableBurialSiteStatusId: number; +export declare const reservedBurialSiteStatusId: number; +export declare const takenBurialSiteStatusId: number; +export declare const preneedContractType: import("../../types/recordTypes.js").ContractType; +export declare const deceasedContractType: import("../../types/recordTypes.js").ContractType; +export declare const cremationContractType: import("../../types/recordTypes.js").ContractType; +export declare const acknowledgedWorkOrderMilestoneTypeId: number | undefined; +export declare const deathWorkOrderMilestoneTypeId: number | undefined; +export declare const funeralWorkOrderMilestoneTypeId: number | undefined; +export declare const cremationWorkOrderMilestoneTypeId: number | undefined; +export declare const intermentWorkOrderMilestoneTypeId: number | undefined; +export declare const workOrderTypeId = 1; diff --git a/temp/legacyImportFromCsv/data.ids.js b/temp/legacyImportFromCsv/data.ids.js new file mode 100644 index 00000000..b14ec10f --- /dev/null +++ b/temp/legacyImportFromCsv/data.ids.js @@ -0,0 +1,30 @@ +// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair +/* eslint-disable @typescript-eslint/no-non-null-assertion, unicorn/no-await-expression-member */ +import * as cacheFunctions from '../../helpers/functions.cache.js'; +/* + * Burial Site Status IDs + */ +export const availableBurialSiteStatusId = (await cacheFunctions.getBurialSiteStatusByBurialSiteStatus('Available')) + .burialSiteStatusId; +export const reservedBurialSiteStatusId = (await cacheFunctions.getBurialSiteStatusByBurialSiteStatus('Reserved')) + .burialSiteStatusId; +export const takenBurialSiteStatusId = (await cacheFunctions.getBurialSiteStatusByBurialSiteStatus('Taken')) + .burialSiteStatusId; +/* + * Contract Type IDs + */ +export const preneedContractType = (await cacheFunctions.getContractTypeByContractType('Preneed')); +export const deceasedContractType = (await cacheFunctions.getContractTypeByContractType('Interment')); +export const cremationContractType = (await cacheFunctions.getContractTypeByContractType('Cremation')); +/* + * Work Order Milestone Type IDs + */ +export const acknowledgedWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Acknowledged'))?.workOrderMilestoneTypeId; +export const deathWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Death'))?.workOrderMilestoneTypeId; +export const funeralWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Funeral'))?.workOrderMilestoneTypeId; +export const cremationWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Cremation'))?.workOrderMilestoneTypeId; +export const intermentWorkOrderMilestoneTypeId = (await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType('Interment'))?.workOrderMilestoneTypeId; +/* + * Work Order Type IDs + */ +export const workOrderTypeId = 1; diff --git a/temp/legacyImportFromCsv/data.ids.ts b/temp/legacyImportFromCsv/data.ids.ts new file mode 100644 index 00000000..62c05faf --- /dev/null +++ b/temp/legacyImportFromCsv/data.ids.ts @@ -0,0 +1,74 @@ +// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair +/* eslint-disable @typescript-eslint/no-non-null-assertion, unicorn/no-await-expression-member */ + +import * as cacheFunctions from '../../helpers/functions.cache.js' + +/* + * Burial Site Status IDs + */ + +export const availableBurialSiteStatusId = + (await cacheFunctions.getBurialSiteStatusByBurialSiteStatus('Available'))! + .burialSiteStatusId + +export const reservedBurialSiteStatusId = + (await cacheFunctions.getBurialSiteStatusByBurialSiteStatus('Reserved'))! + .burialSiteStatusId + +export const takenBurialSiteStatusId = + (await cacheFunctions.getBurialSiteStatusByBurialSiteStatus('Taken'))! + .burialSiteStatusId + + +/* + * Contract Type IDs + */ + +export const preneedContractType = + (await cacheFunctions.getContractTypeByContractType('Preneed'))! + +export const deceasedContractType = + (await cacheFunctions.getContractTypeByContractType('Interment'))! + +export const cremationContractType = + (await cacheFunctions.getContractTypeByContractType('Cremation'))! + +/* + * Work Order Milestone Type IDs + */ + +export const acknowledgedWorkOrderMilestoneTypeId = ( + await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( + 'Acknowledged' + ) +)?.workOrderMilestoneTypeId + +export const deathWorkOrderMilestoneTypeId = ( + await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( + 'Death' + ) +)?.workOrderMilestoneTypeId + +export const funeralWorkOrderMilestoneTypeId = ( + await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( + 'Funeral' + ) +)?.workOrderMilestoneTypeId + +export const cremationWorkOrderMilestoneTypeId = ( + await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( + 'Cremation' + ) +)?.workOrderMilestoneTypeId + +export const intermentWorkOrderMilestoneTypeId = ( + await cacheFunctions.getWorkOrderMilestoneTypeByWorkOrderMilestoneType( + 'Interment' + ) +)?.workOrderMilestoneTypeId + +/* + * Work Order Type IDs + */ + +export const workOrderTypeId = 1 diff --git a/temp/legacyImportFromCsv/data.intermentContainerTypes.d.ts b/temp/legacyImportFromCsv/data.intermentContainerTypes.d.ts new file mode 100644 index 00000000..6024450a --- /dev/null +++ b/temp/legacyImportFromCsv/data.intermentContainerTypes.d.ts @@ -0,0 +1 @@ +export declare function getIntermentContainerTypeIdByKey(intermentContainerTypeKey: string, user: User): Promise; diff --git a/temp/legacyImportFromCsv/data.intermentContainerTypes.js b/temp/legacyImportFromCsv/data.intermentContainerTypes.js new file mode 100644 index 00000000..a4214366 --- /dev/null +++ b/temp/legacyImportFromCsv/data.intermentContainerTypes.js @@ -0,0 +1,16 @@ +import addIntermentContainerType from '../../database/addIntermentContainerType.js'; +import getIntermentContainerTypes from '../../database/getIntermentContainerTypes.js'; +let intermentContainerTypes = await getIntermentContainerTypes(); +export async function getIntermentContainerTypeIdByKey(intermentContainerTypeKey, user) { + const intermentContainerType = intermentContainerTypes.find((intermentContainerType) => intermentContainerType.intermentContainerTypeKey === + intermentContainerTypeKey); + if (intermentContainerType === undefined) { + const intermentContainerTypeId = await addIntermentContainerType({ + intermentContainerTypeKey, + intermentContainerType: intermentContainerTypeKey + }, user); + intermentContainerTypes = await getIntermentContainerTypes(); + return intermentContainerTypeId; + } + return intermentContainerType.intermentContainerTypeId; +} diff --git a/temp/legacyImportFromCsv/data.intermentContainerTypes.ts b/temp/legacyImportFromCsv/data.intermentContainerTypes.ts new file mode 100644 index 00000000..b158a122 --- /dev/null +++ b/temp/legacyImportFromCsv/data.intermentContainerTypes.ts @@ -0,0 +1,31 @@ +import addIntermentContainerType from '../../database/addIntermentContainerType.js' +import getIntermentContainerTypes from '../../database/getIntermentContainerTypes.js' + +let intermentContainerTypes = await getIntermentContainerTypes() + +export async function getIntermentContainerTypeIdByKey( + intermentContainerTypeKey: string, + user: User +): Promise { + const intermentContainerType = intermentContainerTypes.find( + (intermentContainerType) => + intermentContainerType.intermentContainerTypeKey === + intermentContainerTypeKey + ) + + if (intermentContainerType === undefined) { + const intermentContainerTypeId = await addIntermentContainerType( + { + intermentContainerTypeKey, + intermentContainerType: intermentContainerTypeKey + }, + user + ) + + intermentContainerTypes = await getIntermentContainerTypes() + + return intermentContainerTypeId + } + + return intermentContainerType.intermentContainerTypeId +} diff --git a/temp/legacy.importFromCSV.d.ts b/temp/legacyImportFromCsv/index.d.ts similarity index 100% rename from temp/legacy.importFromCSV.d.ts rename to temp/legacyImportFromCsv/index.d.ts diff --git a/temp/legacyImportFromCsv/index.js b/temp/legacyImportFromCsv/index.js new file mode 100644 index 00000000..ea319f4d --- /dev/null +++ b/temp/legacyImportFromCsv/index.js @@ -0,0 +1,818 @@ +// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair +/* eslint-disable @cspell/spellchecker, @typescript-eslint/no-non-null-assertion, no-console, max-lines */ +import fs from 'node:fs'; +import { dateIntegerToString, dateToString } from '@cityssm/utils-datetime'; +import sqlite from 'better-sqlite3'; +import papa from 'papaparse'; +import addBurialSite from '../../database/addBurialSite.js'; +import addContract from '../../database/addContract.js'; +import addContractComment from '../../database/addContractComment.js'; +import addContractFee from '../../database/addContractFee.js'; +import addContractTransaction from '../../database/addContractTransaction.js'; +import addWorkOrder from '../../database/addWorkOrder.js'; +import addWorkOrderBurialSite from '../../database/addWorkOrderBurialSite.js'; +import addWorkOrderContract from '../../database/addWorkOrderContract.js'; +import addWorkOrderMilestone from '../../database/addWorkOrderMilestone.js'; +import closeWorkOrder from '../../database/closeWorkOrder.js'; +import getBurialSite, { getBurialSiteByBurialSiteName } from '../../database/getBurialSite.js'; +import getContracts from '../../database/getContracts.js'; +import getWorkOrder, { getWorkOrderByWorkOrderNumber } from '../../database/getWorkOrder.js'; +import reopenWorkOrder from '../../database/reopenWorkOrder.js'; +import { updateBurialSiteStatus } from '../../database/updateBurialSite.js'; +import { buildBurialSiteName } from '../../helpers/burialSites.helpers.js'; +import { sunriseDB as databasePath } from '../../helpers/database.helpers.js'; +import { getBurialSiteTypeId } from './data.burialSiteTypes.js'; +import { getCemeteryIdByKey } from './data.cemeteries.js'; +import { getCommittalTypeIdByKey } from './data.committalTypes.js'; +import { getDeathAgePeriod } from './data.deathAgePeriods.js'; +import { getFeeIdByFeeDescription } from './data.fees.js'; +import { getFuneralHomeIdByKey } from './data.funeralHomes.js'; +import * as importIds from './data.ids.js'; +import { getIntermentContainerTypeIdByKey } from './data.intermentContainerTypes.js'; +const user = { + userName: 'import.unix', + userProperties: { + canUpdate: true, + isAdmin: false, + apiKey: '' + } +}; +function purgeTables() { + console.time('purgeTables'); + const tablesToPurge = [ + 'WorkOrderMilestones', + 'WorkOrderComments', + 'WorkOrderBurialSites', + 'WorkOrderContracts', + 'WorkOrders', + 'ContractTransactions', + 'ContractFees', + 'ContractFields', + 'ContractComments', + 'ContractInterments', + 'Contracts', + 'FuneralHomes', + 'BurialSiteFields', + 'BurialSiteComments', + 'BurialSites' + ]; + const database = sqlite(databasePath); + for (const tableName of tablesToPurge) { + database.prepare(`delete from ${tableName}`).run(); + database + .prepare('delete from sqlite_sequence where name = ?') + .run(tableName); + } + database.close(); + console.timeEnd('purgeTables'); +} +function purgeConfigTables() { + console.time('purgeConfigTables'); + const database = sqlite(databasePath); + database.prepare('delete from Cemeteries').run(); + database + .prepare("delete from sqlite_sequence where name in ('Cemeteries')") + .run(); + database.close(); + console.timeEnd('purgeConfigTables'); +} +function formatDateString(year, month, day) { + const formattedYear = `0000${year}`.slice(-4); + const formattedMonth = `00${month}`.slice(-2); + const formattedDay = `00${day}`.slice(-2); + return `${formattedYear}-${formattedMonth}-${formattedDay}`; +} +function formatTimeString(hour, minute) { + const formattedHour = `00${hour}`.slice(-2); + const formattedMinute = `00${minute}`.slice(-2); + return `${formattedHour}:${formattedMinute}`; +} +// eslint-disable-next-line complexity +async function importFromMasterCSV() { + console.time('importFromMasterCSV'); + let masterRow; + const rawData = fs.readFileSync('./temp/CMMASTER.csv').toString(); + const cmmaster = papa.parse(rawData, { + delimiter: ',', + header: true, + skipEmptyLines: true + }); + for (const parseError of cmmaster.errors) { + console.log(parseError); + } + try { + for (masterRow of cmmaster.data) { + const cemeteryId = await getCemeteryIdByKey(masterRow.CM_CEMETERY, user); + const burialSiteTypeId = getBurialSiteTypeId(masterRow.CM_CEMETERY); + let burialSiteId; + if (masterRow.CM_CEMETERY !== '00') { + const burialSiteNameSegment1 = masterRow.CM_BLOCK === '0' ? '' : masterRow.CM_BLOCK; + const burialSiteNameSegment2 = (masterRow.CM_RANGE1 === '0' ? '' : masterRow.CM_RANGE1) + + (masterRow.CM_RANGE2 === '0' ? '' : masterRow.CM_RANGE2); + const burialSiteNameSegment3 = (masterRow.CM_LOT1 === '0' ? '' : masterRow.CM_LOT1) + + (masterRow.CM_LOT2 === '0' ? '' : masterRow.CM_LOT2); + const burialSiteNameSegment4 = (masterRow.CM_GRAVE1 === '0' ? '' : masterRow.CM_GRAVE1) + + (masterRow.CM_GRAVE2 === '0' ? '' : masterRow.CM_GRAVE2); + const burialSiteName = buildBurialSiteName(masterRow.CM_CEMETERY, { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4 + }); + const burialSite = await getBurialSiteByBurialSiteName(burialSiteName); + burialSiteId = + burialSite === undefined + ? await addBurialSite({ + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4, + burialSiteTypeId, + burialSiteStatusId: importIds.availableBurialSiteStatusId, + cemeteryId, + cemeterySvgId: '', + burialSiteLatitude: '', + burialSiteLongitude: '' + }, user) + : burialSite.burialSiteId; + } + /* + * Preneed Record + */ + let preneedContractStartDateString; + let preneedContractId; + if (masterRow.CM_PRENEED_OWNER !== '' || masterRow.CM_STATUS === 'P') { + preneedContractStartDateString = formatDateString(masterRow.CM_PURCHASE_YR, masterRow.CM_PURCHASE_MON, masterRow.CM_PURCHASE_DAY); + let contractEndDateString = ''; + if (masterRow.CM_INTERMENT_YR !== '' && + masterRow.CM_INTERMENT_YR !== '0') { + contractEndDateString = formatDateString(masterRow.CM_INTERMENT_YR, masterRow.CM_INTERMENT_MON, masterRow.CM_INTERMENT_DAY); + } + // if purchase date unavailable + if (preneedContractStartDateString === '0000-00-00' && + contractEndDateString !== '') { + preneedContractStartDateString = contractEndDateString; + } + // if end date unavailable + if (preneedContractStartDateString === '0000-00-00' && + masterRow.CM_DEATH_YR !== '' && + masterRow.CM_DEATH_YR !== '0') { + preneedContractStartDateString = formatDateString(masterRow.CM_DEATH_YR, masterRow.CM_DEATH_MON, masterRow.CM_DEATH_DAY); + // if death took place, and there's no preneed end date + if (contractEndDateString === '0000-00-00' || + contractEndDateString === '') { + contractEndDateString = preneedContractStartDateString; + } + } + if (preneedContractStartDateString === '' || + preneedContractStartDateString === '0000-00-00') { + preneedContractStartDateString = '0001-01-01'; + } + const purchaserPostalCode = `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim(); + preneedContractId = await addContract({ + contractTypeId: importIds.preneedContractType.contractTypeId, + burialSiteId: burialSiteId ?? '', + contractStartDateString: preneedContractStartDateString, + contractEndDateString, + contractTypeFieldIds: '', + purchaserName: masterRow.CM_PRENEED_OWNER, + purchaserAddress1: masterRow.CM_ADDRESS, + purchaserAddress2: '', + purchaserCity: masterRow.CM_CITY, + purchaserProvince: masterRow.CM_PROV, + purchaserPostalCode, + purchaserPhoneNumber: '', + purchaserEmail: '', + deceasedName: masterRow.CM_DECEASED_NAME === '' + ? masterRow.CM_PRENEED_OWNER + : masterRow.CM_DECEASED_NAME, + deceasedAddress1: masterRow.CM_ADDRESS, + deceasedAddress2: '', + deceasedCity: masterRow.CM_CITY, + deceasedProvince: masterRow.CM_PROV, + deceasedPostalCode: purchaserPostalCode + }, user); + if (masterRow.CM_REMARK1 !== '') { + await addContractComment({ + contractId: preneedContractId, + commentDateString: preneedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK1 + }, user); + } + if (masterRow.CM_REMARK2 !== '') { + await addContractComment({ + contractId: preneedContractId, + commentDateString: preneedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK2 + }, user); + } + if (masterRow.CM_WORK_ORDER.trim() !== '') { + await addContractComment({ + contractId: preneedContractId, + commentDateString: preneedContractStartDateString, + commentTimeString: '00:00', + comment: `Imported Contract #${masterRow.CM_WORK_ORDER}` + }, user); + } + if (contractEndDateString === '') { + await updateBurialSiteStatus(burialSiteId ?? '', importIds.reservedBurialSiteStatusId, user); + } + } + /* + * Interment Record + */ + let deceasedContractStartDateString; + let deceasedContractId; + if (masterRow.CM_DECEASED_NAME !== '') { + deceasedContractStartDateString = formatDateString(masterRow.CM_INTERMENT_YR, masterRow.CM_INTERMENT_MON, masterRow.CM_INTERMENT_DAY); + // if interment date unavailable + if (deceasedContractStartDateString === '0000-00-00' && + masterRow.CM_DEATH_YR !== '' && + masterRow.CM_DEATH_YR !== '0') { + deceasedContractStartDateString = formatDateString(masterRow.CM_DEATH_YR, masterRow.CM_DEATH_MON, masterRow.CM_DEATH_DAY); + } + if (deceasedContractStartDateString === '' || + deceasedContractStartDateString === '0000-00-00') { + deceasedContractStartDateString = '0001-01-01'; + } + const deceasedContractEndDateString = burialSiteId + ? '' + : deceasedContractStartDateString; + const contractType = burialSiteId + ? importIds.deceasedContractType + : importIds.cremationContractType; + const deceasedPostalCode = `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim(); + const funeralHomeId = masterRow.CM_FUNERAL_HOME === '' + ? '' + : await getFuneralHomeIdByKey(masterRow.CM_FUNERAL_HOME, user); + const funeralDateString = masterRow.CM_FUNERAL_YR === '' + ? '' + : formatDateString(masterRow.CM_FUNERAL_YR, masterRow.CM_FUNERAL_MON, masterRow.CM_FUNERAL_DAY); + const committalTypeId = contractType.contractType === 'Cremation' || + masterRow.CM_COMMITTAL_TYPE === '' + ? '' + : await getCommittalTypeIdByKey(masterRow.CM_COMMITTAL_TYPE, user); + const deathDateString = masterRow.CM_DEATH_YR === '' + ? '' + : formatDateString(masterRow.CM_DEATH_YR, masterRow.CM_DEATH_MON, masterRow.CM_DEATH_DAY); + const intermentContainerTypeKey = contractType.contractType === 'Cremation' && + masterRow.CM_CONTAINER_TYPE !== '' + ? 'U' + : masterRow.CM_CONTAINER_TYPE; + const intermentContainerTypeId = intermentContainerTypeKey === '' + ? '' + : await getIntermentContainerTypeIdByKey(intermentContainerTypeKey, user); + deceasedContractId = await addContract({ + contractTypeId: contractType.contractTypeId, + burialSiteId: burialSiteId ?? '', + contractStartDateString: deceasedContractStartDateString, + contractEndDateString: deceasedContractEndDateString, + contractTypeFieldIds: '', + funeralHomeId, + funeralDirectorName: masterRow.CM_FUNERAL_HOME, + funeralDateString, + committalTypeId, + purchaserName: masterRow.CM_PRENEED_OWNER === '' + ? masterRow.CM_DECEASED_NAME + : masterRow.CM_PRENEED_OWNER, + purchaserAddress1: masterRow.CM_ADDRESS, + purchaserAddress2: '', + purchaserCity: masterRow.CM_CITY, + purchaserProvince: masterRow.CM_PROV, + purchaserPostalCode: deceasedPostalCode, + purchaserPhoneNumber: '', + purchaserEmail: '', + deceasedName: masterRow.CM_DECEASED_NAME, + deceasedAddress1: masterRow.CM_ADDRESS, + deceasedAddress2: '', + deceasedCity: masterRow.CM_CITY, + deceasedProvince: masterRow.CM_PROV, + deceasedPostalCode, + birthDateString: '', + birthPlace: '', + deathDateString, + deathPlace: '', + deathAge: masterRow.CM_AGE, + deathAgePeriod: getDeathAgePeriod(masterRow.CM_PERIOD), + intermentContainerTypeId + }, user); + if (masterRow.CM_REMARK1 !== '') { + await addContractComment({ + contractId: deceasedContractId, + commentDateString: deceasedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK1 + }, user); + } + if (masterRow.CM_REMARK2 !== '') { + await addContractComment({ + contractId: deceasedContractId, + commentDateString: deceasedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK2 + }, user); + } + if (masterRow.CM_WORK_ORDER.trim() !== '') { + await addContractComment({ + contractId: deceasedContractId, + commentDateString: deceasedContractStartDateString, + commentTimeString: '00:00', + comment: `Imported Contract #${masterRow.CM_WORK_ORDER}` + }, user); + } + await updateBurialSiteStatus(burialSiteId ?? '', importIds.takenBurialSiteStatusId, user); + } + } + } + catch (error) { + console.error(error); + console.log(masterRow); + } + console.timeEnd('importFromMasterCSV'); +} +// eslint-disable-next-line complexity +async function importFromPrepaidCSV() { + console.time('importFromPrepaidCSV'); + let prepaidRow; + const rawData = fs.readFileSync('./temp/CMPRPAID.csv').toString(); + const cmprpaid = papa.parse(rawData, { + delimiter: ',', + header: true, + skipEmptyLines: true + }); + for (const parseError of cmprpaid.errors) { + console.log(parseError); + } + try { + for (prepaidRow of cmprpaid.data) { + if (!prepaidRow.CMPP_PREPAID_FOR_NAME) { + continue; + } + let cemeteryKey = prepaidRow.CMPP_CEMETERY; + if (cemeteryKey === '.m') { + cemeteryKey = 'HC'; + } + let burialSite; + if (cemeteryKey !== '') { + const cemeteryId = await getCemeteryIdByKey(cemeteryKey, user); + const burialSiteNameSegment1 = prepaidRow.CMPP_BLOCK === '0' ? '' : prepaidRow.CMPP_BLOCK; + const burialSiteNameSegment2 = (prepaidRow.CMPP_RANGE1 === '0' ? '' : prepaidRow.CMPP_RANGE1) + + (prepaidRow.CMPP_RANGE2 === '0' ? '' : prepaidRow.CMPP_RANGE2); + const burialSiteNameSegment3 = (prepaidRow.CMPP_LOT1 === '0' ? '' : prepaidRow.CMPP_LOT1) + + (prepaidRow.CMPP_LOT2 === '0' ? '' : prepaidRow.CMPP_LOT2); + const burialSiteNameSegment4 = (prepaidRow.CMPP_GRAVE1 === '0' ? '' : prepaidRow.CMPP_GRAVE1) + + (prepaidRow.CMPP_GRAVE2 === '0' ? '' : prepaidRow.CMPP_GRAVE2); + const burialSiteName = buildBurialSiteName(cemeteryKey, { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4 + }); + burialSite = await getBurialSiteByBurialSiteName(burialSiteName); + if (!burialSite) { + const burialSiteTypeId = getBurialSiteTypeId(cemeteryKey); + const burialSiteId = await addBurialSite({ + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4, + burialSiteTypeId, + burialSiteStatusId: importIds.reservedBurialSiteStatusId, + cemeteryId, + cemeterySvgId: burialSiteName.includes(',') + ? burialSiteName.split(',')[0] + : burialSiteName, + burialSiteLatitude: '', + burialSiteLongitude: '' + }, user); + burialSite = await getBurialSite(burialSiteId); + } + } + if (burialSite && + burialSite.burialSiteStatusId === importIds.availableBurialSiteStatusId) { + await updateBurialSiteStatus(burialSite.burialSiteId, importIds.reservedBurialSiteStatusId, user); + } + const contractStartDateString = formatDateString(prepaidRow.CMPP_PURCH_YR, prepaidRow.CMPP_PURCH_MON, prepaidRow.CMPP_PURCH_DAY); + let contractId; + if (burialSite) { + const possibleContracts = await getContracts({ + burialSiteId: burialSite.burialSiteId, + contractTypeId: importIds.preneedContractType.contractTypeId, + deceasedName: prepaidRow.CMPP_PREPAID_FOR_NAME, + contractStartDateString + }, { + includeInterments: false, + includeFees: false, + includeTransactions: false, + limit: -1, + offset: 0 + }); + if (possibleContracts.contracts.length > 0) { + contractId = possibleContracts.contracts[0].contractId; + } + } + contractId ||= await addContract({ + burialSiteId: burialSite ? burialSite.burialSiteId : '', + contractTypeId: importIds.preneedContractType.contractTypeId, + contractStartDateString, + contractEndDateString: '', + purchaserName: prepaidRow.CMPP_ARRANGED_BY_NAME, + deceasedName: prepaidRow.CMPP_PREPAID_FOR_NAME, + deceasedAddress1: prepaidRow.CMPP_ADDRESS, + deceasedAddress2: '', + deceasedCity: prepaidRow.CMPP_CITY, + deceasedProvince: prepaidRow.CMPP_PROV.slice(0, 2), + deceasedPostalCode: `${prepaidRow.CMPP_POSTAL1} ${prepaidRow.CMPP_POSTAL2}` + }, user); + if (prepaidRow.CMPP_FEE_GRAV_SD !== '0.0') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_GRAV_SD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_GRAV_SD, + taxAmount: prepaidRow.CMPP_GST_GRAV_SD + }, user); + } + if (prepaidRow.CMPP_FEE_GRAV_DD !== '0.0') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_GRAV_DD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_GRAV_DD, + taxAmount: prepaidRow.CMPP_GST_GRAV_DD + }, user); + } + if (prepaidRow.CMPP_FEE_CHAP_SD !== '0.0') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_CHAP_SD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_CHAP_SD, + taxAmount: prepaidRow.CMPP_GST_CHAP_SD + }, user); + } + if (prepaidRow.CMPP_FEE_CHAP_DD !== '0.0') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_CHAP_DD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_CHAP_DD, + taxAmount: prepaidRow.CMPP_GST_CHAP_DD + }, user); + } + if (prepaidRow.CMPP_FEE_ENTOMBMENT !== '0.0') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_ENTOMBMENT', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_ENTOMBMENT, + taxAmount: prepaidRow.CMPP_GST_ENTOMBMENT + }, user); + } + if (prepaidRow.CMPP_FEE_CREM !== '0.0') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_CREM', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_CREM, + taxAmount: prepaidRow.CMPP_GST_CREM + }, user); + } + if (prepaidRow.CMPP_FEE_NICHE !== '0.0') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_NICHE', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_NICHE, + taxAmount: prepaidRow.CMPP_GST_NICHE + }, user); + } + if (prepaidRow.CMPP_FEE_DISINTERMENT !== '0.0' && + prepaidRow.CMPP_FEE_DISINTERMENT !== '20202.02') { + await addContractFee({ + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_DISINTERMENT', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_DISINTERMENT, + taxAmount: prepaidRow.CMPP_GST_DISINTERMENT + }, user); + } + const transactionAmount = Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_SD) + + Number.parseFloat(prepaidRow.CMPP_GST_GRAV_SD) + + Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_DD) + + Number.parseFloat(prepaidRow.CMPP_GST_GRAV_DD) + + Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_SD) + + Number.parseFloat(prepaidRow.CMPP_GST_CHAP_SD) + + Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_DD) + + Number.parseFloat(prepaidRow.CMPP_GST_CHAP_DD) + + Number.parseFloat(prepaidRow.CMPP_FEE_ENTOMBMENT) + + Number.parseFloat(prepaidRow.CMPP_GST_ENTOMBMENT) + + Number.parseFloat(prepaidRow.CMPP_FEE_CREM) + + Number.parseFloat(prepaidRow.CMPP_GST_CREM) + + Number.parseFloat(prepaidRow.CMPP_FEE_NICHE) + + Number.parseFloat(prepaidRow.CMPP_GST_NICHE) + + Number.parseFloat(prepaidRow.CMPP_FEE_DISINTERMENT === '20202.02' + ? '0' + : prepaidRow.CMPP_FEE_DISINTERMENT) + + Number.parseFloat(prepaidRow.CMPP_GST_DISINTERMENT === '20202.02' + ? '0' + : prepaidRow.CMPP_GST_DISINTERMENT); + await addContractTransaction({ + contractId, + externalReceiptNumber: '', + transactionAmount, + transactionDateString: contractStartDateString, + transactionNote: `Order Number: ${prepaidRow.CMPP_ORDER_NO}` + }, user); + if (prepaidRow.CMPP_REMARK1 !== '') { + await addContractComment({ + contractId, + commentDateString: contractStartDateString, + comment: prepaidRow.CMPP_REMARK1 + }, user); + } + if (prepaidRow.CMPP_REMARK2 !== '') { + await addContractComment({ + contractId, + commentDateString: contractStartDateString, + comment: prepaidRow.CMPP_REMARK2 + }, user); + } + } + } + catch (error) { + console.error(error); + console.log(prepaidRow); + } + console.timeEnd('importFromPrepaidCSV'); +} +// eslint-disable-next-line complexity +async function importFromWorkOrderCSV() { + console.time('importFromWorkOrderCSV'); + let workOrderRow; + const rawData = fs.readFileSync('./temp/CMWKORDR.csv').toString(); + const cmwkordr = papa.parse(rawData, { + delimiter: ',', + header: true, + skipEmptyLines: true + }); + for (const parseError of cmwkordr.errors) { + console.log(parseError); + } + const currentDateString = dateToString(new Date()); + try { + for (workOrderRow of cmwkordr.data) { + const workOrderNumber = `000000${workOrderRow.WO_WORK_ORDER}`.slice(-6); + let workOrder = await getWorkOrderByWorkOrderNumber(workOrderNumber); + const workOrderOpenDateString = dateIntegerToString(Number.parseInt(workOrderRow.WO_INITIATION_DATE, 10)); + if (workOrder) { + if (workOrder.workOrderCloseDate) { + await reopenWorkOrder(workOrder.workOrderId, user); + delete workOrder.workOrderCloseDate; + delete workOrder.workOrderCloseDateString; + } + } + else { + const workOrderId = await addWorkOrder({ + workOrderNumber, + workOrderTypeId: importIds.workOrderTypeId, + workOrderDescription: `${workOrderRow.WO_REMARK1} ${workOrderRow.WO_REMARK2} ${workOrderRow.WO_REMARK3}`.trim(), + workOrderOpenDateString + }, user); + workOrder = await getWorkOrder(workOrderId, { + includeBurialSites: true, + includeComments: true, + includeMilestones: true + }); + } + let burialSite; + if (workOrderRow.WO_CEMETERY !== '00') { + const burialSiteNameSegment1 = workOrderRow.WO_BLOCK === '0' ? '' : workOrderRow.WO_BLOCK; + const burialSiteNameSegment2 = (workOrderRow.WO_RANGE1 === '0' ? '' : workOrderRow.WO_RANGE1) + + (workOrderRow.WO_RANGE2 === '0' ? '' : workOrderRow.WO_RANGE2); + const burialSiteNameSegment3 = (workOrderRow.WO_LOT1 === '0' ? '' : workOrderRow.WO_LOT1) + + (workOrderRow.WO_LOT2 === '0' ? '' : workOrderRow.WO_LOT2); + const burialSiteNameSegment4 = (workOrderRow.WO_GRAVE1 === '0' ? '' : workOrderRow.WO_GRAVE1) + + (workOrderRow.WO_GRAVE2 === '0' ? '' : workOrderRow.WO_GRAVE2); + const burialSiteName = buildBurialSiteName(workOrderRow.WO_CEMETERY, { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4 + }); + burialSite = await getBurialSiteByBurialSiteName(burialSiteName); + if (burialSite) { + await updateBurialSiteStatus(burialSite.burialSiteId, importIds.takenBurialSiteStatusId, user); + } + else { + const cemeteryId = await getCemeteryIdByKey(workOrderRow.WO_CEMETERY, user); + const burialSiteTypeId = getBurialSiteTypeId(workOrderRow.WO_CEMETERY); + const burialSiteId = await addBurialSite({ + cemeteryId, + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4, + cemeterySvgId: burialSiteName.includes(',') + ? burialSiteName.split(',')[0] + : burialSiteName, + burialSiteStatusId: importIds.takenBurialSiteStatusId, + burialSiteTypeId, + burialSiteLatitude: '', + burialSiteLongitude: '' + }, user); + burialSite = await getBurialSite(burialSiteId); + } + const workOrderContainsLot = workOrder.workOrderBurialSites.find((possibleLot) => (possibleLot.burialSiteId = burialSite.burialSiteId)); + if (!workOrderContainsLot) { + await addWorkOrderBurialSite({ + workOrderId: workOrder.workOrderId, + burialSiteId: burialSite.burialSiteId + }, user); + workOrder.workOrderBurialSites.push(burialSite); + } + } + let contractStartDateString = workOrderOpenDateString; + if (workOrderRow.WO_INTERMENT_YR) { + contractStartDateString = formatDateString(workOrderRow.WO_INTERMENT_YR, workOrderRow.WO_INTERMENT_MON, workOrderRow.WO_INTERMENT_DAY); + } + const contractType = burialSite + ? importIds.deceasedContractType + : importIds.cremationContractType; + const funeralHomeId = workOrderRow.WO_FUNERAL_HOME === '' + ? '' + : await getFuneralHomeIdByKey(workOrderRow.WO_FUNERAL_HOME, user); + const committalTypeId = contractType.contractType === 'Cremation' || + workOrderRow.WO_COMMITTAL_TYPE === '' + ? '' + : await getCommittalTypeIdByKey(workOrderRow.WO_COMMITTAL_TYPE, user); + const intermentContainerTypeKey = contractType.contractType === 'Cremation' && + workOrderRow.WO_CONTAINER_TYPE !== '' + ? 'U' + : workOrderRow.WO_CONTAINER_TYPE; + const intermentContainerTypeId = intermentContainerTypeKey === '' + ? '' + : await getIntermentContainerTypeIdByKey(intermentContainerTypeKey, user); + const contractId = await addContract({ + burialSiteId: burialSite ? burialSite.burialSiteId : '', + contractTypeId: contractType.contractTypeId, + contractStartDateString, + contractEndDateString: '', + funeralHomeId, + funeralDirectorName: workOrderRow.WO_FUNERAL_HOME, + funeralDateString: workOrderRow.WO_FUNERAL_YR === '' + ? '' + : formatDateString(workOrderRow.WO_FUNERAL_YR, workOrderRow.WO_FUNERAL_MON, workOrderRow.WO_FUNERAL_DAY), + committalTypeId, + deceasedName: workOrderRow.WO_DECEASED_NAME, + deceasedAddress1: workOrderRow.WO_ADDRESS, + deceasedAddress2: '', + deceasedCity: workOrderRow.WO_CITY, + deceasedProvince: workOrderRow.WO_PROV.slice(0, 2), + deceasedPostalCode: `${workOrderRow.WO_POST1} ${workOrderRow.WO_POST2}`, + deathDateString: workOrderRow.WO_DEATH_YR === '' + ? '' + : formatDateString(workOrderRow.WO_DEATH_YR, workOrderRow.WO_DEATH_MON, workOrderRow.WO_DEATH_DAY), + deathPlace: workOrderRow.WO_DEATH_PLACE, + deathAge: workOrderRow.WO_AGE, + deathAgePeriod: getDeathAgePeriod(workOrderRow.WO_PERIOD), + intermentContainerTypeId + }, user); + await addWorkOrderContract({ + workOrderId: workOrder.workOrderId, + contractId + }, user); + // Milestones + let hasIncompleteMilestones = !workOrderRow.WO_CONFIRMATION_IN; + let maxMilestoneCompletionDateString = workOrderOpenDateString; + if (importIds.acknowledgedWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone({ + workOrderId: workOrder.workOrderId, + workOrderMilestoneTypeId: importIds.acknowledgedWorkOrderMilestoneTypeId, + workOrderMilestoneDateString: workOrderOpenDateString, + workOrderMilestoneDescription: '', + workOrderMilestoneCompletionDateString: workOrderRow.WO_CONFIRMATION_IN + ? workOrderOpenDateString + : undefined, + workOrderMilestoneCompletionTimeString: workOrderRow.WO_CONFIRMATION_IN ? '00:00' : undefined + }, user); + } + if (workOrderRow.WO_DEATH_YR) { + const workOrderMilestoneDateString = formatDateString(workOrderRow.WO_DEATH_YR, workOrderRow.WO_DEATH_MON, workOrderRow.WO_DEATH_DAY); + if (importIds.deathWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone({ + workOrderId: workOrder.workOrderId, + workOrderMilestoneTypeId: importIds.deathWorkOrderMilestoneTypeId, + workOrderMilestoneDateString, + workOrderMilestoneDescription: `Death Place: ${workOrderRow.WO_DEATH_PLACE}`, + workOrderMilestoneCompletionDateString: workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneDateString + : undefined, + workOrderMilestoneCompletionTimeString: workOrderMilestoneDateString < currentDateString + ? '00:00' + : undefined + }, user); + } + if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { + maxMilestoneCompletionDateString = workOrderMilestoneDateString; + } + if (workOrderMilestoneDateString >= currentDateString) { + hasIncompleteMilestones = true; + } + } + if (workOrderRow.WO_FUNERAL_YR) { + const workOrderMilestoneDateString = formatDateString(workOrderRow.WO_FUNERAL_YR, workOrderRow.WO_FUNERAL_MON, workOrderRow.WO_FUNERAL_DAY); + let funeralHour = Number.parseInt(workOrderRow.WO_FUNERAL_HR === '' ? '0' : workOrderRow.WO_FUNERAL_HR, 10); + if (funeralHour <= 6) { + funeralHour += 12; + } + const workOrderMilestoneTimeString = formatTimeString(funeralHour.toString(), workOrderRow.WO_FUNERAL_MIN === '' ? '0' : workOrderRow.WO_FUNERAL_MIN); + if (importIds.funeralWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone({ + workOrderId: workOrder.workOrderId, + workOrderMilestoneTypeId: importIds.funeralWorkOrderMilestoneTypeId, + workOrderMilestoneDateString, + workOrderMilestoneTimeString, + workOrderMilestoneDescription: `Funeral Home: ${workOrderRow.WO_FUNERAL_HOME}`, + workOrderMilestoneCompletionDateString: workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneDateString + : undefined, + workOrderMilestoneCompletionTimeString: workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneTimeString + : undefined + }, user); + } + if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { + maxMilestoneCompletionDateString = workOrderMilestoneDateString; + } + if (workOrderMilestoneDateString >= currentDateString) { + hasIncompleteMilestones = true; + } + } + if (workOrderRow.WO_CREMATION === 'Y' && + importIds.cremationWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone({ + workOrderId: workOrder.workOrderId, + workOrderMilestoneTypeId: importIds.cremationWorkOrderMilestoneTypeId, + workOrderMilestoneDateString: maxMilestoneCompletionDateString, + workOrderMilestoneDescription: '', + workOrderMilestoneCompletionDateString: maxMilestoneCompletionDateString < currentDateString + ? maxMilestoneCompletionDateString + : undefined, + workOrderMilestoneCompletionTimeString: maxMilestoneCompletionDateString < currentDateString + ? '00:00' + : undefined + }, user); + } + if (workOrderRow.WO_INTERMENT_YR) { + const workOrderMilestoneDateString = formatDateString(workOrderRow.WO_INTERMENT_YR, workOrderRow.WO_INTERMENT_MON, workOrderRow.WO_INTERMENT_DAY); + if (importIds.intermentWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone({ + workOrderId: workOrder.workOrderId, + workOrderMilestoneTypeId: importIds.intermentWorkOrderMilestoneTypeId, + workOrderMilestoneDateString, + workOrderMilestoneDescription: `Depth: ${workOrderRow.WO_DEPTH}`, + workOrderMilestoneCompletionDateString: workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneDateString + : undefined, + workOrderMilestoneCompletionTimeString: workOrderMilestoneDateString < currentDateString + ? '23:59' + : undefined + }, user); + } + if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { + maxMilestoneCompletionDateString = workOrderMilestoneDateString; + } + if (workOrderMilestoneDateString >= currentDateString) { + hasIncompleteMilestones = true; + } + } + if (!hasIncompleteMilestones) { + await closeWorkOrder({ + workOrderId: workOrder.workOrderId, + workOrderCloseDateString: maxMilestoneCompletionDateString + }, user); + } + } + } + catch (error) { + console.error(error); + console.log(workOrderRow); + } + console.timeEnd('importFromWorkOrderCSV'); +} +console.log(`Started ${new Date().toLocaleString()}`); +console.time('importFromCsv'); +// Purge Tables +//purgeTables() +//purgeConfigTables() +// Initialize SSM Data +//await initializeFuneralHomes(user) +// Do Imports +//await importFromMasterCSV() +await importFromPrepaidCSV(); +await importFromWorkOrderCSV(); +console.timeEnd('importFromCsv'); +console.log(`Finished ${new Date().toLocaleString()}`); diff --git a/temp/legacyImportFromCsv/index.ts b/temp/legacyImportFromCsv/index.ts new file mode 100644 index 00000000..1fc7409e --- /dev/null +++ b/temp/legacyImportFromCsv/index.ts @@ -0,0 +1,1409 @@ +// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair +/* eslint-disable @cspell/spellchecker, @typescript-eslint/no-non-null-assertion, no-console, max-lines */ + +import fs from 'node:fs' + +import { + type DateString, + type TimeString, + dateIntegerToString, + dateToString +} from '@cityssm/utils-datetime' +import sqlite from 'better-sqlite3' +import papa from 'papaparse' + +import addBurialSite from '../../database/addBurialSite.js' +import addContract from '../../database/addContract.js' +import addContractComment from '../../database/addContractComment.js' +import addContractFee from '../../database/addContractFee.js' +import addContractTransaction from '../../database/addContractTransaction.js' +import addWorkOrder from '../../database/addWorkOrder.js' +import addWorkOrderBurialSite from '../../database/addWorkOrderBurialSite.js' +import addWorkOrderContract from '../../database/addWorkOrderContract.js' +import addWorkOrderMilestone from '../../database/addWorkOrderMilestone.js' +import closeWorkOrder from '../../database/closeWorkOrder.js' +import getBurialSite, { + getBurialSiteByBurialSiteName +} from '../../database/getBurialSite.js' +import getContracts from '../../database/getContracts.js' +import getWorkOrder, { + getWorkOrderByWorkOrderNumber +} from '../../database/getWorkOrder.js' +import reopenWorkOrder from '../../database/reopenWorkOrder.js' +import { updateBurialSiteStatus } from '../../database/updateBurialSite.js' +import { buildBurialSiteName } from '../../helpers/burialSites.helpers.js' +import { sunriseDB as databasePath } from '../../helpers/database.helpers.js' +import type * as recordTypes from '../../types/recordTypes.js' + +import { getBurialSiteTypeId } from './data.burialSiteTypes.js' +import { getCemeteryIdByKey } from './data.cemeteries.js' +import { getCommittalTypeIdByKey } from './data.committalTypes.js' +import { getDeathAgePeriod } from './data.deathAgePeriods.js' +import { getFeeIdByFeeDescription } from './data.fees.js' +import { + getFuneralHomeIdByKey, + initializeFuneralHomes +} from './data.funeralHomes.js' +import * as importIds from './data.ids.js' +import { getIntermentContainerTypeIdByKey } from './data.intermentContainerTypes.js' + +interface MasterRecord { + CM_SYSREC: string + CM_CEMETERY: string + CM_BLOCK: string + CM_RANGE1: string + CM_RANGE2: string + CM_LOT1: string + CM_LOT2: string + CM_GRAVE1: string + CM_GRAVE2: string + CM_INTERMENT: string + CM_PRENEED_OWNER: string + CM_PRENEED_OWNER_SEQ: string + CM_DECEASED_NAME: string + CM_DECEASED_NAME_SEQ: string + CM_ADDRESS: string + CM_CITY: string + CM_PROV: string + CM_POST1: string + CM_POST2: string + CM_PRENEED_ORDER: string + CM_PURCHASE_YR: string + CM_PURCHASE_MON: string + CM_PURCHASE_DAY: string + CM_NO_GRAVES: string + CM_DEATH_YR: string + CM_DEATH_MON: string + CM_DEATH_DAY: string + CM_WORK_ORDER: string + CM_INTERMENT_YR: string + CM_INTERMENT_MON: string + CM_INTERMENT_DAY: string + CM_AGE: string + CM_CONTAINER_TYPE: string + CM_COMMITTAL_TYPE: string + CM_CREMATION: string + CM_FUNERAL_HOME: string + CM_FUNERAL_YR: string + CM_FUNERAL_MON: string + CM_FUNERAL_DAY: string + CM_RESIDENT_TYPE: string + CM_REMARK1: string + CM_REMARK2: string + CM_STATUS: string + CM_PERIOD: string + CM_LAST_CHG_DATE: string + CM_DEPTH: string +} + +interface PrepaidRecord { + CMPP_SYSREC: string + CMPP_PREPAID_FOR_NAME: string + CMPP_PREPAID_FOR_SEQ: string + CMPP_ADDRESS: string + CMPP_CITY: string + CMPP_PROV: string + CMPP_POSTAL1: string + CMPP_POSTAL2: string + CMPP_ARRANGED_BY_NAME: string + CMPP_ARRANGED_BY_SEQ: string + CMPP_CEMETERY: string + CMPP_BLOCK: string + CMPP_RANGE1: string + CMPP_RANGE2: string + CMPP_LOT1: string + CMPP_LOT2: string + CMPP_GRAVE1: string + CMPP_GRAVE2: string + CMPP_INTERMENT: string + CMPP_ORDER_NO: string + CMPP_PURCH_YR: string + CMPP_PURCH_MON: string + CMPP_PURCH_DAY: string + CMPP_FEE_GRAV_SD: string + CMPP_GST_GRAV_SD: string + CMPP_FEE_GRAV_DD: string + CMPP_GST_GRAV_DD: string + CMPP_FEE_CHAP_SD: string + CMPP_GST_CHAP_SD: string + CMPP_FEE_CHAP_DD: string + CMPP_GST_CHAP_DD: string + CMPP_FEE_ENTOMBMENT: string + CMPP_GST_ENTOMBMENT: string + CMPP_FEE_CREM: string + CMPP_GST_CREM: string + CMPP_FEE_NICHE: string + CMPP_GST_NICHE: string + CMPP_FEE_DISINTERMENT: string + CMPP_GST_DISINTERMENT: string + CMPP_REMARK1: string + CMPP_REMARK2: string +} + +interface WorkOrderRecord { + WO_SYSREC: string + WO_DECEASED_NAME: string + WO_DECEASED_SEQ: string + WO_CEMETERY: string + WO_BLOCK: string + WO_RANGE1: string + WO_RANGE2: string + WO_LOT1: string + WO_LOT2: string + WO_GRAVE1: string + WO_GRAVE2: string + WO_INTERMENT: string + WO_ADDRESS: string + WO_CITY: string + WO_PROV: string + WO_POST1: string + WO_POST2: string + WO_DEATH_YR: string + WO_DEATH_MON: string + WO_DEATH_DAY: string + WO_AGE: string + WO_FUNERAL_HOME: string + WO_FUNERAL_YR: string + WO_FUNERAL_MON: string + WO_FUNERAL_DAY: string + WO_FUNERAL_HR: string + WO_FUNERAL_MIN: string + WO_INTERMENT_YR: string + WO_INTERMENT_MON: string + WO_INTERMENT_DAY: string + WO_COST: string + WO_COMMITTAL_TYPE: string + WO_CONTAINER_TYPE: string + WO_CREMATION: string + WO_CONFIRMATION_IN: string + WO_COMPLETION_YR: string + WO_COMPLETION_MON: string + WO_COMPLETION_DAY: string + WO_INITIATION_DATE: string + WO_WORK_ORDER: string + WO_REMARK1: string + WO_REMARK2: string + WO_REMARK3: string + WO_PERIOD: string + WO_RESIDENT_TYPE: string + WO_DEPTH: string + WO_DEATH_PLACE: string +} + +const user: User = { + userName: 'import.unix', + userProperties: { + canUpdate: true, + isAdmin: false, + apiKey: '' + } +} + +function purgeTables(): void { + console.time('purgeTables') + + const tablesToPurge = [ + 'WorkOrderMilestones', + 'WorkOrderComments', + 'WorkOrderBurialSites', + 'WorkOrderContracts', + 'WorkOrders', + 'ContractTransactions', + 'ContractFees', + 'ContractFields', + 'ContractComments', + 'ContractInterments', + 'Contracts', + 'FuneralHomes', + 'BurialSiteFields', + 'BurialSiteComments', + 'BurialSites' + ] + + const database = sqlite(databasePath) + + for (const tableName of tablesToPurge) { + database.prepare(`delete from ${tableName}`).run() + database + .prepare('delete from sqlite_sequence where name = ?') + .run(tableName) + } + + database.close() + + console.timeEnd('purgeTables') +} + +function purgeConfigTables(): void { + console.time('purgeConfigTables') + + const database = sqlite(databasePath) + database.prepare('delete from Cemeteries').run() + database + .prepare("delete from sqlite_sequence where name in ('Cemeteries')") + .run() + database.close() + + console.timeEnd('purgeConfigTables') +} + +function formatDateString( + year: string, + month: string, + day: string +): DateString { + const formattedYear = `0000${year}`.slice(-4) + const formattedMonth = `00${month}`.slice(-2) + const formattedDay = `00${day}`.slice(-2) + + return `${formattedYear}-${formattedMonth}-${formattedDay}` as DateString +} + +function formatTimeString(hour: string, minute: string): TimeString { + const formattedHour = `00${hour}`.slice(-2) + const formattedMinute = `00${minute}`.slice(-2) + + return `${formattedHour}:${formattedMinute}` as TimeString +} + +// eslint-disable-next-line complexity +async function importFromMasterCSV(): Promise { + console.time('importFromMasterCSV') + + let masterRow: MasterRecord + + const rawData = fs.readFileSync('./temp/CMMASTER.csv').toString() + + const cmmaster: papa.ParseResult = papa.parse(rawData, { + delimiter: ',', + header: true, + skipEmptyLines: true + }) + + for (const parseError of cmmaster.errors) { + console.log(parseError) + } + + try { + for (masterRow of cmmaster.data) { + const cemeteryId = await getCemeteryIdByKey(masterRow.CM_CEMETERY, user) + + const burialSiteTypeId = getBurialSiteTypeId(masterRow.CM_CEMETERY) + + let burialSiteId: number | undefined + + if (masterRow.CM_CEMETERY !== '00') { + const burialSiteNameSegment1 = + masterRow.CM_BLOCK === '0' ? '' : masterRow.CM_BLOCK + const burialSiteNameSegment2 = + (masterRow.CM_RANGE1 === '0' ? '' : masterRow.CM_RANGE1) + + (masterRow.CM_RANGE2 === '0' ? '' : masterRow.CM_RANGE2) + const burialSiteNameSegment3 = + (masterRow.CM_LOT1 === '0' ? '' : masterRow.CM_LOT1) + + (masterRow.CM_LOT2 === '0' ? '' : masterRow.CM_LOT2) + const burialSiteNameSegment4 = + (masterRow.CM_GRAVE1 === '0' ? '' : masterRow.CM_GRAVE1) + + (masterRow.CM_GRAVE2 === '0' ? '' : masterRow.CM_GRAVE2) + + const burialSiteName = buildBurialSiteName(masterRow.CM_CEMETERY, { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4 + }) + + const burialSite = await getBurialSiteByBurialSiteName(burialSiteName) + + burialSiteId = + burialSite === undefined + ? await addBurialSite( + { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4, + burialSiteTypeId, + burialSiteStatusId: importIds.availableBurialSiteStatusId, + cemeteryId, + cemeterySvgId: '', + burialSiteLatitude: '', + burialSiteLongitude: '' + }, + user + ) + : burialSite.burialSiteId + } + + /* + * Preneed Record + */ + + let preneedContractStartDateString: DateString | '' + let preneedContractId: number + + if (masterRow.CM_PRENEED_OWNER !== '' || masterRow.CM_STATUS === 'P') { + preneedContractStartDateString = formatDateString( + masterRow.CM_PURCHASE_YR, + masterRow.CM_PURCHASE_MON, + masterRow.CM_PURCHASE_DAY + ) + + let contractEndDateString: DateString | '' = '' + + if ( + masterRow.CM_INTERMENT_YR !== '' && + masterRow.CM_INTERMENT_YR !== '0' + ) { + contractEndDateString = formatDateString( + masterRow.CM_INTERMENT_YR, + masterRow.CM_INTERMENT_MON, + masterRow.CM_INTERMENT_DAY + ) + } + + // if purchase date unavailable + if ( + preneedContractStartDateString === '0000-00-00' && + contractEndDateString !== '' + ) { + preneedContractStartDateString = contractEndDateString + } + + // if end date unavailable + if ( + preneedContractStartDateString === '0000-00-00' && + masterRow.CM_DEATH_YR !== '' && + masterRow.CM_DEATH_YR !== '0' + ) { + preneedContractStartDateString = formatDateString( + masterRow.CM_DEATH_YR, + masterRow.CM_DEATH_MON, + masterRow.CM_DEATH_DAY + ) + + // if death took place, and there's no preneed end date + if ( + contractEndDateString === '0000-00-00' || + contractEndDateString === '' + ) { + contractEndDateString = preneedContractStartDateString + } + } + + if ( + preneedContractStartDateString === '' || + preneedContractStartDateString === '0000-00-00' + ) { + preneedContractStartDateString = '0001-01-01' + } + + const purchaserPostalCode = + `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim() + + preneedContractId = await addContract( + { + contractTypeId: importIds.preneedContractType.contractTypeId, + burialSiteId: burialSiteId ?? '', + contractStartDateString: preneedContractStartDateString, + contractEndDateString, + contractTypeFieldIds: '', + + purchaserName: masterRow.CM_PRENEED_OWNER, + purchaserAddress1: masterRow.CM_ADDRESS, + purchaserAddress2: '', + purchaserCity: masterRow.CM_CITY, + purchaserProvince: masterRow.CM_PROV, + purchaserPostalCode, + purchaserPhoneNumber: '', + purchaserEmail: '', + + deceasedName: + masterRow.CM_DECEASED_NAME === '' + ? masterRow.CM_PRENEED_OWNER + : masterRow.CM_DECEASED_NAME, + + deceasedAddress1: masterRow.CM_ADDRESS, + deceasedAddress2: '', + deceasedCity: masterRow.CM_CITY, + deceasedProvince: masterRow.CM_PROV, + deceasedPostalCode: purchaserPostalCode + }, + user + ) + + if (masterRow.CM_REMARK1 !== '') { + await addContractComment( + { + contractId: preneedContractId, + commentDateString: preneedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK1 + }, + user + ) + } + + if (masterRow.CM_REMARK2 !== '') { + await addContractComment( + { + contractId: preneedContractId, + commentDateString: preneedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK2 + }, + user + ) + } + + if (masterRow.CM_WORK_ORDER.trim() !== '') { + await addContractComment( + { + contractId: preneedContractId, + commentDateString: preneedContractStartDateString, + commentTimeString: '00:00', + comment: `Imported Contract #${masterRow.CM_WORK_ORDER}` + }, + user + ) + } + + if (contractEndDateString === '') { + await updateBurialSiteStatus( + burialSiteId ?? '', + importIds.reservedBurialSiteStatusId, + user + ) + } + } + + /* + * Interment Record + */ + + let deceasedContractStartDateString: DateString | '' + let deceasedContractId: number + + if (masterRow.CM_DECEASED_NAME !== '') { + deceasedContractStartDateString = formatDateString( + masterRow.CM_INTERMENT_YR, + masterRow.CM_INTERMENT_MON, + masterRow.CM_INTERMENT_DAY + ) + + // if interment date unavailable + if ( + deceasedContractStartDateString === '0000-00-00' && + masterRow.CM_DEATH_YR !== '' && + masterRow.CM_DEATH_YR !== '0' + ) { + deceasedContractStartDateString = formatDateString( + masterRow.CM_DEATH_YR, + masterRow.CM_DEATH_MON, + masterRow.CM_DEATH_DAY + ) + } + + if ( + deceasedContractStartDateString === '' || + deceasedContractStartDateString === '0000-00-00' + ) { + deceasedContractStartDateString = '0001-01-01' + } + + const deceasedContractEndDateString = burialSiteId + ? '' + : deceasedContractStartDateString + + const contractType = burialSiteId + ? importIds.deceasedContractType + : importIds.cremationContractType + + const deceasedPostalCode = + `${masterRow.CM_POST1} ${masterRow.CM_POST2}`.trim() + + const funeralHomeId = + masterRow.CM_FUNERAL_HOME === '' + ? '' + : await getFuneralHomeIdByKey(masterRow.CM_FUNERAL_HOME, user) + + const funeralDateString = + masterRow.CM_FUNERAL_YR === '' + ? '' + : formatDateString( + masterRow.CM_FUNERAL_YR, + masterRow.CM_FUNERAL_MON, + masterRow.CM_FUNERAL_DAY + ) + + const committalTypeId = + contractType.contractType === 'Cremation' || + masterRow.CM_COMMITTAL_TYPE === '' + ? '' + : await getCommittalTypeIdByKey(masterRow.CM_COMMITTAL_TYPE, user) + + const deathDateString = + masterRow.CM_DEATH_YR === '' + ? '' + : formatDateString( + masterRow.CM_DEATH_YR, + masterRow.CM_DEATH_MON, + masterRow.CM_DEATH_DAY + ) + + const intermentContainerTypeKey = + contractType.contractType === 'Cremation' && + masterRow.CM_CONTAINER_TYPE !== '' + ? 'U' + : masterRow.CM_CONTAINER_TYPE + + const intermentContainerTypeId = + intermentContainerTypeKey === '' + ? '' + : await getIntermentContainerTypeIdByKey( + intermentContainerTypeKey, + user + ) + + deceasedContractId = await addContract( + { + contractTypeId: contractType.contractTypeId, + burialSiteId: burialSiteId ?? '', + contractStartDateString: deceasedContractStartDateString, + contractEndDateString: deceasedContractEndDateString, + contractTypeFieldIds: '', + + funeralHomeId, + funeralDirectorName: masterRow.CM_FUNERAL_HOME, + funeralDateString, + committalTypeId, + + purchaserName: + masterRow.CM_PRENEED_OWNER === '' + ? masterRow.CM_DECEASED_NAME + : masterRow.CM_PRENEED_OWNER, + + purchaserAddress1: masterRow.CM_ADDRESS, + purchaserAddress2: '', + purchaserCity: masterRow.CM_CITY, + purchaserProvince: masterRow.CM_PROV, + purchaserPostalCode: deceasedPostalCode, + purchaserPhoneNumber: '', + purchaserEmail: '', + + deceasedName: masterRow.CM_DECEASED_NAME, + deceasedAddress1: masterRow.CM_ADDRESS, + deceasedAddress2: '', + deceasedCity: masterRow.CM_CITY, + deceasedProvince: masterRow.CM_PROV, + deceasedPostalCode, + + birthDateString: '', + birthPlace: '', + deathDateString, + deathPlace: '', + deathAge: masterRow.CM_AGE, + deathAgePeriod: getDeathAgePeriod(masterRow.CM_PERIOD), + intermentContainerTypeId + }, + user + ) + + if (masterRow.CM_REMARK1 !== '') { + await addContractComment( + { + contractId: deceasedContractId, + commentDateString: deceasedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK1 + }, + user + ) + } + + if (masterRow.CM_REMARK2 !== '') { + await addContractComment( + { + contractId: deceasedContractId, + commentDateString: deceasedContractStartDateString, + commentTimeString: '00:00', + comment: masterRow.CM_REMARK2 + }, + user + ) + } + + if (masterRow.CM_WORK_ORDER.trim() !== '') { + await addContractComment( + { + contractId: deceasedContractId, + commentDateString: deceasedContractStartDateString, + commentTimeString: '00:00', + comment: `Imported Contract #${masterRow.CM_WORK_ORDER}` + }, + user + ) + } + + await updateBurialSiteStatus( + burialSiteId ?? '', + importIds.takenBurialSiteStatusId, + user + ) + } + } + } catch (error) { + console.error(error) + console.log(masterRow) + } + + console.timeEnd('importFromMasterCSV') +} + +// eslint-disable-next-line complexity +async function importFromPrepaidCSV(): Promise { + console.time('importFromPrepaidCSV') + + let prepaidRow: PrepaidRecord + + const rawData = fs.readFileSync('./temp/CMPRPAID.csv').toString() + + const cmprpaid: papa.ParseResult = papa.parse(rawData, { + delimiter: ',', + header: true, + skipEmptyLines: true + }) + + for (const parseError of cmprpaid.errors) { + console.log(parseError) + } + + try { + for (prepaidRow of cmprpaid.data) { + if (!prepaidRow.CMPP_PREPAID_FOR_NAME) { + continue + } + + let cemeteryKey = prepaidRow.CMPP_CEMETERY + + if (cemeteryKey === '.m') { + cemeteryKey = 'HC' + } + + let burialSite: recordTypes.BurialSite | undefined + + if (cemeteryKey !== '') { + const cemeteryId = await getCemeteryIdByKey(cemeteryKey, user) + + const burialSiteNameSegment1 = + prepaidRow.CMPP_BLOCK === '0' ? '' : prepaidRow.CMPP_BLOCK + + const burialSiteNameSegment2 = + (prepaidRow.CMPP_RANGE1 === '0' ? '' : prepaidRow.CMPP_RANGE1) + + (prepaidRow.CMPP_RANGE2 === '0' ? '' : prepaidRow.CMPP_RANGE2) + + const burialSiteNameSegment3 = + (prepaidRow.CMPP_LOT1 === '0' ? '' : prepaidRow.CMPP_LOT1) + + (prepaidRow.CMPP_LOT2 === '0' ? '' : prepaidRow.CMPP_LOT2) + + const burialSiteNameSegment4 = + (prepaidRow.CMPP_GRAVE1 === '0' ? '' : prepaidRow.CMPP_GRAVE1) + + (prepaidRow.CMPP_GRAVE2 === '0' ? '' : prepaidRow.CMPP_GRAVE2) + + const burialSiteName = buildBurialSiteName(cemeteryKey, { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4 + }) + + burialSite = await getBurialSiteByBurialSiteName(burialSiteName) + + if (!burialSite) { + const burialSiteTypeId = getBurialSiteTypeId(cemeteryKey) + + const burialSiteId = await addBurialSite( + { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4, + burialSiteTypeId, + burialSiteStatusId: importIds.reservedBurialSiteStatusId, + cemeteryId, + cemeterySvgId: burialSiteName.includes(',') + ? burialSiteName.split(',')[0] + : burialSiteName, + burialSiteLatitude: '', + burialSiteLongitude: '' + }, + user + ) + + burialSite = await getBurialSite(burialSiteId) + } + } + + if ( + burialSite && + burialSite.burialSiteStatusId === importIds.availableBurialSiteStatusId + ) { + await updateBurialSiteStatus( + burialSite.burialSiteId, + importIds.reservedBurialSiteStatusId, + user + ) + } + + const contractStartDateString = formatDateString( + prepaidRow.CMPP_PURCH_YR, + prepaidRow.CMPP_PURCH_MON, + prepaidRow.CMPP_PURCH_DAY + ) + + let contractId: number + + if (burialSite) { + const possibleContracts = await getContracts( + { + burialSiteId: burialSite.burialSiteId, + contractTypeId: importIds.preneedContractType.contractTypeId, + deceasedName: prepaidRow.CMPP_PREPAID_FOR_NAME, + contractStartDateString + }, + { + includeInterments: false, + includeFees: false, + includeTransactions: false, + limit: -1, + offset: 0 + } + ) + + if (possibleContracts.contracts.length > 0) { + contractId = possibleContracts.contracts[0].contractId! + } + } + + contractId ||= await addContract( + { + burialSiteId: burialSite ? burialSite.burialSiteId : '', + contractTypeId: importIds.preneedContractType.contractTypeId, + contractStartDateString, + contractEndDateString: '', + + purchaserName: prepaidRow.CMPP_ARRANGED_BY_NAME, + + deceasedName: prepaidRow.CMPP_PREPAID_FOR_NAME, + deceasedAddress1: prepaidRow.CMPP_ADDRESS, + deceasedAddress2: '', + deceasedCity: prepaidRow.CMPP_CITY, + deceasedProvince: prepaidRow.CMPP_PROV.slice(0, 2), + deceasedPostalCode: `${prepaidRow.CMPP_POSTAL1} ${prepaidRow.CMPP_POSTAL2}` + }, + user + ) + + if (prepaidRow.CMPP_FEE_GRAV_SD !== '0.0') { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_GRAV_SD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_GRAV_SD, + taxAmount: prepaidRow.CMPP_GST_GRAV_SD + }, + user + ) + } + + if (prepaidRow.CMPP_FEE_GRAV_DD !== '0.0') { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_GRAV_DD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_GRAV_DD, + taxAmount: prepaidRow.CMPP_GST_GRAV_DD + }, + user + ) + } + + if (prepaidRow.CMPP_FEE_CHAP_SD !== '0.0') { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_CHAP_SD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_CHAP_SD, + taxAmount: prepaidRow.CMPP_GST_CHAP_SD + }, + user + ) + } + + if (prepaidRow.CMPP_FEE_CHAP_DD !== '0.0') { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_CHAP_DD', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_CHAP_DD, + taxAmount: prepaidRow.CMPP_GST_CHAP_DD + }, + user + ) + } + + if (prepaidRow.CMPP_FEE_ENTOMBMENT !== '0.0') { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_ENTOMBMENT', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_ENTOMBMENT, + taxAmount: prepaidRow.CMPP_GST_ENTOMBMENT + }, + user + ) + } + + if (prepaidRow.CMPP_FEE_CREM !== '0.0') { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_CREM', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_CREM, + taxAmount: prepaidRow.CMPP_GST_CREM + }, + user + ) + } + + if (prepaidRow.CMPP_FEE_NICHE !== '0.0') { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription('CMPP_FEE_NICHE', user), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_NICHE, + taxAmount: prepaidRow.CMPP_GST_NICHE + }, + user + ) + } + + if ( + prepaidRow.CMPP_FEE_DISINTERMENT !== '0.0' && + prepaidRow.CMPP_FEE_DISINTERMENT !== '20202.02' + ) { + await addContractFee( + { + contractId, + feeId: await getFeeIdByFeeDescription( + 'CMPP_FEE_DISINTERMENT', + user + ), + quantity: 1, + feeAmount: prepaidRow.CMPP_FEE_DISINTERMENT, + taxAmount: prepaidRow.CMPP_GST_DISINTERMENT + }, + user + ) + } + + const transactionAmount = + Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_SD) + + Number.parseFloat(prepaidRow.CMPP_GST_GRAV_SD) + + Number.parseFloat(prepaidRow.CMPP_FEE_GRAV_DD) + + Number.parseFloat(prepaidRow.CMPP_GST_GRAV_DD) + + Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_SD) + + Number.parseFloat(prepaidRow.CMPP_GST_CHAP_SD) + + Number.parseFloat(prepaidRow.CMPP_FEE_CHAP_DD) + + Number.parseFloat(prepaidRow.CMPP_GST_CHAP_DD) + + Number.parseFloat(prepaidRow.CMPP_FEE_ENTOMBMENT) + + Number.parseFloat(prepaidRow.CMPP_GST_ENTOMBMENT) + + Number.parseFloat(prepaidRow.CMPP_FEE_CREM) + + Number.parseFloat(prepaidRow.CMPP_GST_CREM) + + Number.parseFloat(prepaidRow.CMPP_FEE_NICHE) + + Number.parseFloat(prepaidRow.CMPP_GST_NICHE) + + Number.parseFloat( + prepaidRow.CMPP_FEE_DISINTERMENT === '20202.02' + ? '0' + : prepaidRow.CMPP_FEE_DISINTERMENT + ) + + Number.parseFloat( + prepaidRow.CMPP_GST_DISINTERMENT === '20202.02' + ? '0' + : prepaidRow.CMPP_GST_DISINTERMENT + ) + + await addContractTransaction( + { + contractId, + externalReceiptNumber: '', + transactionAmount, + transactionDateString: contractStartDateString, + transactionNote: `Order Number: ${prepaidRow.CMPP_ORDER_NO}` + }, + user + ) + + if (prepaidRow.CMPP_REMARK1 !== '') { + await addContractComment( + { + contractId, + commentDateString: contractStartDateString, + comment: prepaidRow.CMPP_REMARK1 + }, + user + ) + } + + if (prepaidRow.CMPP_REMARK2 !== '') { + await addContractComment( + { + contractId, + commentDateString: contractStartDateString, + comment: prepaidRow.CMPP_REMARK2 + }, + user + ) + } + } + } catch (error) { + console.error(error) + console.log(prepaidRow) + } + + console.timeEnd('importFromPrepaidCSV') +} + +// eslint-disable-next-line complexity +async function importFromWorkOrderCSV(): Promise { + console.time('importFromWorkOrderCSV') + + let workOrderRow: WorkOrderRecord + + const rawData = fs.readFileSync('./temp/CMWKORDR.csv').toString() + + const cmwkordr: papa.ParseResult = papa.parse(rawData, { + delimiter: ',', + header: true, + skipEmptyLines: true + }) + + for (const parseError of cmwkordr.errors) { + console.log(parseError) + } + + const currentDateString = dateToString(new Date()) + + try { + for (workOrderRow of cmwkordr.data) { + const workOrderNumber = `000000${workOrderRow.WO_WORK_ORDER}`.slice(-6) + + let workOrder = await getWorkOrderByWorkOrderNumber(workOrderNumber) + + const workOrderOpenDateString = dateIntegerToString( + Number.parseInt(workOrderRow.WO_INITIATION_DATE, 10) + ) + + if (workOrder) { + if (workOrder.workOrderCloseDate) { + await reopenWorkOrder(workOrder.workOrderId!, user) + delete workOrder.workOrderCloseDate + delete workOrder.workOrderCloseDateString + } + } else { + const workOrderId = await addWorkOrder( + { + workOrderNumber, + workOrderTypeId: importIds.workOrderTypeId, + workOrderDescription: + `${workOrderRow.WO_REMARK1} ${workOrderRow.WO_REMARK2} ${workOrderRow.WO_REMARK3}`.trim(), + workOrderOpenDateString + }, + user + ) + + workOrder = await getWorkOrder(workOrderId, { + includeBurialSites: true, + includeComments: true, + includeMilestones: true + }) + } + + let burialSite: recordTypes.BurialSite | undefined + + if (workOrderRow.WO_CEMETERY !== '00') { + const burialSiteNameSegment1 = + workOrderRow.WO_BLOCK === '0' ? '' : workOrderRow.WO_BLOCK + const burialSiteNameSegment2 = + (workOrderRow.WO_RANGE1 === '0' ? '' : workOrderRow.WO_RANGE1) + + (workOrderRow.WO_RANGE2 === '0' ? '' : workOrderRow.WO_RANGE2) + const burialSiteNameSegment3 = + (workOrderRow.WO_LOT1 === '0' ? '' : workOrderRow.WO_LOT1) + + (workOrderRow.WO_LOT2 === '0' ? '' : workOrderRow.WO_LOT2) + const burialSiteNameSegment4 = + (workOrderRow.WO_GRAVE1 === '0' ? '' : workOrderRow.WO_GRAVE1) + + (workOrderRow.WO_GRAVE2 === '0' ? '' : workOrderRow.WO_GRAVE2) + + const burialSiteName = buildBurialSiteName(workOrderRow.WO_CEMETERY, { + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4 + }) + + burialSite = await getBurialSiteByBurialSiteName(burialSiteName) + + if (burialSite) { + await updateBurialSiteStatus( + burialSite.burialSiteId, + importIds.takenBurialSiteStatusId, + user + ) + } else { + const cemeteryId = await getCemeteryIdByKey( + workOrderRow.WO_CEMETERY, + user + ) + + const burialSiteTypeId = getBurialSiteTypeId(workOrderRow.WO_CEMETERY) + + const burialSiteId = await addBurialSite( + { + cemeteryId, + burialSiteNameSegment1, + burialSiteNameSegment2, + burialSiteNameSegment3, + burialSiteNameSegment4, + cemeterySvgId: burialSiteName.includes(',') + ? burialSiteName.split(',')[0] + : burialSiteName, + burialSiteStatusId: importIds.takenBurialSiteStatusId, + burialSiteTypeId, + burialSiteLatitude: '', + burialSiteLongitude: '' + }, + user + ) + + burialSite = await getBurialSite(burialSiteId) + } + + const workOrderContainsLot = workOrder.workOrderBurialSites!.find( + (possibleLot) => (possibleLot.burialSiteId = burialSite.burialSiteId) + ) + + if (!workOrderContainsLot) { + await addWorkOrderBurialSite( + { + workOrderId: workOrder.workOrderId!, + burialSiteId: burialSite.burialSiteId + }, + user + ) + + workOrder.workOrderBurialSites!.push(burialSite) + } + } + + let contractStartDateString = workOrderOpenDateString + + if (workOrderRow.WO_INTERMENT_YR) { + contractStartDateString = formatDateString( + workOrderRow.WO_INTERMENT_YR, + workOrderRow.WO_INTERMENT_MON, + workOrderRow.WO_INTERMENT_DAY + ) + } + + const contractType = burialSite + ? importIds.deceasedContractType + : importIds.cremationContractType + + const funeralHomeId = + workOrderRow.WO_FUNERAL_HOME === '' + ? '' + : await getFuneralHomeIdByKey(workOrderRow.WO_FUNERAL_HOME, user) + + const committalTypeId = + contractType.contractType === 'Cremation' || + workOrderRow.WO_COMMITTAL_TYPE === '' + ? '' + : await getCommittalTypeIdByKey(workOrderRow.WO_COMMITTAL_TYPE, user) + + const intermentContainerTypeKey = + contractType.contractType === 'Cremation' && + workOrderRow.WO_CONTAINER_TYPE !== '' + ? 'U' + : workOrderRow.WO_CONTAINER_TYPE + + const intermentContainerTypeId = + intermentContainerTypeKey === '' + ? '' + : await getIntermentContainerTypeIdByKey( + intermentContainerTypeKey, + user + ) + + const contractId = await addContract( + { + burialSiteId: burialSite ? burialSite.burialSiteId : '', + contractTypeId: contractType.contractTypeId, + contractStartDateString, + contractEndDateString: '', + + funeralHomeId, + funeralDirectorName: workOrderRow.WO_FUNERAL_HOME, + funeralDateString: + workOrderRow.WO_FUNERAL_YR === '' + ? '' + : formatDateString( + workOrderRow.WO_FUNERAL_YR, + workOrderRow.WO_FUNERAL_MON, + workOrderRow.WO_FUNERAL_DAY + ), + committalTypeId, + + deceasedName: workOrderRow.WO_DECEASED_NAME, + deceasedAddress1: workOrderRow.WO_ADDRESS, + deceasedAddress2: '', + deceasedCity: workOrderRow.WO_CITY, + deceasedProvince: workOrderRow.WO_PROV.slice(0, 2), + deceasedPostalCode: `${workOrderRow.WO_POST1} ${workOrderRow.WO_POST2}`, + + deathDateString: + workOrderRow.WO_DEATH_YR === '' + ? '' + : formatDateString( + workOrderRow.WO_DEATH_YR, + workOrderRow.WO_DEATH_MON, + workOrderRow.WO_DEATH_DAY + ), + deathPlace: workOrderRow.WO_DEATH_PLACE, + deathAge: workOrderRow.WO_AGE, + deathAgePeriod: getDeathAgePeriod(workOrderRow.WO_PERIOD), + intermentContainerTypeId + }, + user + ) + + await addWorkOrderContract( + { + workOrderId: workOrder.workOrderId!, + contractId + }, + user + ) + + // Milestones + + let hasIncompleteMilestones = !workOrderRow.WO_CONFIRMATION_IN + let maxMilestoneCompletionDateString = workOrderOpenDateString + + if (importIds.acknowledgedWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone( + { + workOrderId: workOrder.workOrderId!, + workOrderMilestoneTypeId: + importIds.acknowledgedWorkOrderMilestoneTypeId, + workOrderMilestoneDateString: workOrderOpenDateString, + workOrderMilestoneDescription: '', + workOrderMilestoneCompletionDateString: + workOrderRow.WO_CONFIRMATION_IN + ? workOrderOpenDateString + : undefined, + workOrderMilestoneCompletionTimeString: + workOrderRow.WO_CONFIRMATION_IN ? '00:00' : undefined + }, + user + ) + } + + if (workOrderRow.WO_DEATH_YR) { + const workOrderMilestoneDateString = formatDateString( + workOrderRow.WO_DEATH_YR, + workOrderRow.WO_DEATH_MON, + workOrderRow.WO_DEATH_DAY + ) + + if (importIds.deathWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone( + { + workOrderId: workOrder.workOrderId!, + workOrderMilestoneTypeId: importIds.deathWorkOrderMilestoneTypeId, + workOrderMilestoneDateString, + workOrderMilestoneDescription: `Death Place: ${workOrderRow.WO_DEATH_PLACE}`, + workOrderMilestoneCompletionDateString: + workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneDateString + : undefined, + workOrderMilestoneCompletionTimeString: + workOrderMilestoneDateString < currentDateString + ? '00:00' + : undefined + }, + user + ) + } + + if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { + maxMilestoneCompletionDateString = workOrderMilestoneDateString + } + + if (workOrderMilestoneDateString >= currentDateString) { + hasIncompleteMilestones = true + } + } + + if (workOrderRow.WO_FUNERAL_YR) { + const workOrderMilestoneDateString = formatDateString( + workOrderRow.WO_FUNERAL_YR, + workOrderRow.WO_FUNERAL_MON, + workOrderRow.WO_FUNERAL_DAY + ) + + let funeralHour = Number.parseInt( + workOrderRow.WO_FUNERAL_HR === '' ? '0' : workOrderRow.WO_FUNERAL_HR, + 10 + ) + if (funeralHour <= 6) { + funeralHour += 12 + } + + const workOrderMilestoneTimeString = formatTimeString( + funeralHour.toString(), + workOrderRow.WO_FUNERAL_MIN === '' ? '0' : workOrderRow.WO_FUNERAL_MIN + ) + + if (importIds.funeralWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone( + { + workOrderId: workOrder.workOrderId!, + workOrderMilestoneTypeId: + importIds.funeralWorkOrderMilestoneTypeId, + workOrderMilestoneDateString, + workOrderMilestoneTimeString, + workOrderMilestoneDescription: `Funeral Home: ${workOrderRow.WO_FUNERAL_HOME}`, + workOrderMilestoneCompletionDateString: + workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneDateString + : undefined, + workOrderMilestoneCompletionTimeString: + workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneTimeString + : undefined + }, + user + ) + } + + if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { + maxMilestoneCompletionDateString = workOrderMilestoneDateString + } + + if (workOrderMilestoneDateString >= currentDateString) { + hasIncompleteMilestones = true + } + } + + if ( + workOrderRow.WO_CREMATION === 'Y' && + importIds.cremationWorkOrderMilestoneTypeId + ) { + await addWorkOrderMilestone( + { + workOrderId: workOrder.workOrderId!, + workOrderMilestoneTypeId: + importIds.cremationWorkOrderMilestoneTypeId, + workOrderMilestoneDateString: maxMilestoneCompletionDateString, + workOrderMilestoneDescription: '', + workOrderMilestoneCompletionDateString: + maxMilestoneCompletionDateString < currentDateString + ? maxMilestoneCompletionDateString + : undefined, + workOrderMilestoneCompletionTimeString: + maxMilestoneCompletionDateString < currentDateString + ? '00:00' + : undefined + }, + user + ) + } + + if (workOrderRow.WO_INTERMENT_YR) { + const workOrderMilestoneDateString = formatDateString( + workOrderRow.WO_INTERMENT_YR, + workOrderRow.WO_INTERMENT_MON, + workOrderRow.WO_INTERMENT_DAY + ) + + if (importIds.intermentWorkOrderMilestoneTypeId) { + await addWorkOrderMilestone( + { + workOrderId: workOrder.workOrderId!, + workOrderMilestoneTypeId: + importIds.intermentWorkOrderMilestoneTypeId, + workOrderMilestoneDateString, + workOrderMilestoneDescription: `Depth: ${workOrderRow.WO_DEPTH}`, + workOrderMilestoneCompletionDateString: + workOrderMilestoneDateString < currentDateString + ? workOrderMilestoneDateString + : undefined, + workOrderMilestoneCompletionTimeString: + workOrderMilestoneDateString < currentDateString + ? '23:59' + : undefined + }, + user + ) + } + + if (workOrderMilestoneDateString > maxMilestoneCompletionDateString) { + maxMilestoneCompletionDateString = workOrderMilestoneDateString + } + + if (workOrderMilestoneDateString >= currentDateString) { + hasIncompleteMilestones = true + } + } + + if (!hasIncompleteMilestones) { + await closeWorkOrder( + { + workOrderId: workOrder.workOrderId!, + workOrderCloseDateString: maxMilestoneCompletionDateString + }, + user + ) + } + } + } catch (error) { + console.error(error) + console.log(workOrderRow) + } + + console.timeEnd('importFromWorkOrderCSV') +} + +console.log(`Started ${new Date().toLocaleString()}`) +console.time('importFromCsv') + +// Purge Tables +//purgeTables() +//purgeConfigTables() + +// Initialize SSM Data +//await initializeFuneralHomes(user) + +// Do Imports +//await importFromMasterCSV() +await importFromPrepaidCSV() +await importFromWorkOrderCSV() + +console.timeEnd('importFromCsv') +console.log(`Finished ${new Date().toLocaleString()}`) diff --git a/types/configTypes.d.ts b/types/configTypes.d.ts index 6243ef5e..a099884a 100644 --- a/types/configTypes.d.ts +++ b/types/configTypes.d.ts @@ -31,6 +31,7 @@ export interface Config { contracts: { burialSiteIdIsRequired?: boolean; contractEndDateIsRequired?: boolean; + deathAgePeriods?: string[]; prints?: string[]; }; workOrders: { diff --git a/types/configTypes.ts b/types/configTypes.ts index ac3a6e4b..7bc9605d 100644 --- a/types/configTypes.ts +++ b/types/configTypes.ts @@ -32,6 +32,7 @@ export interface Config { contracts: { burialSiteIdIsRequired?: boolean contractEndDateIsRequired?: boolean + deathAgePeriods?: string[] prints?: string[] } workOrders: { diff --git a/types/recordTypes.d.ts b/types/recordTypes.d.ts index 8a54aa08..4ea86c94 100644 --- a/types/recordTypes.d.ts +++ b/types/recordTypes.d.ts @@ -28,6 +28,7 @@ export interface Cemetery extends Record { } export interface FuneralHome extends Record { funeralHomeId?: number; + funeralHomeKey?: string; funeralHomeName?: string; funeralHomeAddress1?: string; funeralHomeAddress2?: string; @@ -172,12 +173,14 @@ export interface DynamicsGPDocument { export interface IntermentContainerType extends Record { intermentContainerTypeId: number; intermentContainerType: string; + intermentContainerTypeKey: string; isCremationType: boolean; orderNumber?: number; } export interface CommittalType extends Record { committalTypeId: number; committalType: string; + committalTypeKey: string; orderNumber?: number; } export interface ContractInterment extends Record { @@ -195,6 +198,8 @@ export interface ContractInterment extends Record { deathDate?: number; deathDateString?: string; deathPlace?: string; + deathAge?: number; + deathAgePeriod?: string; intermentContainerTypeId?: number; intermentContainerType?: string; isCremationType?: boolean; @@ -242,6 +247,7 @@ export interface Contract extends Record { purchaserEmail?: string; purchaserRelationship?: string; funeralHomeId?: number; + funeralHomeKey?: string; funeralHomeName?: string; funeralDirectorName?: string; funeralHomeAddress1?: string; diff --git a/types/recordTypes.ts b/types/recordTypes.ts index 8275db12..f30e4238 100644 --- a/types/recordTypes.ts +++ b/types/recordTypes.ts @@ -39,6 +39,7 @@ export interface Cemetery extends Record { export interface FuneralHome extends Record { funeralHomeId?: number + funeralHomeKey?: string funeralHomeName?: string funeralHomeAddress1?: string funeralHomeAddress2?: string @@ -222,6 +223,7 @@ export interface DynamicsGPDocument { export interface IntermentContainerType extends Record { intermentContainerTypeId: number intermentContainerType: string + intermentContainerTypeKey: string isCremationType: boolean orderNumber?: number } @@ -229,6 +231,7 @@ export interface IntermentContainerType extends Record { export interface CommittalType extends Record { committalTypeId: number committalType: string + committalTypeKey: string orderNumber?: number } @@ -249,7 +252,9 @@ export interface ContractInterment extends Record { deathDate?: number deathDateString?: string - deathPlace?: string + deathPlace?: string + deathAge?: number + deathAgePeriod?: string intermentContainerTypeId?: number intermentContainerType?: string @@ -313,6 +318,7 @@ export interface Contract extends Record { purchaserRelationship?: string funeralHomeId?: number + funeralHomeKey?: string funeralHomeName?: string funeralDirectorName?: string funeralHomeAddress1?: string diff --git a/views/contract-edit.ejs b/views/contract-edit.ejs index 834addd8..121357bb 100644 --- a/views/contract-edit.ejs +++ b/views/contract-edit.ejs @@ -605,7 +605,7 @@ Date of Death
- + @@ -618,11 +618,29 @@ Place of Death
- +
+ +
+
+ +
+
+
+ +
+
+
@@ -842,6 +860,7 @@ exports.contractInterments = <%- JSON.stringify(contract.contractInterments) %>; exports.intermentContainerTypes = <%- JSON.stringify(intermentContainerTypes) %>; + exports.deathAgePeriods = <%- JSON.stringify(configFunctions.getConfigProperty('settings.contracts.deathAgePeriods')) %>; exports.contractComments = <%- JSON.stringify(contract.contractComments) %>; exports.contractFees = <%- JSON.stringify(contract.contractFees) %>; exports.contractTransactions = <%- JSON.stringify(contract.contractTransactions) %>; diff --git a/views/contract-view.ejs b/views/contract-view.ejs index eef1b476..82cc2276 100644 --- a/views/contract-view.ejs +++ b/views/contract-view.ejs @@ -267,6 +267,15 @@ <%= contractInterment.deathPlace ?? '(No Death Place)' %>
+
+
+ Age: +
+
+ <%= contractInterment.deathAge %> + <%= contractInterment.deathAgePeriod %> +
+
Container: diff --git a/views/workOrder-view.ejs b/views/workOrder-view.ejs index c5db0b11..9eda15ca 100644 --- a/views/workOrder-view.ejs +++ b/views/workOrder-view.ejs @@ -148,78 +148,79 @@
" id="relatedTab--contracts"> <% if (workOrder.workOrderContracts.length === 0) { %> -
-

- There are no contracts associated with this work order. -

-
+
+

+ There are no contracts associated with this work order. +

+
<% } else { %> - <% const currentDate = dateTimeFunctions.dateToInteger(new Date()); %> - - + <% const currentDate = dateTimeFunctions.dateToInteger(new Date()); %> +
+ + + + + + + + + + + + <% for (const contract of workOrder.workOrderContracts) { %> + <% const isActive = !(contract.contractEndDate && contract.contractEndDate < currentDate); %> - - - - - - + + + + + + - - - <% for (const contract of workOrder.workOrderContracts) { %> - <% const isActive = !(contract.contractEndDate && contract.contractEndDate < currentDate); %> - - - - - - - - - <% } %> - -
Contract TypeBurial SiteContract DateEnd DateInterments
Contract TypeBurial SiteContract DateEnd DateInterments + <% if (isActive) { %> + + <% } else { %> + + <% } %> + + + <%= contract.contractType %> +
+ + #<%= contract.contractId %> + +
+ <% if (contract.burialSiteId) { %> + <%= contract.burialSiteName %> + <% } else { %> + (No Burial Site) + <% } %> + <%= contract.contractStartDateString %> + <% if (contract.contractEndDate) { %> + <%= contract.contractEndDateString %> + <% } else { %> + (No End Date) + <% } %> + + <% if (contract.contractInterments.length === 0) { %> + + (No Interments) + + <% } else { %> +
    + <% for (const interment of contract.contractInterments) { %> +
  • + + <%= interment.deceasedName %> +
  • + <% } %> +
+ <% } %> +
- <% if (isActive) { %> - - <% } else { %> - - <% } %> - - - <%= contract.contractType %> -
- - #<%= contract.contractId %> - -
- <% if (contract.burialSiteId) { %> - <%= contract.burialSiteName %> - <% } else { %> - (No Burial Site) - <% } %> - <%= contract.contractStartDateString %> - <% if (contract.contractEndDate) { %> - <%= contract.contractEndDateString %> - <% } else { %> - (No End Date) - <% } %> - - <% if (contract.contractInterments.length === 0) { %> - - (No Interments) - - <% } else { %> -
    - <% for (const interment of contract.contractInterments) { %> -
  • - <%= interment.deceasedName %> -
  • - <% } %> -
- <% } %> -
+ <% } %> + + <% } %>
" id="relatedTab--burialSites"> @@ -293,36 +294,36 @@
-
-
-
-

Milestones

-
+
+
+
+

Milestones

-
- <% for (const milestone of workOrder.workOrderMilestones) { %>