- 下单即建分拣/配送,待取货/散客/独立进货守卫 - 30/40/45 直接发车/分拣,入库与分拣二选一 - 分拣完成补上游、清理 pending 验收,直接配送补分拣 - 库存抵扣/计划/实收 FIFO,软扣部分扣减,并发出库串行 - 结束配送不被库存不足/待入库残留阻断 - 待验收并发唯一索引(含 name-only),finalize 共享连接修复 - 售后自动绑定订单明细、客户取货/采购并发修复 - 仓库表格自适应、弹窗滚动锁闪烁修复
337 lines
16 KiB
TypeScript
337 lines
16 KiB
TypeScript
import { readFileSync } from 'node:fs';
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
import type { TenantContext } from '../src/services/tenantScope';
|
||
|
||
const mocks = vi.hoisted(() => ({
|
||
query: vi.fn(),
|
||
pendingOrders: vi.fn(),
|
||
branchPurchase: vi.fn(),
|
||
adminPrep: vi.fn(),
|
||
processing: vi.fn(),
|
||
actualQty: vi.fn(),
|
||
bids: vi.fn(),
|
||
myPicking: vi.fn(),
|
||
driverDelivery: vi.fn(),
|
||
}));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => mocks.query(...args) },
|
||
query: (...args: unknown[]) => mocks.query(...args),
|
||
getRawPoolQuery: () => (...args: unknown[]) => mocks.query(...args),
|
||
}));
|
||
vi.mock('../src/services/orderManagementQueryService', () => ({
|
||
countPendingPickingOrders: (...args: unknown[]) => mocks.pendingOrders(...args),
|
||
}));
|
||
vi.mock('../src/services/purchaseOrderQueryService', () => ({
|
||
countPendingBranchPurchaseTasks: (...args: unknown[]) => mocks.branchPurchase(...args),
|
||
}));
|
||
vi.mock('../src/services/supplierPreparationStatusService', () => ({
|
||
countAdminPendingPreparationsToday: (...args: unknown[]) => mocks.adminPrep(...args),
|
||
}));
|
||
vi.mock('../src/services/inspectionQueryService', () => ({
|
||
MOBILE_INSPECTION_PENDING_SQL: 'i.inspection_time IS NULL',
|
||
}));
|
||
vi.mock('../src/services/processingTaskService', () => ({
|
||
countPendingProcessingTasks: (...args: unknown[]) => mocks.processing(...args),
|
||
}));
|
||
vi.mock('../src/services/mainSystemActualQtyInbox', () => ({
|
||
listActualQtyInbox: (...args: unknown[]) => mocks.actualQty(...args),
|
||
}));
|
||
vi.mock('../src/services/mainSystemBidQuotes', () => ({
|
||
listBidInvitations: (...args: unknown[]) => mocks.bids(...args),
|
||
}));
|
||
vi.mock('../src/services/pickingService', () => ({
|
||
countMyPendingPickingTasks: (...args: unknown[]) => mocks.myPicking(...args),
|
||
}));
|
||
vi.mock('../src/services/deliveryTaskQueryService', () => ({
|
||
countPendingDriverDeliveryTasks: (...args: unknown[]) => mocks.driverDelivery(...args),
|
||
}));
|
||
|
||
import {
|
||
clearNavBadgeCache,
|
||
getNavBadgeDays,
|
||
getNavBadges,
|
||
isNavBadgeAllowed,
|
||
NAV_BADGE_COUNTERS,
|
||
normalizeNavBadgeDays,
|
||
} from '../src/services/navBadgeService';
|
||
|
||
const ctx = (overrides: Partial<TenantContext> = {}): TenantContext => ({
|
||
userId: 'U1',
|
||
roles: ['admin'],
|
||
permissions: [
|
||
'order_manage',
|
||
'purchase_manage',
|
||
'preparation_manage',
|
||
'price_qty_review',
|
||
'bid_quote',
|
||
'inspection_manage',
|
||
'processing_manage',
|
||
'picking_manage',
|
||
'delivery_manage',
|
||
'aftersales_manage',
|
||
],
|
||
branchCode: 'BR002',
|
||
supplierCode: null,
|
||
purchaserCode: null,
|
||
isSuperAdmin: false,
|
||
isBranchAdmin: true,
|
||
isInternalStaff: true,
|
||
isSupplierAccount: false,
|
||
...overrides,
|
||
});
|
||
|
||
beforeEach(() => {
|
||
vi.clearAllMocks();
|
||
clearNavBadgeCache();
|
||
mocks.query.mockImplementation(async (sql: string) =>
|
||
String(sql).includes('self_purchase_stock_inbounds')
|
||
? { rows: [{ c: 0 }], rowCount: 1 }
|
||
: { rows: [{ c: 9 }], rowCount: 1 }
|
||
);
|
||
mocks.pendingOrders.mockResolvedValue(1);
|
||
mocks.branchPurchase.mockResolvedValue(2);
|
||
mocks.adminPrep.mockResolvedValue(3);
|
||
mocks.processing.mockResolvedValue(5);
|
||
mocks.actualQty.mockResolvedValue({ counts: { pending: 6 } });
|
||
mocks.bids.mockResolvedValue({ summary: { pending: 7 } });
|
||
mocks.myPicking.mockResolvedValue(8);
|
||
mocks.driverDelivery.mockResolvedValue(11);
|
||
});
|
||
|
||
describe('navBadgeService', () => {
|
||
it('权限过滤:只返回有权限的 key', async () => {
|
||
const data = await getNavBadges({ ctx: ctx({ roles: ['operator'], permissions: ['order_manage'] }), branchCode: 'BR002', userId: 'U1', scope: 'today' });
|
||
expect(data).toEqual({ 'orders-list': 1 });
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(1);
|
||
expect(mocks.branchPurchase).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('today/all:订单/采购/备货/加工切对应 count,其它 key 不变', async () => {
|
||
const today = await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U1', scope: 'today' });
|
||
expect(today['orders-list']).toBe(1);
|
||
expect(today['purchase-list']).toBe(2);
|
||
expect(today['purchase-preparations']).toBe(9);
|
||
expect(today['inspection-list']).toBe(9);
|
||
expect(today['inspection-processing']).toBe(5);
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(1);
|
||
expect(mocks.branchPurchase).toHaveBeenCalledWith('BR002', 'delivery_date');
|
||
expect(mocks.processing).toHaveBeenCalledWith('created_at');
|
||
|
||
clearNavBadgeCache();
|
||
const all = await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U1', scope: 'all' });
|
||
expect(all['orders-list']).toBe(9);
|
||
expect(all['purchase-list']).toBe(9);
|
||
expect(all['purchase-preparations']).toBe(9);
|
||
expect(all['inspection-processing']).toBe(9);
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(1); // 仅 today 那次
|
||
});
|
||
|
||
it('单项失败只缺该 key,其它照常', async () => {
|
||
mocks.pendingOrders.mockRejectedValue(new Error('boom'));
|
||
const data = await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U1', scope: 'today' });
|
||
expect(data['orders-list']).toBeUndefined();
|
||
expect(data['purchase-list']).toBe(2);
|
||
});
|
||
|
||
it('20 秒缓存:同用户/分公司/scope 只算一次', async () => {
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U1', scope: 'today' });
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U1', scope: 'today' });
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(1);
|
||
// 不同 scope 不共用
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U1', scope: 'all' });
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('缓存键包含权限/角色:同用户改权限不复用旧数据', async () => {
|
||
const user = ctx();
|
||
const adminData = await getNavBadges({ ctx: user, branchCode: 'BR002', userId: 'U1', scope: 'today' });
|
||
expect(adminData['purchase-list']).toBe(2);
|
||
const limited = await getNavBadges({
|
||
ctx: ctx({ roles: ['operator'], permissions: ['order_manage'] }),
|
||
branchCode: 'BR002',
|
||
userId: 'U1',
|
||
scope: 'today',
|
||
});
|
||
expect(limited['orders-list']).toBe(1);
|
||
expect(limited['purchase-list']).toBeUndefined();
|
||
});
|
||
|
||
it('inspection 只读 SQL:today 按配送日/建单日,all 不加日期;不调 countPendingInspectionsAll', async () => {
|
||
const src = readFileSync(new URL('../src/services/navBadgeService.ts', import.meta.url), 'utf8');
|
||
expect(src).not.toContain('import { countPendingInspectionsAll');
|
||
expect(src).not.toMatch(/await countPendingInspectionsAll/);
|
||
expect(src).toContain('inspection_time IS NULL');
|
||
expect(src).toContain("inspectionVisibleInListSql('i')");
|
||
// 先跑 today,再跑 all,确保两种 SQL 都出现
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U-today', scope: 'today' });
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U-all', scope: 'all' });
|
||
const calls = mocks.query.mock.calls.filter(([sql]) => String(sql).includes('FROM inspections'));
|
||
const todaySql = calls.map(([sql]) => String(sql)).find((sql) => sql.includes('delivery_date'));
|
||
const allSql = calls.map(([sql]) => String(sql)).find((sql) => !sql.includes('delivery_date'));
|
||
expect(todaySql).toBeTruthy();
|
||
expect(allSql).toBeTruthy();
|
||
});
|
||
|
||
it('ops = 售后待处理 + 异常待处理', async () => {
|
||
mocks.query.mockImplementation(async (sql: string) => {
|
||
if (String(sql).includes('after_sales')) return { rows: [{ c: 4 }], rowCount: 1 };
|
||
return { rows: [{ c: 9 }], rowCount: 1 };
|
||
});
|
||
const data = await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'U1', scope: 'today' });
|
||
expect(data.ops).toBe(13); // 售后 4 + 异常 9
|
||
const salesCall = mocks.query.mock.calls.find(([s]) => String(s).includes('after_sales'));
|
||
expect(String(salesCall?.[0] || '')).toContain('a.status IN (10, 20)');
|
||
expect(String(salesCall?.[0] || '')).toContain('delivery_date');
|
||
expect((salesCall?.[1] as unknown[])[0]).toBe('BR002');
|
||
expect(String(mocks.query.mock.calls.find(([s]) => String(s).includes('exception_tickets'))?.[0] || '')).toContain('ticket_status < 30');
|
||
});
|
||
|
||
it('nav_badge_days:默认 30、范围 1~365、非法回退;配置读取分支优先', async () => {
|
||
expect(normalizeNavBadgeDays(undefined)).toBe(30);
|
||
expect(normalizeNavBadgeDays(0)).toBe(30);
|
||
expect(normalizeNavBadgeDays(366)).toBe(30);
|
||
expect(normalizeNavBadgeDays('abc')).toBe(30);
|
||
expect(normalizeNavBadgeDays(1)).toBe(1);
|
||
expect(normalizeNavBadgeDays(365)).toBe(365);
|
||
|
||
mocks.query.mockImplementation(async (sql: string) => {
|
||
if (String(sql).includes("config_key = 'nav_badge_days'")) {
|
||
return { rows: [{ config_value: { days: 7 } }], rowCount: 1 };
|
||
}
|
||
return { rows: [{ c: 9 }], rowCount: 1 };
|
||
});
|
||
expect(await getNavBadgeDays('BR002')).toBe(7);
|
||
});
|
||
|
||
it('scope=days:统一滚动窗口 >= 今天-(N-1),缓存含 days', async () => {
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'D7', scope: 'days', days: 7 });
|
||
const sqls = mocks.query.mock.calls.map(([s]) => String(s));
|
||
const daySql = sqls.find((sql) => sql.includes('FROM orders o') && sql.includes('- 6'));
|
||
expect(daySql).toBeTruthy();
|
||
expect(daySql).toContain(')::date + 5)');
|
||
|
||
const before = mocks.query.mock.calls.length;
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'D7', scope: 'days', days: 7 });
|
||
expect(mocks.query.mock.calls.length).toBe(before); // 同 key 缓存
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'D7', scope: 'days', days: 30 });
|
||
expect(mocks.query.mock.calls.length).toBeGreaterThan(before); // days 不同不共用
|
||
});
|
||
|
||
it('menus keys:只算指定 key;refresh=1 绕过缓存;非法 key 抛 400;权限外不返回', async () => {
|
||
const partial = await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'K1', scope: 'today' }, ['orders-list']);
|
||
expect(partial).toEqual({ 'orders-list': 1 });
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(1);
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'K1', scope: 'today' }, ['orders-list']);
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(1); // 缓存命中
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'K1', scope: 'today' }, ['orders-list'], true);
|
||
expect(mocks.pendingOrders).toHaveBeenCalledTimes(2); // refresh 绕过
|
||
|
||
await expect(
|
||
getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'K1', scope: 'month' }, ['nope'])
|
||
).rejects.toMatchObject({ status: 400, code: 'invalid_menu_key' });
|
||
|
||
const noPerm = await getNavBadges(
|
||
{ ctx: ctx({ roles: ['operator'], permissions: ['order_manage'] }), branchCode: 'BR002', userId: 'K2', scope: 'month' },
|
||
['purchase-list']
|
||
);
|
||
expect(noPerm).toEqual({});
|
||
});
|
||
|
||
it('ops 按权限拆分:只有售后只算售后,只有异常只算异常,两者都有相加', async () => {
|
||
mocks.query.mockImplementation(async (sql: string) => {
|
||
if (String(sql).includes('after_sales')) return { rows: [{ c: 4 }], rowCount: 1 };
|
||
if (String(sql).includes('exception_tickets')) return { rows: [{ c: 5 }], rowCount: 1 };
|
||
return { rows: [{ c: 9 }], rowCount: 1 };
|
||
});
|
||
const salesOnly = await getNavBadges({
|
||
ctx: ctx({ roles: ['operator'], permissions: ['aftersales_manage'] }),
|
||
branchCode: 'BR002', userId: 'OPS1', scope: 'today',
|
||
});
|
||
expect(salesOnly.ops).toBe(4);
|
||
expect(mocks.query.mock.calls.some(([s]) => String(s).includes('exception_tickets'))).toBe(false);
|
||
|
||
clearNavBadgeCache();
|
||
const exceptionOnly = await getNavBadges({
|
||
ctx: ctx({ roles: ['operator'], permissions: ['exception_manage'] }),
|
||
branchCode: 'BR002', userId: 'OPS2', scope: 'today',
|
||
});
|
||
expect(exceptionOnly.ops).toBe(5);
|
||
|
||
clearNavBadgeCache();
|
||
const both = await getNavBadges({
|
||
ctx: ctx({ roles: ['operator'], permissions: ['aftersales_manage', 'exception_manage'] }),
|
||
branchCode: 'BR002', userId: 'OPS3', scope: 'today',
|
||
});
|
||
expect(both.ops).toBe(9);
|
||
});
|
||
|
||
it('month:自然月边界条件出现在各业务日期 SQL;default 由前端/route 负责', async () => {
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'MONTH1', scope: 'month' });
|
||
const sqls = mocks.query.mock.calls.map(([s]) => String(s));
|
||
expect(sqls.some((sql) => sql.includes('date_trunc(\'month\'') && sql.includes('INTERVAL \'1 month\''))).toBe(true);
|
||
const monthSqls = sqls.filter((sql) => sql.includes("date_trunc('month'"));
|
||
expect(monthSqls.some((sql) => sql.includes('delivery_date'))).toBe(true);
|
||
expect(monthSqls.some((sql) => sql.includes('pt.created_at'))).toBe(true);
|
||
expect(monthSqls.some((sql) => sql.includes('created_at') && sql.includes('main_system_actual_qty_requests'))).toBe(true);
|
||
expect(monthSqls.some((sql) => sql.includes('respond_deadline'))).toBe(true);
|
||
});
|
||
|
||
it('purchase/prep today 用 delivery_date;inspection 用页面只读口径', async () => {
|
||
await getNavBadges({ ctx: ctx(), branchCode: 'BR002', userId: 'DATE1', scope: 'today' });
|
||
expect(mocks.branchPurchase).toHaveBeenCalledWith('BR002', 'delivery_date');
|
||
const prepSql = mocks.query.mock.calls.map(([s]) => String(s)).find((s) => s.includes('FROM supplier_preparations'));
|
||
expect(prepSql).toContain('o.delivery_date::date');
|
||
expect(prepSql).toContain('sp.created_at');
|
||
const spiSql = mocks.query.mock.calls.map(([s]) => String(s)).find((s) => s.includes('self_purchase_stock_inbounds'));
|
||
expect(spiSql).toContain('inventory_id IS NULL');
|
||
expect(spiSql).toContain('created_at AT TIME ZONE');
|
||
const inspectionSqls = mocks.query.mock.calls.map(([s]) => String(s)).filter((s) => s.includes('FROM inspections'));
|
||
expect(inspectionSqls.some((s) => s.includes('inspection_time IS NULL') && s.includes('delivery_date'))).toBe(true);
|
||
expect(inspectionSqls.every((s) => !s.includes('quality_rating') && !s.includes('actual_qty'))).toBe(true);
|
||
});
|
||
|
||
it('picking/delivery 管理员看分公司全部;作业角色看本人', async () => {
|
||
expect(isNavBadgeAllowed(ctx(), NAV_BADGE_COUNTERS.picking)).toBe(true);
|
||
// 必须先有 picking_manage;roles 只决定本人范围
|
||
expect(
|
||
isNavBadgeAllowed(ctx({ roles: ['picker'], permissions: [] }), NAV_BADGE_COUNTERS.picking)
|
||
).toBe(false);
|
||
expect(
|
||
isNavBadgeAllowed(ctx({ roles: ['operator'], permissions: [] }), NAV_BADGE_COUNTERS.picking)
|
||
).toBe(false);
|
||
|
||
const picker = await getNavBadges({
|
||
ctx: ctx({ roles: ['picker'], permissions: ['picking_manage'], userId: 'P1' }),
|
||
branchCode: 'BR002',
|
||
userId: 'P1',
|
||
scope: 'today',
|
||
});
|
||
expect(picker.picking).toBe(9);
|
||
const pickSql = mocks.query.mock.calls.map(([s]) => String(s)).find((s) => s.includes('FROM picking_tasks'));
|
||
expect(pickSql).toContain('pt.pick_status < 30');
|
||
expect(pickSql).toContain('pt.picker_id = $2');
|
||
expect(pickSql).toContain('delivery_date');
|
||
|
||
clearNavBadgeCache();
|
||
mocks.query.mockImplementation(async (sql: string) =>
|
||
String(sql).includes('delivery_person_users')
|
||
? { rows: [{ person_code: 'D1' }], rowCount: 1 }
|
||
: { rows: [{ c: 9 }], rowCount: 1 }
|
||
);
|
||
const delivery = await getNavBadges({
|
||
ctx: ctx({ roles: ['delivery'], permissions: ['delivery_manage'], userId: 'D1' }),
|
||
branchCode: 'BR002',
|
||
userId: 'D1',
|
||
scope: 'today',
|
||
});
|
||
expect(delivery.delivery).toBe(9);
|
||
const deliverySql = mocks.query.mock.calls.map(([s]) => String(s)).find((s) => s.includes('INNER JOIN delivery_tasks'));
|
||
expect(deliverySql).toContain('COALESCE(dt.task_status, 10) < 30');
|
||
expect(deliverySql).toContain('COALESCE(o.order_status, 0) >= 50');
|
||
expect(deliverySql).toContain('dt.person_code = $2');
|
||
expect(deliverySql).toContain('dt.branch_code = $1 OR dt.branch_code IS NULL');
|
||
expect(deliverySql).toContain('delivery_date');
|
||
});
|
||
});
|