Compare commits

..

No commits in common. "main" and "deepsource-autofix-76c6eb20" have entirely different histories.

1226 changed files with 303135 additions and 29222 deletions

View File

@ -10,7 +10,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
node: [ 20, 22, 23 ] node: [ 18, 20, 21 ]
env: env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
@ -25,12 +25,11 @@ jobs:
- name: Install Application - name: Install Application
run: | run: |
npm uninstall puppeteer
npm ci npm ci
npm install -g mocha c8 cypress@14 npm install -g mocha c8 cypress@13
- name: Copy Test Config - name: Copy Test Config
run: cp ./data/testing.config.js ./data/config.js run: cp ./data/config.testing.js ./data/config.js
- name: Test Application Startup - name: Test Application Startup
run: npm run test:startup run: npm run test:startup
@ -44,14 +43,14 @@ jobs:
run: c8 --reporter=lcov --reporter=text --reporter=text-summary mocha --timeout 10000 --exit run: c8 --reporter=lcov --reporter=text --reporter=text-summary mocha --timeout 10000 --exit
- name: Codecov - name: Codecov
if: ${{ github.event_name != 'pull_request' && env.CODECOV_TOKEN != '' && matrix.node == 22 }} if: ${{ github.event_name != 'pull_request' && env.CODECOV_TOKEN != '' && matrix.node == 20 }}
run: | run: |
curl -Os https://uploader.codecov.io/latest/linux/codecov curl -Os https://uploader.codecov.io/latest/linux/codecov
chmod +x codecov chmod +x codecov
./codecov -t ${CODECOV_TOKEN} ./codecov -t ${CODECOV_TOKEN}
- name: DeepSource - name: DeepSource
if: ${{ github.event_name != 'pull_request' && env.DEEPSOURCE_DSN != '' && matrix.node == 22 }} if: ${{ github.event_name != 'pull_request' && env.DEEPSOURCE_DSN != '' && matrix.node == 20 }}
run: | run: |
# Install deepsource CLI # Install deepsource CLI
curl https://deepsource.io/cli | sh curl https://deepsource.io/cli | sh

View File

@ -1,3 +1,8 @@
{ {
"reject": ["puppeteer"] "reject": [
"@cityssm/bulma-sticky-table",
"@fortawesome/fontawesome-free",
"bulma",
"bulma-calendar"
]
} }

View File

@ -1,4 +1,4 @@
# Thank you for your interest in making Sunrise CMS better # Thank you for your interest in making the Lot Occupancy System better
Together, we can build high quality software that meets the needs of municipalities, Together, we can build high quality software that meets the needs of municipalities,
while remaining open and budget conscious. while remaining open and budget conscious.

View File

