2026-04-27 16:09:26 +08:00

408 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const SettingExpressService = require('../../../../../app/service/systems/setting/express');
function buildRecord(row, calls) {
return {
...row,
async update(updates) {
calls.updatePayload = {
id: Number(this.id),
updates: {
...updates,
},
};
Object.assign(this, updates);
return this;
},
get() {
return { ...this };
},
};
}
function createHarness(options = {}) {
const calls = {
systemExpressListCalls: 0,
findAndCountAllCalls: 0,
findAllCalls: 0,
findOneCalls: [],
createPayload: null,
updatePayload: null,
bulkUpdatePayload: null,
transactionCalls: 0,
cacheDeletes: [],
};
const systemExpressList = options.systemExpressList || [
{ code: 'SF', name: '顺丰' },
{ code: 'YTO', name: '圆通' },
];
const settingRows = options.settingRows || [
{ id: 11, warehouse_id: 100000, code: 'SF-001', name: '顺丰设置', express_code: 'SF', deleted_at: null },
{ id: 12, warehouse_id: 100000, code: 'YTO-001', name: '圆通设置', express_code: 'YTO', deleted_at: null },
];
const expressInterfaceRows = options.expressInterfaceRows || [];
const ctx = {
user: {
store_id: options.storeId || 100000,
},
where: options.where || {},
whereParsed: options.whereParsed || null,
app: {
Sequelize: {
Op,
},
async delCacheAsync(key) {
calls.cacheDeletes.push(key);
},
},
model: {
async transaction(handler) {
calls.transactionCalls += 1;
const transaction = {
commit() {},
rollback() {},
};
if (typeof handler === 'function') {
return await handler(transaction);
}
return transaction;
},
ExpressSetting: {
async findAndCountAll(query) {
calls.findAndCountAllCalls += 1;
calls.findAndCountAllQuery = query;
return {
rows: options.rows || settingRows,
count: options.count !== undefined ? options.count : (options.rows || settingRows).length,
};
},
async findOne(query) {
calls.findOneCalls.push(query);
const where = query.where || {};
const excludedId = where.id && where.id[Op.ne] ? Number(where.id[Op.ne]) : null;
const found = (options.settingRows || settingRows).find(row => {
const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id);
const isExcluded = excludedId && Number(row.id) === excludedId;
if (Object.prototype.hasOwnProperty.call(where, 'deleted_at') && where.deleted_at === null && row.deleted_at !== null) {
return false;
}
if (Object.prototype.hasOwnProperty.call(where, 'id') && !Object.prototype.hasOwnProperty.call(where, 'code')) {
return sameWarehouse && Number(row.id) === Number(where.id) && !isExcluded;
}
if (Object.prototype.hasOwnProperty.call(where, 'code')) {
const sameCode = String(row.code || '') === String(where.code || '');
return sameWarehouse && sameCode && !isExcluded;
}
return sameWarehouse && !isExcluded;
});
return found ? buildRecord({ ...found }, calls) : null;
},
async findAll(query) {
calls.findAllCalls += 1;
calls.findAllQuery = query;
const where = query.where || {};
const ids = where.id && where.id[Op.in]
? where.id[Op.in].map(item => Number(item))
: [];
if (Object.prototype.hasOwnProperty.call(where, 'express_code')) {
return expressInterfaceRows.filter(row => {
const sameWarehouse = Number(row.warehouse_id) === Number(where.warehouse_id);
const sameCode = where.express_code && where.express_code[Op.in]
? where.express_code[Op.in].includes(row.express_code)
: String(row.express_code || '') === String(where.express_code || '');
return sameWarehouse && sameCode;
}).map(row => ({ ...row }));
}
return (options.settingRows || settingRows)
.filter(row => Number(row.warehouse_id) === Number(where.warehouse_id) && ids.includes(Number(row.id)))
.map(row => ({ ...row }));
},
async update(payload, query) {
calls.bulkUpdatePayload = {
payload: {
...payload,
},
query: {
...query,
where: {
...(query && query.where ? query.where : {}),
},
},
};
return [ options.settingRows ? options.settingRows.length : settingRows.length ];
},
async create(payload) {
calls.createPayload = {
...payload,
};
const created = buildRecord({
id: options.createdId || 99,
...payload,
}, calls);
return created;
},
},
ExpressInterface: {
async findAll(query) {
calls.expressInterfaceFindAllQuery = query;
const where = query.where || {};
const codes = where.express_code && where.express_code[Op.in]
? where.express_code[Op.in].map(code => String(code || '').trim())
: [];
return (expressInterfaceRows || [])
.filter(row => Number(row.warehouse_id) === Number(where.warehouse_id) && codes.includes(String(row.express_code || '').trim()))
.map(row => ({ ...row }));
},
},
},
service: {
systems: {
express: {
async getSystemExpressList() {
calls.systemExpressListCalls += 1;
return systemExpressList;
},
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
};
return {
ctx,
calls,
};
}
describe('test/app/service/systems/setting/express.test.js', () => {
it('should list mapped express settings with pagination and system express names', async () => {
const { ctx, calls } = createHarness({
where: {
quickWhere: '设置',
},
whereParsed: {
dynamicConditions: [],
rawConditionsByField: {
quickWhere: {
value: '设置',
},
},
},
rows: [
{ id: 12, warehouse_id: 100000, code: 'YTO-001', name: '圆通设置', express_code: 'YTO' },
],
count: 1,
});
const service = new SettingExpressService(ctx);
const result = await service.list({
page: 2,
page_size: 1,
where: {
quickWhere: '设置',
},
});
assert.equal(calls.findAndCountAllCalls, 1);
assert.equal(calls.systemExpressListCalls, 1);
assert.equal(calls.findAndCountAllQuery.offset, 1);
assert.equal(calls.findAndCountAllQuery.limit, 1);
assert.equal(calls.findAndCountAllQuery.where[Op.and][0].warehouse_id, 100000);
assert.equal(calls.findAndCountAllQuery.where[Op.and].some(item => Object.prototype.hasOwnProperty.call(item, 'deleted_at') && item.deleted_at === null), true);
assert.equal(result.code, 200);
assert.equal(result.data.total, 1);
assert.equal(result.data.page, 2);
assert.equal(result.data.page_size, 1);
assert.deepEqual(result.data.list, [
{
id: 12,
warehouse_id: 100000,
code: 'YTO-001',
name: '圆通设置',
express_code: 'YTO',
express_name: '圆通',
express_label: '圆通',
},
]);
});
it('should prefer pagination object over legacy page fields', async () => {
const { ctx, calls } = createHarness({
whereParsed: {
dynamicConditions: [],
rawConditionsByField: {},
},
});
const service = new SettingExpressService(ctx);
const result = await service.list({
pagination: {
page: 3,
pageSize: 2,
},
page: 1,
page_size: 10,
where: {},
});
assert.equal(calls.findAndCountAllCalls, 1);
assert.equal(calls.findAndCountAllQuery.offset, 4);
assert.equal(calls.findAndCountAllQuery.limit, 2);
assert.equal(result.data.page, 3);
assert.equal(result.data.page_size, 2);
});
it('should load system express base list only', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const result = await service.listBase();
assert.equal(calls.systemExpressListCalls, 1);
assert.deepEqual(result, {
code: 200,
data: [
{ code: 'SF', name: '顺丰' },
{ code: 'YTO', name: '圆通' },
],
});
});
it('should mark code as occupied and exclude current record when checking uniqueness', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const occupied = await service.checkCodeUnique({
code: 'SF-001',
});
const available = await service.checkCodeUnique({
id: 11,
code: 'SF-001',
});
assert.equal(calls.findOneCalls.length, 2);
assert.equal(occupied.data.isUnique, false);
assert.equal(occupied.data.message, '快递编码已被当前仓库使用');
assert.equal(available.data.isUnique, true);
});
it('should create a mapping after validating system express and code uniqueness', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const result = await service.create({
code: 'jd-001',
name: '京东设置',
express_code: 'SF',
});
assert.equal(calls.systemExpressListCalls, 1);
assert.equal(calls.findOneCalls.length, 1);
assert.equal(calls.createPayload.warehouse_id, 100000);
assert.equal(calls.createPayload.code, 'JD-001'.toUpperCase());
assert.equal(calls.createPayload.express_code, 'SF');
assert.equal(calls.cacheDeletes.includes('express:list:100000'), true);
assert.equal(result.data.code, 'JD-001'.toUpperCase());
assert.equal(result.data.express_name, '顺丰');
});
it('should reject create when system express code does not exist', async () => {
const { ctx } = createHarness();
const service = new SettingExpressService(ctx);
await assert.rejects(async () => {
await service.create({
code: 'SF-NEW',
name: '顺丰新增',
express_code: 'NOT_EXISTS',
});
}, /系统快递编码不存在/);
});
it('should update a mapping and allow the same code on the current record', async () => {
const { ctx, calls } = createHarness();
const service = new SettingExpressService(ctx);
const result = await service.update({
id: 11,
code: 'SF-001',
name: '顺丰新设置',
express_code: 'SF',
});
assert.equal(calls.findOneCalls.length >= 1, true);
assert.equal(calls.updatePayload.id, 11);
assert.equal(calls.updatePayload.updates.code, 'SF-001');
assert.equal(calls.updatePayload.updates.name, '顺丰新设置');
assert.equal(calls.updatePayload.updates.express_code, 'SF');
assert.equal(calls.cacheDeletes.includes('express:list:100000'), true);
assert.equal(result.data.code, 'SF-001');
assert.equal(result.data.name, '顺丰新设置');
});
it('should batch soft delete settings and keep already deleted ids in response', async () => {
const { ctx, calls } = createHarness({
settingRows: [
{ id: 11, warehouse_id: 100000, code: 'SF-001', name: '顺丰设置', express_code: 'SF', deleted_at: null },
{ id: 12, warehouse_id: 100000, code: 'YTO-001', name: '圆通设置', express_code: 'YTO', deleted_at: new Date('2026-04-17T00:00:00.000Z') },
],
});
const service = new SettingExpressService(ctx);
const result = await service.delete({
ids: [ 11, 12 ],
});
assert.equal(calls.findAllCalls, 1);
assert.equal(calls.bulkUpdatePayload.payload.deleted_at instanceof Date, true);
assert.equal(calls.bulkUpdatePayload.query.where.deleted_at, null);
assert.equal(calls.transactionCalls, 1);
assert.equal(calls.cacheDeletes.includes('express:list:100000'), true);
assert.deepEqual(result.data, {
ids: [ 11, 12 ],
deleted_ids: [ 11 ],
already_deleted_ids: [ 12 ],
status: 'deleted',
});
});
it('should reject batch delete when any target code is referenced by express interface', async () => {
const { ctx, calls } = createHarness({
expressInterfaceRows: [
{ id: 201, warehouse_id: 100000, express_code: 'SF-001' },
],
});
const service = new SettingExpressService(ctx);
await assert.rejects(async () => {
await service.delete({
ids: [ 11 ],
});
}, /存在快递接口引用的快递编码,无法删除:SF-001/);
assert.equal(calls.bulkUpdatePayload, null);
assert.equal(calls.cacheDeletes.length, 0);
});
});