update export request
This commit is contained in:
78
backend/asset-export-sql-fixture.js
Normal file
78
backend/asset-export-sql-fixture.js
Normal file
@@ -0,0 +1,78 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const sql = require('mssql');
|
||||
const { ensureAssetExportDocumentSchema } = require('./asset-export-documents');
|
||||
const { ensureAssetExportRequestSchema } = require('./asset-export-requests');
|
||||
const { createExportTestApp } = require('./asset-export-test-fixture');
|
||||
|
||||
async function createExportSqlFixture() {
|
||||
require('dotenv').config();
|
||||
const database = `AccManagerExportTest_${randomUUID().replace(/-/g, '')}`;
|
||||
const config = { server: process.env.DB_SERVER || 'localhost', user: process.env.DB_USER || 'sa', password: process.env.DB_PASSWORD,
|
||||
database: 'master', options: { encrypt: /^(true|1)$/i.test(process.env.DB_ENCRYPT || 'false'),
|
||||
trustServerCertificate: !/^(false|0)$/i.test(process.env.DB_TRUST_CERTIFICATE || 'true'), useUTC: false },
|
||||
pool: { min: 0, max: 8, idleTimeoutMillis: 1000 }, connectionTimeout: 15000, requestTimeout: 20000 };
|
||||
if (process.env.DB_PORT) config.port = Number(process.env.DB_PORT);
|
||||
let admin, pool, server, created = false;
|
||||
const cleanup = async () => {
|
||||
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
if (pool) await pool.close();
|
||||
if (created) {
|
||||
if (!/^AccManagerExportTest_[0-9a-f]{32}$/.test(database)) throw new Error('Unsafe test database name');
|
||||
await admin.request().query(`ALTER DATABASE [${database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [${database}];`);
|
||||
}
|
||||
if (admin) await admin.close();
|
||||
};
|
||||
try {
|
||||
admin = await new sql.ConnectionPool(config).connect();
|
||||
await admin.request().query(`CREATE DATABASE [${database}]`); created = true;
|
||||
pool = await new sql.ConnectionPool({ ...config, database }).connect();
|
||||
await pool.request().batch(`
|
||||
CREATE TABLE dbo.Users (UserId INT PRIMARY KEY, Username NVARCHAR(100), FullName NVARCHAR(100));
|
||||
INSERT dbo.Users VALUES (1, 'an', N'Nguyễn An'), (2, 'binh', N'Trần Bình'), (3, 'manager', N'Quản lý kho');
|
||||
CREATE TABLE dbo.AssetInventory (
|
||||
AssetId INT PRIMARY KEY, AssetCode NVARCHAR(100), AssetName NVARCHAR(255), Model NVARCHAR(255), SerialNumber NVARCHAR(255),
|
||||
Quantity INT, ImportInPeriod INT, ExportInPeriod INT, EndingBalance INT, NewQuantity INT, UsedQuantity INT,
|
||||
Unit NVARCHAR(50), Department NVARCHAR(100), Project NVARCHAR(150), Location NVARCHAR(150), Custodian NVARCHAR(100),
|
||||
Borrower NVARCHAR(255), ProjectAllocations NVARCHAR(MAX), ExportedBy NVARCHAR(100), Status NVARCHAR(50), Notes NVARCHAR(MAX),
|
||||
PurchaseDate DATE NULL, PurchasePrice DECIMAL(18,2) NULL, CreatedBy INT NULL,
|
||||
IsArchived BIT NOT NULL DEFAULT 0, ArchivedDate DATETIME NULL, CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
|
||||
UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
|
||||
);
|
||||
INSERT dbo.AssetInventory (AssetId, AssetCode, AssetName, Model, Quantity, ImportInPeriod, ExportInPeriod, EndingBalance, NewQuantity, UsedQuantity, Unit, Custodian, Borrower, ProjectAllocations, Status)
|
||||
VALUES (1, 'TS-001', N'Máy khoan', 'MK-01', 10, 0, 0, 10, 6, 4, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
|
||||
(2, 'TS-002', N'Đồng hồ', 'DH-01', 5, 0, 0, 5, 5, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock'),
|
||||
(3, 'TS-003', N'Động cơ', 'DC-01', 4, 0, 0, 4, 4, 0, N'cái', N'Quản lý kho', NULL, '[]', 'in_stock');
|
||||
CREATE TABLE dbo.AssetExportHistory (
|
||||
ExportHistoryId INT IDENTITY PRIMARY KEY, AssetId INT, AssetCode NVARCHAR(100), AssetName NVARCHAR(255),
|
||||
ExportQuantity INT, ProjectName NVARCHAR(150), CustodianName NVARCHAR(100), ExportedByName NVARCHAR(100),
|
||||
ExportNote NVARCHAR(1000), CreatedBy INT, ExportedDate DATETIME,
|
||||
CreatedDate DATETIME NOT NULL DEFAULT GETDATE(), UpdatedDate DATETIME NOT NULL DEFAULT GETDATE()
|
||||
);
|
||||
CREATE TABLE dbo.AssetBorrowRequests (
|
||||
BorrowId INT IDENTITY PRIMARY KEY, AssetId INT, RequestType NVARCHAR(20) DEFAULT 'borrow', RequestStatus NVARCHAR(20) DEFAULT 'pending',
|
||||
BorrowerName NVARCHAR(100), BorrowQuantity INT, ReturnedQuantity INT DEFAULT 0, Unit NVARCHAR(50), BorrowDate DATE DEFAULT GETDATE(),
|
||||
RequestNote NVARCHAR(500), RejectReason NVARCHAR(1000), CreatedBy INT, ProcessedBy INT, ProcessedByName NVARCHAR(100),
|
||||
ProcessedDate DATETIME, CreatedDate DATETIME DEFAULT GETDATE(), UpdatedDate DATETIME DEFAULT GETDATE()
|
||||
);
|
||||
CREATE TABLE dbo.AssetBorrowRequestLinks (LinkId INT IDENTITY PRIMARY KEY, BorrowId INT, ReturnId INT, Quantity INT,
|
||||
CreatedDate DATETIME DEFAULT GETDATE());
|
||||
`);
|
||||
await ensureAssetExportDocumentSchema(pool);
|
||||
await ensureAssetExportRequestSchema(pool);
|
||||
await ensureAssetExportRequestSchema(pool);
|
||||
const { app } = createExportTestApp(pool);
|
||||
server = app.listen(0, '127.0.0.1');
|
||||
await new Promise(resolve => server.once('listening', resolve));
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
const request = async (suffix, { user = 1, role = 'user', method = 'GET', body } = {}) => {
|
||||
const response = await fetch(`${origin}/api${suffix}`, { method, headers: {
|
||||
'x-test-user': String(user), 'x-test-role': role, ...(body === undefined ? {} : { 'Content-Type': 'application/json' })
|
||||
}, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
if (response.headers.get('content-type')?.includes('application/json')) return { status: response.status, ...(await response.json()) };
|
||||
return { status: response.status, buffer: Buffer.from(await response.arrayBuffer()) };
|
||||
};
|
||||
return { pool, app, origin, request, cleanup };
|
||||
} catch (err) { await cleanup(); throw err; }
|
||||
}
|
||||
|
||||
module.exports = { createExportSqlFixture };
|
||||
Reference in New Issue
Block a user