feat(api): 支持外部客户端创建作品和更新版本
This commit is contained in:
@@ -11,19 +11,38 @@ import type { TextAnnotation } from '../../shared/types.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
function parseTags(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? value.map((tag) => String(tag).trim()).filter(Boolean)
|
||||
: String(value || '').trim() ? [String(value).trim()] : [];
|
||||
}
|
||||
|
||||
function parseImageUrls(value: unknown): { valid: boolean; urls: string[] } {
|
||||
if (value === undefined) return { valid: true, urls: [] };
|
||||
if (!Array.isArray(value)) return { valid: false, urls: [] };
|
||||
const urls = value.map((item) => String(item).trim());
|
||||
const valid = urls.length <= 30 && urls.every((url) => {
|
||||
if (!url || url.length > 2048) return false;
|
||||
try { return ['http:', 'https:'].includes(new URL(url).protocol); }
|
||||
catch { return false; }
|
||||
});
|
||||
return { valid, urls };
|
||||
}
|
||||
|
||||
// GET /api/notes - 笔记列表
|
||||
router.get('/', requireWriter, async (req: AuthRequest, res: Response) => {
|
||||
const { sort, order, q, collectionId, status, tag } = req.query as {
|
||||
const { sort, order, q, collectionId, status, tag, externalId } = req.query as {
|
||||
sort?: string;
|
||||
order?: string;
|
||||
q?: string;
|
||||
collectionId?: string;
|
||||
status?: 'draft' | 'pending' | 'changes_requested' | 'approved';
|
||||
tag?: string;
|
||||
externalId?: string;
|
||||
};
|
||||
const groupId = req.authUser?.role === 'platform_admin' || req.apiKey?.scope === 'platform' ? undefined : req.authUser?.group_id ?? undefined;
|
||||
const projectId = req.apiKey?.scope === 'project' ? req.apiKey.project_id ?? undefined : undefined;
|
||||
const list = await notesService.list({ sort, order, q, collectionId: collectionId ? Number(collectionId) : undefined, status, tag, groupId, projectId });
|
||||
const list = await notesService.list({ sort, order, q, collectionId: collectionId ? Number(collectionId) : undefined, status, tag, groupId, projectId, externalId });
|
||||
res.json(list);
|
||||
});
|
||||
|
||||
@@ -74,8 +93,17 @@ router.post(
|
||||
const title = (req.body.title || '').toString().trim();
|
||||
const description = (req.body.description || '').toString().trim();
|
||||
const collectionId = Number(req.body.collectionId);
|
||||
const tagsText = String(req.body.tags || '');
|
||||
const tags = tagsText ? [tagsText] : [];
|
||||
const tags = parseTags(req.body.tags);
|
||||
const { valid: validImageUrls, urls: imageUrls } = parseImageUrls(req.body.images);
|
||||
const externalId = String(req.body.externalId ?? req.body.external_id ?? '').trim() || null;
|
||||
if (!validImageUrls) {
|
||||
res.status(400).json({ error: 'images 需要包含 1–30 个有效的 HTTP/HTTPS 图片 URL' });
|
||||
return;
|
||||
}
|
||||
if (externalId && (externalId.length > 128 || !/^[A-Za-z0-9._:-]+$/.test(externalId))) {
|
||||
res.status(400).json({ error: 'externalId 仅支持 1–128 位字母、数字、点、下划线、冒号和横线' });
|
||||
return;
|
||||
}
|
||||
if (!title) {
|
||||
res.status(400).json({ error: '标题不能为空' });
|
||||
return;
|
||||
@@ -91,18 +119,32 @@ router.post(
|
||||
res.status(collection ? 403 : 404).json({ error: collection ? '无权向该作品交付集上传作品' : '作品交付集不存在' });
|
||||
return;
|
||||
}
|
||||
if (files.length === 0) {
|
||||
if (externalId) {
|
||||
const existing = await notesService.findByExternalId(collectionId, externalId);
|
||||
if (existing) { res.status(200).json({ ...existing, idempotent: true }); return; }
|
||||
}
|
||||
if (files.length === 0 && imageUrls.length === 0) {
|
||||
res.status(400).json({ error: '请至少上传一张图片' });
|
||||
return;
|
||||
}
|
||||
const note = await notesService.create(
|
||||
title,
|
||||
description,
|
||||
files.map((f) => ({ filename: f.filename, originalname: f.originalname, mimetype: f.mimetype, path: f.path })),
|
||||
collectionId,
|
||||
tags,
|
||||
);
|
||||
await audit(req, 'work.create', 'work', note.id, { collectionId, imageCount: files.length });
|
||||
let note;
|
||||
try {
|
||||
note = files.length
|
||||
? await notesService.create(
|
||||
title,
|
||||
description,
|
||||
files.map((f) => ({ filename: f.filename, originalname: f.originalname, mimetype: f.mimetype, path: f.path })),
|
||||
collectionId,
|
||||
tags,
|
||||
externalId,
|
||||
)
|
||||
: await notesService.createFromUrls(title, description, imageUrls, collectionId, tags, externalId);
|
||||
} catch (error) {
|
||||
const existing = externalId ? await notesService.findByExternalId(collectionId, externalId) : null;
|
||||
if (existing) { res.status(200).json({ ...existing, idempotent: true }); return; }
|
||||
throw error;
|
||||
}
|
||||
await audit(req, 'work.create', 'work', note.id, { collectionId, imageCount: files.length || imageUrls.length, imageSource: files.length ? 'upload' : 'external_url' });
|
||||
res.status(201).json(note);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -117,14 +159,17 @@ router.post('/:noteId/versions', requireWriter, upload.array('images', 30), asyn
|
||||
const context = await database.one<{ title: string; description: string; tags: string; project_id: number }>('SELECT n.title, n.description, n.tags, c.project_id FROM notes n JOIN collections c ON c.id = n.collection_id WHERE n.id = ?', [id]);
|
||||
if (!context) { res.status(404).json({ error: '作品不存在' }); return; }
|
||||
if (!await canWriteProject(req, context.project_id)) { res.status(403).json({ error: '无权操作该作品' }); return; }
|
||||
if (!files.length) { res.status(400).json({ error: '新版本至少需要一张图片' }); return; }
|
||||
const { valid: validImageUrls, urls: imageUrls } = parseImageUrls(req.body.images);
|
||||
if (!validImageUrls) { res.status(400).json({ error: 'images 需要包含 1–30 个有效的 HTTP/HTTPS 图片 URL' }); return; }
|
||||
if (!files.length && !imageUrls.length) { res.status(400).json({ error: '新版本至少需要一张图片' }); return; }
|
||||
const title = String(req.body?.title ?? context.title).trim();
|
||||
const description = String(req.body?.description ?? context.description).trim();
|
||||
const tagsText = String(req.body?.tags ?? '');
|
||||
const tags = tagsText ? [tagsText] : [];
|
||||
const tags = parseTags(req.body?.tags);
|
||||
if (!title) { res.status(400).json({ error: '标题不能为空' }); return; }
|
||||
const note = await notesService.createVersion(id, title, description, files.map((file) => ({ filename: file.filename, originalname: file.originalname, mimetype: file.mimetype, path: file.path })), tags, req.authUser?.id);
|
||||
await audit(req, 'work.version_create', 'work', id, { versionNumber: note.version_number, imageCount: files.length });
|
||||
const note = files.length
|
||||
? await notesService.createVersion(id, title, description, files.map((file) => ({ filename: file.filename, originalname: file.originalname, mimetype: file.mimetype, path: file.path })), tags, req.authUser?.id)
|
||||
: await notesService.createVersionFromUrls(id, title, description, imageUrls, tags, req.authUser?.id);
|
||||
await audit(req, 'work.version_create', 'work', id, { versionNumber: note.version_number, imageCount: files.length || imageUrls.length, imageSource: files.length ? 'upload' : 'external_url' });
|
||||
res.status(201).json(note);
|
||||
} catch (error) { files.forEach((file) => { try { if (fs.existsSync(file.path)) fs.unlinkSync(file.path); } catch { /* noop */ } }); next(error); }
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Router, type Response } from 'express';
|
||||
import { database } from '../database.js';
|
||||
import { audit, canWriteProject, hashPassword, requireRole, requireWriter, type AuthRequest } from '../auth.js';
|
||||
import { audit, canWriteProject, hashPassword, requireWriter, type AuthRequest } from '../auth.js';
|
||||
import type { Project, WorkCollection } from '../../shared/types.js';
|
||||
|
||||
const router = Router();
|
||||
const reader = requireRole('platform_admin', 'group_admin', 'operator');
|
||||
const reader = requireWriter;
|
||||
type ProjectRow = Project & { customer_access_enabled: boolean | number; has_access_password: boolean | number; collection_count: number | string; work_count: number | string };
|
||||
type CollectionRow = WorkCollection & { work_count: number | string; approved_count: number | string };
|
||||
|
||||
@@ -24,9 +24,18 @@ function projectJson(row: ProjectRow) { return { ...row, id: Number(row.id), gro
|
||||
function collectionJson(row: CollectionRow) { return { ...row, id: Number(row.id), project_id: Number(row.project_id), work_count: Number(row.work_count), approved_count: Number(row.approved_count) }; }
|
||||
|
||||
router.get('/', reader, async (req: AuthRequest, res: Response) => {
|
||||
const platform = req.authUser?.role === 'platform_admin';
|
||||
const where = platform ? 'WHERE p.status != ?' : 'WHERE p.group_id = ? AND p.status != ?';
|
||||
const params = platform ? ['archived'] : [req.authUser?.group_id, 'archived'];
|
||||
const platform = req.authUser?.role === 'platform_admin' || req.apiKey?.scope === 'platform';
|
||||
const projectKey = req.apiKey?.scope === 'project';
|
||||
const where = platform
|
||||
? 'WHERE p.status != ?'
|
||||
: projectKey
|
||||
? 'WHERE p.id = ? AND p.status != ?'
|
||||
: 'WHERE p.group_id = ? AND p.status != ?';
|
||||
const params = platform
|
||||
? ['archived']
|
||||
: projectKey
|
||||
? [req.apiKey?.project_id, 'archived']
|
||||
: [req.authUser?.group_id, 'archived'];
|
||||
res.json((await database.all<ProjectRow>(`${projectSelect(where)} ORDER BY p.id DESC`, params)).map(projectJson));
|
||||
});
|
||||
|
||||
@@ -60,7 +69,7 @@ router.patch('/:projectId',requireWriter,async(req:AuthRequest,res:Response)=>{
|
||||
|
||||
router.get('/:projectId/collections',reader,async(req:AuthRequest,res:Response)=>{
|
||||
const id=Number(req.params.projectId);if(!await canWriteProject(req,id)){res.status(403).json({error:'无权查看该项目'});return}
|
||||
const rows=await database.all<CollectionRow>(`SELECT c.*,(SELECT COUNT(*) FROM notes n WHERE n.collection_id=c.id) AS work_count,(SELECT COUNT(*) FROM notes n WHERE n.collection_id=c.id AND n.review_status='approved') AS approved_count FROM collections c WHERE c.project_id=? AND c.status!='archived' ORDER BY c.id DESC`,[id]);res.json(rows.map(collectionJson));
|
||||
const rows=await database.all<CollectionRow>(`SELECT c.*,COALESCE(s.work_count,0) AS work_count,COALESCE(s.approved_count,0) AS approved_count FROM collections c LEFT JOIN (SELECT collection_id,COUNT(*) AS work_count,SUM(CASE WHEN review_status='approved' THEN 1 ELSE 0 END) AS approved_count FROM notes GROUP BY collection_id) s ON s.collection_id=c.id WHERE c.project_id=? AND c.status!='archived' ORDER BY c.id DESC`,[id]);res.json(rows.map(collectionJson));
|
||||
});
|
||||
|
||||
router.patch('/:projectId/customer-access',requireWriter,async(req:AuthRequest,res:Response)=>{
|
||||
@@ -79,7 +88,7 @@ router.post('/:projectId/collections',requireWriter,async(req:AuthRequest,res:Re
|
||||
|
||||
router.patch('/:projectId/collections/:collectionId',requireWriter,async(req:AuthRequest,res:Response)=>{
|
||||
const projectId=Number(req.params.projectId);if(!await canWriteProject(req,projectId)){res.status(403).json({error:'无权操作该项目'});return}const id=Number(req.params.collectionId);const name=String(req.body?.name??'').trim();const description=String(req.body?.client_description??'').trim();if(!name){res.status(400).json({error:'作品交付集名称不能为空'});return}
|
||||
try{if(!(await database.execute('UPDATE collections SET name = ?, client_description = ? WHERE id = ? AND project_id = ?',[name,description,id,projectId])).changes){res.status(404).json({error:'作品交付集不存在'});return}await audit(req,'collection.update','collection',id,{projectId,name});const row=await database.one<CollectionRow>(`SELECT c.*,(SELECT COUNT(*) FROM notes n WHERE n.collection_id=c.id) AS work_count,(SELECT COUNT(*) FROM notes n WHERE n.collection_id=c.id AND n.review_status='approved') AS approved_count FROM collections c WHERE c.id=?`,[id]);res.json(collectionJson(row!))}catch{res.status(409).json({error:'同一项目内作品交付集名称不能重复'})}
|
||||
try{if(!(await database.execute('UPDATE collections SET name = ?, client_description = ? WHERE id = ? AND project_id = ?',[name,description,id,projectId])).changes){res.status(404).json({error:'作品交付集不存在'});return}await audit(req,'collection.update','collection',id,{projectId,name});const row=await database.one<CollectionRow>(`SELECT c.*,COALESCE(s.work_count,0) AS work_count,COALESCE(s.approved_count,0) AS approved_count FROM collections c LEFT JOIN (SELECT collection_id,COUNT(*) AS work_count,SUM(CASE WHEN review_status='approved' THEN 1 ELSE 0 END) AS approved_count FROM notes GROUP BY collection_id) s ON s.collection_id=c.id WHERE c.id=?`,[id]);res.json(collectionJson(row!))}catch{res.status(409).json({error:'同一项目内作品交付集名称不能重复'})}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
Reference in New Issue
Block a user