feat(导航角标): Web 侧边栏待办数字角标(本月/切页单菜单刷新)
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

- 新增只读 GET /api/workflow/nav-badges?scope=today|month|all,按 menuKey 返回待办数;默认自然月
- 10 个菜单:订单/采购/备货/供需变更/待竞价/入库/加工/分拣/配送/售后预警;权限、分公司、作业角色隔离
- 每 key 20s 缓存;菜单切换只刷新当前 key(menus=...&refresh=1),初始/60s/可见时全量
- 配送管理增加“全部日期”入口,便于查看跨日待配送
- 补前后端测试与契约
This commit is contained in:
Ubuntu
2026-10-25 13:34:07 +08:00
parent b32ff32f98
commit fbddcaae1e
18 changed files with 1504 additions and 1 deletions
+2
View File
@@ -30,12 +30,14 @@ import { mountUnitWorkflowRoutes } from './workflow/routes/unitRoutes';
import { mountSkuDirectDeliveryWorkflowRoutes } from './workflow/routes/skuDirectDeliveryRoutes';
import { mountSkuPreferredSupplierWorkflowRoutes } from './workflow/routes/skuPreferredSupplierRoutes';
import { mountUiPreferenceWorkflowRoutes } from './workflow/routes/uiPreferenceRoutes';
import { mountNavBadgeWorkflowRoutes } from './workflow/routes/navBadgeRoutes';
function mountPlatformWorkflowRoutes(router: Router): void {
mountNotificationWorkflowRoutes(router);
mountPlatformConfigWorkflowRoutes(router);
mountImportMappingWorkflowRoutes(router);
mountUiPreferenceWorkflowRoutes(router);
mountNavBadgeWorkflowRoutes(router);
}
export const orderModule: BusinessModuleDescriptor = {
@@ -0,0 +1,71 @@
import { Router, Response } from 'express';
import { authMiddleware, type AuthRequest } from '../../../middleware/auth';
import { readOperatingBranchCode } from '../../../services/tenantScope';
import { runWithTenantDbContext } from '../../../services/tenantDbContext';
import { getNavBadges, NAV_BADGE_COUNTERS, type NavBadgeScope } from '../../../services/navBadgeService';
import { getWorkflowCtx, sendWorkflowError } from '../context';
/**
* GET /api/workflow/nav-badges?scope=today|all
* 只读菜单角标;默认关闭,NAV_BADGES_ENABLED=1/true 才计数(便于灰度)。
*/
export function mountNavBadgeWorkflowRoutes(router: Router): void {
router.get('/nav-badges', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
if (!req.userId) return res.status(401).json({ error: 'invalid_token' });
const tokenScope = String(req.tokenScope || '').trim();
if (tokenScope && tokenScope !== 'web') {
return res.status(403).json({ error: 'forbidden', error_description: '仅 Web token 可访问' });
}
const rawScope = String(req.query?.scope || 'month').trim().toLowerCase();
if (rawScope !== 'today' && rawScope !== 'month' && rawScope !== 'all') {
return res.status(400).json({ error: 'invalid_scope', error_description: 'scope 只能是 today、month 或 all' });
}
const scope = rawScope as NavBadgeScope;
const rawMenus = req.query?.menus;
const requestedMenus = rawMenus === undefined
? undefined
: String(rawMenus).split(',').map((key) => key.trim()).filter(Boolean);
if (requestedMenus && (!requestedMenus.length || requestedMenus.some((key) => !NAV_BADGE_COUNTERS[key]))) {
return res.status(400).json({ error: 'invalid_menu_key', error_description: 'menus 含无效角标 key' });
}
const refresh = String(req.query?.refresh || '') === '1';
const ctx = await getWorkflowCtx(req);
if (!ctx) return res.status(401).json({ error: 'invalid_token' });
if (ctx.isSupplierAccount) {
return res.status(403).json({ error: 'forbidden', error_description: '供应商账号不可访问' });
}
// 注意:readOperatingBranchCode 可能是 null;先判空再 String,避免 "null" 字符串绕过校验
const rawBranchCode = ctx.isSuperAdmin ? readOperatingBranchCode(req) : ctx.branchCode;
const branchCode = rawBranchCode == null ? '' : String(rawBranchCode).trim();
if (!branchCode) {
return res.status(400).json({ error: 'branch_required', error_description: '请选择当前操作分公司' });
}
const enabled = ['1', 'true', 'yes'].includes(
String(process.env.NAV_BADGES_ENABLED || '').trim().toLowerCase()
);
const generatedAt = new Date().toISOString();
if (!enabled) return res.json({ data: {}, disabled: true, scope, generated_at: generatedAt });
const data = await runWithTenantDbContext(branchCode, () =>
getNavBadges(
{
ctx: { ...ctx, branchCode },
branchCode,
userId: ctx.userId,
scope,
},
requestedMenus,
refresh
)
);
return res.json({ data, disabled: false, scope, generated_at: generatedAt });
} catch (error: any) {
return sendWorkflowError(res, error, '加载菜单角标失败');
}
});
}
export default mountNavBadgeWorkflowRoutes;
+488
View File
@@ -0,0 +1,488 @@
import { pool } from '../db';
import type { TenantContext } from './tenantScope';
import { countPendingPickingOrders } from './orderManagementQueryService';
import { countPendingBranchPurchaseTasks } from './purchaseOrderQueryService';
import { inspectionVisibleInListSql } from './independentInboundService';
import { countPendingProcessingTasks } from './processingTaskService';
import { listActualQtyInbox } from './mainSystemActualQtyInbox';
import { listBidInvitations } from './mainSystemBidQuotes';
import { orderCodeActiveExistsSql, orderNotDeletedSql } from './orderTrashScope';
import { purchaseOrderBranchWhereSql } from './purchaserBranchScope';
/**
* Web 侧边栏/菜单角标(只读,2026-10-24)。
*
* 纪律:
* · 只 COUNT、只复用既有页面口径;不写库、不发外部请求;
* · 单个 key 失败只省略该 key,不影响其它 key;
* · 20 秒进程缓存(key = branch|user|scope),防止切页/轮询放大 DB;
* · picking/delivery 管理员看分公司全部、作业角色只看本人。
*/
export type NavBadgeScope = 'today' | 'month' | 'all';
export type NavBadgeContext = {
ctx: TenantContext;
branchCode: string;
userId: string;
scope: NavBadgeScope;
};
type NavBadgeCounter = {
permission: string | string[];
/** 多个权限取 any;不填则仅看 permission */
roles?: string[];
count(input: NavBadgeContext): Promise<number>;
};
const LOCKED_AFTERSALE_TYPES = ['order_return', 'spi_void', 'inbound_switch'];
/** 自然月(Asia/Shanghai)半开区间,供只读 COUNT 复用。 */
function monthRangeSql(dateExpr: string): string {
return `(${dateExpr}) >= date_trunc('month', (NOW() AT TIME ZONE 'Asia/Shanghai')::date)::date
AND (${dateExpr}) < (date_trunc('month', (NOW() AT TIME ZONE 'Asia/Shanghai')::date) + INTERVAL '1 month')::date`;
}
const CACHE_TTL_MS = 20_000;
const cache = new Map<string, { expiresAt: number; value: number }>();
function hasPermission(ctx: TenantContext, permission: string | string[]): boolean {
if (ctx.isSuperAdmin) return true;
const list = Array.isArray(permission) ? permission : [permission];
return list.some((code) => (ctx.permissions || []).includes(code));
}
function isBranchAdmin(ctx: TenantContext): boolean {
return ctx.isSuperAdmin || (ctx.roles || []).includes('admin');
}
function hasRole(ctx: TenantContext, roles: string[]): boolean {
const set = new Set(ctx.roles || []);
return roles.some((role) => set.has(role));
}
/** 管理员 = 分公司全部;picker = 本人;today 只看配送日=今天,pick_status < 30 */
async function countPicking(ctx: TenantContext, branchCode: string, scope: NavBadgeScope): Promise<number> {
const pickerId = !isBranchAdmin(ctx) && hasRole(ctx, ['picker']) ? ctx.userId : null;
const params: unknown[] = [branchCode];
let pickerFilter = '';
if (pickerId) {
params.push(pickerId);
pickerFilter = `AND pt.picker_id = $${params.length}`;
}
const businessDay = `COALESCE(o.delivery_date::date, (o.created_at AT TIME ZONE 'Asia/Shanghai')::date)`;
const dateFilter =
scope === 'today'
? `AND ${businessDay} = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`
: scope === 'month'
? `AND ${monthRangeSql(businessDay)}`
: '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM picking_tasks pt
WHERE pt.pick_status < 30
AND pt.branch_code = $1
${pickerFilter}
AND EXISTS (
SELECT 1
FROM picking_items pi
JOIN orders o ON o.order_code = pi.order_code
WHERE pi.pick_code = pt.pick_code
AND ${orderNotDeletedSql('o')}
AND o.order_status < 50
${dateFilter}
)`,
params
);
return Number(result.rows[0]?.c) || 0;
}
/** 管理员 = 分公司全部;配送员 = 本人;today 只看配送日=今天,task_status = 10 */
async function countDelivery(ctx: TenantContext, branchCode: string, scope: NavBadgeScope): Promise<number> {
let personCode: string | null = null;
if (!isBranchAdmin(ctx) && hasRole(ctx, ['delivery'])) {
const person = await pool.query<{ person_code: string | null }>(
`SELECT dpu.person_code
FROM delivery_person_users dpu
JOIN delivery_persons dp
ON dp.person_code = dpu.person_code AND dp.branch_code = $2
WHERE dpu.user_id = $1
LIMIT 1`,
[ctx.userId, branchCode]
);
personCode = String(person.rows[0]?.person_code || '').trim() || null;
if (!personCode) return 0;
}
const params: unknown[] = [branchCode];
let personFilter = '';
if (personCode) {
params.push(personCode);
personFilter = `AND dt.person_code = $${params.length}`;
}
const businessDay = `COALESCE(o.delivery_date::date, (o.created_at AT TIME ZONE 'Asia/Shanghai')::date)`;
const dateFilter =
scope === 'today'
? `AND ${businessDay} = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`
: scope === 'month'
? `AND ${monthRangeSql(businessDay)}`
: '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM delivery_tasks dt
JOIN orders o ON o.order_code = dt.order_code
WHERE o.branch_code = $1
AND ${orderNotDeletedSql('o')}
AND COALESCE(dt.task_status, 10) = 10
${personFilter}
${dateFilter}`,
params
);
return Number(result.rows[0]?.c) || 0;
}
async function countPurchaseAll(branchCode: string): Promise<number> {
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM purchase_orders po
LEFT JOIN orders o ON o.order_code = po.order_code
WHERE ${purchaseOrderBranchWhereSql('po', '$1')}
AND po.purchase_status IN (10, 32)
AND (
po.order_code IS NULL OR TRIM(po.order_code) = ''
OR ${orderCodeActiveExistsSql('po.order_code')}
)`,
[branchCode]
);
return Number(result.rows[0]?.c) || 0;
}
async function countProcessingAll(): Promise<number> {
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM processing_tasks pt
LEFT JOIN orders o ON o.order_code = pt.order_code
WHERE pt.process_status IN (10, 20, 30)
AND (pt.order_code IS NULL OR ${orderCodeActiveExistsSql('pt.order_code')})`
);
return Number(result.rows[0]?.c) || 0;
}
/**
* 智能入库待验收:只读 COUNT,绝不能调会 prune/DELETE 的旧函数。
* today 与页面默认口径一致:inspection_time IS NULL + 可见性 + 配送日=今天(无订单回退建单日)。
*/
async function countPendingInspectionsReadonly(scope: NavBadgeScope): Promise<number> {
const inspectionDay = `COALESCE(
(SELECT o.delivery_date::date FROM orders o WHERE o.order_code = i.order_code LIMIT 1),
(i.created_at AT TIME ZONE 'Asia/Shanghai')::date
)`;
const dateFilter =
scope === 'today'
? `AND ${inspectionDay} = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`
: scope === 'month'
? `AND ${monthRangeSql(inspectionDay)}`
: '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM inspections i
WHERE i.inspection_time IS NULL
AND ${inspectionVisibleInListSql('i')}
${dateFilter}`
);
return Number(result.rows[0]?.c) || 0;
}
/** 供应商备货待办:today 配送日优先(无订单回退 sp.created_at);all 去日期。 */
async function countPendingPreparationsReadonly(branchCode: string, scope: NavBadgeScope): Promise<number> {
const prepDay = `COALESCE(o.delivery_date::date, (sp.created_at AT TIME ZONE 'Asia/Shanghai')::date)`;
const dateFilter =
scope === 'today'
? `AND ${prepDay} = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`
: scope === 'month'
? `AND ${monthRangeSql(prepDay)}`
: '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM supplier_preparations sp
LEFT JOIN orders o ON o.order_code = sp.order_code
WHERE COALESCE(sp.is_history_repair, false) = false
AND (sp.order_code IS NULL OR TRIM(sp.order_code) = ''
OR ${orderCodeActiveExistsSql('sp.order_code')})
AND COALESCE(sp.transferred_to_purchase, false) = false
AND COALESCE(sp.is_stockout, false) = false
AND COALESCE(sp.prepare_status, 0) = 10
AND (sp.branch_code = $1
OR ((sp.branch_code IS NULL OR TRIM(sp.branch_code) = '') AND o.branch_code = $1))
${dateFilter}`,
[branchCode]
);
return Number(result.rows[0]?.c) || 0;
}
/** 售后按 delivery_date 默认口径 + 异常 <30;按权限拆分,admin/super 两者都算。 */
async function countOps(ctx: TenantContext, branchCode: string, scope: NavBadgeScope): Promise<number> {
const both = ctx.isSuperAdmin || isBranchAdmin(ctx);
const canSales = both || hasPermission(ctx, 'aftersales_manage');
const canException = both || hasPermission(ctx, 'exception_manage');
let sales = 0;
let exceptions = 0;
if (canSales) {
const salesDay = `COALESCE(
NULLIF(o.delivery_date::text, '')::date,
(o.created_at AT TIME ZONE 'Asia/Shanghai')::date,
(a.created_at AT TIME ZONE 'Asia/Shanghai')::date
)`;
const dateFilter =
scope === 'today'
? `AND ${salesDay} = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`
: scope === 'month'
? `AND ${monthRangeSql(salesDay)}`
: '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM after_sales a
LEFT JOIN orders o ON o.order_code = a.order_code
WHERE a.branch_code = $1
AND a.status IN (10, 20)
AND NOT (a.aftersale_type = ANY($2::text[]))
${dateFilter}`,
[branchCode, LOCKED_AFTERSALE_TYPES]
);
sales = Number(result.rows[0]?.c) || 0;
}
if (canException) {
const exceptionDateFilter =
scope === 'month'
? `AND ${monthRangeSql("(et.created_at AT TIME ZONE 'Asia/Shanghai')::date")}`
: '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM exception_tickets et
WHERE et.branch_code = $1 AND et.ticket_status < 30
${exceptionDateFilter}`,
[branchCode]
);
exceptions = Number(result.rows[0]?.c) || 0;
}
return sales + exceptions;
}
/** 自采入库(SPI)待办:页面 pending 口径 = voided_at IS NULL AND inventory_id IS NULL。 */
async function countPendingSpi(branchCode: string, scope: NavBadgeScope): Promise<number> {
const dateFilter =
scope === 'today'
? `AND (spi.created_at AT TIME ZONE 'Asia/Shanghai')::date = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`
: '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM self_purchase_stock_inbounds spi
WHERE spi.branch_code = $1
AND spi.voided_at IS NULL
AND spi.inventory_id IS NULL
${dateFilter}`,
[branchCode]
);
return Number(result.rows[0]?.c) || 0;
}
async function countPurchaseMonth(branchCode: string): Promise<number> {
const day = `COALESCE(o.delivery_date::date, (po.created_at AT TIME ZONE 'Asia/Shanghai')::date)`;
const po = await pool.query(
`SELECT COUNT(*)::int AS c
FROM purchase_orders po
LEFT JOIN orders o ON o.order_code = po.order_code
WHERE ${purchaseOrderBranchWhereSql('po', '$1')}
AND po.purchase_status IN (10, 32)
AND (po.order_code IS NULL OR TRIM(po.order_code) = '' OR ${orderCodeActiveExistsSql('po.order_code')})
AND ${monthRangeSql(day)}`,
[branchCode]
);
const spiDay = `(spi.created_at AT TIME ZONE 'Asia/Shanghai')::date`;
const spi = await pool.query(
`SELECT COUNT(*)::int AS c
FROM self_purchase_stock_inbounds spi
WHERE spi.branch_code = $1
AND spi.voided_at IS NULL
AND spi.inventory_id IS NULL
AND ${monthRangeSql(spiDay)}`,
[branchCode]
);
return (Number(po.rows[0]?.c) || 0) + (Number(spi.rows[0]?.c) || 0);
}
async function countPendingPriceQtyMonth(branchCode: string): Promise<number> {
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM public.main_system_actual_qty_requests
WHERE branch_code = $1
AND status = 'pending'
AND ${monthRangeSql("(created_at AT TIME ZONE 'Asia/Shanghai')::date")}`,
[branchCode]
);
return Number(result.rows[0]?.c) || 0;
}
/** 待竞价:表里没有 invited_at,按 respond_deadline 所在自然月(同页面的报价截止业务日)。 */
async function countPendingBidMonth(branchCode: string): Promise<number> {
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM public.main_system_bid_invitations
WHERE branch_code = $1
AND deleted_at IS NULL
AND local_status = 'pending'
AND respond_deadline IS NOT NULL
AND ${monthRangeSql("(respond_deadline AT TIME ZONE 'Asia/Shanghai')::date")}`,
[branchCode]
);
return Number(result.rows[0]?.c) || 0;
}
export const NAV_BADGE_COUNTERS: Record<string, NavBadgeCounter> = {
'orders-list': {
permission: ['order_manage', 'order_view'],
async count(input) {
if (input.scope === 'today') return countPendingPickingOrders();
const day = `COALESCE(o.delivery_date::date, (o.created_at AT TIME ZONE 'Asia/Shanghai')::date)`;
const dateFilter = input.scope === 'month' ? `AND ${monthRangeSql(day)}` : '';
const result = await pool.query(
`SELECT COUNT(*)::int AS c FROM orders o
WHERE o.order_status < 50 AND ${orderNotDeletedSql('o')} ${dateFilter}`
);
return Number(result.rows[0]?.c) || 0;
},
},
'purchase-list': {
permission: 'purchase_manage',
async count(input) {
// 页面默认 today 是配送日轴(不是 created_at)
if (input.scope === 'month') return countPurchaseMonth(input.branchCode);
const [po, spi] = await Promise.all([
input.scope === 'today'
? countPendingBranchPurchaseTasks(input.branchCode, 'delivery_date')
: countPurchaseAll(input.branchCode),
countPendingSpi(input.branchCode, input.scope),
]);
return po + spi;
},
},
'purchase-preparations': {
permission: 'preparation_manage',
async count(input) {
return countPendingPreparationsReadonly(input.branchCode, input.scope);
},
},
'orders-price-qty': {
permission: 'price_qty_review',
async count(input) {
if (input.scope === 'month') return countPendingPriceQtyMonth(input.branchCode);
const inbox = await listActualQtyInbox({
branchCode: input.branchCode,
scope: 'pending',
page: 1,
pageSize: 1,
});
return Number(inbox.counts?.pending) || 0;
},
},
'orders-bid-invitations': {
permission: 'bid_quote',
async count(input) {
if (input.scope === 'month') return countPendingBidMonth(input.branchCode);
const result = await listBidInvitations({
branchCode: input.branchCode,
status: 'pending',
limit: 1,
});
return Number(result.summary?.pending) || 0;
},
},
'inspection-list': {
permission: 'inspection_manage',
count: (input) => countPendingInspectionsReadonly(input.scope),
},
'inspection-processing': {
permission: 'processing_manage',
async count(input) {
if (input.scope === 'today') return countPendingProcessingTasks('created_at');
if (input.scope === 'month') {
const result = await pool.query(
`SELECT COUNT(*)::int AS c
FROM processing_tasks pt
LEFT JOIN orders o ON o.order_code = pt.order_code
WHERE pt.process_status IN (10, 20, 30)
AND (pt.order_code IS NULL OR ${orderCodeActiveExistsSql('pt.order_code')})
AND ${monthRangeSql("(pt.created_at AT TIME ZONE 'Asia/Shanghai')::date")}`
);
return Number(result.rows[0]?.c) || 0;
}
return countProcessingAll();
},
},
picking: {
permission: 'picking_manage',
roles: ['picker'],
count: (input) => countPicking(input.ctx, input.branchCode, input.scope),
},
delivery: {
permission: 'delivery_manage',
roles: ['delivery'],
count: (input) => countDelivery(input.ctx, input.branchCode, input.scope),
},
ops: {
permission: ['aftersales_manage', 'exception_manage'],
count: (input) => countOps(input.ctx, input.branchCode, input.scope),
},
};
export function isNavBadgeAllowed(ctx: TenantContext, counter: NavBadgeCounter): boolean {
if (ctx.isSuperAdmin) return true;
// 先必须有对应权限(roles 只决定计数范围,不能绕过权限)
if (!hasPermission(ctx, counter.permission)) return false;
if (counter.roles && !isBranchAdmin(ctx) && !hasRole(ctx, counter.roles)) return false;
return true;
}
export function clearNavBadgeCache(): void {
cache.clear();
}
/** 业务缓存 key:同一用户/分公司/scope 20s 内复用 */
export async function getNavBadges(
input: NavBadgeContext,
keys?: string[],
bypassCache = false
): Promise<Record<string, number>> {
const requestedKeys = keys?.length ? [...new Set(keys.map((key) => String(key).trim()).filter(Boolean))] : null;
if (requestedKeys) {
for (const key of requestedKeys) {
if (!NAV_BADGE_COUNTERS[key]) {
throw Object.assign(new Error(`未知角标 key:${key}`), { status: 400, code: 'invalid_menu_key' });
}
}
}
const permissionKey = [...(input.ctx.permissions || [])].sort().join(',');
const roleKey = [...(input.ctx.roles || [])].sort().join(',');
const baseKey = `${input.branchCode}|${input.userId}|${input.scope}|${input.ctx.isSuperAdmin ? 1 : 0}|${permissionKey}|${roleKey}`;
const selectedKeys = requestedKeys ?? Object.keys(NAV_BADGE_COUNTERS);
const data: Record<string, number> = {};
await Promise.all(
selectedKeys.map(async (menuKey) => {
const counter = NAV_BADGE_COUNTERS[menuKey];
if (!counter || !isNavBadgeAllowed(input.ctx, counter)) return;
const cacheKey = `${baseKey}|${menuKey}`;
const hit = cache.get(cacheKey);
if (!bypassCache && hit && hit.expiresAt > Date.now()) {
data[menuKey] = hit.value;
return;
}
try {
const value = Number(await counter.count(input)) || 0;
data[menuKey] = value;
cache.set(cacheKey, { expiresAt: Date.now() + CACHE_TTL_MS, value });
} catch (error) {
// 单项失败只缺 key,不拖垮其它角标
console.error(`[nav-badges] ${menuKey} count failed:`, (error as Error)?.message || error);
}
})
);
return data;
}
+210
View File
@@ -0,0 +1,210 @@
import express from 'express';
import request from 'supertest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { TenantContext } from '../src/services/tenantScope';
const mocks = vi.hoisted(() => ({
getNavBadges: vi.fn(),
getWorkflowCtx: vi.fn(),
runWithTenantDbContext: vi.fn(),
}));
vi.mock('../src/middleware/auth', () => ({
authMiddleware: (req: any, res: any, next: any) => {
if (!req.headers['x-test-user-id']) return res.status(401).json({ error: 'invalid_token' });
req.userId = String(req.headers['x-test-user-id']);
req.tokenScope = String(req.headers['x-test-scope'] || 'web');
next();
},
}));
vi.mock('../src/modules/workflow/context', () => ({
getWorkflowCtx: (...args: unknown[]) => mocks.getWorkflowCtx(...args),
sendWorkflowError: (res: any, error: any, fallback: string) =>
res.status(error?.status || 500).json({ error: 'server_error', error_description: error?.message || fallback }),
}));
vi.mock('../src/services/tenantScope', () => ({
readOperatingBranchCode: (req: any) => {
const raw = req.headers['x-test-operating-branch'];
return raw ? String(raw) : null;
},
}));
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (...args: unknown[]) => mocks.runWithTenantDbContext(...args),
}));
vi.mock('../src/services/navBadgeService', () => ({
getNavBadges: (...args: unknown[]) => mocks.getNavBadges(...args),
NAV_BADGE_COUNTERS: {
'orders-list': {},
picking: {},
'purchase-list': {},
'purchase-preparations': {},
'orders-price-qty': {},
'orders-bid-invitations': {},
'inspection-list': {},
'inspection-processing': {},
delivery: {},
ops: {},
},
}));
import { mountNavBadgeWorkflowRoutes } from '../src/modules/workflow/routes/navBadgeRoutes';
const ctx = (overrides: Partial<TenantContext> = {}): TenantContext => ({
userId: 'U1',
roles: ['admin'],
permissions: ['order_manage'],
branchCode: 'BR002',
supplierCode: null,
purchaserCode: null,
isSuperAdmin: false,
isBranchAdmin: true,
isInternalStaff: true,
isSupplierAccount: false,
...overrides,
});
function buildApp() {
const app = express();
const router = express.Router();
mountNavBadgeWorkflowRoutes(router);
app.use('/api/workflow', router);
return app;
}
beforeEach(() => {
vi.clearAllMocks();
delete process.env.NAV_BADGES_ENABLED;
mocks.getWorkflowCtx.mockResolvedValue(ctx());
mocks.getNavBadges.mockResolvedValue({ 'orders-list': 3 });
mocks.runWithTenantDbContext.mockImplementation(async (_branch: string, fn: () => Promise<unknown>) => fn());
});
afterEach(() => {
delete process.env.NAV_BADGES_ENABLED;
});
describe('GET /api/workflow/nav-badges', () => {
it('scope 非法 ⇒ 400', async () => {
const res = await request(buildApp())
.get('/api/workflow/nav-badges?scope=week')
.set('x-test-user-id', 'U1');
expect(res.status).toBe(400);
expect(res.body.error).toBe('invalid_scope');
});
it('不传 scope 默认 month;scope=month 合法', async () => {
process.env.NAV_BADGES_ENABLED = '1';
const def = await request(buildApp())
.get('/api/workflow/nav-badges')
.set('x-test-user-id', 'U1');
expect(def.status).toBe(200);
expect(def.body.scope).toBe('month');
const month = await request(buildApp())
.get('/api/workflow/nav-badges?scope=month')
.set('x-test-user-id', 'U1');
expect(month.status).toBe(200);
expect(month.body.scope).toBe('month');
});
it('menus 指定 key 传给 service;refresh=1 透传', async () => {
process.env.NAV_BADGES_ENABLED = '1';
const res = await request(buildApp())
.get('/api/workflow/nav-badges?scope=month&menus=orders-list,picking&refresh=1')
.set('x-test-user-id', 'U1');
expect(res.status).toBe(200);
expect(mocks.getNavBadges).toHaveBeenCalledWith(
expect.objectContaining({ branchCode: 'BR002', scope: 'month' }),
['orders-list', 'picking'],
true
);
});
it('menus 非法 key ⇒ 400 且不计数', async () => {
process.env.NAV_BADGES_ENABLED = '1';
mocks.getNavBadges.mockClear();
for (const menus of ['nope', 'orders-list,nope', '']) {
const res = await request(buildApp())
.get(`/api/workflow/nav-badges?scope=month&menus=${encodeURIComponent(menus)}`)
.set('x-test-user-id', 'U1');
expect(res.status, menus).toBe(400);
expect(res.body.error).toBe('invalid_menu_key');
}
expect(mocks.getNavBadges).not.toHaveBeenCalled();
});
it('默认 disabled=true,返回空 data 且不计数', async () => {
const res = await request(buildApp())
.get('/api/workflow/nav-badges?scope=today')
.set('x-test-user-id', 'U1');
expect(res.status).toBe(200);
expect(res.body).toEqual({
data: {},
disabled: true,
scope: 'today',
generated_at: expect.any(String),
});
expect(mocks.getNavBadges).not.toHaveBeenCalled();
});
it('开启后返回 {data,disabled:false},用 ctx 分公司', async () => {
process.env.NAV_BADGES_ENABLED = '1';
const res = await request(buildApp())
.get('/api/workflow/nav-badges?scope=all')
.set('x-test-user-id', 'U1');
expect(res.status).toBe(200);
expect(res.body).toEqual({
data: { 'orders-list': 3 },
disabled: false,
scope: 'all',
generated_at: expect.any(String),
});
expect(mocks.getNavBadges).toHaveBeenCalledWith(
expect.objectContaining({ branchCode: 'BR002', userId: 'U1', scope: 'all' }),
undefined,
false
);
expect(mocks.runWithTenantDbContext).toHaveBeenCalledWith('BR002', expect.any(Function));
});
it('超管未选分公司 ⇒ 400;选了则用 operating branch', async () => {
process.env.NAV_BADGES_ENABLED = '1';
mocks.getWorkflowCtx.mockResolvedValue(ctx({ isSuperAdmin: true, branchCode: null }));
mocks.getNavBadges.mockClear();
const bad = await request(buildApp())
.get('/api/workflow/nav-badges?scope=today')
.set('x-test-user-id', 'SU');
expect(bad.status).toBe(400);
expect(bad.body.error).toBe('branch_required');
expect(mocks.getNavBadges).not.toHaveBeenCalled();
mocks.getWorkflowCtx.mockResolvedValue(ctx({ isSuperAdmin: true, branchCode: null }));
const ok = await request(buildApp())
.get('/api/workflow/nav-badges?scope=today')
.set('x-test-user-id', 'SU')
.set('x-test-operating-branch', 'BR009');
expect(ok.status).toBe(200);
expect(mocks.runWithTenantDbContext).toHaveBeenCalledWith('BR009', expect.any(Function));
});
it('supplier / supplier_integration token 与供应商账号 ⇒ 403', async () => {
for (const scope of ['supplier', 'supplier_integration']) {
const res = await request(buildApp())
.get('/api/workflow/nav-badges?scope=today')
.set('x-test-user-id', 'S1')
.set('x-test-scope', scope);
expect(res.status, scope).toBe(403);
}
mocks.getWorkflowCtx.mockResolvedValue(ctx({ isSupplierAccount: true }));
const supplierAccount = await request(buildApp())
.get('/api/workflow/nav-badges?scope=today')
.set('x-test-user-id', 'S2');
expect(supplierAccount.status).toBe(403);
});
it('mobile token ⇒ 403', async () => {
const res = await request(buildApp())
.get('/api/workflow/nav-badges?scope=today')
.set('x-test-user-id', 'U1')
.set('x-test-scope', 'mobile');
expect(res.status).toBe(403);
});
});
+297
View File
@@ -0,0 +1,297 @@
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, getNavBadges, isNavBadgeAllowed, NAV_BADGE_COUNTERS } 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('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('FROM delivery_tasks'));
expect(deliverySql).toContain('COALESCE(dt.task_status, 10) = 10');
expect(deliverySql).not.toContain('o.order_status');
expect(deliverySql).toContain('dt.person_code = $2');
expect(deliverySql).toContain('delivery_date');
});
});
@@ -0,0 +1,30 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const layout = readFileSync(new URL('./Layout.tsx', import.meta.url), 'utf8');
describe('Layout 导航角标接线', () => {
it('调用 hook + 渲染 NavBadge', () => {
expect(layout).toContain("import { useNavBadgeCounts } from '../hooks/useNavBadgeCounts'");
expect(layout).toContain("import { NavBadge } from './NavBadge'");
expect(layout).toContain("useNavBadgeCounts('month', outletKey, location.pathname)");
});
it('二级菜单用 child.menuKey 映射', () => {
expect(layout).toContain('child.menuKey ? navBadgeCounts[child.menuKey] : 0');
});
it('折叠分组头显示子项合计', () => {
expect(layout).toContain('groupBadgeCount');
expect(layout).toContain('Number(navBadgeCounts[child.menuKey');
expect(layout).toContain('<NavBadge count={!submenuOpen ? groupBadgeCount : 0} />');
});
it('standalone 菜单也显示 item.menuKey 角标', () => {
expect(layout).toContain('item.menuKey ? navBadgeCounts[item.menuKey] : 0');
});
it('不改变原菜单权限过滤/顺序接线', () => {
expect(layout).toContain('filterRuntimeMenuByAccess(items, hasPermission, hasRole)');
});
});
+10
View File
@@ -9,6 +9,8 @@ import { BrandLogo } from './BrandLogo';
import { useAuth } from '../hooks/useAuth';
import { useOperatingBranch } from '../hooks/useOperatingBranch';
import { useMenuLayout } from '../hooks/useMenuLayout';
import { useNavBadgeCounts } from '../hooks/useNavBadgeCounts';
import { NavBadge } from './NavBadge';
import { supabase } from '../supabase/client';
import { NotificationBell } from './NotificationBell';
import { OrderEntryIntakeFab } from './OrderEntryIntakeFab';
@@ -80,6 +82,7 @@ export const Layout: React.FC = () => {
const outletKey = isSuperAdmin
? (operatingBranchCode || profile?.branch_code || 'no-branch')
: (profile?.branch_code || 'default');
const { counts: navBadgeCounts } = useNavBadgeCounts('month', outletKey, location.pathname);
useEffect(() => {
const timer = window.setInterval(() => setCurrentTime(new Date()), 30_000);
@@ -273,6 +276,10 @@ export const Layout: React.FC = () => {
const isActive = hasChildren
? isActiveInMenuGroup(location.pathname, item.children!, allMenuLeafPaths)
: isStandaloneMenuActive(location.pathname, item.path);
const groupBadgeCount = (item.children || []).reduce(
(sum, child) => sum + (Number(navBadgeCounts[child.menuKey || '']) || 0),
0
);
return (
<div key={`${item.path}:${item.label}`} className="nav-group-container">
@@ -290,6 +297,7 @@ export const Layout: React.FC = () => {
>
<MenuNavIcon icon={item.icon} iconSvg={item.iconSvg} className="nav-group-icon" />
<span className="flex-1 text-left truncate">{item.label}</span>
<NavBadge count={!submenuOpen ? groupBadgeCount : 0} />
<ChevronRight
className="group-chevron-icon shrink-0"
style={{
@@ -328,6 +336,7 @@ export const Layout: React.FC = () => {
}
>
<span>{child.label}</span>
<NavBadge count={child.menuKey ? navBadgeCounts[child.menuKey] : 0} />
</NavLink>
))}
</div>
@@ -344,6 +353,7 @@ export const Layout: React.FC = () => {
<MenuNavIcon icon={item.icon} iconSvg={item.iconSvg} className="nav-icon" />
)}
<span className="nav-item-text sidebar-hide-collapsed">{item.label}</span>
<NavBadge count={item.menuKey ? navBadgeCounts[item.menuKey] : 0} />
</NavLink>
)}
</div>
+29
View File
@@ -0,0 +1,29 @@
// @vitest-environment jsdom
import React from 'react';
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { NavBadge } from './NavBadge';
describe('NavBadge', () => {
it('0 不渲染', () => {
const { container } = render(<NavBadge count={0} />);
expect(container.firstChild).toBeNull();
});
it('9 / 99 显示原数字', () => {
const { rerender } = render(<NavBadge count={9} />);
expect(screen.getByText('9')).toBeTruthy();
rerender(<NavBadge count={99} />);
expect(screen.getByText('99')).toBeTruthy();
});
it('100 显示 99+', () => {
render(<NavBadge count={100} />);
expect(screen.getByText('99+')).toBeTruthy();
});
it('可选 aria-label', () => {
render(<NavBadge count={3} ariaLabel="待处理 3 条" />);
expect(screen.getByLabelText('待处理 3 条')).toBeTruthy();
});
});
+24
View File
@@ -0,0 +1,24 @@
import React from 'react';
export type NavBadgeProps = {
count?: number | null;
/** 可选无障碍标签(默认纯数字文本,不硬编码中文) */
ariaLabel?: string;
};
/** 菜单数字角标:<=0 不渲染,>99 显示 99+。 */
export const NavBadge: React.FC<NavBadgeProps> = ({ count, ariaLabel }) => {
const n = Math.max(0, Math.floor(Number(count) || 0));
if (n <= 0) return null;
const text = n > 99 ? '99+' : String(n);
return (
<span
className="nav-dot-indicator inline-flex items-center justify-center min-w-[16px] h-4 px-1 rounded-full bg-red-500 text-white text-[10px] leading-none tabular-nums shrink-0"
aria-label={ariaLabel || text}
>
{text}
</span>
);
};
export default NavBadge;
+12
View File
@@ -15,4 +15,16 @@ describe('chinaLast7DayRange', () => {
const src = readFileSync(path.join(__dirname, 'ListDateToolbar.tsx'), 'utf8');
expect(src).toContain("clearPreset = 'today'");
});
it('配送管理可显式切到全部日期(逾期单入口),不影响其它列表默认', () => {
const toolbar = readFileSync(path.join(__dirname, 'ListDateToolbar.tsx'), 'utf8');
const delivery = readFileSync(
path.join(__dirname, '../../pages/delivery/DeliveryManagement.tsx'),
'utf8'
);
expect(toolbar).toContain('showAll?: boolean');
expect(toolbar).toContain("onPresetChange('all')");
expect(delivery).toContain('showAll');
expect(delivery).toContain('clearPreset="all"');
});
});
+16 -1
View File
@@ -27,8 +27,10 @@ type Props = {
className?: string;
/** 无障碍标签;不传则按 field 取默认文案 */
'aria-label'?: string;
/** 清空日期时的 preset;默认 today,备货表传 all 以免显示当天 */
/** 清空日期时的 preset;默认 today,备货表/配送管理传 all 以免显示当天 */
clearPreset?: OrderDatePreset;
/** 显示「全部日期」快捷按钮(明确入口,避免只能靠清空日期) */
showAll?: boolean;
};
const presetBtn = (active: boolean) =>
@@ -64,6 +66,7 @@ export const ListDateToolbar: React.FC<Props> = ({
className = '',
'aria-label': ariaLabel,
clearPreset = 'today',
showAll = false,
}) => {
const t = useT();
const options = fieldOptions ?? [
@@ -109,6 +112,18 @@ export const ListDateToolbar: React.FC<Props> = ({
>
{t('common.listDate.last7')}
</button>
{showAll && (
<button
type="button"
onClick={() => {
onRangeChange(null);
onPresetChange('all');
}}
className={presetBtn(preset === 'all')}
>
{t('common.listDate.all')}
</button>
)}
</div>
<DateRangeFilterButton
value={pickerRange}
+172
View File
@@ -0,0 +1,172 @@
// @vitest-environment jsdom
import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({ fetchNavBadgeCountsApi: vi.fn() }));
vi.mock('../utils/workflowApi', () => ({
fetchNavBadgeCountsApi: (...args: unknown[]) => mocks.fetchNavBadgeCountsApi(...args),
}));
import { menuKeyForPath, useNavBadgeCounts } from './useNavBadgeCounts';
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
mocks.fetchNavBadgeCountsApi.mockResolvedValue({ data: { 'orders-list': 3 } });
});
afterEach(() => {
cleanup();
vi.useRealTimers();
});
describe('useNavBadgeCounts', () => {
it('挂载拉一次,60s 再拉一次', async () => {
const { result } = renderHook(() => useNavBadgeCounts());
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.counts['orders-list']).toBe(3);
expect(mocks.fetchNavBadgeCountsApi).toHaveBeenCalledTimes(1);
expect(mocks.fetchNavBadgeCountsApi).toHaveBeenCalledWith('month');
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000);
});
expect(mocks.fetchNavBadgeCountsApi).toHaveBeenCalledTimes(2);
});
it('页面重新可见时刷新', async () => {
const { result } = renderHook(() => useNavBadgeCounts());
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.counts['orders-list']).toBe(3);
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
mocks.fetchNavBadgeCountsApi.mockResolvedValueOnce({ data: { 'orders-list': 4 } });
await act(async () => {
document.dispatchEvent(new Event('visibilitychange'));
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
});
expect(result.current.counts['orders-list']).toBe(4);
});
it('branchKey 变化:清空并丢弃旧分公司响应', async () => {
let resolveOld: (value: unknown) => void = () => {};
mocks.fetchNavBadgeCountsApi.mockReturnValueOnce(
new Promise((resolve) => {
resolveOld = resolve;
})
);
const { rerender, result } = renderHook(
({ branchKey }) => useNavBadgeCounts('today', branchKey),
{ initialProps: { branchKey: 'BR002' } }
);
mocks.fetchNavBadgeCountsApi.mockResolvedValueOnce({ data: { 'orders-list': 4 } });
rerender({ branchKey: 'BR003' });
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.counts['orders-list']).toBe(4);
await act(async () => {
resolveOld({ data: { 'orders-list': 99 } });
await Promise.resolve();
});
expect(result.current.counts['orders-list']).toBe(4);
});
it('reloadKey 变化只请求当前 menuKey(refresh=1)并合并,不清空', async () => {
let resolveReload: (value: unknown) => void = () => {};
const { rerender, result } = renderHook(
({ reloadKey }) => useNavBadgeCounts('today', 'BR002', reloadKey),
{ initialProps: { reloadKey: '/orders' } }
);
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.counts['orders-list']).toBe(3);
mocks.fetchNavBadgeCountsApi.mockReturnValueOnce(
new Promise((resolve) => {
resolveReload = resolve;
})
);
rerender({ reloadKey: '/purchase' });
expect(result.current.counts['orders-list']).toBe(3); // 刷新期间不清空
expect(mocks.fetchNavBadgeCountsApi).toHaveBeenLastCalledWith('today', ['purchase-list'], true);
await act(async () => {
resolveReload({ data: { 'purchase-list': 5 } });
await Promise.resolve();
});
expect(result.current.counts['orders-list']).toBe(3);
expect(result.current.counts['purchase-list']).toBe(5);
});
it('pathname→menuKey 最长前缀映射,无匹配不发请求', async () => {
expect(menuKeyForPath('/orders/price-qty-requests')).toBe('orders-price-qty');
expect(menuKeyForPath('/orders/bid-invitations')).toBe('orders-bid-invitations');
expect(menuKeyForPath('/orders')).toBe('orders-list');
expect(menuKeyForPath('/purchase/preparations')).toBe('purchase-preparations');
expect(menuKeyForPath('/purchase')).toBe('purchase-list');
expect(menuKeyForPath('/inspection/processing')).toBe('inspection-processing');
expect(menuKeyForPath('/inspection')).toBe('inspection-list');
expect(menuKeyForPath('/picking')).toBe('picking');
expect(menuKeyForPath('/delivery')).toBe('delivery');
expect(menuKeyForPath('/ops')).toBe('ops');
expect(menuKeyForPath('/finance')).toBeNull();
const { rerender } = renderHook(
({ reloadKey }) => useNavBadgeCounts('today', 'BR002', reloadKey),
{ initialProps: { reloadKey: '/orders' } }
);
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
const before = mocks.fetchNavBadgeCountsApi.mock.calls.length;
rerender({ reloadKey: '/finance' });
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
expect(mocks.fetchNavBadgeCountsApi.mock.calls.length).toBe(before);
});
it('失败保留旧值', async () => {
const { result } = renderHook(() => useNavBadgeCounts());
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.counts['orders-list']).toBe(3);
mocks.fetchNavBadgeCountsApi.mockRejectedValueOnce(new Error('offline'));
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000);
});
expect(result.current.counts['orders-list']).toBe(3);
});
it('disabled 时清空且不报错', async () => {
mocks.fetchNavBadgeCountsApi.mockResolvedValueOnce({ data: {}, disabled: true });
const { result } = renderHook(() => useNavBadgeCounts());
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
expect(result.current.disabled).toBe(true);
expect(result.current.counts).toEqual({});
});
it('卸载后不再拉取', async () => {
const { unmount } = renderHook(() => useNavBadgeCounts());
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
const before = mocks.fetchNavBadgeCountsApi.mock.calls.length;
unmount();
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000);
});
expect(mocks.fetchNavBadgeCountsApi.mock.calls.length).toBe(before);
});
});
+123
View File
@@ -0,0 +1,123 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { MENU_CATALOG } from '../config/menuCatalog';
import { fetchNavBadgeCountsApi } from '../utils/workflowApi';
export type NavBadgeScope = 'today' | 'month' | 'all';
/** 后端 NAV_BADGE_COUNTERS 的 key;pathname 只映射这些,避免把无角标菜单发给接口 */
export const NAV_BADGE_MENU_KEYS = new Set([
'orders-list',
'purchase-list',
'purchase-preparations',
'orders-price-qty',
'orders-bid-invitations',
'inspection-list',
'inspection-processing',
'picking',
'delivery',
'ops',
]);
/** pathname → menuKey:MENU_CATALOG 最长前缀匹配(只认有角标的 key)。 */
export function menuKeyForPath(pathname: string): string | null {
const path = String(pathname || '').split('?')[0].split('#')[0];
if (!path) return null;
let best: { key: string; path: string } | null = null;
for (const entry of MENU_CATALOG) {
if (!NAV_BADGE_MENU_KEYS.has(entry.menuKey)) continue;
const catalogPath = String(entry.path || '');
if (!catalogPath) continue;
if (path !== catalogPath && !path.startsWith(`${catalogPath}/`)) continue;
if (!best || catalogPath.length > best.path.length) {
best = { key: entry.menuKey, path: catalogPath };
}
}
return best?.key || null;
}
/**
* 侧边栏角标:挂载/切分公司/60s/可见时拉全量;路由变化只刷新当前 menuKey(refresh=1)。
*
* - branchKey 变化:清空旧值并换代,旧响应必须丢弃(切分公司竞态)。
* - reloadKey(pathname)变化:只请求当前 key 并合并,不清空;无匹配不发请求。
* - 任一请求带 seq;旧响应不能覆盖新值;失败保留旧值。
*/
export function useNavBadgeCounts(
scope: NavBadgeScope = 'month',
branchKey = '',
reloadKey = ''
) {
const [counts, setCounts] = useState<Record<string, number>>({});
const [disabled, setDisabled] = useState(false);
const mountedRef = useRef(true);
const seqRef = useRef(0);
const prevReloadRef = useRef(reloadKey);
const load = useCallback(async () => {
const seq = ++seqRef.current;
try {
const result = await fetchNavBadgeCountsApi(scope);
if (!mountedRef.current || seq !== seqRef.current) return;
if (result?.disabled) {
setDisabled(true);
setCounts({});
return;
}
setDisabled(false);
setCounts(result?.data || {});
} catch {
// 失败保留旧值:角标不是主流程,不能让一次网络抖动把数字清零
}
}, [scope]);
const loadMenu = useCallback(
async (menuKey: string) => {
const seq = ++seqRef.current;
try {
const result = await fetchNavBadgeCountsApi(scope, [menuKey], true);
if (!mountedRef.current || seq !== seqRef.current) return;
if (result?.disabled) {
setDisabled(true);
setCounts({});
return;
}
setDisabled(false);
setCounts((prev) => ({ ...prev, ...(result?.data || {}) }));
} catch {
// 切页刷新失败保留旧值
}
},
[scope]
);
useEffect(() => {
mountedRef.current = true;
// 切分公司/账号先清空(旧响应因 seq 不匹配而丢弃)
setCounts({});
setDisabled(false);
void load();
const timer = window.setInterval(() => {
void load();
}, 60_000);
const onVisibilityChange = () => {
if (document.visibilityState === 'visible') void load();
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => {
mountedRef.current = false;
seqRef.current += 1;
window.clearInterval(timer);
document.removeEventListener('visibilitychange', onVisibilityChange);
};
}, [load, branchKey]);
// 路由变化只刷新当前 key,不清空旧值;首次挂载由上面的 branch effect 负责
useEffect(() => {
if (prevReloadRef.current === reloadKey) return;
prevReloadRef.current = reloadKey;
const menuKey = menuKeyForPath(reloadKey);
if (menuKey) void loadMenu(menuKey);
}, [loadMenu, reloadKey]);
return { counts, disabled };
}
+1
View File
@@ -49,6 +49,7 @@ export const common = {
'listDate.ariaOrder': 'Order date filter',
'listDate.today': 'Today',
'listDate.last7': 'Last 7 days',
'listDate.all': 'All dates',
'listDate.specified': 'Range',
'listDate.empty': 'Pick start and end',
preparing: 'Preparing…',
+1
View File
@@ -49,6 +49,7 @@ export const common = {
'listDate.ariaOrder': 'Filter tgl pesan',
'listDate.today': 'Hari ini',
'listDate.last7': '7 hari',
'listDate.all': 'Semua tanggal',
'listDate.specified': 'Pilih',
'listDate.empty': 'Pilih awal dan akhir',
preparing: 'Menyiapkan…',
+1
View File
@@ -49,6 +49,7 @@ export const common = {
'listDate.ariaOrder': '下单日筛选',
'listDate.today': '今天',
'listDate.last7': '近七天',
'listDate.all': '全部日期',
'listDate.specified': '指定',
'listDate.empty': '选择起止日期',
preparing: '准备中…',
@@ -1718,6 +1718,8 @@ export const DeliveryManagement: React.FC = () => {
range={dateRange}
onPresetChange={setDatePreset}
onRangeChange={setDateRange}
showAll
clearPreset="all"
trailing={
<>
<DocumentExportButton
+15
View File
@@ -7500,3 +7500,18 @@ export async function confirmReturnQualityApi(returnCode: string, qualified: boo
{ method: 'POST', body: JSON.stringify({ qualified }) }
).then((r) => r.data);
}
/**
* 菜单角标(task-36 后端聚合接口)。
* 默认关闭时后端返回 `{data:{},disabled:true}`;调用方据此不显示角标。
*/
export async function fetchNavBadgeCountsApi(
scope: 'today' | 'month' | 'all' = 'month',
menus?: string[],
refresh = false
) {
const params = new URLSearchParams({ scope });
if (menus?.length) params.set('menus', menus.join(','));
if (refresh) params.set('refresh', '1');
return workflowFetch<{ data: Record<string, number>; disabled?: boolean }>(`/nav-badges?${params.toString()}`);
}