@ -1,70 +1,27 @@
<div align=center>
# Sunrise Cemetery Management System (CMS) # Sunrise Cemetery Management System (CMS)
[![DeepSource](https://app.deepsource.com/gh/cityssm/sunrise-cms.svg/?label=active+issues&show_trend=true&token=AhEAYh9dbdDAe7cgW95_SVqP)](https://app.deepsource.com/gh/cityssm/sunrise-cms/) ![Sunrise CMS Logo](./public/images/sunrise-cms.png)
[![codecov](https://codecov.io/gh/cityssm/sunrise-cms/graph/badge.svg?token=OY7SWY1PLC)](https://codecov.io/gh/cityssm/sunrise-cms)
[![sunrise-cms](https://img.shields.io/endpoint?url=https://cloud.cypress.io/badge/simple/26a4bi&style=flat&logo=cypress)](https://cloud.cypress.io/projects/26a4bi/runs)
[![Coverage Testing](https://github.com/cityssm/sunrise-cms/actions/workflows/coverage.yml/badge.svg)](https://github.com/cityssm/sunrise-cms/actions/workflows/coverage.yml)
![Sunrise CMS](./docs/images/socialPreview.png)
🚧 **In development** 🚧 🚧 **In development** 🚧
**A web-based application to assist cemetery managers with managing their cemetery records.** **A web-based application to assist cemetery managers with managing their cemetery records**
![Burial Site View](./docs/images/burialSite-view.png) </div>
This is a major refactoring of the now archived This is a major refactoring of the
[Lot Occupancy System](https://github.com/cityssm/lot-occupancy-system), [Lot Occupancy System](https://github.com/cityssm/lot-occupancy-system),
originally built with multiple focuses in mind. This fork completely reworks the project originally built with multiple focuses. This fork reworks the project to focus exculsively
to focus exculsively on cemetery management. on cemetery management.
[**User Documentation (In the Works)**](./docs/README.md)
## Why Sunrise CMS?
### ✔️ Cemetery Maps are NOT Required
Many cemetery applications rely on maps to drill down into burial sites.
In Sunrise CMS, maps are completely optional, greatly reducing the effort needed to get started,
and reducing the maintenance work when new blocks of burial sites are introduced.
### ✔️ The System Requirements are Very Low
Sunrise CMS does not need an expensive server to run.
No separate database server is required either.
The whole application could run on a current, modest workstation.
### ✔️ Track Unlimited Cemeteries, Unlimited Burial Sites, Unlimited Contracts...
There are no limits to the number of records that can be tracked in Sunrise CMS.
### ✔️ Includes a Simple Built-In Work Order System
In addition to tracking data related to cemetery plots,
Sunrise CMS can also track work order activities, like interments and grave maintenance.
### ✔️ Sunrise CMS is Free and Open Source
There's no cost to use it.
## About this Project ## About this Project
- 📘 [Documentation](./docs/README.md) - [Code of Conduct](CODE_OF_CONDUCT.md)
- 🤗 [Code of Conduct](CODE_OF_CONDUCT.md) - [Contributing Guidelines](CONTRIBUTING.md)
- 🥰 [Contributing Guidelines](CONTRIBUTING.md) - [Security Policy](SECURITY.md)
- 🛡️ [Security Policy](SECURITY.md) - [MIT Licence](LICENSE.md)
- 📃 [MIT Licence](LICENSE.md)
Although the system is quite niche, it's being released in an open source environment in hopes to pool developer resources from other municipalities looking to move away from older, legacy systems. Although the system is quite niche, it's being released in an open source environment in hopes to pool developer resources from other municipalities looking to move away from older, legacy systems.
It is being shared to start the dialog among other municipalities and present an option to those who may be looking to refresh their own cemetery systems. It is being shared to start the dialog among other municipalities and present an option to those who may be looking to refresh their own cemetery systems.
## More City Management Applications from the City of Sault Ste. Marie
[**General Licence Manager**](https://cityssm.github.io/general-licence-manager/)<br />
An application built to manage the general licences issued by municipalities.
[**Attendance Tracking**](https://cityssm.github.io/attendance-tracking/)<br />
Track employee absences, call outs, and more.
💡 Discover even more on [the City of Sault Ste. Marie's GitHub page](https://cityssm.github.io/).

View File

@ -1,2 +1,2 @@
theme: jekyll-theme-cayman theme: jekyll-theme-cayman
title: Sunrise Cemetery Management System (CMS) title: Sunrise Cemetery Management System

88
app.js
View File

@ -1,6 +1,5 @@
import path from 'node:path'; import path from 'node:path';
import { secondsToMillis } from '@cityssm/to-millis'; import * as dateTimeFns from '@cityssm/utils-datetime';
import * as dateTimeFunctions from '@cityssm/utils-datetime';
import compression from 'compression'; import compression from 'compression';
import cookieParser from 'cookie-parser'; import cookieParser from 'cookie-parser';
import csurf from 'csurf'; import csurf from 'csurf';
@ -10,12 +9,12 @@ import rateLimit from 'express-rate-limit';
import session from 'express-session'; import session from 'express-session';
import createError from 'http-errors'; import createError from 'http-errors';
import FileStore from 'session-file-store'; import FileStore from 'session-file-store';
import dataLists from './data/dataLists.js'; import { initializeDatabase } from './database/initializeDatabase.js';
import { DEBUG_NAMESPACE } from './debug.config.js'; import { DEBUG_NAMESPACE } from './debug.config.js';
import * as permissionHandlers from './handlers/permissions.js'; import * as permissionHandlers from './handlers/permissions.js';
import { getSafeRedirectURL } from './helpers/authentication.helpers.js';
import * as configFunctions from './helpers/config.helpers.js'; import * as configFunctions from './helpers/config.helpers.js';
import { useTestDatabases } from './helpers/database.helpers.js'; import { useTestDatabases } from './helpers/database.helpers.js';
import { getSafeRedirectURL } from './helpers/functions.authentication.js';
import * as printFunctions from './helpers/functions.print.js'; import * as printFunctions from './helpers/functions.print.js';
import routerAdmin from './routes/admin.js'; import routerAdmin from './routes/admin.js';
import routerApi from './routes/api.js'; import routerApi from './routes/api.js';
@ -29,7 +28,11 @@ import routerPrint from './routes/print.js';
import routerReports from './routes/reports.js'; import routerReports from './routes/reports.js';
import routerWorkOrders from './routes/workOrders.js'; import routerWorkOrders from './routes/workOrders.js';
import { version } from './version.js'; import { version } from './version.js';
const debug = Debug(`${DEBUG_NAMESPACE}:app:${process.pid.toString().padEnd(5)}`); const debug = Debug(`${DEBUG_NAMESPACE}:app:${process.pid}`);
/*
* INITIALIZE THE DATABASE
*/
await initializeDatabase();
/* /*
* INITIALIZE APP * INITIALIZE APP
*/ */
@ -54,18 +57,29 @@ app.use(express.urlencoded({
extended: false extended: false
})); }));
app.use(cookieParser()); app.use(cookieParser());
app.use( app.use(csurf({
// eslint-disable-next-line sonarjs/insecure-cookie, sonarjs/cookie-no-httponly
csurf({
cookie: true cookie: true
})); }));
/* /*
* Rate Limiter * Rate Limiter
*/ */
app.use(rateLimit({ app.use(rateLimit({
max: useTestDatabases ? 1_000_000 : 200, windowMs: 10_000,
windowMs: secondsToMillis(10) max: useTestDatabases ? 1_000_000 : 200
})); }));
/*
* STATIC ROUTES
*/
const urlPrefix = configFunctions.getConfigProperty('reverseProxy.urlPrefix');
if (urlPrefix !== '') {
debug(`urlPrefix = ${urlPrefix}`);
}
app.use(urlPrefix, express.static(path.join('public')));
app.use(`${urlPrefix}/lib/cityssm-bulma-js/bulma-js.js`, express.static(path.join('node_modules', '@cityssm', 'bulma-js', 'dist', 'bulma-js.js')));
app.use(`${urlPrefix}/lib/cityssm-bulma-webapp-js`, express.static(path.join('node_modules', '@cityssm', 'bulma-webapp-js', 'dist')));
app.use(`${urlPrefix}/lib/fa`, express.static(path.join('node_modules', '@fortawesome', 'fontawesome-free')));
app.use(`${urlPrefix}/lib/leaflet`, express.static(path.join('node_modules', 'leaflet', 'dist')));
app.use(`${urlPrefix}/lib/randomcolor/randomColor.js`, express.static(path.join('node_modules', 'randomcolor', 'randomColor.js')));
/* /*
* SESSION MANAGEMENT * SESSION MANAGEMENT
*/ */
@ -73,20 +87,20 @@ const sessionCookieName = configFunctions.getConfigProperty('session.cookieName'
const FileStoreSession = FileStore(session); const FileStoreSession = FileStore(session);
// Initialize session // Initialize session
app.use(session({ app.use(session({
store: new FileStoreSession({
path: './data/sessions',
logFn: Debug(`${DEBUG_NAMESPACE}:session:${process.pid}`),
retries: 20
}),
name: sessionCookieName, name: sessionCookieName,
secret: configFunctions.getConfigProperty('session.secret'),
resave: true,
saveUninitialized: false,
rolling: true,
cookie: { cookie: {
maxAge: configFunctions.getConfigProperty('session.maxAgeMillis'), maxAge: configFunctions.getConfigProperty('session.maxAgeMillis'),
sameSite: 'strict' sameSite: 'strict'
}, }
secret: configFunctions.getConfigProperty('session.secret'),
store: new FileStoreSession({
logFn: Debug(`${DEBUG_NAMESPACE}:session:${process.pid.toString().padEnd(5)}`),
path: './data/sessions',
retries: 20
}),
resave: true,
rolling: true,
saveUninitialized: false
})); }));
// Clear cookie if no corresponding session // Clear cookie if no corresponding session
app.use((request, response, next) => { app.use((request, response, next) => {
@ -96,34 +110,6 @@ app.use((request, response, next) => {
} }
next(); next();
}); });
/*
* STATIC ROUTES
*/
const urlPrefix = configFunctions.getConfigProperty('reverseProxy.urlPrefix');
if (urlPrefix !== '') {
debug(`urlPrefix = ${urlPrefix}`);
}
app.use(`${urlPrefix}/internal`, (request, response, next) => {
if (Object.hasOwn(request.session, 'user') &&
Object.hasOwn(request.cookies, sessionCookieName)) {
next();
return;
}
response.sendStatus(403);
}, express.static(configFunctions.getConfigProperty('settings.publicInternalPath')));
app.use(urlPrefix, express.static(path.join('public')));
app.use(`${urlPrefix}/lib/bulma`, express.static(path.join('node_modules', 'bulma', 'css')));
app.use(`${urlPrefix}/lib/bulma-tooltip`, express.static(path.join('node_modules', 'bulma-tooltip', 'dist', 'css')));
app.use(`${urlPrefix}/lib/cityssm-bulma-js/bulma-js.js`, express.static(path.join('node_modules', '@cityssm', 'bulma-js', 'dist', 'bulma-js.js')));
app.use(`${urlPrefix}/lib/cityssm-fa-glow`, express.static(path.join('node_modules', '@cityssm', 'fa-glow')));
app.use(`${urlPrefix}/lib/cityssm-bulma-sticky-table`, express.static(path.join('node_modules', '@cityssm', 'bulma-sticky-table')));
app.use(`${urlPrefix}/lib/cityssm-bulma-webapp-js`, express.static(path.join('node_modules', '@cityssm', 'bulma-webapp-js', 'dist')));
app.use(`${urlPrefix}/lib/fa`, express.static(path.join('node_modules', '@fortawesome', 'fontawesome-free')));
app.use(`${urlPrefix}/lib/leaflet`, express.static(path.join('node_modules', 'leaflet', 'dist')));
app.use(`${urlPrefix}/lib/randomcolor/randomColor.js`, express.static(path.join('node_modules', 'randomcolor', 'randomColor.js')));
/*
* ROUTES
*/
// Redirect logged in users // Redirect logged in users
const sessionChecker = (request, response, next) => { const sessionChecker = (request, response, next) => {
if (Object.hasOwn(request.session, 'user') && if (Object.hasOwn(request.session, 'user') &&
@ -134,6 +120,9 @@ const sessionChecker = (request, response, next) => {
const redirectUrl = getSafeRedirectURL(request.originalUrl); const redirectUrl = getSafeRedirectURL(request.originalUrl);
response.redirect(`${urlPrefix}/login?redirect=${encodeURIComponent(redirectUrl)}`); response.redirect(`${urlPrefix}/login?redirect=${encodeURIComponent(redirectUrl)}`);
}; };
/*
* ROUTES
*/
// Make the user and config objects available to the templates // Make the user and config objects available to the templates
app.use((request, response, next) => { app.use((request, response, next) => {
response.locals.buildNumber = version; response.locals.buildNumber = version;
@ -141,8 +130,7 @@ app.use((request, response, next) => {
response.locals.csrfToken = request.csrfToken(); response.locals.csrfToken = request.csrfToken();
response.locals.configFunctions = configFunctions; response.locals.configFunctions = configFunctions;
response.locals.printFunctions = printFunctions; response.locals.printFunctions = printFunctions;
response.locals.dateTimeFunctions = dateTimeFunctions; response.locals.dateTimeFunctions = dateTimeFns;
response.locals.dataLists = dataLists;
response.locals.urlPrefix = configFunctions.getConfigProperty('reverseProxy.urlPrefix'); response.locals.urlPrefix = configFunctions.getConfigProperty('reverseProxy.urlPrefix');
next(); next();
}); });

146
app.ts
View File

@ -1,7 +1,6 @@
import path from 'node:path' import path from 'node:path'
import { secondsToMillis } from '@cityssm/to-millis' import * as dateTimeFns from '@cityssm/utils-datetime'
import * as dateTimeFunctions from '@cityssm/utils-datetime'
import compression from 'compression' import compression from 'compression'
import cookieParser from 'cookie-parser' import cookieParser from 'cookie-parser'
import csurf from 'csurf' import csurf from 'csurf'
@ -12,12 +11,12 @@ import session from 'express-session'
import createError from 'http-errors' import createError from 'http-errors'
import FileStore from 'session-file-store' import FileStore from 'session-file-store'
import dataLists from './data/dataLists.js' import { initializeDatabase } from './database/initializeDatabase.js'
import { DEBUG_NAMESPACE } from './debug.config.js' import { DEBUG_NAMESPACE } from './debug.config.js'
import * as permissionHandlers from './handlers/permissions.js' import * as permissionHandlers from './handlers/permissions.js'
import { getSafeRedirectURL } from './helpers/authentication.helpers.js'
import * as configFunctions from './helpers/config.helpers.js' import * as configFunctions from './helpers/config.helpers.js'
import { useTestDatabases } from './helpers/database.helpers.js' import { useTestDatabases } from './helpers/database.helpers.js'
import { getSafeRedirectURL } from './helpers/functions.authentication.js'
import * as printFunctions from './helpers/functions.print.js' import * as printFunctions from './helpers/functions.print.js'
import routerAdmin from './routes/admin.js' import routerAdmin from './routes/admin.js'
import routerApi from './routes/api.js' import routerApi from './routes/api.js'
@ -32,7 +31,13 @@ import routerReports from './routes/reports.js'
import routerWorkOrders from './routes/workOrders.js' import routerWorkOrders from './routes/workOrders.js'
import { version } from './version.js' import { version } from './version.js'
const debug = Debug(`${DEBUG_NAMESPACE}:app:${process.pid.toString().padEnd(5)}`) const debug = Debug(`${DEBUG_NAMESPACE}:app:${process.pid}`)
/*
* INITIALIZE THE DATABASE
*/
await initializeDatabase()
/* /*
* INITIALIZE APP * INITIALIZE APP
@ -71,7 +76,6 @@ app.use(
app.use(cookieParser()) app.use(cookieParser())
app.use( app.use(
// eslint-disable-next-line sonarjs/insecure-cookie, sonarjs/cookie-no-httponly
csurf({ csurf({
cookie: true cookie: true
}) })
@ -83,54 +87,11 @@ app.use(
app.use( app.use(
rateLimit({ rateLimit({
max: useTestDatabases ? 1_000_000 : 200, windowMs: 10_000,
windowMs: secondsToMillis(10) max: useTestDatabases ? 1_000_000 : 200
}) })
) )
/*
* SESSION MANAGEMENT
*/
const sessionCookieName: string =
configFunctions.getConfigProperty('session.cookieName')
const FileStoreSession = FileStore(session)
// Initialize session
app.use(
session({
name: sessionCookieName,
cookie: {
maxAge: configFunctions.getConfigProperty('session.maxAgeMillis'),
sameSite: 'strict'
},
secret: configFunctions.getConfigProperty('session.secret'),
store: new FileStoreSession({
logFn: Debug(`${DEBUG_NAMESPACE}:session:${process.pid.toString().padEnd(5)}`),
path: './data/sessions',
retries: 20
}),
resave: true,
rolling: true,
saveUninitialized: false
})
)
// Clear cookie if no corresponding session
app.use((request, response, next) => {
if (
Object.hasOwn(request.cookies, sessionCookieName) &&
!Object.hasOwn(request.session, 'user')
) {
response.clearCookie(sessionCookieName)
}
next()
})
/* /*
* STATIC ROUTES * STATIC ROUTES
*/ */
@ -141,34 +102,8 @@ if (urlPrefix !== '') {
debug(`urlPrefix = ${urlPrefix}`) debug(`urlPrefix = ${urlPrefix}`)
} }
app.use(
`${urlPrefix}/internal`,
(request, response, next) => {
if (
Object.hasOwn(request.session, 'user') &&
Object.hasOwn(request.cookies, sessionCookieName)
) {
next()
return
}
response.sendStatus(403)
},
express.static(configFunctions.getConfigProperty('settings.publicInternalPath'))
)
app.use(urlPrefix, express.static(path.join('public'))) app.use(urlPrefix, express.static(path.join('public')))
app.use(
`${urlPrefix}/lib/bulma`,
express.static(path.join('node_modules', 'bulma', 'css'))
)
app.use(
`${urlPrefix}/lib/bulma-tooltip`,
express.static(path.join('node_modules', 'bulma-tooltip', 'dist', 'css'))
)
app.use( app.use(
`${urlPrefix}/lib/cityssm-bulma-js/bulma-js.js`, `${urlPrefix}/lib/cityssm-bulma-js/bulma-js.js`,
express.static( express.static(
@ -176,16 +111,6 @@ app.use(
) )
) )
app.use(
`${urlPrefix}/lib/cityssm-fa-glow`,
express.static(path.join('node_modules', '@cityssm', 'fa-glow'))
)
app.use(
`${urlPrefix}/lib/cityssm-bulma-sticky-table`,
express.static(path.join('node_modules', '@cityssm', 'bulma-sticky-table'))
)
app.use( app.use(
`${urlPrefix}/lib/cityssm-bulma-webapp-js`, `${urlPrefix}/lib/cityssm-bulma-webapp-js`,
express.static( express.static(
@ -209,9 +134,46 @@ app.use(
) )
/* /*
* ROUTES * SESSION MANAGEMENT
*/ */
const sessionCookieName: string =
configFunctions.getConfigProperty('session.cookieName')
const FileStoreSession = FileStore(session)
// Initialize session
app.use(
session({
store: new FileStoreSession({
path: './data/sessions',
logFn: Debug(`${DEBUG_NAMESPACE}:session:${process.pid}`),
retries: 20
}),
name: sessionCookieName,
secret: configFunctions.getConfigProperty('session.secret'),
resave: true,
saveUninitialized: false,
rolling: true,
cookie: {
maxAge: configFunctions.getConfigProperty('session.maxAgeMillis'),
sameSite: 'strict'
}
})
)
// Clear cookie if no corresponding session
app.use((request, response, next) => {
if (
Object.hasOwn(request.cookies, sessionCookieName) &&
!Object.hasOwn(request.session, 'user')
) {
response.clearCookie(sessionCookieName)
}
next()
})
// Redirect logged in users // Redirect logged in users
const sessionChecker = ( const sessionChecker = (
request: express.Request, request: express.Request,
@ -233,6 +195,10 @@ const sessionChecker = (
) )
} }
/*
* ROUTES
*/
// Make the user and config objects available to the templates // Make the user and config objects available to the templates
app.use((request, response, next) => { app.use((request, response, next) => {
@ -243,9 +209,7 @@ app.use((request, response, next) => {
response.locals.configFunctions = configFunctions response.locals.configFunctions = configFunctions
response.locals.printFunctions = printFunctions response.locals.printFunctions = printFunctions
response.locals.dateTimeFunctions = dateTimeFunctions response.locals.dateTimeFunctions = dateTimeFns
response.locals.dataLists = dataLists
response.locals.urlPrefix = configFunctions.getConfigProperty( response.locals.urlPrefix = configFunctions.getConfigProperty(
'reverseProxy.urlPrefix' 'reverseProxy.urlPrefix'

View File

@ -6,26 +6,19 @@ import ntfyPublish from '@cityssm/ntfy-publish';
import { secondsToMillis } from '@cityssm/to-millis'; import { secondsToMillis } from '@cityssm/to-millis';
import Debug from 'debug'; import Debug from 'debug';
import exitHook from 'exit-hook'; import exitHook from 'exit-hook';
import { initializeDatabase } from '../database/initializeDatabase.js';
import { DEBUG_NAMESPACE } from '../debug.config.js'; import { DEBUG_NAMESPACE } from '../debug.config.js';
import { getConfigProperty } from '../helpers/config.helpers.js'; import { getConfigProperty } from '../helpers/config.helpers.js';
import version from '../version.js';
const debug = Debug(`${DEBUG_NAMESPACE}:www:${process.pid}`); const debug = Debug(`${DEBUG_NAMESPACE}:www:${process.pid}`);
// INITIALIZE THE DATABASE
initializeDatabase();
const directoryName = path.dirname(fileURLToPath(import.meta.url)); const directoryName = path.dirname(fileURLToPath(import.meta.url));
const processCount = Math.min(getConfigProperty('application.maximumProcesses'), os.cpus().length * 2); const processCount = Math.min(getConfigProperty('application.maximumProcesses'), os.cpus().length);
const applicationName = getConfigProperty('application.applicationName'); process.title = `${getConfigProperty('application.applicationName')} (Primary)`;
process.title = `${applicationName} (Primary)`;
debug(`Primary pid: ${process.pid}`); debug(`Primary pid: ${process.pid}`);
debug(`Primary title: ${process.title}`); debug(`Primary title: ${process.title}`);
debug(`Version: ${version}`);
debug(`Launching ${processCount} processes`); debug(`Launching ${processCount} processes`);
const clusterSettings = { const clusterSettings = {
exec: `${directoryName}/wwwProcess.js` exec: `${directoryName}/wwwProcess.js`
}; };
cluster.setupPrimary(clusterSettings); cluster.setupPrimary(clusterSettings);
let doShutdown = false;
const activeWorkers = new Map(); const activeWorkers = new Map();
for (let index = 0; index < processCount; index += 1) { for (let index = 0; index < processCount; index += 1) {
const worker = cluster.fork(); const worker = cluster.fork();
@ -33,7 +26,6 @@ for (let index = 0; index < processCount; index += 1) {
} }
cluster.on('message', (worker, message) => { cluster.on('message', (worker, message) => {
for (const [pid, activeWorker] of activeWorkers.entries()) { 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) { if (activeWorker === undefined || pid === message.pid) {
continue; continue;
} }
@ -44,27 +36,24 @@ cluster.on('message', (worker, message) => {
cluster.on('exit', (worker) => { cluster.on('exit', (worker) => {
debug(`Worker ${(worker.process.pid ?? 0).toString()} has been killed`); debug(`Worker ${(worker.process.pid ?? 0).toString()} has been killed`);
activeWorkers.delete(worker.process.pid ?? 0); activeWorkers.delete(worker.process.pid ?? 0);
if (!doShutdown) {
debug('Starting another worker'); debug('Starting another worker');
const newWorker = cluster.fork(); cluster.fork();
activeWorkers.set(newWorker.process.pid ?? 0, newWorker);
}
}); });
const ntfyStartupConfig = getConfigProperty('application.ntfyStartup'); const ntfyStartupConfig = getConfigProperty('application.ntfyStartup');
if (ntfyStartupConfig !== undefined) { if (ntfyStartupConfig !== undefined) {
const topic = ntfyStartupConfig.topic; const topic = ntfyStartupConfig.topic;
const server = ntfyStartupConfig.server; const server = ntfyStartupConfig.server;
const ntfyStartupMessage = { const ntfyStartupMessage = {
topic,
title: getConfigProperty('application.applicationName'),
message: 'Application Started', message: 'Application Started',
tags: ['arrow_up'], tags: ['arrow_up']
title: applicationName,
topic
}; };
const ntfyShutdownMessage = { const ntfyShutdownMessage = {
topic,
title: getConfigProperty('application.applicationName'),
message: 'Application Shut Down', message: 'Application Shut Down',
tags: ['arrow_down'], tags: ['arrow_down']
title: applicationName,
topic
}; };
if (server !== undefined) { if (server !== undefined) {
ntfyStartupMessage.server = server; ntfyStartupMessage.server = server;
@ -81,16 +70,7 @@ if (process.env.STARTUP_TEST === 'true') {
debug(`Killing processes in ${killSeconds} seconds...`); debug(`Killing processes in ${killSeconds} seconds...`);
setTimeout(() => { setTimeout(() => {
debug('Killing processes'); debug('Killing processes');
doShutdown = true;
// eslint-disable-next-line unicorn/no-process-exit // eslint-disable-next-line unicorn/no-process-exit
process.exit(0); process.exit(0);
}, secondsToMillis(killSeconds)); }, secondsToMillis(killSeconds));
} }
exitHook(() => {
doShutdown = true;
debug('Shutting down...');
for (const worker of activeWorkers.values()) {
debug(`Killing worker ${worker.process.pid}`);
worker.kill();
}
});

View File

@ -8,31 +8,23 @@ import { secondsToMillis } from '@cityssm/to-millis'
import Debug from 'debug' import Debug from 'debug'
import exitHook from 'exit-hook' import exitHook from 'exit-hook'
import { initializeDatabase } from '../database/initializeDatabase.js'
import { DEBUG_NAMESPACE } from '../debug.config.js' import { DEBUG_NAMESPACE } from '../debug.config.js'
import { getConfigProperty } from '../helpers/config.helpers.js' import { getConfigProperty } from '../helpers/config.helpers.js'
import type { WorkerMessage } from '../types/application.types.js' import type { WorkerMessage } from '../types/applicationTypes.js'
import version from '../version.js'
const debug = Debug(`${DEBUG_NAMESPACE}:www:${process.pid}`) const debug = Debug(`${DEBUG_NAMESPACE}:www:${process.pid}`)
// INITIALIZE THE DATABASE
initializeDatabase()
const directoryName = path.dirname(fileURLToPath(import.meta.url)) const directoryName = path.dirname(fileURLToPath(import.meta.url))
const processCount = Math.min( const processCount = Math.min(
getConfigProperty('application.maximumProcesses'), getConfigProperty('application.maximumProcesses'),
os.cpus().length * 2 os.cpus().length
) )
const applicationName = getConfigProperty('application.applicationName') process.title = `${getConfigProperty('application.applicationName')} (Primary)`
process.title = `${applicationName} (Primary)`
debug(`Primary pid: ${process.pid}`) debug(`Primary pid: ${process.pid}`)
debug(`Primary title: ${process.title}`) debug(`Primary title: ${process.title}`)
debug(`Version: ${version}`)
debug(`Launching ${processCount} processes`) debug(`Launching ${processCount} processes`)
const clusterSettings = { const clusterSettings = {
@ -41,7 +33,6 @@ const clusterSettings = {
cluster.setupPrimary(clusterSettings) cluster.setupPrimary(clusterSettings)
let doShutdown = false
const activeWorkers = new Map<number, Worker>() const activeWorkers = new Map<number, Worker>()
for (let index = 0; index < processCount; index += 1) { for (let index = 0; index < processCount; index += 1) {
@ -51,7 +42,6 @@ for (let index = 0; index < processCount; index += 1) {
cluster.on('message', (worker, message: WorkerMessage) => { cluster.on('message', (worker, message: WorkerMessage) => {
for (const [pid, activeWorker] of activeWorkers.entries()) { 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) { if (activeWorker === undefined || pid === message.pid) {
continue continue
} }
@ -65,12 +55,8 @@ cluster.on('exit', (worker) => {
debug(`Worker ${(worker.process.pid ?? 0).toString()} has been killed`) debug(`Worker ${(worker.process.pid ?? 0).toString()} has been killed`)
activeWorkers.delete(worker.process.pid ?? 0) activeWorkers.delete(worker.process.pid ?? 0)
if (!doShutdown) {
debug('Starting another worker') debug('Starting another worker')
const newWorker = cluster.fork() cluster.fork()
activeWorkers.set(newWorker.process.pid ?? 0, newWorker)
}
}) })
const ntfyStartupConfig = getConfigProperty('application.ntfyStartup') const ntfyStartupConfig = getConfigProperty('application.ntfyStartup')
@ -80,17 +66,17 @@ if (ntfyStartupConfig !== undefined) {
const server = ntfyStartupConfig.server const server = ntfyStartupConfig.server
const ntfyStartupMessage: NtfyMessageOptions = { const ntfyStartupMessage: NtfyMessageOptions = {
topic,
title: getConfigProperty('application.applicationName'),
message: 'Application Started', message: 'Application Started',
tags: ['arrow_up'], tags: ['arrow_up']
title: applicationName,
topic
} }
const ntfyShutdownMessage: NtfyMessageOptions = { const ntfyShutdownMessage: NtfyMessageOptions = {
topic,
title: getConfigProperty('application.applicationName'),
message: 'Application Shut Down', message: 'Application Shut Down',
tags: ['arrow_down'], tags: ['arrow_down']
title: applicationName,
topic
} }
if (server !== undefined) { if (server !== undefined) {
@ -114,19 +100,7 @@ if (process.env.STARTUP_TEST === 'true') {
setTimeout(() => { setTimeout(() => {
debug('Killing processes') debug('Killing processes')
doShutdown = true
// eslint-disable-next-line unicorn/no-process-exit // eslint-disable-next-line unicorn/no-process-exit
process.exit(0) process.exit(0)
}, secondsToMillis(killSeconds)) }, secondsToMillis(killSeconds))
} }
exitHook(() => {
doShutdown = true
debug('Shutting down...')
for (const worker of activeWorkers.values()) {
debug(`Killing worker ${worker.process.pid}`)
worker.kill()
}
})

View File

@ -4,14 +4,9 @@ import http from 'node:http';
import Debug from 'debug'; import Debug from 'debug';
import exitHook from 'exit-hook'; import exitHook from 'exit-hook';
import { app } from '../app.js'; import { app } from '../app.js';
import { initializeDatabase } from '../database/initializeDatabase.js';
import { DEBUG_NAMESPACE } from '../debug.config.js'; import { DEBUG_NAMESPACE } from '../debug.config.js';
import { getConfigProperty } from '../helpers/config.helpers.js'; import { getConfigProperty } from '../helpers/config.helpers.js';
const debug = Debug(`${DEBUG_NAMESPACE}:wwwProcess:${process.pid.toString().padEnd(5)}`); const debug = Debug(`${DEBUG_NAMESPACE}:wwwProcess:${process.pid}`);
if (process.send === undefined) {
// INITIALIZE THE DATABASE
initializeDatabase();
}
function onError(error) { function onError(error) {
if (error.syscall !== 'listen') { if (error.syscall !== 'listen') {
throw error; throw error;

View File

@ -7,20 +7,14 @@ import Debug from 'debug'
import exitHook from 'exit-hook' import exitHook from 'exit-hook'
import { app } from '../app.js' import { app } from '../app.js'
import { initializeDatabase } from '../database/initializeDatabase.js'
import { DEBUG_NAMESPACE } from '../debug.config.js' import { DEBUG_NAMESPACE } from '../debug.config.js'
import { getConfigProperty } from '../helpers/config.helpers.js' import { getConfigProperty } from '../helpers/config.helpers.js'
const debug = Debug(`${DEBUG_NAMESPACE}:wwwProcess:${process.pid.toString().padEnd(5)}`) const debug = Debug(`${DEBUG_NAMESPACE}:wwwProcess:${process.pid}`)
if (process.send === undefined) {
// INITIALIZE THE DATABASE
initializeDatabase()
}
interface ServerError extends Error { interface ServerError extends Error {
code: string
syscall: string syscall: string
code: string
} }
function onError(error: ServerError): void { function onError(error: ServerError): void {

View File

@ -1,9 +1,9 @@
import { defineConfig } from 'cypress'; import { defineConfig } from 'cypress';
export default defineConfig({ export default defineConfig({
e2e: { e2e: {
baseUrl: 'http://localhost:9000', baseUrl: 'http://localhost:7000',
projectId: '26a4bi',
specPattern: 'cypress/e2e/**/*.cy.js', specPattern: 'cypress/e2e/**/*.cy.js',
supportFile: false supportFile: false,
projectId: '26a4bi'
} }
}); });

View File

@ -2,9 +2,9 @@ import { defineConfig } from 'cypress'
export default defineConfig({ export default defineConfig({
e2e: { e2e: {
baseUrl: 'http://localhost:9000', baseUrl: 'http://localhost:7000',
projectId: '26a4bi',
specPattern: 'cypress/e2e/**/*.cy.js', specPattern: 'cypress/e2e/**/*.cy.js',
supportFile: false supportFile: false,
projectId: '26a4bi'
} }
}) })

View File

@ -1,6 +1,6 @@
import { getConfigProperty } from '../../../helpers/config.helpers.js' import { getConfigProperty } from '../../../helpers/config.helpers.js'
import { testAdmin } from '../../../test/_globals.js' import { testAdmin } from '../../../test/_globals.js'
import type { Fee } from '../../../types/record.types.js' import type { Fee } from '../../../types/recordTypes.js'
import { ajaxDelayMillis, login, logout } from '../../support/index.js' import { ajaxDelayMillis, login, logout } from '../../support/index.js'
describe('Admin - Fee Management', () => { describe('Admin - Fee Management', () => {

View File

@ -1,6 +1,6 @@
import { getConfigProperty } from '../../../helpers/config.helpers.js' import { getConfigProperty } from '../../../helpers/config.helpers.js'
import { testUpdate } from '../../../test/_globals.js' import { testUpdate } from '../../../test/_globals.js'
import type { Cemetery } from '../../../types/record.types.js' import type { Cemetery } from '../../../types/recordTypes.js'
import { login, logout } from '../../support/index.js' import { login, logout } from '../../support/index.js'
describe('Update - Cemeteries', () => { describe('Update - Cemeteries', () => {

View File

@ -1,21 +0,0 @@
import { testUpdate } from '../../../test/_globals.js';
import { login, logout } from '../../support/index.js';
describe('Update - Funeral Homes', () => {
beforeEach('Loads page', () => {
logout();
login(testUpdate);
});
afterEach(logout);
it('Has a "Create" link on the Funeral Home Search', () => {
cy.visit('/funeralHomes');
cy.location('pathname').should('equal', '/funeralHomes');
cy.get("a[href$='/funeralHomes/new']").should('exist');
});
describe('Creates a New Funeral Home', () => {
it('Has no detectable accessibility issues', () => {
cy.visit('/funeralHomes/new');
cy.injectAxe();
cy.checkA11y();
});
});
});

View File

@ -1,25 +0,0 @@
import { testUpdate } from '../../../test/_globals.js'
import { login, logout } from '../../support/index.js'
describe('Update - Funeral Homes', () => {
beforeEach('Loads page', () => {
logout()
login(testUpdate)
})
afterEach(logout)
it('Has a "Create" link on the Funeral Home Search', () => {
cy.visit('/funeralHomes')
cy.location('pathname').should('equal', '/funeralHomes')
cy.get("a[href$='/funeralHomes/new']").should('exist')
})
describe('Creates a New Funeral Home', () => {
it('Has no detectable accessibility issues', () => {
cy.visit('/funeralHomes/new')
cy.injectAxe()
cy.checkA11y()
})
})
})

View File

@ -1,3 +1,3 @@
import type { Config } from '../types/config.types.js'; import type { Config } from '../types/configTypes.js';
export declare const config: Config; export declare const config: Config;
export default config; export default config;

View File

@ -1,21 +1,19 @@
export const config = { export const config = {
aliases: {},
application: {}, application: {},
reverseProxy: {},
session: {}, session: {},
reverseProxy: {},
users: {},
aliases: {},
settings: { settings: {
adminCleanup: {}, fees: {},
burialSites: {}, burialSites: {},
burialSiteTypes: {},
cemeteries: {},
contracts: {}, contracts: {},
workOrders: {},
adminCleanup: {},
printPdf: {},
dynamicsGP: { dynamicsGP: {
integrationIsEnabled: false integrationIsEnabled: false
}, }
fees: {}, }
printPdf: {},
workOrders: {}
},
users: {}
}; };
export default config; export default config;

View File

@ -1,24 +1,22 @@
import type { Config } from '../types/config.types.js' import type { Config } from '../types/configTypes.js'
export const config: Config = { export const config: Config = {
aliases: {},
application: {}, application: {},
reverseProxy: {},
session: {}, session: {},
reverseProxy: {},
users: {},
aliases: {},
settings: { settings: {
adminCleanup: {}, fees: {},
burialSites: {}, burialSites: {},
burialSiteTypes: {},
cemeteries: {},
contracts: {}, contracts: {},
workOrders: {},
adminCleanup: {},
printPdf: {},
dynamicsGP: { dynamicsGP: {
integrationIsEnabled: false integrationIsEnabled: false
}, }
fees: {}, }
printPdf: {},
workOrders: {}
},
users: {}
} }
export default config export default config

2
data/config.baseOntario.d.ts vendored 100644
View File

@ -0,0 +1,2 @@
export declare const config: import("../types/configTypes.js").Config;
export default config;

View File

@ -0,0 +1,5 @@
import { config as baseConfig } from './config.base.js';
export const config = Object.assign({}, baseConfig);
config.settings.provinceDefault = 'ON';
config.settings.fees.taxPercentageDefault = 13;
export default config;

View File

@ -0,0 +1,9 @@
import { config as baseConfig } from './config.base.js'
export const config = Object.assign({}, baseConfig)
config.settings.provinceDefault = 'ON'
config.settings.fees.taxPercentageDefault = 13
export default config

View File

@ -1,3 +1,3 @@
import type { Config } from '../types/config.types.js'; import type { Config } from '../types/configTypes.js';
export declare const config: Config; export declare const config: Config;
export default config; export default config;

View File

@ -1,52 +1,45 @@
import { config as cemeteryConfig } from './ontario.config.js'; import { config as cemeteryConfig } from './config.baseOntario.js';
export const config = { ...cemeteryConfig }; export const config = { ...cemeteryConfig };
config.aliases.externalReceiptNumber = 'GP Receipt Number'; config.aliases.externalReceiptNumber = 'GP Receipt Number';
config.settings.publicInternalPath =
'../sunrise-cms-saultstemarie/public-internal';
config.settings.burialSites.burialSiteNameSegments = { config.settings.burialSites.burialSiteNameSegments = {
includeCemeteryKey: true,
separator: '-', separator: '-',
includeCemeteryKey: true,
segments: { segments: {
1: { 1: {
isAvailable: true,
isRequired: false, isRequired: false,
isAvailable: true,
label: 'Block', label: 'Block',
maxLength: 1, minLength: 1,
minLength: 1 maxLength: 1
}, },
2: { 2: {
isRequired: true,
isAvailable: true, isAvailable: true,
isRequired: false,
label: 'Range', label: 'Range',
maxLength: 3, minLength: 1,
minLength: 1 maxLength: 3
}, },
3: { 3: {
isAvailable: true,
isRequired: true, isRequired: true,
isAvailable: true,
label: 'Lot', label: 'Lot',
maxLength: 4, minLength: 1,
minLength: 1 maxLength: 4
}, },
4: { 4: {
isAvailable: true,
isRequired: true, isRequired: true,
isAvailable: true,
label: 'Grave', label: 'Grave',
maxLength: 2, minLength: 1,
minLength: 1 maxLength: 2
} }
} }
}; };
config.settings.cityDefault = 'Sault Ste. Marie'; config.settings.cityDefault = 'Sault Ste. Marie';
config.settings.latitudeMax = 46.75;
config.settings.latitudeMin = 46.4;
config.settings.longitudeMax = -84.2;
config.settings.longitudeMin = -84.5;
config.settings.contracts.prints = [ config.settings.contracts.prints = [
'pdf/ssm.cemetery.burialPermit', 'pdf/ssm.cemetery.burialPermit',
'pdf/ssm.cemetery.contract' 'pdf/ssm.cemetery.contract'
]; ];
config.settings.printPdf.browser = 'firefox';
config.settings.workOrders.workOrderNumberLength = 6; config.settings.workOrders.workOrderNumberLength = 6;
config.settings.workOrders.workOrderMilestoneDateRecentBeforeDays = 7; config.settings.workOrders.workOrderMilestoneDateRecentBeforeDays = 7;
config.settings.workOrders.workOrderMilestoneDateRecentAfterDays = 30; config.settings.workOrders.workOrderMilestoneDateRecentAfterDays = 30;

View File

@ -1,64 +1,53 @@
import type { Config } from '../types/config.types.js' import type { Config } from '../types/configTypes.js'
import { config as cemeteryConfig } from './ontario.config.js' import { config as cemeteryConfig } from './config.baseOntario.js'
export const config: Config = { ...cemeteryConfig } export const config: Config = { ...cemeteryConfig }
config.aliases.externalReceiptNumber = 'GP Receipt Number' config.aliases.externalReceiptNumber = 'GP Receipt Number'
config.settings.publicInternalPath =
'../sunrise-cms-saultstemarie/public-internal'
config.settings.burialSites.burialSiteNameSegments = { config.settings.burialSites.burialSiteNameSegments = {
includeCemeteryKey: true,
separator: '-', separator: '-',
includeCemeteryKey: true,
segments: { segments: {
1: { 1: {
isAvailable: true,
isRequired: false, isRequired: false,
isAvailable: true,
label: 'Block', label: 'Block',
maxLength: 1, minLength: 1,
minLength: 1 maxLength: 1
}, },
2: { 2: {
isRequired: true,
isAvailable: true, isAvailable: true,
isRequired: false,
label: 'Range', label: 'Range',
maxLength: 3, minLength: 1,
minLength: 1 maxLength: 3
}, },
3: { 3: {
isAvailable: true,
isRequired: true, isRequired: true,
isAvailable: true,
label: 'Lot', label: 'Lot',
maxLength: 4, minLength: 1,
minLength: 1 maxLength: 4
}, },
4: { 4: {
isAvailable: true,
isRequired: true, isRequired: true,
isAvailable: true,
label: 'Grave', label: 'Grave',
maxLength: 2, minLength: 1,
minLength: 1 maxLength: 2
} }
} }
} }
config.settings.cityDefault = 'Sault Ste. Marie' config.settings.cityDefault = 'Sault Ste. Marie'
config.settings.latitudeMax = 46.75
config.settings.latitudeMin = 46.4
config.settings.longitudeMax = -84.2
config.settings.longitudeMin = -84.5
config.settings.contracts.prints = [ config.settings.contracts.prints = [
'pdf/ssm.cemetery.burialPermit', 'pdf/ssm.cemetery.burialPermit',
'pdf/ssm.cemetery.contract' 'pdf/ssm.cemetery.contract'
] ]
config.settings.printPdf.browser = 'firefox'
config.settings.workOrders.workOrderNumberLength = 6 config.settings.workOrders.workOrderNumberLength = 6
config.settings.workOrders.workOrderMilestoneDateRecentBeforeDays = 7 config.settings.workOrders.workOrderMilestoneDateRecentBeforeDays = 7
config.settings.workOrders.workOrderMilestoneDateRecentAfterDays = 30 config.settings.workOrders.workOrderMilestoneDateRecentAfterDays = 30

View File

@ -1,54 +1,41 @@
import type { config as MSSQLConfig } from 'mssql'; import type { config as MSSQLConfig } from 'mssql';
import type { ConfigActiveDirectory, ConfigBurialSiteNameSegments, ConfigNtfyStartup, DynamicsGPLookup } from '../types/config.types.js'; import type { ConfigActiveDirectory, ConfigBurialSiteNameSegments, ConfigNtfyStartup, DynamicsGPLookup } from '../types/configTypes.js';
export declare const configDefaultValues: { export declare const configDefaultValues: {
activeDirectory: ConfigActiveDirectory; activeDirectory: ConfigActiveDirectory;
'application.applicationName': string; 'application.applicationName': string;
'application.backgroundURL': string; 'application.backgroundURL': string;
'application.httpPort': number;
'application.logoURL': string; 'application.logoURL': string;
'application.maximumProcesses': number; 'application.httpPort': number;
'application.ntfyStartup': ConfigNtfyStartup | undefined;
'application.userDomain': string; 'application.userDomain': string;
'application.useTestDatabases': boolean; 'application.useTestDatabases': boolean;
'application.maximumProcesses': number;
'application.ntfyStartup': ConfigNtfyStartup | undefined;
'reverseProxy.disableCompression': boolean; 'reverseProxy.disableCompression': boolean;
'reverseProxy.disableEtag': boolean; 'reverseProxy.disableEtag': boolean;
'reverseProxy.urlPrefix': string; 'reverseProxy.urlPrefix': string;
'session.cookieName': string; 'session.cookieName': string;
'session.doKeepAlive': boolean;
'session.maxAgeMillis': number;
'session.secret': string; 'session.secret': string;
'session.maxAgeMillis': number;
'session.doKeepAlive': boolean;
'users.testing': string[];
'users.canLogin': string[]; 'users.canLogin': string[];
'users.canUpdate': string[]; 'users.canUpdate': string[];
'users.canUpdateWorkOrders': string[];
'users.isAdmin': string[]; 'users.isAdmin': string[];
'users.testing': string[];
'aliases.externalReceiptNumber': string; 'aliases.externalReceiptNumber': string;
'aliases.workOrderCloseDate': string;
'aliases.workOrderOpenDate': string; 'aliases.workOrderOpenDate': string;
'aliases.workOrderCloseDate': string;
'settings.cityDefault': string; 'settings.cityDefault': string;
'settings.provinceDefault': string; 'settings.provinceDefault': string;
'settings.publicInternalPath': string;
'settings.latitudeMax': number;
'settings.latitudeMin': number;
'settings.longitudeMax': number;
'settings.longitudeMin': number;
'settings.cemeteries.refreshImageChanges': boolean;
'settings.burialSiteTypes.bodyCapacityMaxDefault': number;
'settings.burialSiteTypes.crematedCapacityMaxDefault': number;
'settings.burialSites.burialSiteNameSegments': ConfigBurialSiteNameSegments; 'settings.burialSites.burialSiteNameSegments': ConfigBurialSiteNameSegments;
'settings.burialSites.burialSiteNameSegments.includeCemeteryKey': boolean;
'settings.burialSites.refreshImageChanges': boolean;
'settings.contracts.burialSiteIdIsRequired': boolean; 'settings.contracts.burialSiteIdIsRequired': boolean;
'settings.contracts.contractEndDateIsRequired': boolean;
'settings.contracts.prints': string[]; 'settings.contracts.prints': string[];
'settings.fees.taxPercentageDefault': number; 'settings.fees.taxPercentageDefault': number;
'settings.workOrders.workOrderNumberLength': number; 'settings.workOrders.workOrderNumberLength': number;
'settings.workOrders.workOrderMilestoneDateRecentBeforeDays': number;
'settings.workOrders.workOrderMilestoneDateRecentAfterDays': number;
'settings.workOrders.calendarEmailAddress': string; 'settings.workOrders.calendarEmailAddress': string;
'settings.workOrders.prints': string[]; 'settings.workOrders.prints': string[];
'settings.workOrders.workOrderMilestoneDateRecentAfterDays': number;
'settings.workOrders.workOrderMilestoneDateRecentBeforeDays': number;
'settings.adminCleanup.recordDeleteAgeDays': number; 'settings.adminCleanup.recordDeleteAgeDays': number;
'settings.printPdf.browser': "chrome" | "firefox";
'settings.printPdf.contentDisposition': "attachment" | "inline"; 'settings.printPdf.contentDisposition': "attachment" | "inline";
'settings.dynamicsGP.integrationIsEnabled': boolean; 'settings.dynamicsGP.integrationIsEnabled': boolean;
'settings.dynamicsGP.mssqlConfig': MSSQLConfig; 'settings.dynamicsGP.mssqlConfig': MSSQLConfig;
@ -57,4 +44,3 @@ export declare const configDefaultValues: {
'settings.dynamicsGP.itemNumbers': string[]; 'settings.dynamicsGP.itemNumbers': string[];
'settings.dynamicsGP.trialBalanceCodes': string[]; 'settings.dynamicsGP.trialBalanceCodes': string[];
}; };
export default configDefaultValues;

View File

@ -3,65 +3,49 @@ export const configDefaultValues = {
activeDirectory: undefined, activeDirectory: undefined,
'application.applicationName': 'Sunrise CMS', 'application.applicationName': 'Sunrise CMS',
'application.backgroundURL': '/images/cemetery-background.jpg', 'application.backgroundURL': '/images/cemetery-background.jpg',
'application.httpPort': 9000, 'application.logoURL': '/images/sunrise-cms.png',
'application.logoURL': '/images/sunrise-cms.svg', 'application.httpPort': 7000,
'application.maximumProcesses': 4,
'application.ntfyStartup': undefined,
'application.userDomain': '', 'application.userDomain': '',
'application.useTestDatabases': false, 'application.useTestDatabases': false,
'application.maximumProcesses': 4,
'application.ntfyStartup': undefined,
'reverseProxy.disableCompression': false, 'reverseProxy.disableCompression': false,
'reverseProxy.disableEtag': false, 'reverseProxy.disableEtag': false,
'reverseProxy.urlPrefix': '', 'reverseProxy.urlPrefix': '',
'session.cookieName': 'sunrise-user-sid', 'session.cookieName': 'sunrise-user-sid',
'session.doKeepAlive': false,
'session.maxAgeMillis': hoursToMillis(1),
'session.secret': 'cityssm/sunrise', 'session.secret': 'cityssm/sunrise',
'session.maxAgeMillis': hoursToMillis(1),
'session.doKeepAlive': false,
'users.testing': [],
'users.canLogin': ['administrator'], 'users.canLogin': ['administrator'],
'users.canUpdate': [], 'users.canUpdate': [],
'users.canUpdateWorkOrders': [],
'users.isAdmin': ['administrator'], 'users.isAdmin': ['administrator'],
'users.testing': [],
'aliases.externalReceiptNumber': 'External Receipt Number', 'aliases.externalReceiptNumber': 'External Receipt Number',
'aliases.workOrderCloseDate': 'Completion Date',
'aliases.workOrderOpenDate': 'Order Date', 'aliases.workOrderOpenDate': 'Order Date',
'aliases.workOrderCloseDate': 'Completion Date',
'settings.cityDefault': '', 'settings.cityDefault': '',
'settings.provinceDefault': '', 'settings.provinceDefault': '',
'settings.publicInternalPath': 'public-internal',
'settings.latitudeMax': 90,
'settings.latitudeMin': -90,
'settings.longitudeMax': 180,
'settings.longitudeMin': -180,
'settings.cemeteries.refreshImageChanges': false,
// eslint-disable-next-line no-secrets/no-secrets
'settings.burialSiteTypes.bodyCapacityMaxDefault': 2,
// eslint-disable-next-line no-secrets/no-secrets
'settings.burialSiteTypes.crematedCapacityMaxDefault': 6,
'settings.burialSites.burialSiteNameSegments': { 'settings.burialSites.burialSiteNameSegments': {
includeCemeteryKey: false,
separator: '-', separator: '-',
segments: { segments: {
1: { 1: {
isAvailable: true,
isRequired: true, isRequired: true,
isAvailable: true,
label: 'Plot Number', label: 'Plot Number',
maxLength: 20, minLength: 1,
minLength: 1 maxLength: 20
} }
} }
}, },
'settings.burialSites.burialSiteNameSegments.includeCemeteryKey': false,
'settings.burialSites.refreshImageChanges': false,
'settings.contracts.burialSiteIdIsRequired': true, 'settings.contracts.burialSiteIdIsRequired': true,
'settings.contracts.contractEndDateIsRequired': false,
'settings.contracts.prints': ['screen/contract'], 'settings.contracts.prints': ['screen/contract'],
'settings.fees.taxPercentageDefault': 0, 'settings.fees.taxPercentageDefault': 0,
'settings.workOrders.workOrderNumberLength': 6, 'settings.workOrders.workOrderNumberLength': 6,
'settings.workOrders.workOrderMilestoneDateRecentBeforeDays': 5,
'settings.workOrders.workOrderMilestoneDateRecentAfterDays': 60,
'settings.workOrders.calendarEmailAddress': 'no-reply@127.0.0.1', 'settings.workOrders.calendarEmailAddress': 'no-reply@127.0.0.1',
'settings.workOrders.prints': ['pdf/workOrder', 'pdf/workOrder-commentLog'], 'settings.workOrders.prints': ['pdf/workOrder', 'pdf/workOrder-commentLog'],
'settings.workOrders.workOrderMilestoneDateRecentAfterDays': 60,
'settings.workOrders.workOrderMilestoneDateRecentBeforeDays': 5,
'settings.adminCleanup.recordDeleteAgeDays': 60, 'settings.adminCleanup.recordDeleteAgeDays': 60,
'settings.printPdf.browser': 'chrome',
'settings.printPdf.contentDisposition': 'attachment', 'settings.printPdf.contentDisposition': 'attachment',
'settings.dynamicsGP.integrationIsEnabled': false, 'settings.dynamicsGP.integrationIsEnabled': false,
'settings.dynamicsGP.mssqlConfig': undefined, 'settings.dynamicsGP.mssqlConfig': undefined,
@ -71,4 +55,3 @@ export const configDefaultValues = {
'settings.dynamicsGP.itemNumbers': [], 'settings.dynamicsGP.itemNumbers': [],
'settings.dynamicsGP.trialBalanceCodes': [] 'settings.dynamicsGP.trialBalanceCodes': []
}; };
export default configDefaultValues;

View File

@ -6,93 +6,70 @@ import type {
ConfigBurialSiteNameSegments, ConfigBurialSiteNameSegments,
ConfigNtfyStartup, ConfigNtfyStartup,
DynamicsGPLookup DynamicsGPLookup
} from '../types/config.types.js' } from '../types/configTypes.js'
export const configDefaultValues = { export const configDefaultValues = {
activeDirectory: undefined as unknown as ConfigActiveDirectory, activeDirectory: undefined as unknown as ConfigActiveDirectory,
'application.applicationName': 'Sunrise CMS', 'application.applicationName': 'Sunrise CMS',
'application.backgroundURL': '/images/cemetery-background.jpg', 'application.backgroundURL': '/images/cemetery-background.jpg',
'application.httpPort': 9000, 'application.logoURL': '/images/sunrise-cms.png',
'application.logoURL': '/images/sunrise-cms.svg', 'application.httpPort': 7000,
'application.maximumProcesses': 4,
'application.ntfyStartup': undefined as ConfigNtfyStartup | undefined,
'application.userDomain': '', 'application.userDomain': '',
'application.useTestDatabases': false, 'application.useTestDatabases': false,
'application.maximumProcesses': 4,
'application.ntfyStartup': undefined as ConfigNtfyStartup | undefined,
'reverseProxy.disableCompression': false, 'reverseProxy.disableCompression': false,
'reverseProxy.disableEtag': false, 'reverseProxy.disableEtag': false,
'reverseProxy.urlPrefix': '', 'reverseProxy.urlPrefix': '',
'session.cookieName': 'sunrise-user-sid', 'session.cookieName': 'sunrise-user-sid',
'session.doKeepAlive': false,
'session.maxAgeMillis': hoursToMillis(1),
'session.secret': 'cityssm/sunrise', 'session.secret': 'cityssm/sunrise',
'session.maxAgeMillis': hoursToMillis(1),
'session.doKeepAlive': false,
'users.testing': [] as string[],
'users.canLogin': ['administrator'], 'users.canLogin': ['administrator'],
'users.canUpdate': [] as string[], 'users.canUpdate': [] as string[],
'users.canUpdateWorkOrders': [] as string[],
'users.isAdmin': ['administrator'], 'users.isAdmin': ['administrator'],
'users.testing': [] as string[],
'aliases.externalReceiptNumber': 'External Receipt Number', 'aliases.externalReceiptNumber': 'External Receipt Number',
'aliases.workOrderCloseDate': 'Completion Date',
'aliases.workOrderOpenDate': 'Order Date', 'aliases.workOrderOpenDate': 'Order Date',
'aliases.workOrderCloseDate': 'Completion Date',
'settings.cityDefault': '', 'settings.cityDefault': '',
'settings.provinceDefault': '', 'settings.provinceDefault': '',
'settings.publicInternalPath': 'public-internal',
'settings.latitudeMax': 90,
'settings.latitudeMin': -90,
'settings.longitudeMax': 180,
'settings.longitudeMin': -180,
'settings.cemeteries.refreshImageChanges': false,
// eslint-disable-next-line no-secrets/no-secrets
'settings.burialSiteTypes.bodyCapacityMaxDefault': 2,
// eslint-disable-next-line no-secrets/no-secrets
'settings.burialSiteTypes.crematedCapacityMaxDefault': 6,
'settings.burialSites.burialSiteNameSegments': { 'settings.burialSites.burialSiteNameSegments': {
includeCemeteryKey: false,
separator: '-', separator: '-',
segments: { segments: {
1: { 1: {
isAvailable: true,
isRequired: true, isRequired: true,
isAvailable: true,
label: 'Plot Number', label: 'Plot Number',
maxLength: 20, minLength: 1,
minLength: 1 maxLength: 20
} }
} }
} as unknown as ConfigBurialSiteNameSegments, } as unknown as ConfigBurialSiteNameSegments,
'settings.burialSites.burialSiteNameSegments.includeCemeteryKey': false,
'settings.burialSites.refreshImageChanges': false,
'settings.contracts.burialSiteIdIsRequired': true, 'settings.contracts.burialSiteIdIsRequired': true,
'settings.contracts.contractEndDateIsRequired': false,
'settings.contracts.prints': ['screen/contract'], 'settings.contracts.prints': ['screen/contract'],
'settings.fees.taxPercentageDefault': 0, 'settings.fees.taxPercentageDefault': 0,
'settings.workOrders.workOrderNumberLength': 6, 'settings.workOrders.workOrderNumberLength': 6,
'settings.workOrders.workOrderMilestoneDateRecentBeforeDays': 5,
'settings.workOrders.workOrderMilestoneDateRecentAfterDays': 60,
'settings.workOrders.calendarEmailAddress': 'no-reply@127.0.0.1', 'settings.workOrders.calendarEmailAddress': 'no-reply@127.0.0.1',
'settings.workOrders.prints': ['pdf/workOrder', 'pdf/workOrder-commentLog'], 'settings.workOrders.prints': ['pdf/workOrder', 'pdf/workOrder-commentLog'],
'settings.workOrders.workOrderMilestoneDateRecentAfterDays': 60,
'settings.workOrders.workOrderMilestoneDateRecentBeforeDays': 5,
'settings.adminCleanup.recordDeleteAgeDays': 60, 'settings.adminCleanup.recordDeleteAgeDays': 60,
'settings.printPdf.browser': 'chrome' as 'chrome' | 'firefox',
'settings.printPdf.contentDisposition': 'attachment' as 'settings.printPdf.contentDisposition': 'attachment' as
| 'attachment' | 'attachment'
| 'inline', | 'inline',
@ -107,5 +84,3 @@ export const configDefaultValues = {
'settings.dynamicsGP.itemNumbers': [] as string[], 'settings.dynamicsGP.itemNumbers': [] as string[],
'settings.dynamicsGP.trialBalanceCodes': [] as string[] 'settings.dynamicsGP.trialBalanceCodes': [] as string[]
} }
export default configDefaultValues

View File

@ -1,3 +1,3 @@
import type { Config } from '../types/config.types.js'; import type { Config } from '../types/configTypes.js';
export declare const config: Config; export declare const config: Config;
export default config; export default config;

View File

@ -1,14 +1,12 @@
import { config as cemeteryConfig } from './ssm.ontario.config.js'; import { config as cemeteryConfig } from './config.baseSsm.js';
export const config = { ...cemeteryConfig }; export const config = { ...cemeteryConfig };
config.application.useTestDatabases = true; config.application.useTestDatabases = true;
config.session.doKeepAlive = true; config.session.doKeepAlive = true;
config.users = { config.users = {
testing: ['*testView', '*testUpdate', '*testAdmin'],
canLogin: ['*testView', '*testUpdate', '*testAdmin'], canLogin: ['*testView', '*testUpdate', '*testAdmin'],
canUpdate: ['*testUpdate'], canUpdate: ['*testUpdate'],
canUpdateWorkOrders: ['*testUpdate'], isAdmin: ['*testAdmin']
isAdmin: ['*testAdmin'],
testing: ['*testView', '*testUpdate', '*testAdmin']
}; };
config.settings.publicInternalPath = 'public-internal';
config.settings.dynamicsGP.integrationIsEnabled = false; config.settings.dynamicsGP.integrationIsEnabled = false;
export default config; export default config;

View File

@ -1,6 +1,6 @@
import type { Config } from '../types/config.types.js' import type { Config } from '../types/configTypes.js'
import { config as cemeteryConfig } from './ssm.ontario.config.js' import { config as cemeteryConfig } from './config.baseSsm.js'
export const config: Config = { ...cemeteryConfig } export const config: Config = { ...cemeteryConfig }
@ -9,15 +9,12 @@ config.application.useTestDatabases = true
config.session.doKeepAlive = true config.session.doKeepAlive = true
config.users = { config.users = {
testing: ['*testView', '*testUpdate', '*testAdmin'],
canLogin: ['*testView', '*testUpdate', '*testAdmin'], canLogin: ['*testView', '*testUpdate', '*testAdmin'],
canUpdate: ['*testUpdate'], canUpdate: ['*testUpdate'],
canUpdateWorkOrders: ['*testUpdate'], isAdmin: ['*testAdmin']
isAdmin: ['*testAdmin'],
testing: ['*testView', '*testUpdate', '*testAdmin']
} }
config.settings.publicInternalPath = 'public-internal'
config.settings.dynamicsGP!.integrationIsEnabled = false config.settings.dynamicsGP!.integrationIsEnabled = false
export default config export default config

9
data/dataLists.d.ts vendored
View File

@ -1,9 +0,0 @@
export declare const deathAgePeriods: readonly ["Years", "Months", "Days", "Stillborn"];
export declare const purchaserRelationships: readonly ["Spouse", "Husband", "Wife", "Child", "Parent", "Sibling", "Friend", "Self"];
export declare const directionsOfArrival: readonly ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
declare const _default: {
deathAgePeriods: readonly ["Years", "Months", "Days", "Stillborn"];
directionsOfArrival: readonly ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
purchaserRelationships: readonly ["Spouse", "Husband", "Wife", "Child", "Parent", "Sibling", "Friend", "Self"];
};
export default _default;

View File

@ -1,26 +0,0 @@
export const deathAgePeriods = ['Years', 'Months', 'Days', 'Stillborn'];
export const purchaserRelationships = [
'Spouse',
'Husband',
'Wife',
'Child',
'Parent',
'Sibling',
'Friend',
'Self'
];
export const directionsOfArrival = [
'N',
'NE',
'E',
'SE',
'S',
'SW',
'W',
'NW'
];
export default {
deathAgePeriods,
directionsOfArrival,
purchaserRelationships
};

View File

@ -1,29 +0,0 @@
export const deathAgePeriods = ['Years', 'Months', 'Days', 'Stillborn'] as const
export const purchaserRelationships = [
'Spouse',
'Husband',
'Wife',
'Child',
'Parent',
'Sibling',
'Friend',
'Self'
] as const
export const directionsOfArrival = [
'N',
'NE',
'E',
'SE',
'S',
'SW',
'W',
'NW'
] as const
export default {
deathAgePeriods,
directionsOfArrival,
purchaserRelationships
}

View File

@ -1,2 +0,0 @@
export declare const config: import("../types/config.types.js").Config;
export default config;

View File

@ -1,9 +0,0 @@
import { config as baseConfig } from './base.config.js';
export const config = Object.assign({}, baseConfig);
config.settings.provinceDefault = 'ON';
config.settings.latitudeMax = 56.85;
config.settings.latitudeMin = 41.68;
config.settings.longitudeMax = -74;
config.settings.longitudeMin = -95.15;
config.settings.fees.taxPercentageDefault = 13;
export default config;

View File

@ -1,15 +0,0 @@
import { config as baseConfig } from './base.config.js'
export const config = Object.assign({}, baseConfig)
config.settings.provinceDefault = 'ON'
config.settings.latitudeMax = 56.85
config.settings.latitudeMin = 41.68
config.settings.longitudeMax = -74
config.settings.longitudeMin = -95.15
config.settings.fees.taxPercentageDefault = 13
export default config

View File

@ -1,29 +1,16 @@
export interface AddBurialSiteForm { export interface AddBurialSiteForm {
burialSiteNameSegment1?: string; burialSiteNameSegment1: string;
burialSiteNameSegment2?: string; burialSiteNameSegment2?: string;
burialSiteNameSegment3?: string; burialSiteNameSegment3?: string;
burialSiteNameSegment4?: string; burialSiteNameSegment4?: string;
burialSiteNameSegment5?: string; burialSiteNameSegment5?: string;
burialSiteStatusId: number | string; burialSiteTypeId: string | number;
burialSiteTypeId: number | string; burialSiteStatusId: string | number;
bodyCapacity?: number | string; cemeteryId: string | number;
crematedCapacity?: number | string; cemeterySvgId: string;
burialSiteImage?: string; burialSiteLatitude: string;
cemeteryId: number | string; burialSiteLongitude: string;
cemeterySvgId?: string;
burialSiteLatitude?: string;
burialSiteLongitude?: string;
burialSiteTypeFieldIds?: string; burialSiteTypeFieldIds?: string;
[fieldValue_burialSiteTypeFieldId: string]: unknown; [fieldValue_burialSiteTypeFieldId: string]: unknown;
} }
/** export default function addBurialSite(burialSiteForm: AddBurialSiteForm, user: User): Promise<number>;
* Creates a new burial site.
* @param burialSiteForm - The new burial site's information
* @param user - The user making the request
* @returns The new burial site's id.
* @throws If an active burial site with the same name already exists.
*/
export default function addBurialSite(burialSiteForm: AddBurialSiteForm, user: User): {
burialSiteId: number;
burialSiteName: string;
};

View File

@ -1,35 +1,12 @@
import sqlite from 'better-sqlite3';
import { buildBurialSiteName } from '../helpers/burialSites.helpers.js'; import { buildBurialSiteName } from '../helpers/burialSites.helpers.js';
import { sunriseDB } from '../helpers/database.helpers.js';
import addOrUpdateBurialSiteField from './addOrUpdateBurialSiteField.js'; import addOrUpdateBurialSiteField from './addOrUpdateBurialSiteField.js';
import getCemetery from './getCemetery.js'; import getCemetery from './getCemetery.js';
/** import { acquireConnection } from './pool.js';
* Creates a new burial site. export default async function addBurialSite(burialSiteForm, user) {
* @param burialSiteForm - The new burial site's information const database = await acquireConnection();
* @param user - The user making the request
* @returns The new burial site's id.
* @throws If an active burial site with the same name already exists.
*/
// eslint-disable-next-line complexity
export default function addBurialSite(burialSiteForm, user) {
const database = sqlite(sunriseDB);
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const cemetery = burialSiteForm.cemeteryId === '' const cemetery = burialSiteForm.cemeteryId === '' ? undefined : await getCemetery(burialSiteForm.cemeteryId, database);
? undefined
: getCemetery(burialSiteForm.cemeteryId, database);
const burialSiteName = buildBurialSiteName(cemetery?.cemeteryKey, burialSiteForm); const burialSiteName = buildBurialSiteName(cemetery?.cemeteryKey, burialSiteForm);
// Ensure no active burial sites share the same name
const existingBurialSite = database
.prepare(`select burialSiteId
from BurialSites
where burialSiteName = ?
and recordDelete_timeMillis is null`)
.pluck()
.get(burialSiteName);
if (existingBurialSite !== undefined) {
database.close();
throw new Error('An active burial site with that name already exists.');
}
const result = database const result = database
.prepare(`insert into BurialSites ( .prepare(`insert into BurialSites (
burialSiteNameSegment1, burialSiteNameSegment1,
@ -39,41 +16,27 @@ export default function addBurialSite(burialSiteForm, user) {
burialSiteNameSegment5, burialSiteNameSegment5,
burialSiteName, burialSiteName,
burialSiteTypeId, burialSiteStatusId, burialSiteTypeId, burialSiteStatusId,
bodyCapacity, crematedCapacity, cemeteryId, cemeterySvgId,
cemeteryId, cemeterySvgId, burialSiteImage,
burialSiteLatitude, burialSiteLongitude, burialSiteLatitude, burialSiteLongitude,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, values (?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?)`) ?, ?, ?, ?)`)
.run(burialSiteForm.burialSiteNameSegment1 ?? '', burialSiteForm.burialSiteNameSegment2 ?? '', burialSiteForm.burialSiteNameSegment3 ?? '', burialSiteForm.burialSiteNameSegment4 ?? '', burialSiteForm.burialSiteNameSegment5 ?? '', burialSiteName, burialSiteForm.burialSiteTypeId, burialSiteForm.burialSiteStatusId === '' .run(burialSiteForm.burialSiteNameSegment1, burialSiteForm.burialSiteNameSegment2 ?? '', burialSiteForm.burialSiteNameSegment3 ?? '', burialSiteForm.burialSiteNameSegment4 ?? '', burialSiteForm.burialSiteNameSegment5 ?? '', burialSiteName, burialSiteForm.burialSiteTypeId, burialSiteForm.burialSiteStatusId === '' ? undefined : burialSiteForm.burialSiteStatusId, burialSiteForm.cemeteryId === '' ? undefined : burialSiteForm.cemeteryId, burialSiteForm.cemeterySvgId, burialSiteForm.burialSiteLatitude === '' ? undefined : burialSiteForm.burialSiteLatitude, burialSiteForm.burialSiteLongitude === '' ? undefined : burialSiteForm.burialSiteLongitude, user.userName, rightNowMillis, user.userName, rightNowMillis);
? undefined
: burialSiteForm.burialSiteStatusId, burialSiteForm.bodyCapacity === ''
? undefined
: burialSiteForm.bodyCapacity, burialSiteForm.crematedCapacity === ''
? undefined
: burialSiteForm.crematedCapacity, burialSiteForm.cemeteryId === '' ? undefined : burialSiteForm.cemeteryId, burialSiteForm.cemeterySvgId, burialSiteForm.burialSiteImage ?? '', burialSiteForm.burialSiteLatitude === ''
? undefined
: burialSiteForm.burialSiteLatitude, burialSiteForm.burialSiteLongitude === ''
? undefined
: burialSiteForm.burialSiteLongitude, user.userName, rightNowMillis, user.userName, rightNowMillis);
const burialSiteId = result.lastInsertRowid; const burialSiteId = result.lastInsertRowid;
const burialSiteTypeFieldIds = (burialSiteForm.burialSiteTypeFieldIds ?? '').split(','); const burialSiteTypeFieldIds = (burialSiteForm.burialSiteTypeFieldIds ?? '').split(',');
for (const burialSiteTypeFieldId of burialSiteTypeFieldIds) { for (const burialSiteTypeFieldId of burialSiteTypeFieldIds) {
const fieldValue = burialSiteForm[`burialSiteFieldValue_${burialSiteTypeFieldId}`]; const fieldValue = burialSiteForm[`burialSiteFieldValue_${burialSiteTypeFieldId}`];
if ((fieldValue ?? '') !== '') { if ((fieldValue ?? '') !== '') {
addOrUpdateBurialSiteField({ await addOrUpdateBurialSiteField({
burialSiteId, burialSiteId,
burialSiteTypeFieldId, burialSiteTypeFieldId,
fieldValue: fieldValue ?? '' fieldValue: fieldValue ?? ''
}, user, database); }, user, database);
} }
} }
database.close(); database.release();
return { return burialSiteId;
burialSiteId,
burialSiteName
};
} }

View File

@ -1,78 +1,42 @@
import sqlite from 'better-sqlite3'
import { buildBurialSiteName } from '../helpers/burialSites.helpers.js' import { buildBurialSiteName } from '../helpers/burialSites.helpers.js'
import { sunriseDB } from '../helpers/database.helpers.js'
import addOrUpdateBurialSiteField from './addOrUpdateBurialSiteField.js' import addOrUpdateBurialSiteField from './addOrUpdateBurialSiteField.js'
import getCemetery from './getCemetery.js' import getCemetery from './getCemetery.js'
import { acquireConnection } from './pool.js'
export interface AddBurialSiteForm { export interface AddBurialSiteForm {
burialSiteNameSegment1?: string burialSiteNameSegment1: string
burialSiteNameSegment2?: string burialSiteNameSegment2?: string
burialSiteNameSegment3?: string burialSiteNameSegment3?: string
burialSiteNameSegment4?: string burialSiteNameSegment4?: string
burialSiteNameSegment5?: string burialSiteNameSegment5?: string
burialSiteStatusId: number | string burialSiteTypeId: string | number
burialSiteTypeId: number | string burialSiteStatusId: string | number
bodyCapacity?: number | string cemeteryId: string | number
crematedCapacity?: number | string cemeterySvgId: string
burialSiteImage?: string burialSiteLatitude: string
cemeteryId: number | string burialSiteLongitude: string
cemeterySvgId?: string
burialSiteLatitude?: string
burialSiteLongitude?: string
burialSiteTypeFieldIds?: string burialSiteTypeFieldIds?: string
[fieldValue_burialSiteTypeFieldId: string]: unknown [fieldValue_burialSiteTypeFieldId: string]: unknown
} }
/** export default async function addBurialSite(
* Creates a new burial site.
* @param burialSiteForm - The new burial site's information
* @param user - The user making the request
* @returns The new burial site's id.
* @throws If an active burial site with the same name already exists.
*/
// eslint-disable-next-line complexity
export default function addBurialSite(
burialSiteForm: AddBurialSiteForm, burialSiteForm: AddBurialSiteForm,
user: User user: User
): { burialSiteId: number; burialSiteName: string } { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
const cemetery = const cemetery = burialSiteForm.cemeteryId === '' ? undefined : await getCemetery(burialSiteForm.cemeteryId, database)
burialSiteForm.cemeteryId === ''
? undefined
: getCemetery(burialSiteForm.cemeteryId, database)
const burialSiteName = buildBurialSiteName( const burialSiteName = buildBurialSiteName(
cemetery?.cemeteryKey, cemetery?.cemeteryKey,
burialSiteForm burialSiteForm)
)
// Ensure no active burial sites share the same name
const existingBurialSite = database
.prepare(
`select burialSiteId
from BurialSites
where burialSiteName = ?
and recordDelete_timeMillis is null`
)
.pluck()
.get(burialSiteName) as number | undefined
if (existingBurialSite !== undefined) {
database.close()
throw new Error('An active burial site with that name already exists.')
}
const result = database const result = database
.prepare( .prepare(
@ -84,45 +48,28 @@ export default function addBurialSite(
burialSiteNameSegment5, burialSiteNameSegment5,
burialSiteName, burialSiteName,
burialSiteTypeId, burialSiteStatusId, burialSiteTypeId, burialSiteStatusId,
bodyCapacity, crematedCapacity, cemeteryId, cemeterySvgId,
cemeteryId, cemeterySvgId, burialSiteImage,
burialSiteLatitude, burialSiteLongitude, burialSiteLatitude, burialSiteLongitude,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, values (?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?)` ?, ?, ?, ?)`
) )
.run( .run(
burialSiteForm.burialSiteNameSegment1 ?? '', burialSiteForm.burialSiteNameSegment1,
burialSiteForm.burialSiteNameSegment2 ?? '', burialSiteForm.burialSiteNameSegment2 ?? '',
burialSiteForm.burialSiteNameSegment3 ?? '', burialSiteForm.burialSiteNameSegment3 ?? '',
burialSiteForm.burialSiteNameSegment4 ?? '', burialSiteForm.burialSiteNameSegment4 ?? '',
burialSiteForm.burialSiteNameSegment5 ?? '', burialSiteForm.burialSiteNameSegment5 ?? '',
burialSiteName, burialSiteName,
burialSiteForm.burialSiteTypeId, burialSiteForm.burialSiteTypeId,
burialSiteForm.burialSiteStatusId === '' burialSiteForm.burialSiteStatusId === '' ? undefined : burialSiteForm.burialSiteStatusId,
? undefined
: burialSiteForm.burialSiteStatusId,
burialSiteForm.bodyCapacity === ''
? undefined
: burialSiteForm.bodyCapacity,
burialSiteForm.crematedCapacity === ''
? undefined
: burialSiteForm.crematedCapacity,
burialSiteForm.cemeteryId === '' ? undefined : burialSiteForm.cemeteryId, burialSiteForm.cemeteryId === '' ? undefined : burialSiteForm.cemeteryId,
burialSiteForm.cemeterySvgId, burialSiteForm.cemeterySvgId,
burialSiteForm.burialSiteImage ?? '', burialSiteForm.burialSiteLatitude === '' ? undefined : burialSiteForm.burialSiteLatitude,
burialSiteForm.burialSiteLatitude === '' burialSiteForm.burialSiteLongitude === '' ? undefined : burialSiteForm.burialSiteLongitude,
? undefined
: burialSiteForm.burialSiteLatitude,
burialSiteForm.burialSiteLongitude === ''
? undefined
: burialSiteForm.burialSiteLongitude,
user.userName, user.userName,
rightNowMillis, rightNowMillis,
user.userName, user.userName,
@ -131,17 +78,13 @@ export default function addBurialSite(
const burialSiteId = result.lastInsertRowid as number const burialSiteId = result.lastInsertRowid as number
const burialSiteTypeFieldIds = ( const burialSiteTypeFieldIds = (burialSiteForm.burialSiteTypeFieldIds ?? '').split(',')
burialSiteForm.burialSiteTypeFieldIds ?? ''
).split(',')
for (const burialSiteTypeFieldId of burialSiteTypeFieldIds) { for (const burialSiteTypeFieldId of burialSiteTypeFieldIds) {
const fieldValue = burialSiteForm[ const fieldValue = burialSiteForm[`burialSiteFieldValue_${burialSiteTypeFieldId}`] as string | undefined
`burialSiteFieldValue_${burialSiteTypeFieldId}`
] as string | undefined
if ((fieldValue ?? '') !== '') { if ((fieldValue ?? '') !== '') {
addOrUpdateBurialSiteField( await addOrUpdateBurialSiteField(
{ {
burialSiteId, burialSiteId,
burialSiteTypeFieldId, burialSiteTypeFieldId,
@ -153,10 +96,7 @@ export default function addBurialSite(
} }
} }
database.close() database.release()
return { return burialSiteId
burialSiteId,
burialSiteName
}
} }

View File

@ -2,4 +2,4 @@ export interface AddBurialSiteCommentForm {
burialSiteId: string; burialSiteId: string;
comment: string; comment: string;
} }
export default function addBurialSiteComment(commentForm: AddBurialSiteCommentForm, user: User): number; export default function addBurialSiteComment(commentForm: AddBurialSiteCommentForm, user: User): Promise<number>;

View File

@ -1,8 +1,7 @@
import { dateToInteger, dateToTimeInteger } from '@cityssm/utils-datetime'; import { dateToInteger, dateToTimeInteger } from '@cityssm/utils-datetime';
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addBurialSiteComment(commentForm, user) {
export default function addBurialSiteComment(commentForm, user) { const database = await acquireConnection();
const database = sqlite(sunriseDB);
const rightNow = new Date(); const rightNow = new Date();
const result = database const result = database
.prepare(`insert into BurialSiteComments ( .prepare(`insert into BurialSiteComments (
@ -12,6 +11,6 @@ export default function addBurialSiteComment(commentForm, user) {
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?)`)
.run(commentForm.burialSiteId, dateToInteger(rightNow), dateToTimeInteger(rightNow), commentForm.comment, user.userName, rightNow.getTime(), user.userName, rightNow.getTime()); .run(commentForm.burialSiteId, dateToInteger(rightNow), dateToTimeInteger(rightNow), commentForm.comment, user.userName, rightNow.getTime(), user.userName, rightNow.getTime());
database.close(); database.release();
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,18 +1,17 @@
import { dateToInteger, dateToTimeInteger } from '@cityssm/utils-datetime' import { dateToInteger, dateToTimeInteger } from '@cityssm/utils-datetime'
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js' import { acquireConnection } from './pool.js'
export interface AddBurialSiteCommentForm { export interface AddBurialSiteCommentForm {
burialSiteId: string burialSiteId: string
comment: string comment: string
} }
export default function addBurialSiteComment( export default async function addBurialSiteComment(
commentForm: AddBurialSiteCommentForm, commentForm: AddBurialSiteCommentForm,
user: User user: User
): number { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNow = new Date() const rightNow = new Date()
@ -36,7 +35,7 @@ export default function addBurialSiteComment(
rightNow.getTime() rightNow.getTime()
) )
database.close() database.release()
return result.lastInsertRowid as number return result.lastInsertRowid as number
} }

View File

@ -1,7 +0,0 @@
export interface AddBurialSiteTypeForm {
burialSiteType: string;
bodyCapacityMax: number | string;
crematedCapacityMax: number | string;
orderNumber?: number | string;
}
export default function addBurialSiteType(addForm: AddBurialSiteTypeForm, user: User): number;

View File

@ -1,20 +0,0 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { clearCacheByTableName } from '../helpers/functions.cache.js';
export default function addBurialSiteType(addForm, user) {
const database = sqlite(sunriseDB);
const rightNowMillis = Date.now();
const result = database
.prepare(`insert into BurialSiteTypes (
burialSiteType, bodyCapacityMax, crematedCapacityMax,
orderNumber,
recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.burialSiteType, addForm.bodyCapacityMax === '' ? undefined : addForm.bodyCapacityMax, addForm.crematedCapacityMax === ''
? undefined
: addForm.crematedCapacityMax, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
database.close();
clearCacheByTableName('BurialSiteTypes');
return result.lastInsertRowid;
}

View File

@ -1,50 +0,0 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import { clearCacheByTableName } from '../helpers/functions.cache.js'
export interface AddBurialSiteTypeForm {
burialSiteType: string
bodyCapacityMax: number | string
crematedCapacityMax: number | string
orderNumber?: number | string
}
export default function addBurialSiteType(
addForm: AddBurialSiteTypeForm,
user: User
): number {
const database = sqlite(sunriseDB)
const rightNowMillis = Date.now()
const result = database
.prepare(
`insert into BurialSiteTypes (
burialSiteType, bodyCapacityMax, crematedCapacityMax,
orderNumber,
recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?)`
)
.run(
addForm.burialSiteType,
addForm.bodyCapacityMax === '' ? undefined : addForm.bodyCapacityMax,
addForm.crematedCapacityMax === ''
? undefined
: addForm.crematedCapacityMax,
addForm.orderNumber ?? -1,
user.userName,
rightNowMillis,
user.userName,
rightNowMillis
)
database.close()
clearCacheByTableName('BurialSiteTypes')
return result.lastInsertRowid as number
}

View File

@ -1,12 +1,12 @@
export interface AddBurialSiteTypeFieldForm { export interface AddBurialSiteTypeFieldForm {
burialSiteTypeId: number | string; burialSiteTypeId: string | number;
burialSiteTypeField: string; burialSiteTypeField: string;
fieldType?: string; fieldType?: string;
fieldValues?: string; fieldValues?: string;
isRequired?: string; isRequired?: string;
maxLength?: number | string;
minLength?: number | string;
pattern?: string; pattern?: string;
minLength?: string | number;
maxLength?: string | number;
orderNumber?: number; orderNumber?: number;
} }
export default function addBurialSiteTypeField(addForm: AddBurialSiteTypeFieldForm, user: User): number; export default function addBurialSiteTypeField(addForm: AddBurialSiteTypeFieldForm, user: User): Promise<number>;

View File

@ -1,8 +1,7 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { clearCacheByTableName } from '../helpers/functions.cache.js'; import { clearCacheByTableName } from '../helpers/functions.cache.js';
export default function addBurialSiteTypeField(addForm, user) { import { acquireConnection } from './pool.js';
const database = sqlite(sunriseDB); export default async function addBurialSiteTypeField(addForm, user) {
const database = await acquireConnection();
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into BurialSiteTypeFields ( .prepare(`insert into BurialSiteTypeFields (
@ -14,10 +13,8 @@ export default function addBurialSiteTypeField(addForm, user) {
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.burialSiteTypeId, addForm.burialSiteTypeField, addForm.fieldType ?? 'text', addForm.fieldValues ?? '', addForm.isRequired === '' ? 0 : 1, addForm.pattern ?? '', addForm.minLength ?? 0, .run(addForm.burialSiteTypeId, addForm.burialSiteTypeField, addForm.fieldType ?? 'text', addForm.fieldValues ?? '', addForm.isRequired === '' ? 0 : 1, addForm.pattern ?? '', addForm.minLength ?? 0, addForm.maxLength ?? 100, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers database.release();
addForm.maxLength ?? 100, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
database.close();
clearCacheByTableName('BurialSiteTypeFields'); clearCacheByTableName('BurialSiteTypeFields');
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,29 +1,24 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import { clearCacheByTableName } from '../helpers/functions.cache.js' import { clearCacheByTableName } from '../helpers/functions.cache.js'
import { acquireConnection } from './pool.js'
export interface AddBurialSiteTypeFieldForm { export interface AddBurialSiteTypeFieldForm {
burialSiteTypeId: number | string burialSiteTypeId: string | number
burialSiteTypeField: string burialSiteTypeField: string
fieldType?: string fieldType?: string
fieldValues?: string fieldValues?: string
isRequired?: string isRequired?: string
maxLength?: number | string
minLength?: number | string
pattern?: string pattern?: string
minLength?: string | number
maxLength?: string | number
orderNumber?: number orderNumber?: number
} }
export default function addBurialSiteTypeField( export default async function addBurialSiteTypeField(
addForm: AddBurialSiteTypeFieldForm, addForm: AddBurialSiteTypeFieldForm,
user: User user: User
): number { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -47,7 +42,6 @@ export default function addBurialSiteTypeField(
addForm.isRequired === '' ? 0 : 1, addForm.isRequired === '' ? 0 : 1,
addForm.pattern ?? '', addForm.pattern ?? '',
addForm.minLength ?? 0, addForm.minLength ?? 0,
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
addForm.maxLength ?? 100, addForm.maxLength ?? 100,
addForm.orderNumber ?? -1, addForm.orderNumber ?? -1,
user.userName, user.userName,
@ -56,7 +50,7 @@ export default function addBurialSiteTypeField(
rightNowMillis rightNowMillis
) )
database.close() database.release()
clearCacheByTableName('BurialSiteTypeFields') clearCacheByTableName('BurialSiteTypeFields')

View File

@ -1,17 +1,15 @@
import { type UpdateCemeteryDirectionsOfArrivalForm } from './updateCemeteryDirectionsOfArrival.js'; export interface AddCemeteryForm {
export type AddCemeteryForm = UpdateCemeteryDirectionsOfArrivalForm & {
cemeteryDescription: string;
cemeteryKey: string;
cemeteryName: string; cemeteryName: string;
parentCemeteryId: string; cemeteryKey: string;
cemeteryDescription: string;
cemeterySvg: string;
cemeteryLatitude: string; cemeteryLatitude: string;
cemeteryLongitude: string; cemeteryLongitude: string;
cemeterySvg: string;
cemeteryAddress1: string; cemeteryAddress1: string;
cemeteryAddress2: string; cemeteryAddress2: string;
cemeteryCity: string; cemeteryCity: string;
cemeteryPostalCode: string;
cemeteryProvince: string; cemeteryProvince: string;
cemeteryPostalCode: string;
cemeteryPhoneNumber: string; cemeteryPhoneNumber: string;
}; }
export default function addCemetery(addForm: AddCemeteryForm, user: User): number; export default function addCemetery(addForm: AddCemeteryForm, user: User): Promise<number>;

View File

@ -1,8 +1,6 @@
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addCemetery(addForm, user) {
import updateCemeteryDirectionsOfArrival from './updateCemeteryDirectionsOfArrival.js'; const database = await acquireConnection();
export default function addCemetery(addForm, user) {
const database = sqlite(sunriseDB);
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into Cemeteries ( .prepare(`insert into Cemeteries (
@ -11,13 +9,10 @@ export default function addCemetery(addForm, user) {
cemeteryAddress1, cemeteryAddress2, cemeteryAddress1, cemeteryAddress2,
cemeteryCity, cemeteryProvince, cemeteryPostalCode, cemeteryCity, cemeteryProvince, cemeteryPostalCode,
cemeteryPhoneNumber, cemeteryPhoneNumber,
parentCemeteryId,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.cemeteryName, addForm.cemeteryKey, addForm.cemeteryDescription, addForm.cemeterySvg, addForm.cemeteryLatitude === '' ? undefined : addForm.cemeteryLatitude, addForm.cemeteryLongitude === '' ? undefined : addForm.cemeteryLongitude, addForm.cemeteryAddress1, addForm.cemeteryAddress2, addForm.cemeteryCity, addForm.cemeteryProvince, addForm.cemeteryPostalCode, addForm.cemeteryPhoneNumber, addForm.parentCemeteryId === '' ? undefined : addForm.parentCemeteryId, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(addForm.cemeteryName, addForm.cemeteryKey, addForm.cemeteryDescription, addForm.cemeterySvg, addForm.cemeteryLatitude === '' ? undefined : addForm.cemeteryLatitude, addForm.cemeteryLongitude === '' ? undefined : addForm.cemeteryLongitude, addForm.cemeteryAddress1, addForm.cemeteryAddress2, addForm.cemeteryCity, addForm.cemeteryProvince, addForm.cemeteryPostalCode, addForm.cemeteryPhoneNumber, user.userName, rightNowMillis, user.userName, rightNowMillis);
const cemeteryId = result.lastInsertRowid; database.release();
updateCemeteryDirectionsOfArrival(cemeteryId, addForm, database); return result.lastInsertRowid;
database.close();
return cemeteryId;
} }

View File

@ -1,35 +1,27 @@
import sqlite from 'better-sqlite3' import { acquireConnection } from './pool.js'
import { sunriseDB } from '../helpers/database.helpers.js' export interface AddCemeteryForm {
import updateCemeteryDirectionsOfArrival, {
type UpdateCemeteryDirectionsOfArrivalForm
} from './updateCemeteryDirectionsOfArrival.js'
export type AddCemeteryForm = UpdateCemeteryDirectionsOfArrivalForm & {
cemeteryDescription: string
cemeteryKey: string
cemeteryName: string cemeteryName: string
parentCemeteryId: string cemeteryKey: string
cemeteryDescription: string
cemeterySvg: string
cemeteryLatitude: string cemeteryLatitude: string
cemeteryLongitude: string cemeteryLongitude: string
cemeterySvg: string
cemeteryAddress1: string cemeteryAddress1: string
cemeteryAddress2: string cemeteryAddress2: string
cemeteryCity: string cemeteryCity: string
cemeteryPostalCode: string
cemeteryProvince: string cemeteryProvince: string
cemeteryPostalCode: string
cemeteryPhoneNumber: string cemeteryPhoneNumber: string
} }
export default function addCemetery( export default async function addCemetery(
addForm: AddCemeteryForm, addForm: AddCemeteryForm,
user: User user: User
): number { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -41,10 +33,9 @@ export default function addCemetery(
cemeteryAddress1, cemeteryAddress2, cemeteryAddress1, cemeteryAddress2,
cemeteryCity, cemeteryProvince, cemeteryPostalCode, cemeteryCity, cemeteryProvince, cemeteryPostalCode,
cemeteryPhoneNumber, cemeteryPhoneNumber,
parentCemeteryId,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
) )
.run( .run(
addForm.cemeteryName, addForm.cemeteryName,
@ -59,18 +50,13 @@ export default function addCemetery(
addForm.cemeteryProvince, addForm.cemeteryProvince,
addForm.cemeteryPostalCode, addForm.cemeteryPostalCode,
addForm.cemeteryPhoneNumber, addForm.cemeteryPhoneNumber,
addForm.parentCemeteryId === '' ? undefined : addForm.parentCemeteryId,
user.userName, user.userName,
rightNowMillis, rightNowMillis,
user.userName, user.userName,
rightNowMillis rightNowMillis
) )
const cemeteryId = result.lastInsertRowid as number database.release()
updateCemeteryDirectionsOfArrival(cemeteryId, addForm, database) return result.lastInsertRowid as number
database.close()
return cemeteryId
} }

View File

@ -1,6 +0,0 @@
export interface AddForm {
committalType: string;
committalTypeKey?: string;
orderNumber?: number | string;
}
export default function addCommittalType(addForm: AddForm, user: User): number;

View File

@ -1,17 +0,0 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { clearCacheByTableName } from '../helpers/functions.cache.js';
export default function addCommittalType(addForm, user) {
const database = sqlite(sunriseDB);
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.close();
clearCacheByTableName('CommittalTypes');
return result.lastInsertRowid;
}

View File

@ -1,40 +0,0 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import { clearCacheByTableName } from '../helpers/functions.cache.js'
export interface AddForm {
committalType: string
committalTypeKey?: string
orderNumber?: number | string
}
export default function addCommittalType(addForm: AddForm, user: User): number {
const database = sqlite(sunriseDB)
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.close()
clearCacheByTableName('CommittalTypes')
return result.lastInsertRowid as number
}

View File

@ -1,39 +1,36 @@
import { type DateString, type TimeString } from '@cityssm/utils-datetime'; import { type DateString, type TimeString } from '@cityssm/utils-datetime';
import sqlite from 'better-sqlite3'; import type { PoolConnection } from 'better-sqlite-pool';
export interface AddContractForm { export interface AddContractForm {
burialSiteId: number | string; contractTypeId: string | number;
contractEndDateString: '' | DateString; burialSiteId: string | number;
contractStartDateString: '' | DateString; contractStartDateString: DateString | '';
contractTypeId: number | string; contractEndDateString: DateString | '';
[fieldValue_contractTypeFieldId: `fieldValue_${string}`]: unknown;
contractTypeFieldIds?: string; contractTypeFieldIds?: string;
committalTypeId?: number | string; [fieldValue_contractTypeFieldId: `fieldValue_${string}`]: unknown;
directionOfArrival?: string; purchaserName?: string;
funeralDateString?: '' | DateString;
funeralDirectorName?: string;
funeralHomeId?: number | string;
funeralTimeString?: '' | TimeString;
purchaserAddress1?: string; purchaserAddress1?: string;
purchaserAddress2?: string; purchaserAddress2?: string;
purchaserCity?: string; purchaserCity?: string;
purchaserEmail?: string;
purchaserName?: string;
purchaserPhoneNumber?: string;
purchaserPostalCode?: string;
purchaserProvince?: string; purchaserProvince?: string;
purchaserPostalCode?: string;
purchaserPhoneNumber?: string;
purchaserEmail?: string;
purchaserRelationship?: string; purchaserRelationship?: string;
birthDateString?: '' | DateString; funeralHomeId?: string | number;
birthPlace?: string; funeralDirectorName?: string;
deathAge?: string; funeralDateString?: DateString | '';
deathAgePeriod?: string; funeralTimeString?: TimeString | '';
deathDateString?: '' | DateString; committalTypeId?: string | number;
deathPlace?: string; deceasedName?: string;
deceasedAddress1?: string; deceasedAddress1?: string;
deceasedAddress2?: string; deceasedAddress2?: string;
deceasedCity?: string; deceasedCity?: string;
deceasedName?: string;
deceasedPostalCode?: string;
deceasedProvince?: string; deceasedProvince?: string;
intermentContainerTypeId?: number | string; deceasedPostalCode?: string;
birthDateString?: DateString | '';
birthPlace?: string;
deathDateString?: DateString | '';
deathPlace?: string;
intermentContainerTypeId?: string | number;
} }
export default function addContract(addForm: AddContractForm, user: User, connectedDatabase?: sqlite.Database): number; export default function addContract(addForm: AddContractForm, user: User, connectedDatabase?: PoolConnection): Promise<number>;

View File

@ -1,10 +1,9 @@
import { dateStringToInteger, timeStringToInteger } from '@cityssm/utils-datetime'; import { dateStringToInteger, timeStringToInteger } from '@cityssm/utils-datetime';
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import addOrUpdateContractField from './addOrUpdateContractField.js'; import addOrUpdateContractField from './addOrUpdateContractField.js';
import { acquireConnection } from './pool.js';
// eslint-disable-next-line complexity // eslint-disable-next-line complexity
export default function addContract(addForm, user, connectedDatabase) { export default async function addContract(addForm, user, connectedDatabase) {
const database = connectedDatabase ?? sqlite(sunriseDB); const database = connectedDatabase ?? (await acquireConnection());
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const contractStartDate = dateStringToInteger(addForm.contractStartDateString); const contractStartDate = dateStringToInteger(addForm.contractStartDateString);
const result = database const result = database
@ -16,17 +15,17 @@ export default function addContract(addForm, user, connectedDatabase) {
purchaserPhoneNumber, purchaserEmail, purchaserRelationship, purchaserPhoneNumber, purchaserEmail, purchaserRelationship,
funeralHomeId, funeralDirectorName, funeralHomeId, funeralDirectorName,
funeralDate, funeralTime, funeralDate, funeralTime,
directionOfArrival, committalTypeId, committalTypeId,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.contractTypeId, addForm.burialSiteId === '' ? undefined : addForm.burialSiteId, contractStartDate, addForm.contractEndDateString === '' .run(addForm.contractTypeId, addForm.burialSiteId === '' ? undefined : addForm.burialSiteId, contractStartDate, addForm.contractEndDateString === ''
? undefined ? undefined
: dateStringToInteger(addForm.contractEndDateString), addForm.purchaserName ?? '', addForm.purchaserAddress1 ?? '', addForm.purchaserAddress2 ?? '', addForm.purchaserCity ?? '', addForm.purchaserProvince ?? '', addForm.purchaserPostalCode ?? '', addForm.purchaserPhoneNumber ?? '', addForm.purchaserEmail ?? '', addForm.purchaserRelationship ?? '', addForm.funeralHomeId === '' ? undefined : addForm.funeralHomeId, addForm.funeralDirectorName ?? '', addForm.funeralDateString === '' : dateStringToInteger(addForm.contractEndDateString), addForm.purchaserName ?? '', addForm.purchaserAddress1 ?? '', addForm.purchaserAddress2 ?? '', addForm.purchaserCity ?? '', addForm.purchaserProvince ?? '', addForm.purchaserPostalCode ?? '', addForm.purchaserPhoneNumber ?? '', addForm.purchaserEmail ?? '', addForm.purchaserRelationship ?? '', addForm.funeralHomeId === '' ? undefined : addForm.funeralHomeId, addForm.funeralDirectorName ?? '', addForm.funeralDateString === ''
? undefined ? undefined
: dateStringToInteger(addForm.funeralDateString), addForm.funeralTimeString === '' : dateStringToInteger(addForm.funeralDateString), addForm.funeralTimeString === ''
? undefined ? undefined
: timeStringToInteger(addForm.funeralTimeString), addForm.directionOfArrival ?? '', addForm.committalTypeId === '' ? undefined : addForm.committalTypeId, user.userName, rightNowMillis, user.userName, rightNowMillis); : timeStringToInteger(addForm.funeralTimeString), addForm.committalTypeId === '' ? undefined : addForm.committalTypeId, user.userName, rightNowMillis, user.userName, rightNowMillis);
const contractId = result.lastInsertRowid; const contractId = result.lastInsertRowid;
/* /*
* Add contract fields * Add contract fields
@ -35,7 +34,7 @@ export default function addContract(addForm, user, connectedDatabase) {
for (const contractTypeFieldId of contractTypeFieldIds) { for (const contractTypeFieldId of contractTypeFieldIds) {
const fieldValue = addForm[`fieldValue_${contractTypeFieldId}`]; const fieldValue = addForm[`fieldValue_${contractTypeFieldId}`];
if ((fieldValue ?? '') !== '') { if ((fieldValue ?? '') !== '') {
addOrUpdateContractField({ await addOrUpdateContractField({
contractId, contractId,
contractTypeFieldId, contractTypeFieldId,
fieldValue: fieldValue ?? '' fieldValue: fieldValue ?? ''
@ -53,21 +52,20 @@ export default function addContract(addForm, user, connectedDatabase) {
deceasedCity, deceasedProvince, deceasedPostalCode, deceasedCity, deceasedProvince, deceasedPostalCode,
birthDate, deathDate, birthDate, deathDate,
birthPlace, deathPlace, birthPlace, deathPlace,
deathAge, deathAgePeriod,
intermentContainerTypeId, intermentContainerTypeId,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.run(contractId, 1, addForm.deceasedName ?? '', addForm.deceasedAddress1 ?? '', addForm.deceasedAddress2 ?? '', addForm.deceasedCity ?? '', addForm.deceasedProvince ?? '', addForm.deceasedPostalCode ?? '', addForm.birthDateString === '' .run(contractId, 1, addForm.deceasedName ?? '', addForm.deceasedAddress1 ?? '', addForm.deceasedAddress2 ?? '', addForm.deceasedCity ?? '', addForm.deceasedProvince ?? '', addForm.deceasedPostalCode ?? '', addForm.birthDateString === ''
? undefined ? undefined
: dateStringToInteger(addForm.birthDateString), addForm.deathDateString === '' : dateStringToInteger(addForm.birthDateString), addForm.deathDateString === ''
? undefined ? undefined
: dateStringToInteger(addForm.deathDateString), addForm.birthPlace ?? '', addForm.deathPlace ?? '', addForm.deathAge ?? undefined, addForm.deathAgePeriod ?? '', addForm.intermentContainerTypeId === '' : dateStringToInteger(addForm.deathDateString), addForm.birthPlace ?? '', addForm.deathPlace ?? '', addForm.intermentContainerTypeId === ''
? undefined ? undefined
: addForm.intermentContainerTypeId, user.userName, rightNowMillis, user.userName, rightNowMillis); : addForm.intermentContainerTypeId, user.userName, rightNowMillis, user.userName, rightNowMillis);
} }
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close(); database.release();
} }
return contractId; return contractId;
} }

View File

@ -4,60 +4,58 @@ import {
dateStringToInteger, dateStringToInteger,
timeStringToInteger timeStringToInteger
} from '@cityssm/utils-datetime' } from '@cityssm/utils-datetime'
import sqlite from 'better-sqlite3' import type { PoolConnection } from 'better-sqlite-pool'
import { sunriseDB } from '../helpers/database.helpers.js'
import addOrUpdateContractField from './addOrUpdateContractField.js' import addOrUpdateContractField from './addOrUpdateContractField.js'
import { acquireConnection } from './pool.js'
export interface AddContractForm { export interface AddContractForm {
burialSiteId: number | string contractTypeId: string | number
contractEndDateString: '' | DateString burialSiteId: string | number
contractStartDateString: '' | DateString
contractTypeId: number | string contractStartDateString: DateString | ''
contractEndDateString: DateString | ''
[fieldValue_contractTypeFieldId: `fieldValue_${string}`]: unknown
contractTypeFieldIds?: string contractTypeFieldIds?: string
[fieldValue_contractTypeFieldId: `fieldValue_${string}`]: unknown
committalTypeId?: number | string purchaserName?: string
directionOfArrival?: string
funeralDateString?: '' | DateString
funeralDirectorName?: string
funeralHomeId?: number | string
funeralTimeString?: '' | TimeString
purchaserAddress1?: string purchaserAddress1?: string
purchaserAddress2?: string purchaserAddress2?: string
purchaserCity?: string purchaserCity?: string
purchaserEmail?: string
purchaserName?: string
purchaserPhoneNumber?: string
purchaserPostalCode?: string
purchaserProvince?: string purchaserProvince?: string
purchaserPostalCode?: string
purchaserPhoneNumber?: string
purchaserEmail?: string
purchaserRelationship?: string purchaserRelationship?: string
birthDateString?: '' | DateString funeralHomeId?: string | number
birthPlace?: string funeralDirectorName?: string
deathAge?: string funeralDateString?: DateString | ''
deathAgePeriod?: string funeralTimeString?: TimeString | ''
deathDateString?: '' | DateString committalTypeId?: string | number
deathPlace?: string
deceasedName?: string
deceasedAddress1?: string deceasedAddress1?: string
deceasedAddress2?: string deceasedAddress2?: string
deceasedCity?: string deceasedCity?: string
deceasedName?: string
deceasedPostalCode?: string
deceasedProvince?: string deceasedProvince?: string
intermentContainerTypeId?: number | string deceasedPostalCode?: string
birthDateString?: DateString | ''
birthPlace?: string
deathDateString?: DateString | ''
deathPlace?: string
intermentContainerTypeId?: string | number
} }
// eslint-disable-next-line complexity // eslint-disable-next-line complexity
export default function addContract( export default async function addContract(
addForm: AddContractForm, addForm: AddContractForm,
user: User, user: User,
connectedDatabase?: sqlite.Database connectedDatabase?: PoolConnection
): number { ): Promise<number> {
const database = connectedDatabase ?? sqlite(sunriseDB) const database = connectedDatabase ?? (await acquireConnection())
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -75,10 +73,10 @@ export default function addContract(
purchaserPhoneNumber, purchaserEmail, purchaserRelationship, purchaserPhoneNumber, purchaserEmail, purchaserRelationship,
funeralHomeId, funeralDirectorName, funeralHomeId, funeralDirectorName,
funeralDate, funeralTime, funeralDate, funeralTime,
directionOfArrival, committalTypeId, committalTypeId,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
) )
.run( .run(
addForm.contractTypeId, addForm.contractTypeId,
@ -104,7 +102,6 @@ export default function addContract(
addForm.funeralTimeString === '' addForm.funeralTimeString === ''
? undefined ? undefined
: timeStringToInteger(addForm.funeralTimeString as TimeString), : timeStringToInteger(addForm.funeralTimeString as TimeString),
addForm.directionOfArrival ?? '',
addForm.committalTypeId === '' ? undefined : addForm.committalTypeId, addForm.committalTypeId === '' ? undefined : addForm.committalTypeId,
user.userName, user.userName,
rightNowMillis, rightNowMillis,
@ -126,7 +123,7 @@ export default function addContract(
| undefined | undefined
if ((fieldValue ?? '') !== '') { if ((fieldValue ?? '') !== '') {
addOrUpdateContractField( await addOrUpdateContractField(
{ {
contractId, contractId,
contractTypeFieldId, contractTypeFieldId,
@ -151,11 +148,10 @@ export default function addContract(
deceasedCity, deceasedProvince, deceasedPostalCode, deceasedCity, deceasedProvince, deceasedPostalCode,
birthDate, deathDate, birthDate, deathDate,
birthPlace, deathPlace, birthPlace, deathPlace,
deathAge, deathAgePeriod,
intermentContainerTypeId, intermentContainerTypeId,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
) )
.run( .run(
@ -175,8 +171,6 @@ export default function addContract(
: dateStringToInteger(addForm.deathDateString as DateString), : dateStringToInteger(addForm.deathDateString as DateString),
addForm.birthPlace ?? '', addForm.birthPlace ?? '',
addForm.deathPlace ?? '', addForm.deathPlace ?? '',
addForm.deathAge ?? undefined,
addForm.deathAgePeriod ?? '',
addForm.intermentContainerTypeId === '' addForm.intermentContainerTypeId === ''
? undefined ? undefined
: addForm.intermentContainerTypeId, : addForm.intermentContainerTypeId,
@ -188,7 +182,7 @@ export default function addContract(
} }
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close() database.release()
} }
return contractId return contractId

View File

@ -1,8 +1,8 @@
import { type DateString, type TimeString } from '@cityssm/utils-datetime'; import { type DateString, type TimeString } from '@cityssm/utils-datetime';
export interface AddContractCommentForm { export interface AddContractCommentForm {
contractId: number | string; contractId: string | number;
comment: string;
commentDateString?: DateString; commentDateString?: DateString;
commentTimeString?: TimeString; commentTimeString?: TimeString;
comment: string;
} }
export default function addContractComment(commentForm: AddContractCommentForm, user: User): number; export default function addContractComment(commentForm: AddContractCommentForm, user: User): Promise<number>;

View File

@ -1,7 +1,6 @@
import { dateStringToInteger, dateToInteger, dateToTimeInteger, timeStringToInteger } from '@cityssm/utils-datetime'; import { dateStringToInteger, dateToInteger, dateToTimeInteger, timeStringToInteger } from '@cityssm/utils-datetime';
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addContractComment(commentForm, user) {
export default function addContractComment(commentForm, user) {
const rightNow = new Date(); const rightNow = new Date();
let commentDate = 0; let commentDate = 0;
let commentTime = 0; let commentTime = 0;
@ -13,7 +12,7 @@ export default function addContractComment(commentForm, user) {
commentDate = dateStringToInteger(commentForm.commentDateString); commentDate = dateStringToInteger(commentForm.commentDateString);
commentTime = timeStringToInteger(commentForm.commentTimeString); commentTime = timeStringToInteger(commentForm.commentTimeString);
} }
const database = sqlite(sunriseDB); const database = await acquireConnection();
const result = database const result = database
.prepare(`insert into ContractComments ( .prepare(`insert into ContractComments (
contractId, contractId,
@ -23,6 +22,6 @@ export default function addContractComment(commentForm, user) {
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?)`)
.run(commentForm.contractId, commentDate, commentTime ?? 0, commentForm.comment, user.userName, rightNow.getTime(), user.userName, rightNow.getTime()); .run(commentForm.contractId, commentDate, commentTime ?? 0, commentForm.comment, user.userName, rightNow.getTime(), user.userName, rightNow.getTime());
database.close(); database.release();
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -6,22 +6,20 @@ import {
dateToTimeInteger, dateToTimeInteger,
timeStringToInteger timeStringToInteger
} from '@cityssm/utils-datetime' } from '@cityssm/utils-datetime'
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js' import { acquireConnection } from './pool.js'
export interface AddContractCommentForm { export interface AddContractCommentForm {
contractId: number | string contractId: string | number
comment: string
commentDateString?: DateString commentDateString?: DateString
commentTimeString?: TimeString commentTimeString?: TimeString
comment: string
} }
export default function addContractComment( export default async function addContractComment(
commentForm: AddContractCommentForm, commentForm: AddContractCommentForm,
user: User user: User
): number { ): Promise<number> {
const rightNow = new Date() const rightNow = new Date()
let commentDate = 0 let commentDate = 0
@ -39,7 +37,7 @@ export default function addContractComment(
) )
} }
const database = sqlite(sunriseDB) const database = await acquireConnection()
const result = database const result = database
.prepare( .prepare(
@ -62,7 +60,7 @@ export default function addContractComment(
rightNow.getTime() rightNow.getTime()
) )
database.close() database.release()
return result.lastInsertRowid as number return result.lastInsertRowid as number
} }

View File

@ -1,9 +1,9 @@
import sqlite from 'better-sqlite3'; import type { PoolConnection } from 'better-sqlite-pool';
export interface AddContractFeeForm { export interface AddContractFeeForm {
contractId: number | string; contractId: number | string;
feeId: number | string; feeId: number | string;
feeAmount?: number | string;
quantity: number | string; quantity: number | string;
feeAmount?: number | string;
taxAmount?: number | string; taxAmount?: number | string;
} }
export default function addContractFee(addFeeForm: AddContractFeeForm, user: User, connectedDatabase?: sqlite.Database): Promise<boolean>; export default function addContractFee(addFeeForm: AddContractFeeForm, user: User, connectedDatabase?: PoolConnection): Promise<boolean>;

View File

@ -1,17 +1,16 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { calculateFeeAmount, calculateTaxAmount } from '../helpers/functions.fee.js'; import { calculateFeeAmount, calculateTaxAmount } from '../helpers/functions.fee.js';
import getContract from './getContract.js'; import getContract from './getContract.js';
import getFee from './getFee.js'; import getFee from './getFee.js';
import { acquireConnection } from './pool.js';
export default async function addContractFee(addFeeForm, user, connectedDatabase) { export default async function addContractFee(addFeeForm, user, connectedDatabase) {
const database = connectedDatabase ?? sqlite(sunriseDB); const database = connectedDatabase ?? (await acquireConnection());
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
// Calculate fee and tax (if not set) // Calculate fee and tax (if not set)
let feeAmount; let feeAmount;
let taxAmount; let taxAmount;
if ((addFeeForm.feeAmount ?? '') === '') { if ((addFeeForm.feeAmount ?? '') === '') {
const contract = (await getContract(addFeeForm.contractId)); const contract = (await getContract(addFeeForm.contractId));
const fee = getFee(addFeeForm.feeId); const fee = (await getFee(addFeeForm.feeId));
feeAmount = calculateFeeAmount(fee, contract); feeAmount = calculateFeeAmount(fee, contract);
taxAmount = calculateTaxAmount(fee, feeAmount); taxAmount = calculateTaxAmount(fee, feeAmount);
} }
@ -84,7 +83,7 @@ export default async function addContractFee(addFeeForm, user, connectedDatabase
} }
finally { finally {
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close(); database.release();
} }
} }
} }

View File

@ -1,30 +1,29 @@
import sqlite from 'better-sqlite3' import type { PoolConnection } from 'better-sqlite-pool'
import { sunriseDB } from '../helpers/database.helpers.js'
import { import {
calculateFeeAmount, calculateFeeAmount,
calculateTaxAmount calculateTaxAmount
} from '../helpers/functions.fee.js' } from '../helpers/functions.fee.js'
import type { Contract, Fee } from '../types/record.types.js' import type { Contract, Fee } from '../types/recordTypes.js'
import getContract from './getContract.js' import getContract from './getContract.js'
import getFee from './getFee.js' import getFee from './getFee.js'
import { acquireConnection } from './pool.js'
export interface AddContractFeeForm { export interface AddContractFeeForm {
contractId: number | string contractId: number | string
feeId: number | string feeId: number | string
feeAmount?: number | string
quantity: number | string quantity: number | string
feeAmount?: number | string
taxAmount?: number | string taxAmount?: number | string
} }
export default async function addContractFee( export default async function addContractFee(
addFeeForm: AddContractFeeForm, addFeeForm: AddContractFeeForm,
user: User, user: User,
connectedDatabase?: sqlite.Database connectedDatabase?: PoolConnection
): Promise<boolean> { ): Promise<boolean> {
const database = connectedDatabase ?? sqlite(sunriseDB) const database = connectedDatabase ?? (await acquireConnection())
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -33,9 +32,11 @@ export default async function addContractFee(
let taxAmount: number let taxAmount: number
if ((addFeeForm.feeAmount ?? '') === '') { if ((addFeeForm.feeAmount ?? '') === '') {
const contract = (await getContract(addFeeForm.contractId)) as Contract const contract = (await getContract(
addFeeForm.contractId
)) as Contract
const fee = getFee(addFeeForm.feeId) as Fee const fee = (await getFee(addFeeForm.feeId)) as Fee
feeAmount = calculateFeeAmount(fee, contract) feeAmount = calculateFeeAmount(fee, contract)
taxAmount = calculateTaxAmount(fee, feeAmount) taxAmount = calculateTaxAmount(fee, feeAmount)
@ -63,7 +64,6 @@ export default async function addContractFee(
| { | {
feeAmount: number | null feeAmount: number | null
taxAmount: number | null taxAmount: number | null
recordDelete_timeMillis: number | null recordDelete_timeMillis: number | null
} }
| undefined | undefined
@ -155,7 +155,7 @@ export default async function addContractFee(
return result.changes > 0 return result.changes > 0
} finally { } finally {
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close() database.release()
} }
} }
} }

View File

@ -1,10 +1,9 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import addContractFee from './addContractFee.js'; import addContractFee from './addContractFee.js';
import { getFeeCategory } from './getFeeCategories.js'; import { getFeeCategory } from './getFeeCategories.js';
import { acquireConnection } from './pool.js';
export default async function addContractFeeCategory(addFeeCategoryForm, user) { export default async function addContractFeeCategory(addFeeCategoryForm, user) {
const database = sqlite(sunriseDB); const database = await acquireConnection();
const feeCategory = getFeeCategory(addFeeCategoryForm.feeCategoryId, database); const feeCategory = await getFeeCategory(addFeeCategoryForm.feeCategoryId, database);
let addedFeeCount = 0; let addedFeeCount = 0;
for (const fee of feeCategory?.fees ?? []) { for (const fee of feeCategory?.fees ?? []) {
const success = await addContractFee({ const success = await addContractFee({
@ -16,6 +15,6 @@ export default async function addContractFeeCategory(addFeeCategoryForm, user) {
addedFeeCount += 1; addedFeeCount += 1;
} }
} }
database.close(); database.release();
return addedFeeCount; return addedFeeCount;
} }

View File

@ -1,9 +1,6 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import addContractFee from './addContractFee.js' import addContractFee from './addContractFee.js'
import { getFeeCategory } from './getFeeCategories.js' import { getFeeCategory } from './getFeeCategories.js'
import { acquireConnection } from './pool.js'
export interface AddContractCategoryForm { export interface AddContractCategoryForm {
contractId: number | string contractId: number | string
@ -14,9 +11,12 @@ export default async function addContractFeeCategory(
addFeeCategoryForm: AddContractCategoryForm, addFeeCategoryForm: AddContractCategoryForm,
user: User user: User
): Promise<number> { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const feeCategory = getFeeCategory(addFeeCategoryForm.feeCategoryId, database) const feeCategory = await getFeeCategory(
addFeeCategoryForm.feeCategoryId,
database
)
let addedFeeCount = 0 let addedFeeCount = 0
@ -36,7 +36,7 @@ export default async function addContractFeeCategory(
} }
} }
database.close() database.release()
return addedFeeCount return addedFeeCount
} }

View File

@ -1,19 +1,16 @@
import { type DateString } from '@cityssm/utils-datetime'; import { type DateString } from '@cityssm/utils-datetime';
import sqlite from 'better-sqlite3';
export interface AddForm { export interface AddForm {
contractId: number | string; contractId: string | number;
deceasedName: string; deceasedName: string;
deceasedAddress1: string; deceasedAddress1: string;
deceasedAddress2: string; deceasedAddress2: string;
deceasedCity: string; deceasedCity: string;
deceasedPostalCode: string;
deceasedProvince: string; deceasedProvince: string;
birthDateString: '' | DateString; deceasedPostalCode: string;
birthDateString: DateString | '';
birthPlace: string; birthPlace: string;
deathDateString: '' | DateString; deathDateString: DateString | '';
deathPlace: string; deathPlace: string;
deathAge: number | string; intermentContainerTypeId: string | number;
deathAgePeriod: string;
intermentContainerTypeId: number | string;
} }
export default function addContractInterment(contractForm: AddForm, user: User, connectedDatabase?: sqlite.Database): number; export default function addContractInterment(contractForm: AddForm, user: User): Promise<number>;

View File

@ -1,8 +1,7 @@
import { dateStringToInteger } from '@cityssm/utils-datetime'; import { dateStringToInteger } from '@cityssm/utils-datetime';
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addContractInterment(contractForm, user) {
export default function addContractInterment(contractForm, user, connectedDatabase) { const database = await acquireConnection();
const database = connectedDatabase ?? sqlite(sunriseDB);
const maxIntermentNumber = (database const maxIntermentNumber = (database
.prepare(`select max(intermentNumber) as maxIntermentNumber .prepare(`select max(intermentNumber) as maxIntermentNumber
from ContractInterments from ContractInterments
@ -26,8 +25,6 @@ export default function addContractInterment(contractForm, user, connectedDataba
: dateStringToInteger(contractForm.deathDateString), contractForm.deathPlace, contractForm.intermentContainerTypeId === '' : dateStringToInteger(contractForm.deathDateString), contractForm.deathPlace, contractForm.intermentContainerTypeId === ''
? undefined ? undefined
: contractForm.intermentContainerTypeId, user.userName, rightNowMillis, user.userName, rightNowMillis); : contractForm.intermentContainerTypeId, user.userName, rightNowMillis, user.userName, rightNowMillis);
if (connectedDatabase === undefined) { database.release();
database.close();
}
return newIntermentNumber; return newIntermentNumber;
} }

View File

@ -1,36 +1,27 @@
import { type DateString, dateStringToInteger } from '@cityssm/utils-datetime' import { type DateString, dateStringToInteger } from '@cityssm/utils-datetime'
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js' import { acquireConnection } from './pool.js'
export interface AddForm { export interface AddForm {
contractId: number | string contractId: string | number
deceasedName: string deceasedName: string
deceasedAddress1: string deceasedAddress1: string
deceasedAddress2: string deceasedAddress2: string
deceasedCity: string deceasedCity: string
deceasedPostalCode: string
deceasedProvince: string deceasedProvince: string
deceasedPostalCode: string
birthDateString: '' | DateString birthDateString: DateString | ''
birthPlace: string birthPlace: string
deathDateString: '' | DateString deathDateString: DateString | ''
deathPlace: string deathPlace: string
intermentContainerTypeId: string | number
deathAge: number | string
deathAgePeriod: string
intermentContainerTypeId: number | string
} }
export default function addContractInterment( export default async function addContractInterment(
contractForm: AddForm, contractForm: AddForm,
user: User, user: User
connectedDatabase?: sqlite.Database ): Promise<number> {
): number { const database = await acquireConnection()
const database = connectedDatabase ?? sqlite(sunriseDB)
const maxIntermentNumber = (database const maxIntermentNumber = (database
.prepare( .prepare(
@ -80,9 +71,7 @@ export default function addContractInterment(
rightNowMillis rightNowMillis
) )
if (connectedDatabase === undefined) { database.release()
database.close()
}
return newIntermentNumber return newIntermentNumber
} }

View File

@ -1,10 +1,9 @@
import { type DateString, type TimeString } from '@cityssm/utils-datetime';
export interface AddTransactionForm { export interface AddTransactionForm {
contractId: number | string; contractId: string | number;
transactionDateString?: '' | DateString; transactionDateString?: string;
transactionTimeString?: '' | TimeString; transactionTimeString?: string;
transactionAmount: string | number;
externalReceiptNumber: string; externalReceiptNumber: string;
transactionAmount: number | string;
transactionNote: string; transactionNote: string;
} }
export default function addContractTransaction(contractTransactionForm: AddTransactionForm, user: User): number; export default function addContractTransaction(contractTransactionForm: AddTransactionForm, user: User): Promise<number>;

View File

@ -1,8 +1,7 @@
import { dateStringToInteger, dateToInteger, dateToTimeInteger, timeStringToInteger } from '@cityssm/utils-datetime'; import { dateStringToInteger, dateToInteger, dateToTimeInteger, timeStringToInteger } from '@cityssm/utils-datetime';
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addContractTransaction(contractTransactionForm, user) {
export default function addContractTransaction(contractTransactionForm, user) { const database = await acquireConnection();
const database = sqlite(sunriseDB);
let transactionIndex = 0; let transactionIndex = 0;
const maxIndexResult = database const maxIndexResult = database
.prepare(`select transactionIndex .prepare(`select transactionIndex
@ -15,12 +14,12 @@ export default function addContractTransaction(contractTransactionForm, user) {
transactionIndex = maxIndexResult.transactionIndex + 1; transactionIndex = maxIndexResult.transactionIndex + 1;
} }
const rightNow = new Date(); const rightNow = new Date();
const transactionDate = (contractTransactionForm.transactionDateString ?? '') === '' const transactionDate = contractTransactionForm.transactionDateString
? dateToInteger(rightNow) ? dateStringToInteger(contractTransactionForm.transactionDateString)
: dateStringToInteger(contractTransactionForm.transactionDateString); : dateToInteger(rightNow);
const transactionTime = (contractTransactionForm.transactionTimeString ?? '') === '' const transactionTime = contractTransactionForm.transactionTimeString
? dateToTimeInteger(rightNow) ? timeStringToInteger(contractTransactionForm.transactionTimeString)
: timeStringToInteger(contractTransactionForm.transactionTimeString); : dateToTimeInteger(rightNow);
database database
.prepare(`insert into ContractTransactions ( .prepare(`insert into ContractTransactions (
contractId, transactionIndex, contractId, transactionIndex,
@ -30,6 +29,6 @@ export default function addContractTransaction(contractTransactionForm, user) {
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.run(contractTransactionForm.contractId, transactionIndex, transactionDate, transactionTime, contractTransactionForm.transactionAmount, contractTransactionForm.externalReceiptNumber, contractTransactionForm.transactionNote, user.userName, rightNow.getTime(), user.userName, rightNow.getTime()); .run(contractTransactionForm.contractId, transactionIndex, transactionDate, transactionTime, contractTransactionForm.transactionAmount, contractTransactionForm.externalReceiptNumber, contractTransactionForm.transactionNote, user.userName, rightNow.getTime(), user.userName, rightNow.getTime());
database.close(); database.release();
return transactionIndex; return transactionIndex;
} }

View File

@ -1,31 +1,26 @@
import { import {
type DateString,
type TimeString,
dateStringToInteger, dateStringToInteger,
dateToInteger, dateToInteger,
dateToTimeInteger, dateToTimeInteger,
timeStringToInteger timeStringToInteger
} from '@cityssm/utils-datetime' } from '@cityssm/utils-datetime'
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js' import { acquireConnection } from './pool.js'
export interface AddTransactionForm { export interface AddTransactionForm {
contractId: number | string contractId: string | number
transactionDateString?: string
transactionDateString?: '' | DateString transactionTimeString?: string
transactionTimeString?: '' | TimeString transactionAmount: string | number
externalReceiptNumber: string externalReceiptNumber: string
transactionAmount: number | string
transactionNote: string transactionNote: string
} }
export default function addContractTransaction( export default async function addContractTransaction(
contractTransactionForm: AddTransactionForm, contractTransactionForm: AddTransactionForm,
user: User user: User
): number { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
let transactionIndex = 0 let transactionIndex = 0
@ -47,19 +42,13 @@ export default function addContractTransaction(
const rightNow = new Date() const rightNow = new Date()
const transactionDate = const transactionDate = contractTransactionForm.transactionDateString
(contractTransactionForm.transactionDateString ?? '') === '' ? dateStringToInteger(contractTransactionForm.transactionDateString)
? dateToInteger(rightNow) : dateToInteger(rightNow)
: dateStringToInteger(
contractTransactionForm.transactionDateString as DateString
)
const transactionTime = const transactionTime = contractTransactionForm.transactionTimeString
(contractTransactionForm.transactionTimeString ?? '') === '' ? timeStringToInteger(contractTransactionForm.transactionTimeString)
? dateToTimeInteger(rightNow) : dateToTimeInteger(rightNow)
: timeStringToInteger(
contractTransactionForm.transactionTimeString as TimeString
)
database database
.prepare( .prepare(
@ -85,7 +74,7 @@ export default function addContractTransaction(
rightNow.getTime() rightNow.getTime()
) )
database.close() database.release()
return transactionIndex return transactionIndex
} }

View File

@ -3,4 +3,4 @@ export interface AddForm {
isPreneed?: string; isPreneed?: string;
orderNumber?: number; orderNumber?: number;
} }
export default function addContractType(addForm: AddForm, user: User): number; export default function addContractType(addForm: AddForm, user: User): Promise<number>;

View File

@ -1,8 +1,7 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { clearCacheByTableName } from '../helpers/functions.cache.js'; import { clearCacheByTableName } from '../helpers/functions.cache.js';
export default function addContractType(addForm, user) { import { acquireConnection } from './pool.js';
const database = sqlite(sunriseDB); export default async function addContractType(addForm, user) {
const database = await acquireConnection();
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into ContractTypes ( .prepare(`insert into ContractTypes (
@ -11,7 +10,7 @@ export default function addContractType(addForm, user) {
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.contractType, addForm.isPreneed === undefined ? 0 : 1, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(addForm.contractType, addForm.isPreneed === undefined ? 0 : 1, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
database.close(); database.release();
clearCacheByTableName('ContractTypes'); clearCacheByTableName('ContractTypes');
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,16 +1,18 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import { clearCacheByTableName } from '../helpers/functions.cache.js' import { clearCacheByTableName } from '../helpers/functions.cache.js'
import { acquireConnection } from './pool.js'
export interface AddForm { export interface AddForm {
contractType: string contractType: string
isPreneed?: string isPreneed?: string
orderNumber?: number orderNumber?: number
} }
export default function addContractType(addForm: AddForm, user: User): number { export default async function addContractType(
const database = sqlite(sunriseDB) addForm: AddForm,
user: User
): Promise<number> {
const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -32,7 +34,7 @@ export default function addContractType(addForm: AddForm, user: User): number {
rightNowMillis rightNowMillis
) )
database.close() database.release()
clearCacheByTableName('ContractTypes') clearCacheByTableName('ContractTypes')

View File

@ -1,12 +1,12 @@
export interface AddContractTypeFieldForm { export interface AddContractTypeFieldForm {
contractTypeId?: number | string; contractTypeId?: string | number;
contractTypeField: string; contractTypeField: string;
fieldType?: string;
fieldValues?: string; fieldValues?: string;
fieldType?: string;
isRequired?: string; isRequired?: string;
maxLength?: number | string;
minLength?: number | string;
pattern?: string; pattern?: string;
minLength?: string | number;
maxLength?: string | number;
orderNumber?: number; orderNumber?: number;
} }
export default function addContractTypeField(addForm: AddContractTypeFieldForm, user: User): number; export default function addContractTypeField(addForm: AddContractTypeFieldForm, user: User): Promise<number>;

View File

@ -1,8 +1,7 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { clearCacheByTableName } from '../helpers/functions.cache.js'; import { clearCacheByTableName } from '../helpers/functions.cache.js';
export default function addContractTypeField(addForm, user) { import { acquireConnection } from './pool.js';
const database = sqlite(sunriseDB); export default async function addContractTypeField(addForm, user) {
const database = await acquireConnection();
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into ContractTypeFields ( .prepare(`insert into ContractTypeFields (
@ -13,10 +12,8 @@ export default function addContractTypeField(addForm, user) {
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.contractTypeId ?? undefined, addForm.contractTypeField, addForm.fieldType ?? 'text', addForm.fieldValues ?? '', addForm.isRequired === '' ? 0 : 1, addForm.pattern ?? '', addForm.minLength ?? 0, .run(addForm.contractTypeId ?? undefined, addForm.contractTypeField, addForm.fieldType ?? 'text', addForm.fieldValues ?? '', addForm.isRequired === '' ? 0 : 1, addForm.pattern ?? '', addForm.minLength ?? 0, addForm.maxLength ?? 100, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers database.release();
addForm.maxLength ?? 100, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
database.close();
clearCacheByTableName('ContractTypeFields'); clearCacheByTableName('ContractTypeFields');
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,28 +1,24 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import { clearCacheByTableName } from '../helpers/functions.cache.js' import { clearCacheByTableName } from '../helpers/functions.cache.js'
import { acquireConnection } from './pool.js'
export interface AddContractTypeFieldForm { export interface AddContractTypeFieldForm {
contractTypeId?: number | string contractTypeId?: string | number
contractTypeField: string contractTypeField: string
fieldType?: string
fieldValues?: string fieldValues?: string
fieldType?: string
isRequired?: string isRequired?: string
maxLength?: number | string
minLength?: number | string
pattern?: string pattern?: string
minLength?: string | number
maxLength?: string | number
orderNumber?: number orderNumber?: number
} }
export default function addContractTypeField( export default async function addContractTypeField(
addForm: AddContractTypeFieldForm, addForm: AddContractTypeFieldForm,
user: User user: User
): number { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -45,7 +41,6 @@ export default function addContractTypeField(
addForm.isRequired === '' ? 0 : 1, addForm.isRequired === '' ? 0 : 1,
addForm.pattern ?? '', addForm.pattern ?? '',
addForm.minLength ?? 0, addForm.minLength ?? 0,
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
addForm.maxLength ?? 100, addForm.maxLength ?? 100,
addForm.orderNumber ?? -1, addForm.orderNumber ?? -1,
user.userName, user.userName,
@ -54,7 +49,7 @@ export default function addContractTypeField(
rightNowMillis rightNowMillis
) )
database.close() database.release()
clearCacheByTableName('ContractTypeFields') clearCacheByTableName('ContractTypeFields')

View File

@ -1,6 +1,6 @@
export interface AddContractTypePrintForm { export interface AddContractTypePrintForm {
contractTypeId: number | string; contractTypeId: string | number;
printEJS: string; printEJS: string;
orderNumber?: number; orderNumber?: number;
} }
export default function addContractTypePrint(addForm: AddContractTypePrintForm, user: User): boolean; export default function addContractTypePrint(addForm: AddContractTypePrintForm, user: User): Promise<boolean>;

View File

@ -1,8 +1,7 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { clearCacheByTableName } from '../helpers/functions.cache.js'; import { clearCacheByTableName } from '../helpers/functions.cache.js';
export default function addContractTypePrint(addForm, user) { import { acquireConnection } from './pool.js';
const database = sqlite(sunriseDB); export default async function addContractTypePrint(addForm, user) {
const database = await acquireConnection();
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
let result = database let result = database
.prepare(`update ContractTypePrints .prepare(`update ContractTypePrints
@ -22,7 +21,7 @@ export default function addContractTypePrint(addForm, user) {
values (?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.contractTypeId, addForm.printEJS, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(addForm.contractTypeId, addForm.printEJS, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
} }
database.close(); database.release();
clearCacheByTableName('ContractTypePrints'); clearCacheByTableName('ContractTypePrints');
return result.changes > 0; return result.changes > 0;
} }

View File

@ -1,20 +1,18 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import { clearCacheByTableName } from '../helpers/functions.cache.js' import { clearCacheByTableName } from '../helpers/functions.cache.js'
export interface AddContractTypePrintForm { import { acquireConnection } from './pool.js'
contractTypeId: number | string
printEJS: string
export interface AddContractTypePrintForm {
contractTypeId: string | number
printEJS: string
orderNumber?: number orderNumber?: number
} }
export default function addContractTypePrint( export default async function addContractTypePrint(
addForm: AddContractTypePrintForm, addForm: AddContractTypePrintForm,
user: User user: User
): boolean { ): Promise<boolean> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -55,7 +53,7 @@ export default function addContractTypePrint(
) )
} }
database.close() database.release()
clearCacheByTableName('ContractTypePrints') clearCacheByTableName('ContractTypePrints')

View File

@ -1,10 +1,10 @@
export interface AddFeeForm { export interface AddFeeForm {
feeCategoryId: number | string; feeCategoryId: string;
feeName: string; feeName: string;
feeDescription: string; feeDescription: string;
feeAccount: string; feeAccount: string;
contractTypeId: number | string; contractTypeId: string;
burialSiteTypeId: number | string; burialSiteTypeId: string;
feeAmount?: string; feeAmount?: string;
feeFunction?: string; feeFunction?: string;
taxAmount?: string; taxAmount?: string;
@ -14,4 +14,4 @@ export interface AddFeeForm {
isRequired?: '' | '1'; isRequired?: '' | '1';
orderNumber?: number; orderNumber?: number;
} }
export default function addFee(feeForm: AddFeeForm, user: User): number; export default function addFee(feeForm: AddFeeForm, user: User): Promise<number>;

View File

@ -1,7 +1,6 @@
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addFee(feeForm, user) {
export default function addFee(feeForm, user) { const database = await acquireConnection();
const database = sqlite(sunriseDB);
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into Fees ( .prepare(`insert into Fees (
@ -15,7 +14,7 @@ export default function addFee(feeForm, user) {
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.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); .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);
database.close(); database.release();
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,14 +1,12 @@
import sqlite from 'better-sqlite3' import { acquireConnection } from './pool.js'
import { sunriseDB } from '../helpers/database.helpers.js'
export interface AddFeeForm { export interface AddFeeForm {
feeCategoryId: number | string feeCategoryId: string
feeName: string feeName: string
feeDescription: string feeDescription: string
feeAccount: string feeAccount: string
contractTypeId: number | string contractTypeId: string
burialSiteTypeId: number | string burialSiteTypeId: string
feeAmount?: string feeAmount?: string
feeFunction?: string feeFunction?: string
taxAmount?: string taxAmount?: string
@ -19,8 +17,11 @@ export interface AddFeeForm {
orderNumber?: number orderNumber?: number
} }
export default function addFee(feeForm: AddFeeForm, user: User): number { export default async function addFee(
const database = sqlite(sunriseDB) feeForm: AddFeeForm,
user: User
): Promise<number> {
const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -45,10 +46,10 @@ export default function addFee(feeForm: AddFeeForm, user: User): number {
feeForm.feeAccount, feeForm.feeAccount,
feeForm.contractTypeId === '' ? undefined : feeForm.contractTypeId, feeForm.contractTypeId === '' ? undefined : feeForm.contractTypeId,
feeForm.burialSiteTypeId === '' ? undefined : feeForm.burialSiteTypeId, feeForm.burialSiteTypeId === '' ? undefined : feeForm.burialSiteTypeId,
feeForm.feeAmount === '' ? undefined : feeForm.feeAmount, feeForm.feeAmount ?? undefined,
feeForm.feeFunction ?? undefined, feeForm.feeFunction ?? undefined,
feeForm.taxAmount === '' ? undefined : feeForm.taxAmount, feeForm.taxAmount ?? undefined,
feeForm.taxPercentage === '' ? undefined : feeForm.taxPercentage, feeForm.taxPercentage ?? undefined,
(feeForm.includeQuantity ?? '') === '' ? 0 : 1, (feeForm.includeQuantity ?? '') === '' ? 0 : 1,
feeForm.quantityUnit, feeForm.quantityUnit,
(feeForm.isRequired ?? '') === '' ? 0 : 1, (feeForm.isRequired ?? '') === '' ? 0 : 1,
@ -59,7 +60,7 @@ export default function addFee(feeForm: AddFeeForm, user: User): number {
rightNowMillis rightNowMillis
) )
database.close() database.release()
return result.lastInsertRowid as number return result.lastInsertRowid as number
} }

View File

@ -3,4 +3,4 @@ export interface AddFeeCategoryForm {
isGroupedFee?: '1'; isGroupedFee?: '1';
orderNumber?: number; orderNumber?: number;
} }
export default function addFeeCategory(feeCategoryForm: AddFeeCategoryForm, user: User): number; export default function addFeeCategory(feeCategoryForm: AddFeeCategoryForm, user: User): Promise<number>;

View File

@ -1,7 +1,6 @@
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addFeeCategory(feeCategoryForm, user) {
export default function addFeeCategory(feeCategoryForm, user) { const database = await acquireConnection();
const database = sqlite(sunriseDB);
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into FeeCategories ( .prepare(`insert into FeeCategories (
@ -11,6 +10,6 @@ export default function addFeeCategory(feeCategoryForm, user) {
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?)`)
.run(feeCategoryForm.feeCategory, (feeCategoryForm.isGroupedFee ?? '') === '1' ? 1 : 0, feeCategoryForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(feeCategoryForm.feeCategory, (feeCategoryForm.isGroupedFee ?? '') === '1' ? 1 : 0, feeCategoryForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
database.close(); database.release();
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,6 +1,4 @@
import sqlite from 'better-sqlite3' import { acquireConnection } from './pool.js'
import { sunriseDB } from '../helpers/database.helpers.js'
export interface AddFeeCategoryForm { export interface AddFeeCategoryForm {
feeCategory: string feeCategory: string
@ -8,11 +6,11 @@ export interface AddFeeCategoryForm {
orderNumber?: number orderNumber?: number
} }
export default function addFeeCategory( export default async function addFeeCategory(
feeCategoryForm: AddFeeCategoryForm, feeCategoryForm: AddFeeCategoryForm,
user: User user: User
): number { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -35,7 +33,7 @@ export default function addFeeCategory(
rightNowMillis rightNowMillis
) )
database.close() database.release()
return result.lastInsertRowid as number return result.lastInsertRowid as number
} }

View File

@ -1,11 +1,10 @@
export interface AddForm { export interface AddForm {
funeralHomeKey: string;
funeralHomeName: string; funeralHomeName: string;
funeralHomeAddress1: string; funeralHomeAddress1: string;
funeralHomeAddress2: string; funeralHomeAddress2: string;
funeralHomeCity: string; funeralHomeCity: string;
funeralHomePostalCode: string;
funeralHomeProvince: string; funeralHomeProvince: string;
funeralHomePostalCode: string;
funeralHomePhoneNumber: string; funeralHomePhoneNumber: string;
} }
export default function addFuneralHome(addForm: AddForm, user: User): number; export default function addFuneralHome(addForm: AddForm, user: User): Promise<number>;

View File

@ -1,16 +1,15 @@
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addFuneralHome(addForm, user) {
export default function addFuneralHome(addForm, user) { const database = await acquireConnection();
const database = sqlite(sunriseDB);
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into FuneralHomes ( .prepare(`insert into FuneralHomes (
funeralHomeName, funeralHomeKey, funeralHomeAddress1, funeralHomeAddress2, funeralHomeName, funeralHomeAddress1, funeralHomeAddress2,
funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.funeralHomeName, addForm.funeralHomeKey, addForm.funeralHomeAddress1, addForm.funeralHomeAddress2, addForm.funeralHomeCity, addForm.funeralHomeProvince, addForm.funeralHomePostalCode, addForm.funeralHomePhoneNumber, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(addForm.funeralHomeName, addForm.funeralHomeAddress1, addForm.funeralHomeAddress2, addForm.funeralHomeCity, addForm.funeralHomeProvince, addForm.funeralHomePostalCode, addForm.funeralHomePhoneNumber, user.userName, rightNowMillis, user.userName, rightNowMillis);
database.close(); database.release();
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,37 +1,34 @@
import sqlite from 'better-sqlite3' import { acquireConnection } from './pool.js'
import { sunriseDB } from '../helpers/database.helpers.js'
export interface AddForm { export interface AddForm {
funeralHomeKey: string
funeralHomeName: string funeralHomeName: string
funeralHomeAddress1: string funeralHomeAddress1: string
funeralHomeAddress2: string funeralHomeAddress2: string
funeralHomeCity: string funeralHomeCity: string
funeralHomePostalCode: string
funeralHomeProvince: string funeralHomeProvince: string
funeralHomePostalCode: string
funeralHomePhoneNumber: string funeralHomePhoneNumber: string
} }
export default function addFuneralHome(addForm: AddForm, user: User): number { export default async function addFuneralHome(
const database = sqlite(sunriseDB) addForm: AddForm,
user: User
): Promise<number> {
const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
const result = database const result = database
.prepare( .prepare(
`insert into FuneralHomes ( `insert into FuneralHomes (
funeralHomeName, funeralHomeKey, funeralHomeAddress1, funeralHomeAddress2, funeralHomeName, funeralHomeAddress1, funeralHomeAddress2,
funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber, funeralHomeCity, funeralHomeProvince, funeralHomePostalCode, funeralHomePhoneNumber,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
) )
.run( .run(
addForm.funeralHomeName, addForm.funeralHomeName,
addForm.funeralHomeKey,
addForm.funeralHomeAddress1, addForm.funeralHomeAddress1,
addForm.funeralHomeAddress2, addForm.funeralHomeAddress2,
addForm.funeralHomeCity, addForm.funeralHomeCity,
@ -44,7 +41,7 @@ export default function addFuneralHome(addForm: AddForm, user: User): number {
rightNowMillis rightNowMillis
) )
database.close() database.release()
return result.lastInsertRowid as number return result.lastInsertRowid as number
} }

View File

@ -1,7 +1,6 @@
export interface AddIntermentContainerTypeForm { export interface AddForm {
intermentContainerType: string; intermentContainerType: string;
intermentContainerTypeKey?: string; isCremationType?: string;
isCremationType?: '0' | '1'; orderNumber?: number;
orderNumber?: number | string;
} }
export default function addIntermentContainerType(addForm: AddIntermentContainerTypeForm, user: User): number; export default function addIntermentContainerType(addForm: AddForm, user: User): Promise<number>;

View File

@ -1,17 +1,16 @@
import sqlite from 'better-sqlite3';
import { sunriseDB } from '../helpers/database.helpers.js';
import { clearCacheByTableName } from '../helpers/functions.cache.js'; import { clearCacheByTableName } from '../helpers/functions.cache.js';
export default function addIntermentContainerType(addForm, user) { import { acquireConnection } from './pool.js';
const database = sqlite(sunriseDB); export default async function addIntermentContainerType(addForm, user) {
const database = await acquireConnection();
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
const result = database const result = database
.prepare(`insert into IntermentContainerTypes ( .prepare(`insert into IntermentContainerTypes (
intermentContainerType, intermentContainerTypeKey, isCremationType, orderNumber, intermentContainerType, isCremationType, orderNumber,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?)`) values (?, ?, ?, ?, ?, ?, ?)`)
.run(addForm.intermentContainerType, addForm.intermentContainerTypeKey ?? '', addForm.isCremationType ?? '0', addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(addForm.intermentContainerType, addForm.isCremationType === undefined ? 0 : 1, addForm.orderNumber ?? -1, user.userName, rightNowMillis, user.userName, rightNowMillis);
database.close(); database.release();
clearCacheByTableName('IntermentContainerTypes'); clearCacheByTableName('IntermentContainerTypes');
return result.lastInsertRowid; return result.lastInsertRowid;
} }

View File

@ -1,35 +1,32 @@
import sqlite from 'better-sqlite3'
import { sunriseDB } from '../helpers/database.helpers.js'
import { clearCacheByTableName } from '../helpers/functions.cache.js' import { clearCacheByTableName } from '../helpers/functions.cache.js'
export interface AddIntermentContainerTypeForm { import { acquireConnection } from './pool.js'
export interface AddForm {
intermentContainerType: string intermentContainerType: string
intermentContainerTypeKey?: string isCremationType?: string
isCremationType?: '0' | '1' orderNumber?: number
orderNumber?: number | string
} }
export default function addIntermentContainerType( export default async function addIntermentContainerType(
addForm: AddIntermentContainerTypeForm, addForm: AddForm,
user: User user: User
): number { ): Promise<number> {
const database = sqlite(sunriseDB) const database = await acquireConnection()
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
const result = database const result = database
.prepare( .prepare(
`insert into IntermentContainerTypes ( `insert into IntermentContainerTypes (
intermentContainerType, intermentContainerTypeKey, isCremationType, orderNumber, intermentContainerType, isCremationType, orderNumber,
recordCreate_userName, recordCreate_timeMillis, recordCreate_userName, recordCreate_timeMillis,
recordUpdate_userName, recordUpdate_timeMillis) recordUpdate_userName, recordUpdate_timeMillis)
values (?, ?, ?, ?, ?, ?, ?, ?)` values (?, ?, ?, ?, ?, ?, ?)`
) )
.run( .run(
addForm.intermentContainerType, addForm.intermentContainerType,
addForm.intermentContainerTypeKey ?? '', addForm.isCremationType === undefined ? 0 : 1,
addForm.isCremationType ?? '0',
addForm.orderNumber ?? -1, addForm.orderNumber ?? -1,
user.userName, user.userName,
rightNowMillis, rightNowMillis,
@ -37,7 +34,7 @@ export default function addIntermentContainerType(
rightNowMillis rightNowMillis
) )
database.close() database.release()
clearCacheByTableName('IntermentContainerTypes') clearCacheByTableName('IntermentContainerTypes')

View File

@ -1,7 +1,7 @@
import sqlite from 'better-sqlite3'; import type { PoolConnection } from 'better-sqlite-pool';
export interface BurialSiteFieldForm { export interface BurialSiteFieldForm {
burialSiteId: number | string; burialSiteId: string | number;
burialSiteTypeFieldId: number | string; burialSiteTypeFieldId: string | number;
fieldValue: string; fieldValue: string;
} }
export default function addOrUpdateBurialSiteField(fieldForm: BurialSiteFieldForm, user: User, connectedDatabase?: sqlite.Database): boolean; export default function addOrUpdateBurialSiteField(fieldForm: BurialSiteFieldForm, user: User, connectedDatabase?: PoolConnection): Promise<boolean>;

View File

@ -1,7 +1,6 @@
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addOrUpdateBurialSiteField(fieldForm, user, connectedDatabase) {
export default function addOrUpdateBurialSiteField(fieldForm, user, connectedDatabase) { const database = connectedDatabase ?? (await acquireConnection());
const database = connectedDatabase ?? sqlite(sunriseDB);
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
let result = database let result = database
.prepare(`update BurialSiteFields .prepare(`update BurialSiteFields
@ -23,7 +22,7 @@ export default function addOrUpdateBurialSiteField(fieldForm, user, connectedDat
.run(fieldForm.burialSiteId, fieldForm.burialSiteTypeFieldId, fieldForm.fieldValue, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(fieldForm.burialSiteId, fieldForm.burialSiteTypeFieldId, fieldForm.fieldValue, user.userName, rightNowMillis, user.userName, rightNowMillis);
} }
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close(); database.release();
} }
return result.changes > 0; return result.changes > 0;
} }

View File

@ -1,19 +1,19 @@
import sqlite from 'better-sqlite3' import type { PoolConnection } from 'better-sqlite-pool'
import { sunriseDB } from '../helpers/database.helpers.js' import { acquireConnection } from './pool.js'
export interface BurialSiteFieldForm { export interface BurialSiteFieldForm {
burialSiteId: number | string burialSiteId: string | number
burialSiteTypeFieldId: number | string burialSiteTypeFieldId: string | number
fieldValue: string fieldValue: string
} }
export default function addOrUpdateBurialSiteField( export default async function addOrUpdateBurialSiteField(
fieldForm: BurialSiteFieldForm, fieldForm: BurialSiteFieldForm,
user: User, user: User,
connectedDatabase?: sqlite.Database connectedDatabase?: PoolConnection
): boolean { ): Promise<boolean> {
const database = connectedDatabase ?? sqlite(sunriseDB) const database = connectedDatabase ?? (await acquireConnection())
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -57,7 +57,7 @@ export default function addOrUpdateBurialSiteField(
} }
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close() database.release()
} }
return result.changes > 0 return result.changes > 0

View File

@ -1,7 +1,7 @@
import sqlite from 'better-sqlite3'; import type { PoolConnection } from 'better-sqlite-pool';
export interface ContractFieldForm { export interface ContractFieldForm {
contractId: number | string; contractId: string | number;
contractTypeFieldId: number | string; contractTypeFieldId: string | number;
fieldValue: string; fieldValue: string;
} }
export default function addOrUpdateContractField(fieldForm: ContractFieldForm, user: User, connectedDatabase?: sqlite.Database): boolean; export default function addOrUpdateContractField(fieldForm: ContractFieldForm, user: User, connectedDatabase?: PoolConnection): Promise<boolean>;

View File

@ -1,7 +1,6 @@
import sqlite from 'better-sqlite3'; import { acquireConnection } from './pool.js';
import { sunriseDB } from '../helpers/database.helpers.js'; export default async function addOrUpdateContractField(fieldForm, user, connectedDatabase) {
export default function addOrUpdateContractField(fieldForm, user, connectedDatabase) { const database = connectedDatabase ?? (await acquireConnection());
const database = connectedDatabase ?? sqlite(sunriseDB);
const rightNowMillis = Date.now(); const rightNowMillis = Date.now();
let result = database let result = database
.prepare(`update ContractFields .prepare(`update ContractFields
@ -23,7 +22,7 @@ export default function addOrUpdateContractField(fieldForm, user, connectedDatab
.run(fieldForm.contractId, fieldForm.contractTypeFieldId, fieldForm.fieldValue, user.userName, rightNowMillis, user.userName, rightNowMillis); .run(fieldForm.contractId, fieldForm.contractTypeFieldId, fieldForm.fieldValue, user.userName, rightNowMillis, user.userName, rightNowMillis);
} }
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close(); database.release();
} }
return result.changes > 0; return result.changes > 0;
} }

View File

@ -1,19 +1,19 @@
import sqlite from 'better-sqlite3' import type { PoolConnection } from 'better-sqlite-pool'
import { sunriseDB } from '../helpers/database.helpers.js' import { acquireConnection } from './pool.js'
export interface ContractFieldForm { export interface ContractFieldForm {
contractId: number | string contractId: string | number
contractTypeFieldId: number | string contractTypeFieldId: string | number
fieldValue: string fieldValue: string
} }
export default function addOrUpdateContractField( export default async function addOrUpdateContractField(
fieldForm: ContractFieldForm, fieldForm: ContractFieldForm,
user: User, user: User,
connectedDatabase?: sqlite.Database connectedDatabase?: PoolConnection
): boolean { ): Promise<boolean> {
const database = connectedDatabase ?? sqlite(sunriseDB) const database = connectedDatabase ?? (await acquireConnection())
const rightNowMillis = Date.now() const rightNowMillis = Date.now()
@ -57,7 +57,7 @@ export default function addOrUpdateContractField(
} }
if (connectedDatabase === undefined) { if (connectedDatabase === undefined) {
database.close() database.release()
} }
return result.changes > 0 return result.changes > 0

Some files were not shown because too many files have changed in this diff Show More