Files
tap/lib/server/attachments.ts

100 lines
6.7 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, STAGED_ATTACHMENT_TTL_MS, type Attachment } from '../attachments.ts';
import type { Demand } from '../demand.ts';
import { invalidateProposal } from '../demand-review.ts';
import { AuthError, jsonResponse } from './auth.ts';
import { getDatabase } from './database.ts';
import { readableDemandWhere, readableDemandBindings, type DemandViewer } from './demand-access.ts';
type AttachmentRow = { id: string; owner_id: string; demand_id: string | null; name: string; size: number; created_at: string };
const metadata = (row: AttachmentRow): Attachment => ({ id: row.id, name: row.name, size: row.size, createdAt: row.created_at });
const idSchema = z.string().uuid();
export function attachmentIds(value: unknown): string[] | undefined {
if (value === undefined) return undefined;
const parsed = z.array(idSchema).max(MAX_ATTACHMENTS).safeParse(value);
if (!parsed.success || new Set(parsed.data).size !== parsed.data.length) throw new AuthError(`附件列表无效,每条需求最多 ${MAX_ATTACHMENTS} 个附件。`);
return parsed.data;
}
export function storeUpload(userId: string, inputName: string, bytes: Uint8Array): Attachment {
const name = inputName.replace(/[\\/\u0000-\u001f\u007f]/g, '_').trim();
if (!name || name.length > 200) throw new AuthError('文件名须为 1–200 个字符。');
if (!bytes.byteLength) throw new AuthError('不能上传空文件。');
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) throw new AuthError('单个文件不能超过 20 MB。', 413);
const database = getDatabase();
return database.transaction(() => {
const now = new Date().toISOString();
database.prepare('DELETE FROM attachments WHERE demand_id IS NULL AND created_at < ?').bind(new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()).run();
const pending = database.prepare('SELECT COUNT(*) AS count FROM attachments WHERE owner_id = ? AND demand_id IS NULL').bind(userId).first<{ count: number }>()!;
if (pending.count >= MAX_ATTACHMENTS) throw new AuthError('未保存附件已达 10 个,请先保存需求或移除未使用的附件。', 409);
const id = randomUUID();
database.prepare('INSERT INTO attachments (id, owner_id, name, size, content, created_at) VALUES (?, ?, ?, ?, ?, ?)').bind(id, userId, name, bytes.byteLength, bytes, now).run();
return { id, name, size: bytes.byteLength, createdAt: now };
});
}
/** Called inside the same transaction that writes the demand. No claims or removals escape a failed save. */
export function syncDemandAttachments(record: Demand, ownerId: string, ids: string[] | undefined, now: string): boolean {
if (ids === undefined) return false;
const database = getDatabase();
const cutoff = new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString();
const selected = ids.map(id => {
const row = database.prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE id = ?').bind(id).first<AttachmentRow>();
if (!row || row.owner_id !== ownerId || (row.demand_id !== null && row.demand_id !== record.id) || (!row.demand_id && row.created_at < cutoff)) throw new AuthError('附件已失效或无法访问,请移除后重新上传。');
return metadata(row);
});
const before = (record.attachments ?? []).map(file => file.id).sort().join(',');
const changed = before !== [...ids].sort().join(',');
if (changed) invalidateProposal(record, now, '参考附件已修改,需开发责任人重新提交方案并由业务方确认。');
record.attachments = selected;
return changed;
}
/** The demand row must exist first so foreign keys remain valid. Historical review files are retained. */
export function commitDemandAttachments(record: Demand, ownerId: string): void {
const database = getDatabase();
for (const file of record.attachments ?? []) database.prepare('UPDATE attachments SET demand_id = ? WHERE id = ? AND owner_id = ? AND demand_id IS NULL').bind(record.id, file.id, ownerId).run();
const retained = new Set([
...(record.attachments ?? []).map(file => file.id),
...(record.review?.proposals ?? []).flatMap(proposal => (proposal.businessAttachments ?? []).map(file => file.id)),
]);
for (const row of database.prepare('SELECT id FROM attachments WHERE demand_id = ?').bind(record.id).all<{ id: string }>().results) {
if (!retained.has(row.id)) database.prepare('DELETE FROM attachments WHERE id = ? AND demand_id = ?').bind(row.id, record.id).run();
}
}
export function downloadAttachment(id: string, user: DemandViewer): { file: Attachment; bytes: Uint8Array } {
if (!idSchema.safeParse(id).success) throw new AuthError('找不到该附件或你没有访问权限。', 404);
const database = getDatabase();
const row = database.prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE id = ?').bind(id).first<AttachmentRow>();
if (!row) throw new AuthError('找不到该附件或你没有访问权限。', 404);
if (row.demand_id) {
const demand = database.prepare(`SELECT id FROM demands WHERE id = ? AND ${readableDemandWhere}`)
.bind(row.demand_id, ...readableDemandBindings(user)).first();
if (!demand) throw new AuthError('找不到该附件或你没有访问权限。', 404);
} else if (row.owner_id !== user.userId || row.created_at < new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()) {
throw new AuthError('找不到该附件或你没有访问权限。', 404);
}
const content = database.prepare('SELECT content FROM attachments WHERE id = ?').bind(id).first<{ content: Uint8Array }>()!;
return { file: metadata(row), bytes: content.content };
}
export function deleteStagedAttachment(id: string, userId: string): void {
const database = getDatabase();
const result = database.prepare('DELETE FROM attachments WHERE id = ? AND owner_id = ? AND demand_id IS NULL').bind(id, userId).run();
if (!result.meta.changes) throw new AuthError('该附件已保存或无法访问,请在需求表单中移除并保存。', 409);
}
export function listStagedAttachments(userId: string): Attachment[] {
return getDatabase().prepare('SELECT id, owner_id, demand_id, name, size, created_at FROM attachments WHERE owner_id = ? AND demand_id IS NULL AND created_at >= ? ORDER BY created_at')
.bind(userId, new Date(Date.now() - STAGED_ATTACHMENT_TTL_MS).toISOString()).all<AttachmentRow>().results.map(metadata);
}
export function attachmentFailure(error: unknown): Response {
if (error instanceof AuthError) return jsonResponse({ error: error.message }, error.status);
console.error('Attachment operation failed', error);
return jsonResponse({ error: '附件服务暂时不可用,请稍后重试。' }, 503);
}