61 lines
1.5 KiB
JavaScript
61 lines
1.5 KiB
JavaScript
const prisma = require('../../config/prisma');
|
|
const ApiError = require('../../utils/ApiError');
|
|
|
|
const SOFT_DELETE_TABLES = new Set([
|
|
'vendors',
|
|
'locations',
|
|
'departments',
|
|
'users',
|
|
'purchase_orders',
|
|
'grn',
|
|
'grn_items',
|
|
'asset_categories',
|
|
]);
|
|
|
|
const toDateOnly = (value) => {
|
|
if (!value) return null;
|
|
const date = new Date(value);
|
|
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
|
};
|
|
|
|
const assertReference = async (table, id, label, { requireActive = true } = {}) => {
|
|
if (!id) return null;
|
|
const row = await prisma[table].findFirst({
|
|
where: {
|
|
id: BigInt(id),
|
|
...(SOFT_DELETE_TABLES.has(table) ? { deleted_at: null } : {}),
|
|
},
|
|
});
|
|
if (!row) throw new ApiError(422, `Invalid ${label}`);
|
|
if (requireActive && row.is_active === false) throw new ApiError(422, `${label} is inactive`);
|
|
return row;
|
|
};
|
|
|
|
const getAssetOrThrow = async (id) => {
|
|
const asset = await prisma.assets.findFirst({
|
|
where: { id: BigInt(id), deleted_at: null },
|
|
});
|
|
if (!asset) throw new ApiError(404, 'Asset not found');
|
|
return asset;
|
|
};
|
|
|
|
const deactivateOtherActive = async (tx, table, assetId, excludeId = null) => {
|
|
await tx[table].updateMany({
|
|
where: {
|
|
asset_id: BigInt(assetId),
|
|
is_active: true,
|
|
deleted_at: null,
|
|
...(excludeId ? { id: { not: BigInt(excludeId) } } : {}),
|
|
},
|
|
data: { is_active: false },
|
|
});
|
|
};
|
|
|
|
module.exports = {
|
|
toDateOnly,
|
|
assertReference,
|
|
getAssetOrThrow,
|
|
deactivateOtherActive,
|
|
SOFT_DELETE_TABLES,
|
|
};
|