import { readFileSync } from 'fs'; import path from 'path'; import { describe, expect, it } from 'vitest'; import { DELIVERY_DEADLINE_AT_SAFE_SQL, DELIVERY_DEADLINE_PARSEABLE_SQL, DELIVERY_DEADLINE_TIME_TEXT_SQL, } from '../src/services/deliveryDeadlineSql'; /** * P0-3 回归护栏:`customers.delivery_time` 是**自由文本**(如「早上8点」「早 6-8 点」), * 任何 `(delivery_date::text || ' ' || delivery_time || ':00')::timestamp` 的写法都会抛 * `invalid input syntax for type timestamp`,而看板 periodStats 是 Promise.all 的第一条 → * /dashboard/summary 整页 500(销售/成本/损耗/客户画像全部不可用)。 * 见 docs/design/20260914-on-time-deadline-parse.md */ const repoRoot = path.join(__dirname, '..', '..'); const readSrc = (rel: string) => readFileSync(path.join(repoRoot, rel), 'utf8'); describe('须送达时刻解析:只用 CASE 短路的安全实现', () => { it('看板不再把自由文本裸转 timestamp', () => { const src = readSrc('server/src/services/dashboardService.ts'); expect(src).not.toMatch(/delivery_time[^\n]*\|\|\s*':00'\)::timestamp/); expect(src).not.toMatch(/\|\|\s*':00'\)::timestamp/); expect(src).toContain('DELIVERY_DEADLINE_AT_SAFE_SQL'); }); it('安全实现是 CASE 短路:正则命中才做 split_part(...)::int,越界走内层 CASE', () => { expect(DELIVERY_DEADLINE_AT_SAFE_SQL).toContain('CASE'); expect(DELIVERY_DEADLINE_AT_SAFE_SQL).toContain('WHEN NULLIF(TRIM(c.delivery_time), \'\') IS NULL THEN NULL'); expect(DELIVERY_DEADLINE_AT_SAFE_SQL).toContain(DELIVERY_DEADLINE_PARSEABLE_SQL); // 小时范围校验必须在正则之后(内层 CASE),否则 25:00 会算出错误时间 expect(DELIVERY_DEADLINE_AT_SAFE_SQL).toMatch(/BETWEEN 0 AND 23 THEN/); // 不含任何裸 ::timestamp 转换 expect(DELIVERY_DEADLINE_AT_SAFE_SQL).not.toContain('::timestamp'); }); it('文本归一化支持全角冒号与首尾空白', () => { expect(DELIVERY_DEADLINE_TIME_TEXT_SQL).toBe("replace(TRIM(c.delivery_time), ':', ':')"); expect(DELIVERY_DEADLINE_PARSEABLE_SQL).toContain('[0-9]{1,2}:[0-5][0-9]'); }); it('看板 on_time 口径保持:未设/无法解析按准时计(deadline 为 NULL 不算超时)', () => { const src = readSrc('server/src/services/dashboardService.ts'); expect(src).toContain('NOT (d.deadline_at IS NOT NULL AND d.delivered_at > d.deadline_at)'); }); });