PPPAIMT-Crest/backend/src/services/applications.js

363 lines
10 KiB
JavaScript

import { randomUUID } from 'node:crypto';
import Boom from '@hapi/boom';
import { db } from '../db/knex.js';
import { auditFromRequest } from '../middleware/audit.js';
import { draftApplicationSchema, finalizeApplicationSchema } from '../schemas/application.js';
import { decryptField, encryptField, panLookup } from './fieldCrypto.js';
import { readImageDataUrl } from './png.js';
import { deleteObject, putObject } from './storage.js';
import { generateToken, hashToken } from './tokens.js';
import { sendResumeLink } from './mail.js';
import { readUserId } from './userAuth.js';
/** Max decoded cancelled-cheque image size (PNG/JPEG). */
const CHEQUE_LIMIT = 10 * 1024 * 1024;
const CODE_FIELDS = ['pan', 'ifsc', 'gstin'];
/**
* @param {unknown} value
* @returns {string | null}
*/
function formatDate(value) {
if (!value) {
return null;
}
if (typeof value === 'string') {
return value.slice(0, 10);
}
const month = String(value.getMonth() + 1).padStart(2, '0');
const day = String(value.getDate()).padStart(2, '0');
return `${value.getFullYear()}-${month}-${day}`;
}
/**
* @param {Record<string, unknown>} row
*/
export function presentApplication(row) {
return {
public_id: row.public_id,
email: row.email,
status: row.status,
agreement_date: formatDate(row.agreement_date),
full_name: row.full_name,
age: row.age,
address: row.address,
registration_no: row.registration_no,
medical_council: row.medical_council,
pan: decryptField(row.pan),
gstin: row.gstin,
bank_name: row.bank_name,
account_holder: row.account_holder,
account_number: decryptField(row.account_number),
ifsc: row.ifsc,
accepted: Boolean(row.accepted),
rejection_reason: row.rejection_reason,
version: row.version,
};
}
/**
* Ensures required physician + bank fields are present, and a cancelled cheque
* has been uploaded, before preview or sign.
* @param {Record<string, unknown>} application
*/
export function assertCompleteApplication(application) {
const merged = presentApplication(application);
if (merged.gstin == null || merged.gstin === '') {
delete merged.gstin;
}
const parsed = finalizeApplicationSchema.safeParse(merged);
if (!parsed.success) {
throw Boom.badRequest(zodMessage(parsed.error));
}
if (!application.cancelled_cheque_key) {
throw Boom.badRequest('cancelled_cheque: Upload a cancelled cheque image');
}
return parsed.data;
}
function zodMessage(error) {
return error.issues
.map((issue) => `${issue.path.join('.') || 'body'}: ${issue.message}`)
.join('; ');
}
/**
* @param {unknown} value
* @returns {string | null}
*/
function jwtFromCookie(value) {
if (typeof value === 'string') {
return value;
}
if (value && typeof value === 'object' && 'token' in value && typeof value.token === 'string') {
return value.token;
}
return null;
}
/**
* Resolve the physician application from a logged-in user cookie or a resume Bearer token.
* @param {import('@hapi/hapi').Request} request
*/
export async function applicationFromRequest(request) {
const userJwt = jwtFromCookie(request.state.user_token);
const userId = userJwt ? readUserId(userJwt) : null;
if (userId) {
const user = await db('users').where({ id: Number(userId), is_active: true }).first();
if (!user) {
throw Boom.unauthorized('Authentication required');
}
const application = await db('applications').where({ user_id: user.id }).first();
if (!application) {
throw Boom.badRequest('No application is linked to this account');
}
return application;
}
const header = request.headers.authorization ?? '';
const match = header.match(/^Bearer\s+(\S+)$/i);
if (!match) {
throw Boom.unauthorized('Authentication required');
}
const tokenRow = await db('resume_tokens')
.where({ token_hash: hashToken(match[1]) })
.whereNull('revoked_at')
.first();
if (!tokenRow) {
throw Boom.unauthorized('This resume link is invalid or has expired');
}
const application = await db('applications').where({ id: tokenRow.application_id }).first();
if (!application) {
throw Boom.unauthorized('This resume link is invalid or has expired');
}
return application;
}
/**
* @param {import('@hapi/hapi').Request} request
* @param {string} email
*/
export async function startApplication(request, email) {
const normalizedEmail = email.trim().toLowerCase();
let application = await db('applications')
.where({ email: normalizedEmail, status: 'DRAFT' })
.first();
const created = !application;
if (!application) {
const [id] = await db('applications').insert({
public_id: randomUUID(),
email: normalizedEmail,
status: 'DRAFT',
});
application = await db('applications').where({ id }).first();
} else {
await db('resume_tokens')
.where({ application_id: application.id })
.whereNull('revoked_at')
.update({ revoked_at: new Date() });
}
const token = generateToken();
await db('resume_tokens').insert({
application_id: application.id,
token_hash: hashToken(token),
created_at: new Date(),
});
await sendResumeLink({
applicationId: application.id,
toEmail: normalizedEmail,
token,
});
await auditFromRequest(request, {
actorType: 'PHYSICIAN',
actorId: application.id,
action: created ? 'APPLICATION_CREATED' : 'RESUME_LINK_RESENT',
entityType: 'applications',
entityId: application.id,
});
return { public_id: application.public_id, status: application.status, token };
}
/**
* @param {Record<string, unknown>} payload
*/
function normalizePayload(payload) {
const normalized = { ...payload };
for (const field of CODE_FIELDS) {
if (typeof normalized[field] === 'string') {
normalized[field] = normalized[field].trim().toUpperCase();
}
}
return normalized;
}
/**
* @param {Record<string, unknown>} updates
*/
function protectSecrets(updates) {
if (typeof updates.pan === 'string' && updates.pan) {
updates.pan_lookup = panLookup(updates.pan);
updates.pan = encryptField(updates.pan);
} else if (updates.pan === null) {
updates.pan_lookup = null;
}
if (typeof updates.account_number === 'string' && updates.account_number) {
updates.account_number = encryptField(updates.account_number);
}
}
/**
* Persist draft/finalize updates and return the updated application row.
* Callers that need download URLs should wrap with presentWithPdf.
* @param {import('@hapi/hapi').Request} request
* @param {Record<string, unknown>} application
* @param {Record<string, unknown>} payload
* @param {boolean} finalize
* @returns {Promise<Record<string, unknown>>}
*/
export async function saveApplication(request, application, payload, finalize) {
if (application.status === 'SUBMITTED' || application.status === 'APPROVED') {
throw Boom.conflict('This application can no longer be edited');
}
const parsed = draftApplicationSchema.safeParse(normalizePayload(payload));
if (!parsed.success) {
throw Boom.badRequest(zodMessage(parsed.error));
}
/** @type {Record<string, unknown>} */
const updates = {};
const chequePayload = parsed.data.cancelled_cheque;
for (const [key, value] of Object.entries(parsed.data)) {
if (value !== undefined && key !== 'cancelled_cheque') {
updates[key] = value;
}
}
if (chequePayload === null) {
if (application.cancelled_cheque_key) {
await deleteObject(String(application.cancelled_cheque_key)).catch(() => {});
}
updates.cancelled_cheque_key = null;
} else if (typeof chequePayload === 'string') {
const image = readImageDataUrl(
chequePayload,
CHEQUE_LIMIT,
'The cancelled cheque image must be 10MB or smaller',
);
const key = `applications/${application.public_id}/v${application.version}/cancelled-cheque.${image.extension}`;
await putObject(key, image.buffer, image.contentType);
if (
application.cancelled_cheque_key &&
String(application.cancelled_cheque_key) !== key
) {
await deleteObject(String(application.cancelled_cheque_key)).catch(() => {});
}
updates.cancelled_cheque_key = key;
}
if (finalize) {
const merged = {
...presentApplication(application),
...updates,
};
if (merged.gstin == null) {
delete merged.gstin;
}
merged.accepted = updates.accepted ?? Boolean(application.accepted);
const full = finalizeApplicationSchema.safeParse(merged);
if (!full.success) {
throw Boom.badRequest(zodMessage(full.error));
}
Object.assign(updates, full.data);
}
if (updates.registration_no) {
const duplicate = await db('applications')
.where({ registration_no: updates.registration_no })
.whereNot({ id: application.id })
.first();
if (duplicate) {
throw Boom.conflict('This registration number is already in use');
}
}
const signature = await db('signatures').where({ application_id: application.id }).first();
const hasDocument =
signature ||
application.draft_pdf_key ||
application.signed_pdf_key ||
application.final_pdf_key;
if (hasDocument && Object.keys(updates).length > 0) {
updates.version = Number(application.version) + 1;
}
if (application.status === 'REJECTED') {
updates.status = 'DRAFT';
await db('signatures')
.where({ application_id: application.id })
.whereNull('voided_at')
.update({ voided_at: new Date() });
}
protectSecrets(updates);
if (Object.keys(updates).length > 0) {
try {
await db('applications').where({ id: application.id }).update(updates);
} catch (error) {
if (error && typeof error === 'object' && 'code' in error && error.code === 'ER_DUP_ENTRY') {
throw Boom.conflict('This registration number is already in use');
}
throw error;
}
}
await auditFromRequest(request, {
actorType: 'PHYSICIAN',
actorId: application.id,
action: 'APPLICATION_UPDATED',
entityType: 'applications',
entityId: application.id,
metadata: { finalize },
});
return db('applications').where({ id: application.id }).first();
}