Archived
放行存档(archiveAssetFiles)与在办列单(assetFilesOf)取行都用 taskView(where:{}) ——
那是「正式版全表 + 本单草稿」的合并视图,而资料常落在主数据上,整表里躺着别单放行过的行。
抽 assetRowsOf 两处同用,touched 为必填入参;e2e 补份数断言。
顺手清两笔:wake.test.ts 的 as unknown as(lint 红)、wake 契约的 api-report 快照(api:check 红)。
217 lines
9.8 KiB
TypeScript
217 lines
9.8 KiB
TypeScript
/**
|
|
* 产出的资料文件**存档** —— 放行那一刻把它冻住。
|
|
*
|
|
* 在办期间文件是台账那一行的投影(现造,见 `file-compose.ts`):台账改一格,文件跟着变,
|
|
* 两处永远一致 —— 那时这样最好。**收工之后不该再变**:归档件说的是「他签字那一刻
|
|
* 交出去的是什么」,台账后来被下一单改了,归档的那份不能跟着改口。
|
|
*
|
|
* 还有一条更硬的理由:资料常落在**主数据**上(如 `content.asset` 品牌内容库),
|
|
* 而试跑单放行时主数据只留在活动缓存、不落正式表(免得试跑往正式库里塞真资产)——
|
|
* 不存这一份,试跑单一放行,人在工作成果里就什么都点不开了。
|
|
*
|
|
* 一单一行一份,重复放行覆盖(不留两份说法不一的档)。
|
|
*
|
|
* **「这一单产出的」认的是本单碰过的行**,不是这张表里现有的所有行 ——
|
|
* 见 `assetRowsOf` 的病根记档。
|
|
*/
|
|
import { sql } from 'drizzle-orm';
|
|
import type { TaskId } from '@contracts';
|
|
import { composeFile, isFileFormat, type FileFormat } from './file-compose.ts';
|
|
|
|
/** 存档里的一份 —— 列表用(不带字节) */
|
|
export type ArchivedAssetFile = {
|
|
readonly id: string;
|
|
readonly address: string;
|
|
readonly key: Record<string, string>;
|
|
readonly title: string;
|
|
readonly format: FileFormat;
|
|
readonly name: string;
|
|
readonly size: number;
|
|
readonly at: string;
|
|
};
|
|
|
|
type Db = { execute(query: unknown): Promise<unknown> };
|
|
|
|
function rowsOf<T>(result: unknown): T[] {
|
|
if (Array.isArray(result)) return result as T[];
|
|
const rows = (result as { rows?: unknown }).rows;
|
|
return Array.isArray(rows) ? (rows as T[]) : [];
|
|
}
|
|
|
|
/** 一张台账表的声明 —— 带 `file` 段的才产资料;这份声明同时是授权面 */
|
|
export type AssetDeclaration = {
|
|
readonly domain: string;
|
|
readonly object: string;
|
|
readonly fields: ReadonlyArray<{ name: string; primaryKey?: boolean }>;
|
|
readonly file?: { titleColumn: string; bodyColumn: string; formatColumn: string } | undefined;
|
|
};
|
|
|
|
/** 本单碰过的一行(`ledger.taskDrafts()` 那一份的形状) */
|
|
export type TouchedKey = {
|
|
readonly domain: string;
|
|
readonly object: string;
|
|
readonly key: Readonly<Record<string, unknown>>;
|
|
};
|
|
|
|
/** 这一单产出的一份资料 —— 还没造成字节的那一步 */
|
|
export type AssetRow = {
|
|
readonly address: string;
|
|
readonly key: Record<string, string>;
|
|
readonly title: string;
|
|
readonly format: FileFormat;
|
|
readonly markdown: string;
|
|
};
|
|
|
|
/**
|
|
* 这一单**产出的**资料行 —— 存档与工作成果两处同一段,不各写一份。
|
|
*
|
|
* 「产出的」认的是**本单碰过的行**(草稿键),不是这张表里现有的所有行。
|
|
* 病根记档(2026-08-25 柴浩实测:「工作成果怎么有 4 个资料,这单只会产出一个」):
|
|
* 两处从前都拿 `taskView` 的整页,而那是「正式版全表 + 本单草稿」的合并视图 ——
|
|
* 资料常落在**主数据**上(品牌内容库 `content.asset`,历次跑出来的资产都躺在里面),
|
|
* 于是一单产 1 份、工作成果里摆 4 份:前三份是别单的成果,冒充这一单交出去的东西。
|
|
* 台账契约本就把这两件事分得很清楚(`taskDrafts` 的注释:「引擎求值要区分
|
|
* 『这一单的事实』与『别人放行后的事实』」),视图模版也一律绑 `mine:` ——
|
|
* 只有资料这两处忘了。
|
|
*
|
|
* 值仍取合并视图那一份(正式现值 + 本单草稿叠加):改过一格的行要按
|
|
* 「落库后的样子」造文件,只拿草稿会缺掉这轮没碰过的那几列(与 `touched:` 同一道理)。
|
|
*/
|
|
export function assetRowsOf(
|
|
declared: AssetDeclaration,
|
|
rows: ReadonlyArray<Record<string, unknown>>,
|
|
touched: ReadonlyArray<TouchedKey>,
|
|
): AssetRow[] {
|
|
const spec = declared.file;
|
|
if (spec === undefined) return []; // 没声明 `file` 段的表不产资料 —— 存档与列表都认这道授权面
|
|
const keys = declared.fields.filter((f) => f.primaryKey === true).map((f) => f.name);
|
|
if (keys.length === 0) return [];
|
|
const mine = touched.filter((t) => t.domain === declared.domain && t.object === declared.object);
|
|
const address = `${declared.domain}.${declared.object}`;
|
|
const out: AssetRow[] = [];
|
|
for (const row of rows) {
|
|
const key: Record<string, string> = {};
|
|
for (const k of keys) key[k] = String(row[k] ?? '');
|
|
if (Object.values(key).some((v) => v === '')) continue; // 主键不全的行认不出来,存了也取不回
|
|
if (!mine.some((t) => keys.every((k) => String(t.key[k] ?? '') === key[k]))) continue; // 别单的成果不算这一单的
|
|
const markdown = String(row[spec.bodyColumn] ?? '').trim();
|
|
if (markdown === '') continue; // 没正文的行不是资料,别摆一份空壳
|
|
const title = String(row[spec.titleColumn] ?? '').trim() || Object.values(key).join('-');
|
|
const rawFormat = String(row[spec.formatColumn] ?? '').trim().toLowerCase();
|
|
out.push({ address, key, title, format: isFileFormat(rawFormat) ? rawFormat : 'md', markdown });
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* 主键 → 一个**稳定的**字符串(按列名排序后拼)。
|
|
* 稳定是要害:存的时候与取的时候拼法不一样,那一行就永远对不上。
|
|
*/
|
|
export function keyText(key: Readonly<Record<string, unknown>>): string {
|
|
return Object.keys(key)
|
|
.sort()
|
|
.map((k) => `${k}=${String(key[k] ?? '')}`)
|
|
.join(',');
|
|
}
|
|
|
|
/** 这一单已存档的资料(不含字节) */
|
|
export async function listArchived(db: Db, taskId: TaskId): Promise<ArchivedAssetFile[]> {
|
|
const rows = rowsOf<{
|
|
id: string;
|
|
address: string;
|
|
row_key: unknown;
|
|
title: string;
|
|
format: string;
|
|
name: string;
|
|
size: number;
|
|
created_at: unknown;
|
|
}>(
|
|
await db.execute(sql`
|
|
select id, address, row_key, title, format, name, size, created_at
|
|
from sys.task_asset_file where task_id = ${taskId} order by created_at, name`),
|
|
);
|
|
return rows.map((r) => ({
|
|
id: r.id,
|
|
address: r.address,
|
|
key: (typeof r.row_key === 'object' && r.row_key !== null ? r.row_key : {}) as Record<string, string>,
|
|
title: r.title,
|
|
format: isFileFormat(r.format) ? r.format : 'md',
|
|
name: r.name,
|
|
size: Number(r.size ?? 0),
|
|
at: r.created_at instanceof Date ? r.created_at.toISOString() : String(r.created_at),
|
|
}));
|
|
}
|
|
|
|
/** 取存档里的那一份字节 —— 按 (单, 地址, 主键) 认 */
|
|
export async function readArchived(
|
|
db: Db,
|
|
taskId: TaskId,
|
|
address: string,
|
|
key: Readonly<Record<string, string>>,
|
|
): Promise<{ bytes: Uint8Array; title: string; format: FileFormat; name: string } | undefined> {
|
|
const rows = rowsOf<{ bytes: unknown; title: string; format: string; name: string }>(
|
|
await db.execute(sql`
|
|
select bytes, title, format, name from sys.task_asset_file
|
|
where task_id = ${taskId} and address = ${address} and row_key = ${JSON.stringify(key)}::jsonb
|
|
limit 1`),
|
|
);
|
|
const one = rows[0];
|
|
if (one === undefined) return undefined;
|
|
const raw = one.bytes;
|
|
/*
|
|
* **必须拷一份成独立的 Uint8Array** —— pg 取回来的是 Node `Buffer`,
|
|
* 而 Buffer 挂在一块**共享的 64KB 内存池**上:`buf.slice()` 是视图不是拷贝,
|
|
* `.buffer` 拿到的是整个池子。直接交出去,一份 3KB 的文件会变成 65536 字节
|
|
* (后面全是别人的残渣)—— 实测下载三份资料,三份都是 65536。
|
|
* `Uint8Array.from` 按元素拷,新数组的 buffer 恰好这么长。
|
|
*/
|
|
const bytes =
|
|
raw instanceof Uint8Array
|
|
? Uint8Array.from(raw)
|
|
: typeof raw === 'string'
|
|
? Uint8Array.from(Buffer.from(raw, 'hex'))
|
|
: undefined;
|
|
if (bytes === undefined) return undefined;
|
|
return { bytes, title: one.title, format: isFileFormat(one.format) ? one.format : 'md', name: one.name };
|
|
}
|
|
|
|
/**
|
|
* 把这一单产出的资料**全部存一份**。放行落地之前调 —— 那时草稿还在、人的修订也已落回,
|
|
* 存下来的正是他签字那一刻的样子。
|
|
*
|
|
* 返回存了几份;一份都没有(活动没声明 `file` 段、或这一单一行也没写)时返回 0,不报错 ——
|
|
* 大多数活动本来就不产资料文件。
|
|
*/
|
|
export async function archiveAssetFiles(input: {
|
|
readonly db: Db;
|
|
readonly taskId: TaskId;
|
|
readonly ids: { next(): string };
|
|
/** 活动清单声明的台账对象(带 `file` 段的才算) */
|
|
readonly declarations: ReadonlyArray<AssetDeclaration>;
|
|
/**
|
|
* **本单碰过的行** —— `ledger.taskDrafts()` 那一份。
|
|
* 「哪几行是这一单产出的」只有这一个答案:表里现有的行不作数(见 `assetRowsOf`)。
|
|
*/
|
|
readonly touched: ReadonlyArray<TouchedKey>;
|
|
/** 该地址的合并行(正式现值 + 本单草稿)—— 值按「落库后的样子」造文件 */
|
|
readonly rowsOfAddress: (address: { domain: string; object: string }) => Promise<Array<Record<string, unknown>>>;
|
|
}): Promise<number> {
|
|
let saved = 0;
|
|
for (const declared of input.declarations) {
|
|
if (declared.file === undefined) continue; // 整张表不产资料,连取行都免了
|
|
const rows = await input.rowsOfAddress({ domain: declared.domain, object: declared.object });
|
|
for (const asset of assetRowsOf(declared, rows, input.touched)) {
|
|
const composed = composeFile({ title: asset.title, markdown: asset.markdown, format: asset.format });
|
|
await input.db.execute(sql`
|
|
insert into sys.task_asset_file (id, task_id, address, row_key, title, format, name, bytes, size)
|
|
values (${input.ids.next()}, ${input.taskId}, ${asset.address}, ${JSON.stringify(asset.key)}::jsonb,
|
|
${asset.title}, ${asset.format}, ${composed.fileName}, ${Buffer.from(composed.bytes)}, ${composed.bytes.length})
|
|
on conflict (task_id, address, row_key) do update set
|
|
title = excluded.title, format = excluded.format, name = excluded.name,
|
|
bytes = excluded.bytes, size = excluded.size, created_at = now()`);
|
|
saved += 1;
|
|
}
|
|
}
|
|
return saved;
|
|
}
|