来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
310 lines
11 KiB
TypeScript
310 lines
11 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
}));
|
||
|
||
import {
|
||
addDaysYmd,
|
||
computeAlertSide,
|
||
dailyQuota,
|
||
daysInCalendarMonth,
|
||
listCustomerBudgetAlerts,
|
||
miscShareForCustomerDay,
|
||
mondayOfWeek,
|
||
normalizeBudgetAlertDateField,
|
||
pickDeliveryPerson,
|
||
resolveAlertWindow,
|
||
shareAmount,
|
||
windowQuota,
|
||
} from '../src/services/customerBudgetAlertService';
|
||
import {
|
||
assertCustomerCredit,
|
||
checkCustomerCredit,
|
||
checkCustomerOrderBudget,
|
||
} from '../src/services/customerBudgetService';
|
||
|
||
describe('customerBudgetAlertService quota', () => {
|
||
it('splits monthly budget by calendar days of that month', () => {
|
||
expect(daysInCalendarMonth('2026-01-15')).toBe(31);
|
||
expect(dailyQuota(3100, '2026-01-15')).toBe(100);
|
||
});
|
||
|
||
it('week quota in a single month is daily × 7', () => {
|
||
const from = mondayOfWeek('2026-01-14');
|
||
expect(from).toBe('2026-01-12');
|
||
expect(windowQuota(3100, from, addDaysYmd(from, 6))).toBe(700);
|
||
});
|
||
|
||
it('cross-month week uses each day’s own month length', () => {
|
||
const q = dailyQuota(3100, '2026-01-26') * 6 + dailyQuota(3100, '2026-02-01');
|
||
expect(windowQuota(3100, '2026-01-26', '2026-02-01')).toBe(Math.round(q * 100) / 100);
|
||
expect(windowQuota(3100, '2026-01-26', '2026-02-01')).not.toBe(700);
|
||
});
|
||
|
||
it('sales side reuses windowQuota; zero monthly is not over', () => {
|
||
const from = '2026-01-15';
|
||
const over = computeAlertSide(3100, 150, from, from);
|
||
expect(over.quota).toBe(100);
|
||
expect(over.isOver).toBe(true);
|
||
expect(over.over).toBe(50);
|
||
const salesOnlyCostSide = computeAlertSide(0, 999, from, from);
|
||
expect(salesOnlyCostSide.isOver).toBe(false);
|
||
expect(salesOnlyCostSide.over).toBe(0);
|
||
expect(salesOnlyCostSide.isOver || over.isOver).toBe(true);
|
||
});
|
||
|
||
it('month grain window is calendar month of asOf', () => {
|
||
expect(resolveAlertWindow({ grain: 'month', dateTo: '2026-01-20' })).toEqual({
|
||
from: '2026-01-01',
|
||
to: '2026-01-31',
|
||
});
|
||
});
|
||
|
||
it('uses date_from/date_to as the window even when grain is day', () => {
|
||
expect(
|
||
resolveAlertWindow({
|
||
grain: 'day',
|
||
dateFrom: '2026-08-01',
|
||
dateTo: '2026-08-31',
|
||
})
|
||
).toEqual({ from: '2026-08-01', to: '2026-08-31' });
|
||
});
|
||
});
|
||
|
||
describe('budget alert cost share helpers', () => {
|
||
it('defaults date field to created_at', () => {
|
||
expect(normalizeBudgetAlertDateField(null)).toBe('created_at');
|
||
expect(normalizeBudgetAlertDateField('delivery_date')).toBe('delivery_date');
|
||
});
|
||
|
||
it('shares fixed pool across all enabled customers', () => {
|
||
expect(shareAmount(100, 2)).toBe(50);
|
||
expect(shareAmount(100, 0)).toBe(0);
|
||
});
|
||
|
||
it('shares driver misc by that driver stop count', () => {
|
||
expect(shareAmount(80, 2)).toBe(40);
|
||
expect(shareAmount(80, 10)).toBe(8);
|
||
});
|
||
|
||
it('does not allocate misc to assigned-only customers when the driver has stops', () => {
|
||
const lookup = {
|
||
personByCustDay: new Map([['A|2026-09-01', 'DP1'], ['B|2026-09-01', 'DP1']]),
|
||
stopsByDayPerson: new Map([['2026-09-01|DP1', 2]]),
|
||
primaryByCustomer: new Map([
|
||
['A', 'DP1'],
|
||
['B', 'DP1'],
|
||
['C', 'DP1'],
|
||
]),
|
||
bindCountByPerson: new Map([['DP1', 3]]),
|
||
miscByDayPerson: new Map([['2026-09-01|DP1', 80]]),
|
||
};
|
||
expect(miscShareForCustomerDay('A', '2026-09-01', lookup)).toBe(40);
|
||
expect(miscShareForCustomerDay('B', '2026-09-01', lookup)).toBe(40);
|
||
expect(miscShareForCustomerDay('C', '2026-09-01', lookup)).toBe(0);
|
||
});
|
||
|
||
// 2026-09-22 口径变更(开发者定稿):严格按「该员当天实际配送客户数」,
|
||
// 当天该客户没有配送记录 → 0(= 当天没下单、没配送),不再回退到"绑定客户数"。
|
||
it('no delivery record that day → 0(不再用绑定客户数兜底)', () => {
|
||
const lookup = {
|
||
personByCustDay: new Map<string, string>(),
|
||
stopsByDayPerson: new Map<string, number>(),
|
||
miscByDayPerson: new Map<string, number>([['2026-09-01|DP1', 80]]),
|
||
};
|
||
expect(miscShareForCustomerDay('A', '2026-09-01', lookup)).toBe(0);
|
||
expect(miscShareForCustomerDay('B', '2026-09-01', lookup)).toBe(0);
|
||
});
|
||
|
||
it('prefers primary person when a customer has two drivers the same day', () => {
|
||
expect(pickDeliveryPerson('DP2', 'DP1', 'DP1')).toBe('DP1');
|
||
expect(pickDeliveryPerson('DP2', 'DP3', '')).toBe('DP2');
|
||
});
|
||
});
|
||
|
||
describe('customer credit vs budget occupancy', () => {
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
});
|
||
|
||
it('does not block when occupancy would exceed monthly budget', async () => {
|
||
query.mockResolvedValueOnce({
|
||
rows: [{ credit_frozen: false, credit_limit: 0, used_budget: 99999 }],
|
||
});
|
||
const check = await checkCustomerOrderBudget('CUS1', 5000);
|
||
expect(check.allowed).toBe(true);
|
||
expect(check.disabled).toBe(true);
|
||
expect(check.level).not.toBe('block');
|
||
});
|
||
|
||
it('does not block frozen credit or credit limit on Node submit check', async () => {
|
||
query.mockResolvedValue({
|
||
rows: [{ credit_frozen: true, credit_limit: 100, used_budget: 0 }],
|
||
});
|
||
await expect(assertCustomerCredit('CUS1', 1)).resolves.toMatchObject({
|
||
allowed: true,
|
||
creditFrozen: true,
|
||
});
|
||
const credit = await checkCustomerCredit('CUS1', 30);
|
||
expect(credit.allowed).toBe(true);
|
||
});
|
||
|
||
it('still blocks when the customer does not exist', async () => {
|
||
query.mockResolvedValue({ rows: [] });
|
||
await expect(assertCustomerCredit('MISSING', 1)).rejects.toMatchObject({
|
||
status: 403,
|
||
code: 'credit_blocked',
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('cost/sales budget wiring', () => {
|
||
it('alert list reads cost_budget and PATCH exists; zero-price gate stays', () => {
|
||
const fs = require('node:fs') as typeof import('node:fs');
|
||
const path = require('node:path') as typeof import('node:path');
|
||
const alert = fs.readFileSync(
|
||
path.join(__dirname, '../src/services/customerBudgetAlertService.ts'),
|
||
'utf8'
|
||
);
|
||
expect(alert).toContain('c.cost_budget');
|
||
expect(alert).toContain('sales_budget');
|
||
expect(alert).toContain('ORDER_ITEM_REVENUE_SQL');
|
||
// 2026-09-22 起:① 商品成本改为订单行口径;② 固定成本取 fixed_costs 本月总额
|
||
expect(alert).toContain('oi.unit_cost');
|
||
expect(alert).toContain('FROM fixed_costs');
|
||
expect(alert).not.toContain('self_purchase_stock_inbounds');
|
||
expect(alert).not.toContain('ensureFixedCostsCarriedForward');
|
||
expect(alert).not.toContain('FROM customers e');
|
||
expect(alert).toContain('COUNT(*)::int AS enabled_n');
|
||
expect(alert).toContain('delivery_tasks');
|
||
expect(alert).toContain('hasMisc');
|
||
expect(alert).toContain('::text[]');
|
||
expect(alert).toContain('is_sales_over');
|
||
expect(alert).toContain('export async function updateCustomerCostSalesBudgets');
|
||
|
||
const credit = fs.readFileSync(path.join(__dirname, '../src/services/customerBudgetService.ts'), 'utf8');
|
||
expect(credit).not.toContain('超出信用额度');
|
||
expect(credit).not.toContain('客户信用已冻结');
|
||
|
||
const submit = fs.readFileSync(
|
||
path.join(__dirname, '../src/services/customerOrderSubmitService.ts'),
|
||
'utf8'
|
||
);
|
||
expect(submit).toContain('zero_price_blocked');
|
||
expect(submit).toContain('isBlockZeroSaleOnSubmitEnabled');
|
||
|
||
const routes = fs.readFileSync(
|
||
path.join(__dirname, '../src/modules/workflow/routes/financeRoutes.ts'),
|
||
'utf8'
|
||
);
|
||
expect(routes).toContain("/finance/cost/budget-alerts/:customerCode/budget");
|
||
expect(routes).toContain('updateCustomerCostSalesBudgets');
|
||
});
|
||
});
|
||
|
||
function sqlKind(sql: string): string {
|
||
if (sql.includes('delivery_tasks')) return 'delivery';
|
||
if (sql.includes('FROM customer_delivery_assignments')) return 'assign';
|
||
if (sql.includes('cost_pool')) return 'pool';
|
||
if (sql.includes('AS sku_cost')) return 'sku';
|
||
if (sql.includes('AS sales_amount')) return 'sales';
|
||
if (sql.includes('AS enabled_n')) return 'enabled';
|
||
return 'customers';
|
||
}
|
||
|
||
describe('listCustomerBudgetAlerts query budget', () => {
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
});
|
||
|
||
it('returns empty after one customer-list query when nobody has a budget', async () => {
|
||
query.mockResolvedValue({ rows: [] });
|
||
const listed = await listCustomerBudgetAlerts({
|
||
dateFrom: '2026-09-01',
|
||
dateTo: '2026-09-07',
|
||
onlyOver: true,
|
||
});
|
||
expect(listed.with_budget).toBe(0);
|
||
expect(listed.rows).toEqual([]);
|
||
expect(query).toHaveBeenCalledTimes(1);
|
||
expect(sqlKind(String(query.mock.calls[0][0]))).toBe('customers');
|
||
});
|
||
|
||
it('skips delivery stop SQL when the cost pool has no misc rows', async () => {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const kind = sqlKind(String(sql));
|
||
if (kind === 'customers') {
|
||
return {
|
||
rows: [
|
||
{
|
||
customer_code: 'C001',
|
||
customer_name: '张记',
|
||
monthly_budget: 3100,
|
||
sales_budget: 0,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
if (kind === 'enabled') return { rows: [{ enabled_n: 2 }] };
|
||
if (kind === 'sku') return { rows: [{ customer_code: 'C001', sku_cost: 10 }] };
|
||
if (kind === 'sales') return { rows: [] };
|
||
if (kind === 'pool') return { rows: [{ kind: 'fixed', d: '2026-09-01', person_code: null, amt: 20 }] };
|
||
throw new Error(`unexpected query ${kind}`);
|
||
});
|
||
const listed = await listCustomerBudgetAlerts({
|
||
dateFrom: '2026-09-01',
|
||
dateTo: '2026-09-01',
|
||
onlyOver: false,
|
||
});
|
||
expect(listed.with_budget).toBe(1);
|
||
expect(listed.rows[0]?.misc_share).toBe(0);
|
||
const kinds = query.mock.calls.map((call) => sqlKind(String(call[0])));
|
||
expect(kinds).toContain('customers');
|
||
expect(kinds).toContain('pool');
|
||
expect(kinds).not.toContain('delivery');
|
||
expect(kinds).not.toContain('assign');
|
||
});
|
||
|
||
it('loads delivery stops when misc rows exist', async () => {
|
||
query.mockImplementation(async (sql: string) => {
|
||
const kind = sqlKind(String(sql));
|
||
if (kind === 'customers') {
|
||
return {
|
||
rows: [
|
||
{
|
||
customer_code: 'C001',
|
||
customer_name: '张记',
|
||
monthly_budget: 3100,
|
||
sales_budget: 0,
|
||
},
|
||
],
|
||
};
|
||
}
|
||
if (kind === 'enabled') return { rows: [{ enabled_n: 1 }] };
|
||
if (kind === 'sku') return { rows: [] };
|
||
if (kind === 'sales') return { rows: [] };
|
||
if (kind === 'pool') {
|
||
return { rows: [{ kind: 'misc', d: '2026-09-01', person_code: 'DP1', amt: 80 }] };
|
||
}
|
||
if (kind === 'delivery') {
|
||
return { rows: [{ customer_code: 'C001', d: '2026-09-01', person_code: 'DP1' }] };
|
||
}
|
||
if (kind === 'assign') return { rows: [{ customer_code: 'C001', person_code: 'DP1' }] };
|
||
throw new Error(`unexpected query ${kind}`);
|
||
});
|
||
const listed = await listCustomerBudgetAlerts({
|
||
dateFrom: '2026-09-01',
|
||
dateTo: '2026-09-01',
|
||
onlyOver: false,
|
||
});
|
||
const kinds = query.mock.calls.map((call) => sqlKind(String(call[0])));
|
||
expect(kinds).toContain('delivery');
|
||
expect(kinds).toContain('assign');
|
||
expect(listed.rows[0]?.misc_share).toBe(80);
|
||
});
|
||
});
|