来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
223 lines
9.4 KiB
TypeScript
223 lines
9.4 KiB
TypeScript
/**
|
||
* 验收照片归档:核心不变量与月份口径。
|
||
*
|
||
* 重点钉住三条(其余为口径回归):
|
||
* I1 归档包写入失败 → **一个原件都不能删**(先验证后删)
|
||
* I2 只删本轮入包的文件名;库内无引用的孤儿对象不碰
|
||
* I4 幂等:已完成月份直接跳过;未满期的月份拒绝归档
|
||
*/
|
||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
const state = vi.hoisted(() => ({
|
||
sql: [] as string[],
|
||
params: [] as unknown[][],
|
||
ledger: null as null | { id: string; status: number },
|
||
refs: [] as string[],
|
||
failUpload: false,
|
||
deleted: [] as string[],
|
||
putCalls: 0,
|
||
getCalls: 0,
|
||
}));
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: {
|
||
query: vi.fn(async (sql: string, params?: unknown[]) => {
|
||
state.sql.push(sql.replace(/\s+/g, ' ').trim());
|
||
state.params.push(params || []);
|
||
if (/FROM inspection_photo_archive_entries/.test(sql)) return { rowCount: 0, rows: [] };
|
||
if (/SELECT id, status FROM inspection_photo_archives/.test(sql)) {
|
||
return state.ledger ? { rowCount: 1, rows: [state.ledger] } : { rowCount: 0, rows: [] };
|
||
}
|
||
if (/INSERT INTO inspection_photo_archives/.test(sql)) {
|
||
state.ledger = { id: 'archive-1', status: 10 };
|
||
return { rowCount: 1, rows: [{ id: 'archive-1' }] };
|
||
}
|
||
if (/SELECT DISTINCT p AS filename/.test(sql)) {
|
||
// 只让 inspections 这一路有引用,processing_tasks 走空 → 断言聚焦单一来源
|
||
const list = /FROM processing_tasks/.test(sql) ? [] : state.refs;
|
||
return { rowCount: list.length, rows: list.map((filename) => ({ filename })) };
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}),
|
||
},
|
||
getRawPoolQuery: () => vi.fn(),
|
||
}));
|
||
|
||
vi.mock('../src/services/tenantDbContext', () => ({
|
||
runWithTenantDbContext: (_branch: string, fn: () => Promise<unknown>) => fn(),
|
||
}));
|
||
|
||
vi.mock('../src/services/platformBranch', () => ({
|
||
listActiveBranchCodes: async () => ['BR002'],
|
||
}));
|
||
|
||
const storage = vi.hoisted(() => ({
|
||
getObject: vi.fn(async (_bucket: string, filename: string) => {
|
||
state.getCalls += 1;
|
||
if (filename.includes('missing')) return null;
|
||
return { buffer: Buffer.from(`bytes:${filename}`), contentType: 'image/jpeg' };
|
||
}),
|
||
putObjectStream: vi.fn(async (_bucket: string, _name: string, source: NodeJS.ReadableStream) => {
|
||
state.putCalls += 1;
|
||
let bytes = 0;
|
||
for await (const chunk of source as AsyncIterable<Buffer>) bytes += chunk.length;
|
||
if (state.failUpload) throw new Error('upload boom');
|
||
return { bytes };
|
||
}),
|
||
deleteObject: vi.fn(async (_bucket: string, filename: string) => {
|
||
state.deleted.push(filename);
|
||
}),
|
||
exists: vi.fn(async () => true),
|
||
}));
|
||
|
||
vi.mock('../src/services/storageProvider', () => ({
|
||
getStorageProvider: () => storage,
|
||
}));
|
||
|
||
import {
|
||
archivableMonths,
|
||
chinaMonthKey,
|
||
chinaMonthLastDay,
|
||
PHOTO_ARCHIVE_LOCK_KEY,
|
||
photoTimestampMs,
|
||
runInspectionPhotoArchive,
|
||
} from '../src/services/inspectionPhotoArchiveService';
|
||
|
||
// 目标月不写死:按当前默认口径(60 天)取「最新可归档月」,避免测试被绝对日期绑死
|
||
const TARGET_YM = archivableMonths(Date.now())[0];
|
||
const TARGET_TS = Date.UTC(
|
||
Number(TARGET_YM.slice(0, 4)),
|
||
Number(TARGET_YM.slice(5, 7)) - 1,
|
||
15,
|
||
4,
|
||
0,
|
||
0
|
||
);
|
||
const refInTarget = `合格/ku-gua-${TARGET_TS}-abc123.jpg`;
|
||
const missingInTarget = `合格/missing-${TARGET_TS}-zzz999.jpg`;
|
||
|
||
describe('照片归档:月份口径(纯函数)', () => {
|
||
it('文件名时间戳解析覆盖两种真实形状', () => {
|
||
expect(photoTimestampMs('合格/lian-hua-bai-1786020214310-8297nk.jpg')).toBe(1786020214310);
|
||
expect(photoTimestampMs('合格/lao-nan-gua/1786659046419-oyo6jk.jpg')).toBe(1786659046419);
|
||
expect(photoTimestampMs('合格/no-timestamp.jpg')).toBeNull();
|
||
});
|
||
|
||
it('按中国时区归月(+08:00)', () => {
|
||
// 2026-07-31T17:00:00Z = 2026-08-01 01:00 北京 → 应归 8 月
|
||
expect(chinaMonthKey(Date.UTC(2026, 6, 31, 17, 0, 0))).toBe('2026-08');
|
||
expect(chinaMonthKey(Date.UTC(2026, 6, 31, 15, 0, 0))).toBe('2026-07');
|
||
expect(chinaMonthLastDay('2026-02')).toBe('2026-02-28');
|
||
expect(chinaMonthLastDay('2026-07')).toBe('2026-07-31');
|
||
});
|
||
|
||
it('只把「已结束且整月满保留期」的月份列为可归档,且由新到旧', () => {
|
||
const asOf = Date.UTC(2026, 8, 23, 4, 0, 0); // 2026-09-23 12:00 北京
|
||
const months = archivableMonths(asOf, 30);
|
||
// 30 天口径(旧):2026-07(07-31+30d=08-30 ≤ 今天)可归档
|
||
expect(months[0]).toBe('2026-07');
|
||
expect(months).not.toContain('2026-08');
|
||
expect(months).not.toContain('2026-09');
|
||
// 降序
|
||
expect([...months].sort().reverse()).toEqual(months);
|
||
});
|
||
|
||
it('当前口径 60 天:整月满 60 天才归档(2026-07 要等 09-29 之后)', () => {
|
||
const asOf = Date.UTC(2026, 8, 23, 4, 0, 0); // 2026-09-23 12:00 北京
|
||
// asOf - 60d = 2026-07-25;2026-07 最后一天 07-31 尚未到期 → 最新可归档月是 2026-06
|
||
const months = archivableMonths(asOf, 60);
|
||
expect(months[0]).toBe('2026-06');
|
||
expect(months).not.toContain('2026-07');
|
||
// 07-31 + 60d = 09-29,从这天起 2026-07 才可归档
|
||
expect(archivableMonths(Date.UTC(2026, 8, 28, 4, 0, 0), 60)).not.toContain('2026-07');
|
||
expect(archivableMonths(Date.UTC(2026, 8, 29, 4, 0, 0), 60)).toContain('2026-07');
|
||
// 同一时点用旧口径 30 天,2026-07 当时就可归档 —— 证明这次改的是「口径」而不是别的
|
||
expect(archivableMonths(asOf, 30)[0]).toBe('2026-07');
|
||
});
|
||
});
|
||
|
||
describe('照片归档:核心不变量', () => {
|
||
beforeEach(() => {
|
||
state.sql = [];
|
||
state.params = [];
|
||
state.ledger = null;
|
||
state.refs = [refInTarget, missingInTarget];
|
||
state.failUpload = false;
|
||
state.deleted = [];
|
||
state.putCalls = 0;
|
||
state.getCalls = 0;
|
||
vi.clearAllMocks();
|
||
});
|
||
|
||
it('I1 归档包写入失败 → 一个原件都不删,台账记 status=30', async () => {
|
||
state.failUpload = true;
|
||
const result = await runInspectionPhotoArchive({ months: [TARGET_YM], branchCodes: ['BR002'], dryRun: false });
|
||
|
||
expect(storage.deleteObject).not.toHaveBeenCalled();
|
||
expect(result.archived).toHaveLength(0);
|
||
expect(result.failures.length).toBeGreaterThan(0);
|
||
const failed = state.sql.some((sql) => /status = 30/.test(sql));
|
||
expect(failed, '应把台账置为失败态').toBe(true);
|
||
});
|
||
|
||
it('成功路径:入包 → 写条目 → 置 20 → 才删原件(且只删入包的)', async () => {
|
||
const result = await runInspectionPhotoArchive({ months: [TARGET_YM], branchCodes: ['BR002'], dryRun: false });
|
||
|
||
expect(state.putCalls).toBe(1);
|
||
expect(storage.deleteObject).toHaveBeenCalledTimes(1);
|
||
expect(state.deleted).toEqual([refInTarget]); // 缺失对象不在删除列表里(I2)
|
||
// 两个候选:一个桶内存在、一个引用存在但对象已缺失 → 只入包/只删存在的那个
|
||
expect(result.archived[0]).toMatchObject({ branch_code: 'BR002', ym: TARGET_YM, entries: 1, purged: 1, missing: 1 });
|
||
expect(result.warnings.some((w) => w.includes('对象缺失'))).toBe(true);
|
||
|
||
// 顺序:条目写入 + 置 20 都发生在 deleteObject 之前
|
||
const upsertIdx = state.sql.findIndex((sql) => /INSERT INTO inspection_photo_archives/.test(sql));
|
||
const entryIdx = state.sql.findIndex((sql) => /INSERT INTO inspection_photo_archive_entries/.test(sql));
|
||
const doneIdx = state.sql.findIndex((sql) => /status = 20/.test(sql));
|
||
const purgedIdx = state.sql.findIndex((sql) => /purged_at = NOW\(\)/.test(sql));
|
||
expect(upsertIdx).toBeGreaterThanOrEqual(0);
|
||
expect(entryIdx).toBeGreaterThan(upsertIdx);
|
||
expect(doneIdx).toBeGreaterThan(entryIdx);
|
||
expect(purgedIdx).toBeGreaterThan(doneIdx);
|
||
});
|
||
|
||
it('I4 幂等:该月台账已完成 → 跳过,不碰存储', async () => {
|
||
state.ledger = { id: 'archive-1', status: 20 };
|
||
const result = await runInspectionPhotoArchive({ months: [TARGET_YM], branchCodes: ['BR002'], dryRun: false });
|
||
|
||
expect(result.archived).toHaveLength(0);
|
||
expect(result.skipped.some((s) => s.reason === 'already_archived')).toBe(true);
|
||
expect(state.putCalls).toBe(0);
|
||
expect(storage.deleteObject).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('干跑:只出计划,不写包、不写台账、不删', async () => {
|
||
const result = await runInspectionPhotoArchive({ months: [TARGET_YM], branchCodes: ['BR002'], dryRun: true });
|
||
|
||
expect(result.dry_run).toBe(true);
|
||
// 干跑不探测对象是否存在,因此两个候选都计入计划
|
||
expect(result.plan).toEqual([
|
||
{ branch_code: 'BR002', bucket: 'inspection-photos', ym: TARGET_YM, entries: 2, already_archived: false },
|
||
]);
|
||
expect(state.putCalls).toBe(0);
|
||
expect(storage.deleteObject).not.toHaveBeenCalled();
|
||
expect(state.sql.some((sql) => /INSERT INTO inspection_photo_archives/.test(sql))).toBe(false);
|
||
});
|
||
|
||
it('未满期的月份拒绝归档(保护在途数据)', async () => {
|
||
const asOfMonth = chinaMonthKey(Date.now());
|
||
const result = await runInspectionPhotoArchive({
|
||
months: [asOfMonth],
|
||
branchCodes: ['BR002'],
|
||
dryRun: false,
|
||
});
|
||
expect(result.archived).toHaveLength(0);
|
||
expect(result.skipped.some((s) => s.reason === 'not_eligible_yet')).toBe(true);
|
||
expect(state.putCalls).toBe(0);
|
||
});
|
||
|
||
it('锁 key 常量稳定(定时任务与手动补跑共用)', () => {
|
||
expect(PHOTO_ARCHIVE_LOCK_KEY).toBe('scheduler:inspection-photo-archive');
|
||
});
|
||
});
|