187 lines
13 KiB
JavaScript
187 lines
13 KiB
JavaScript
const express = require('express');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
|
|
const MAX_LINES = 500;
|
|
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
|
|
function positiveId(value) {
|
|
if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value)) || Number(value) < 1 || Number(value) > 2147483647) {
|
|
throw fail('Mã dữ liệu không hợp lệ');
|
|
}
|
|
return Number(value);
|
|
}
|
|
function textField(value, max, label, required = false) {
|
|
if (typeof value !== 'string' || value.trim().length > max || (required && !value.trim())) {
|
|
throw fail(`${label} ${required ? 'không được trống và ' : ''}tối đa ${max} ký tự`);
|
|
}
|
|
return value.trim();
|
|
}
|
|
function quantity(value, unit) {
|
|
if (!/^\d+(\.\d{1,4})?$/.test(String(value)) || !Number.isFinite(Number(value)) || Number(value) <= 0 || Number(value) > 100000) {
|
|
throw fail('Số lượng phải lớn hơn 0, tối đa 100.000 và không quá 4 chữ số thập phân');
|
|
}
|
|
const fractional = /^(m|m2|m²|m3|m³|mét|met|kg|g|gam|l|lít|lit|ml|mm|cm|tấn|tan)$/i.test(String(unit).trim());
|
|
if (String(unit).trim() && !fractional && !Number.isInteger(Number(value))) throw fail(`Đơn vị ${unit} yêu cầu số lượng nguyên`);
|
|
return Number(value);
|
|
}
|
|
function normalizeLines(input) {
|
|
if (!Array.isArray(input) || input.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
|
|
return input.map((line, index) => {
|
|
if (!line || typeof line !== 'object' || Array.isArray(line)) throw fail(`Vật tư dòng ${index + 1} không hợp lệ`);
|
|
const unit = textField(line.unit ?? '', 50, 'Đơn vị');
|
|
return { SourceType: 'manual', SourceId: null,
|
|
Name: textField(line.name, 255, 'Tên vật tư', true),
|
|
Code: textField(line.code ?? '', 100, 'Mã vật tư'), Model: textField(line.model ?? '', 255, 'Model vật tư'),
|
|
Unit: unit, GroupName: textField(line.groupName ?? '', 100, 'Cụm lắp ráp'),
|
|
Position: textField(line.position ?? '', 150, 'Vị trí lắp'), Quantity: quantity(line.quantity ?? 1, unit),
|
|
SourceInfo: textField(line.sourceInfo ?? '', 1000, 'Nguồn'),
|
|
Notes: textField(line.notes ?? '', 500, 'Ghi chú'), SortOrder: index };
|
|
});
|
|
}
|
|
async function ensureRobotBomSchema(pool) {
|
|
await pool.request().batch(fs.readFileSync(path.join(__dirname, 'robot-bom-schema.sql'), 'utf8'));
|
|
}
|
|
function createRobotBomRouter({ getPool, sql, requireManage, sendInternalError }) {
|
|
const router = express.Router();
|
|
const handle = fn => async (req, res) => {
|
|
try { req.body ??= {}; await fn(req, res); }
|
|
catch (error) {
|
|
if (error.status) return res.status(error.status).json({ success: false, message: error.message });
|
|
if ([2601, 2627, 1205].includes(error.number)) return res.status(409).json({ success: false, message: 'Dữ liệu vừa được thay đổi. Hãy tải lại BOM rồi thử lại.' });
|
|
return sendInternalError(res, error, 'Không thể xử lý BOM robot');
|
|
}
|
|
};
|
|
const inTransaction = async fn => {
|
|
const transaction = new sql.Transaction(getPool());
|
|
await transaction.begin();
|
|
try { const result = await fn(() => new sql.Request(transaction)); await transaction.commit(); return result; }
|
|
catch (error) { try { await transaction.rollback(); } catch {} throw error; }
|
|
};
|
|
const loadHeader = async (request, id, lock = false) => {
|
|
const result = await request.input('id', sql.Int, positiveId(id)).query(`
|
|
SELECT * FROM dbo.RobotBomRevisions ${lock ? 'WITH (UPDLOCK, HOLDLOCK)' : ''} WHERE BomId = @id`);
|
|
if (!result.recordset[0]) throw fail('Không tìm thấy phiên bản BOM', 404);
|
|
return result.recordset[0];
|
|
};
|
|
const checkDraft = (header, version) => {
|
|
if (header.Status !== 'draft') throw fail('BOM đã phát hành. Hãy sao chép thành phiên bản nháp mới để chỉnh sửa.', 409);
|
|
if (header.LockVersion !== positiveId(version)) throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi lưu.', 409);
|
|
};
|
|
const readLines = async (request, id) => (await request.input('id', sql.Int, id)
|
|
.query('SELECT * FROM dbo.RobotBomLines WHERE BomId = @id ORDER BY SortOrder, LineId')).recordset;
|
|
async function insertLines(request, id, lines) {
|
|
for (const line of lines) {
|
|
await request().input('bomId', sql.Int, id)
|
|
.input('sourceType', sql.VarChar(10), line.SourceType).input('sourceId', sql.Int, line.SourceId)
|
|
.input('code', sql.NVarChar(100), line.Code).input('name', sql.NVarChar(255), line.Name)
|
|
.input('model', sql.NVarChar(255), line.Model).input('unit', sql.NVarChar(50), line.Unit)
|
|
.input('groupName', sql.NVarChar(100), line.GroupName).input('position', sql.NVarChar(150), line.Position)
|
|
.input('quantity', sql.Decimal(18, 4), line.Quantity).input('notes', sql.NVarChar(500), line.Notes)
|
|
.input('sourceInfo', sql.NVarChar(1000), line.SourceInfo || '')
|
|
.input('sortOrder', sql.Int, line.SortOrder).query(`
|
|
INSERT dbo.RobotBomLines (BomId, SourceType, SourceId, Code, Name, Model, Unit, GroupName, Position, Quantity, Notes, SourceInfo, SortOrder)
|
|
VALUES (@bomId, @sourceType, @sourceId, @code, @name, @model, @unit, @groupName, @position, @quantity, @notes, @sourceInfo, @sortOrder)`);
|
|
}
|
|
}
|
|
router.get('/models', handle(async (_req, res) => {
|
|
const result = await getPool().request().query(`
|
|
WITH ModelCatalog AS (
|
|
SELECT Model, TypeId FROM dbo.Robots
|
|
UNION SELECT RobotModel, RobotTypeId FROM dbo.RobotBomRevisions
|
|
)
|
|
SELECT MIN(r.RobotId) AS RobotId, m.Model, m.TypeId, t.Name AS Type,
|
|
COALESCE(MIN(r.Name), N'BOM đã lưu theo model') AS Name
|
|
FROM ModelCatalog m JOIN dbo.RobotTypes t ON t.TypeId = m.TypeId
|
|
LEFT JOIN dbo.Robots r ON r.Model = m.Model AND r.TypeId = m.TypeId
|
|
GROUP BY m.Model, m.TypeId, t.Name ORDER BY m.Model, t.Name`);
|
|
res.json({ success: true, data: result.recordset });
|
|
}));
|
|
router.get('/catalog', handle(async (_req, res) => {
|
|
// This picker copies descriptions only. All quantities belong to the BOM.
|
|
const result = await getPool().request().query(`
|
|
SELECT AssetId AS Id, AssetCode AS Code, AssetName AS Name,
|
|
ISNULL(Model, '') AS Model, ISNULL(Unit, '') AS Unit
|
|
FROM dbo.AssetInventory WHERE IsArchived = 0 ORDER BY AssetName, AssetCode`);
|
|
res.json({ success: true, data: result.recordset });
|
|
}));
|
|
router.get('/', handle(async (req, res) => {
|
|
const model = textField(req.query.model, 255, 'Model robot', true);
|
|
const result = await getPool().request().input('model', sql.NVarChar(255), model)
|
|
.input('typeId', sql.Int, positiveId(req.query.typeId)).query(`
|
|
SELECT b.*, (SELECT COUNT(*) FROM dbo.RobotBomLines l WHERE l.BomId = b.BomId) AS LineCount
|
|
FROM dbo.RobotBomRevisions b WHERE RobotModel = @model AND RobotTypeId = @typeId ORDER BY Revision DESC`);
|
|
res.json({ success: true, data: result.recordset });
|
|
}));
|
|
router.get('/:id', handle(async (req, res) => {
|
|
const header = await loadHeader(getPool().request(), req.params.id);
|
|
res.json({ success: true, data: { ...header, Lines: await readLines(getPool().request(), header.BomId) } });
|
|
}));
|
|
router.post('/', requireManage, handle(async (req, res) => {
|
|
const copyFrom = req.body.copyFromId == null ? null : positiveId(req.body.copyFromId);
|
|
const robotId = req.body.robotId == null && copyFrom ? null : positiveId(req.body.robotId);
|
|
const header = await inTransaction(async request => {
|
|
const source = copyFrom ? await loadHeader(request(), copyFrom, true) : null;
|
|
const robot = robotId == null ? { Model: source.RobotModel, TypeId: source.RobotTypeId }
|
|
: (await request().input('robotId', sql.Int, robotId)
|
|
.query('SELECT Model, TypeId FROM dbo.Robots WITH (HOLDLOCK) WHERE RobotId = @robotId')).recordset[0];
|
|
if (!robot) throw fail('Robot không còn trong danh mục. Hãy tải lại danh sách.', 404);
|
|
const revision = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
|
|
.query(`SELECT ISNULL(MAX(Revision), 0) + 1 AS NextRevision FROM dbo.RobotBomRevisions WITH (UPDLOCK, HOLDLOCK)
|
|
WHERE RobotModel = @model AND RobotTypeId = @typeId`)).recordset[0].NextRevision;
|
|
const inserted = (await request().input('model', sql.NVarChar(255), robot.Model).input('typeId', sql.Int, robot.TypeId)
|
|
.input('revision', sql.Int, revision).input('userId', sql.Int, req.user.UserId)
|
|
.query(`INSERT dbo.RobotBomRevisions (RobotModel, RobotTypeId, Revision, CreatedBy)
|
|
OUTPUT INSERTED.* VALUES (@model, @typeId, @revision, @userId)`)).recordset[0];
|
|
if (copyFrom) {
|
|
await insertLines(request, inserted.BomId, await readLines(request(), copyFrom));
|
|
}
|
|
return inserted;
|
|
});
|
|
res.status(201).json({ success: true, data: header, message: 'Đã tạo phiên bản BOM nháp' });
|
|
}));
|
|
router.put('/:id', requireManage, handle(async (req, res) => {
|
|
const id = positiveId(req.params.id);
|
|
if (!Array.isArray(req.body.lines) || req.body.lines.length > MAX_LINES) throw fail(`BOM tối đa ${MAX_LINES} dòng vật tư`);
|
|
const saved = await inTransaction(async request => {
|
|
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
|
|
const lines = normalizeLines(req.body.lines);
|
|
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
|
|
await insertLines(request, id, lines);
|
|
const updated = (await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions
|
|
SET LockVersion = LockVersion + 1, UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME())
|
|
OUTPUT INSERTED.UpdatedDate WHERE BomId = @id`)).recordset[0];
|
|
return { BomId: id, LockVersion: header.LockVersion + 1, UpdatedDate: updated.UpdatedDate, Lines: lines };
|
|
});
|
|
res.json({ success: true, data: saved, message: 'Đã lưu BOM nháp' });
|
|
}));
|
|
router.delete('/:id', requireManage, handle(async (req, res) => {
|
|
const id = positiveId(req.params.id);
|
|
await inTransaction(async request => {
|
|
const header = await loadHeader(request(), id, true);
|
|
if (header.LockVersion !== positiveId(req.body.lockVersion)) {
|
|
throw fail('BOM đã được người khác thay đổi. Hãy tải lại trước khi xóa.', 409);
|
|
}
|
|
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomLines WHERE BomId = @id');
|
|
await request().input('id', sql.Int, id).query('DELETE FROM dbo.RobotBomRevisions WHERE BomId = @id');
|
|
});
|
|
res.json({ success: true, message: 'Đã xóa phiên bản BOM' });
|
|
}));
|
|
router.post('/:id/publish', requireManage, handle(async (req, res) => {
|
|
const id = positiveId(req.params.id);
|
|
await inTransaction(async request => {
|
|
const header = await loadHeader(request(), id, true); checkDraft(header, req.body.lockVersion);
|
|
const lines = await readLines(request(), id);
|
|
if (!lines.length) throw fail('BOM cần có ít nhất một vật tư trước khi phát hành');
|
|
normalizeLines(lines.map(line => ({ name: line.Name, unit: line.Unit, quantity: line.Quantity,
|
|
code: line.Code, model: line.Model, groupName: line.GroupName, position: line.Position, notes: line.Notes,
|
|
sourceInfo: line.SourceInfo || '' })));
|
|
await request().input('id', sql.Int, id).query(`UPDATE dbo.RobotBomRevisions SET Status = 'released',
|
|
LockVersion = LockVersion + 1, ReleasedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()),
|
|
UpdatedDate = DATEADD(HOUR, 7, SYSUTCDATETIME()) WHERE BomId = @id`);
|
|
});
|
|
res.json({ success: true, message: 'Đã phát hành BOM. Có thể sao chép thành phiên bản mới khi cần chỉnh sửa.' });
|
|
}));
|
|
return router;
|
|
}
|
|
module.exports = { ensureRobotBomSchema, createRobotBomRouter, normalizeLines, quantity };
|