'use strict'; const assert = require('node:assert/strict'); const OperationLogService = require('../../../../app/service/systems/operation_log'); /** * 创建 operation_log 批量写入测试桩。 * * @param {Object} [options={}] 测试选项。 * @return {{ service: OperationLogService, calls: Object }} 服务实例与调用记录。 */ function createBatchHarness(options = {}) { const calls = { createArgs: null, bulkCreateArgs: null, createCount: 0, }; const operationLogModel = { async create(values, createOptions = {}) { calls.createCount += 1; calls.createArgs = { values, createOptions }; return { id: 1, ...values, }; }, async bulkCreate(rows, bulkCreateOptions = {}) { calls.bulkCreateArgs = { rows, bulkCreateOptions }; if (options.forceBulkError) { throw new Error('bulk create failed'); } return rows.map((row, index) => ({ id: index + 1, ...row, })); }, }; const app = { config: {}, logger: { info() {}, warn() {}, error() {}, }, }; const ctx = { app, user: { platform_code: 'web', }, model: { OperationLog: operationLogModel, }, logger: { info() {}, warn() {}, error() {}, }, }; app.model = ctx.model; return { service: new OperationLogService(ctx), calls, }; } describe('test/app/service/systems/operation_log.batchCreate.test.js', () => { it('should bulk create operation logs and aggregate payloads in one call', async () => { const { service, calls } = createBatchHarness(); const result = await service.createOperationLogs([ { businessType: 'order', businessId: 101, operationCode: 'ORDER_CREATE', operator: { id: 1, name: '测试员' }, extras: { warehouseId: 100000, message: '订单创建' }, }, { businessType: 'order', businessId: 102, operationCode: 'ORDER_CREATE', operator: { id: 1, name: '测试员' }, extras: { warehouseId: 100000, message: '订单创建2' }, }, ]); assert.equal(Array.isArray(result), true); assert.equal(result.length, 2); assert.ok(calls.bulkCreateArgs); assert.equal(calls.bulkCreateArgs.rows.length, 2); assert.equal(calls.bulkCreateArgs.rows[0].business_id, '101'); assert.equal(calls.bulkCreateArgs.rows[1].business_id, '102'); assert.equal(calls.bulkCreateArgs.rows[0].platform_code, 'web'); assert.equal(calls.createCount, 0); }); it('should pass transaction to both single create and bulk create', async () => { const { service, calls } = createBatchHarness(); const transaction = { id: 'tx-001' }; await service.createOperationLog({ businessType: 'order', businessId: 201, operationCode: 'ORDER_UPDATE', operator: { id: 9, name: '事务用户' }, extras: { warehouseId: 100000 }, transaction, }); assert.equal(calls.createArgs.createOptions.transaction, transaction); await service.createOperationLogs([ { businessType: 'order', businessId: 202, operationCode: 'ORDER_UPDATE', operator: { id: 9, name: '事务用户' }, extras: { warehouseId: 100000 }, }, ], { transaction, }); assert.equal(calls.bulkCreateArgs.bulkCreateOptions.transaction, transaction); }); });