|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// Copyright 2026 Aaron K. Clark |
| 3 | +"use strict"; |
| 4 | + |
| 5 | +/** |
| 6 | + * Shared factory for bulk-create controllers on entities that scope |
| 7 | + * directly to a single company via a *CompId column. Customer's |
| 8 | + * bulkCreate predates this helper and has the same shape baked in; |
| 9 | + * we don't migrate it here to keep the diff focused on the new |
| 10 | + * endpoints (P3-H), but a follow-up should consolidate them. |
| 11 | + * |
| 12 | + * What this factory replaces: 5 near-identical controllers |
| 13 | + * (worker/billingtype/inventoryitem/inventorytransaction/ |
| 14 | + * purchaseordervendor) each repeating the same auth-scope-loop- |
| 15 | + * transaction-bulkCreate-handle-error scaffold. |
| 16 | + * |
| 17 | + * What varies between entities — passed as config: |
| 18 | + * - Model the sequelize model (db.Worker etc.) |
| 19 | + * - modelKey string label for logs ("Worker", "BillingType") |
| 20 | + * - compIdField the company-scope column ("workerCompId", "btCompId", |
| 21 | + * "invitCompId", "invtCompanyId", "povCompId") |
| 22 | + * - allowedFields whitelist for each entry (the same list the |
| 23 | + * single-create endpoint accepts, minus the *Arch |
| 24 | + * column which the controller sets to false) |
| 25 | + * - archField soft-delete column ("workerArch", "btArch", etc.) |
| 26 | + * - bodyKey JSON key the array hangs off ("workers", |
| 27 | + * "billingTypes", etc.) — matches the zod schema's |
| 28 | + * outer key. |
| 29 | + * - createdKey response key for the inserted rows ("workers", ...) |
| 30 | + */ |
| 31 | + |
| 32 | +const db = require('../config/db.config.js'); |
| 33 | +const log = require('../config/logger.js'); |
| 34 | +const auth = require('../middleware/auth.js'); |
| 35 | + |
| 36 | +function makeBulkCreate({ |
| 37 | + Model, |
| 38 | + modelKey, |
| 39 | + compIdField, |
| 40 | + allowedFields, |
| 41 | + archField, |
| 42 | + bodyKey, |
| 43 | + createdKey, |
| 44 | +}) { |
| 45 | + return async function bulkCreate(req, res) { |
| 46 | + const authKey = req.get('authKey'); |
| 47 | + if (!authKey) { |
| 48 | + return res.status(403).json({ message: "Authorization key not sent." }); |
| 49 | + } |
| 50 | + |
| 51 | + let isAuthKeyMasterKey; |
| 52 | + try { |
| 53 | + isAuthKeyMasterKey = await auth.isMaster(authKey); |
| 54 | + } catch (error) { |
| 55 | + log.error({ err: error }, `${modelKey}: isMaster failed`); |
| 56 | + return res.status(500).json({ message: "Error!", error: String(error) }); |
| 57 | + } |
| 58 | + |
| 59 | + const input = (req.body && Array.isArray(req.body[bodyKey])) |
| 60 | + ? req.body[bodyKey] |
| 61 | + : []; |
| 62 | + if (input.length === 0) { |
| 63 | + return res.status(400).json({ message: `${bodyKey} array is required and must be non-empty.` }); |
| 64 | + } |
| 65 | + |
| 66 | + // Resolve authKey's company once for non-master path. |
| 67 | + let authKeyCompanyId = null; |
| 68 | + if (!isAuthKeyMasterKey) { |
| 69 | + try { |
| 70 | + authKeyCompanyId = await auth.getCompanyId(authKey); |
| 71 | + } catch (error) { |
| 72 | + log.error({ err: error }, `${modelKey}: getCompanyId failed`); |
| 73 | + return res.status(500).json({ message: "Error!", error: String(error) }); |
| 74 | + } |
| 75 | + if (authKeyCompanyId === -1) { |
| 76 | + return res.status(403).json({ message: "Invalid Authorization Key." }); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + // Whitelist + auth-scope each entry. |
| 81 | + const payloads = []; |
| 82 | + for (let i = 0; i < input.length; i += 1) { |
| 83 | + const entry = input[i] || {}; |
| 84 | + const p = {}; |
| 85 | + for (const f of allowedFields) { |
| 86 | + if (entry[f] !== undefined) p[f] = entry[f]; |
| 87 | + } |
| 88 | + if (isAuthKeyMasterKey) { |
| 89 | + if (p[compIdField] === undefined || Number(p[compIdField]) <= 0) { |
| 90 | + return res.status(400).json({ |
| 91 | + message: `${bodyKey}[${i}]: master-key requests must specify ${compIdField}.`, |
| 92 | + }); |
| 93 | + } |
| 94 | + } else { |
| 95 | + if (p[compIdField] !== undefined && Number(p[compIdField]) !== authKeyCompanyId) { |
| 96 | + return res.status(403).json({ |
| 97 | + message: `${bodyKey}[${i}]: cannot create for a company you do not belong to.`, |
| 98 | + }); |
| 99 | + } |
| 100 | + p[compIdField] = authKeyCompanyId; |
| 101 | + } |
| 102 | + // archField intentionally defaulted to false here so |
| 103 | + // partially-archived bulk inserts can't be smuggled in. |
| 104 | + p[archField] = false; |
| 105 | + payloads.push(p); |
| 106 | + } |
| 107 | + |
| 108 | + const t = await db.sequelize.transaction(); |
| 109 | + try { |
| 110 | + const created = await Model.bulkCreate(payloads, { |
| 111 | + transaction: t, |
| 112 | + validate: true, |
| 113 | + returning: true, |
| 114 | + }); |
| 115 | + await t.commit(); |
| 116 | + const responseBody = { |
| 117 | + message: `Created ${created.length} ${modelKey}(s).`, |
| 118 | + count: created.length, |
| 119 | + }; |
| 120 | + responseBody[createdKey] = created; |
| 121 | + return res.status(201).json(responseBody); |
| 122 | + } catch (error) { |
| 123 | + try { await t.rollback(); } catch (_) { /* swallow */ } |
| 124 | + log.error({ err: error }, `${modelKey}.bulkCreate failed`); |
| 125 | + return res.status(500).json({ message: "Error!", error: String(error) }); |
| 126 | + } |
| 127 | + }; |
| 128 | +} |
| 129 | + |
| 130 | +module.exports = { makeBulkCreate }; |
0 commit comments