Merge remote-tracking branch 'origin/feat/s680-upload'
# Conflicts: # app/src/lib/api.ts # app/src/views/FamilyDetailView.vue
This commit is contained in:
@@ -0,0 +1,319 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { api, dermaImageUrl } from '../lib/api'
|
||||
import { DERMA_FINGER_IDS, dermaFingerLabel } from '../types'
|
||||
import type { DermaUploadSet } from '../types'
|
||||
|
||||
// S680 指纹图像上传(fingerprint-capture-options §6 第四来源 s680_win_upload):
|
||||
// 教练在电脑上用 S680 官方软件(Windows)采集十指图像文件 → 此处十槽位选择+预览+重传
|
||||
// → 全部就绪批量 multipart 上传 → 服务端落盘并建 capture_method=s680_win_upload 待判读记录
|
||||
// → 提示去天赋检测页按图人工录入纹型完成判读(App 不做 CV 自动识别,红线不变)
|
||||
// 判读对照:下方「最近上传」保留服务端最近 3 套,录纹型时可回到这里看图。
|
||||
const props = defineProps<{ slug: string }>()
|
||||
const emit = defineEmits<{ (e: 'close'): void }>()
|
||||
const router = useRouter()
|
||||
|
||||
const MAX_BYTES = 2 * 1024 * 1024 // 与服务端一致:≤2MB/指
|
||||
const ACCEPT = '.png,.bmp,.jpg,.jpeg,image/png,image/bmp,image/jpeg'
|
||||
|
||||
interface Slot { name: string; size: number; url: string; file: File }
|
||||
const files = ref<Record<string, Slot | null>>(Object.fromEntries(DERMA_FINGER_IDS.map((f) => [f, null])))
|
||||
const gender = ref<'male' | 'female'>('male')
|
||||
const uploading = ref(false)
|
||||
const errMsg = ref('')
|
||||
const doneInfo = ref<{ record_id: string; removed: string[] } | null>(null)
|
||||
|
||||
const readyCount = computed(() => DERMA_FINGER_IDS.filter((f) => files.value[f]).length)
|
||||
const allReady = computed(() => readyCount.value === 10)
|
||||
|
||||
function revoke(f: string) {
|
||||
const s = files.value[f]
|
||||
if (s) URL.revokeObjectURL(s.url)
|
||||
}
|
||||
|
||||
function onPick(f: string, ev: Event) {
|
||||
const input = ev.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
input.value = '' // 允许连选同一文件重传
|
||||
if (!file) return
|
||||
errMsg.value = ''
|
||||
if (file.size > MAX_BYTES) {
|
||||
errMsg.value = `${dermaFingerLabel(f)} 图像超过 2MB(${(file.size / 1048576).toFixed(1)}MB),请在 S680 软件中导出 PNG/BMP/JPG`
|
||||
return
|
||||
}
|
||||
const isImage = file.type === 'image/png' || file.type === 'image/bmp' || file.type === 'image/jpeg' || /\.(png|bmp|jpe?g)$/i.test(file.name)
|
||||
if (!isImage) {
|
||||
errMsg.value = `${dermaFingerLabel(f)} 仅支持 PNG/BMP/JPG 图像`
|
||||
return
|
||||
}
|
||||
revoke(f)
|
||||
files.value[f] = { name: file.name, size: file.size, url: URL.createObjectURL(file), file }
|
||||
}
|
||||
|
||||
function clearFinger(f: string) {
|
||||
revoke(f)
|
||||
files.value[f] = null
|
||||
errMsg.value = ''
|
||||
}
|
||||
|
||||
async function upload() {
|
||||
if (!allReady.value || uploading.value) return
|
||||
uploading.value = true
|
||||
errMsg.value = ''
|
||||
try {
|
||||
const fd = new FormData()
|
||||
fd.append('gender', gender.value)
|
||||
for (const f of DERMA_FINGER_IDS) fd.append(`finger_${f}`, files.value[f]!.file, files.value[f]!.name)
|
||||
const r = await api.dermaUpload(props.slug, fd)
|
||||
doneInfo.value = { record_id: r.record_id, removed: r.removed_sets ?? [] }
|
||||
await loadUploads()
|
||||
} catch (e) {
|
||||
errMsg.value = e instanceof Error ? e.message : '上传失败,请重试'
|
||||
} finally {
|
||||
uploading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function goDerma() {
|
||||
// new=1 强制重新采集(跳过"已有报告直达"),family 预选本家庭
|
||||
router.push({ path: '/derma', query: { family: props.slug, new: '1' } })
|
||||
}
|
||||
|
||||
// 最近上传(服务端保留 3 套):判读时对照图像
|
||||
const uploads = ref<DermaUploadSet[]>([])
|
||||
const uploadsLoading = ref(false)
|
||||
async function loadUploads() {
|
||||
uploadsLoading.value = true
|
||||
try {
|
||||
const r = await api.dermaUploadList(props.slug)
|
||||
uploads.value = r.uploads ?? []
|
||||
} catch {
|
||||
uploads.value = [] /* 加载失败不阻塞上传主流程 */
|
||||
} finally {
|
||||
uploadsLoading.value = false
|
||||
}
|
||||
}
|
||||
onMounted(loadUploads)
|
||||
|
||||
function fmtTime(iso?: string): string {
|
||||
if (!iso) return ''
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return ''
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="s680 card-inset">
|
||||
<div class="s680-head">
|
||||
<h3 style="margin: 0">💻 S680 指纹图像上传</h3>
|
||||
<button type="button" class="btn small ghost" @click="emit('close')">收起 ✕</button>
|
||||
</div>
|
||||
<p class="hint" style="margin: 6px 0 10px">
|
||||
在电脑上用 S680 官方软件采集十指图像(PNG/BMP/JPG,≤2MB/指)→ 逐指选文件 → 十指就绪后批量上传;
|
||||
上传后请在天赋检测页按图录入纹型完成判读。服务端同家庭只保留最近 3 套图像。
|
||||
</p>
|
||||
|
||||
<!-- 待判读性别(建待判读记录用,录入纹型时还会再确认) -->
|
||||
<div class="s680-gender">
|
||||
<span class="hint">孩子性别</span>
|
||||
<button
|
||||
v-for="g in (['male', 'female'] as const)"
|
||||
:key="g"
|
||||
type="button"
|
||||
class="btn small"
|
||||
:class="{ on: gender === g }"
|
||||
@click="gender = g"
|
||||
>
|
||||
{{ g === 'male' ? '男' : '女' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 十指槽位(label 直连隐藏 input,原生触发文件选择) -->
|
||||
<div class="s680-grid">
|
||||
<div v-for="f in DERMA_FINGER_IDS" :key="f" class="s680-slot" :class="{ filled: files[f] }">
|
||||
<span class="s680-fname">{{ dermaFingerLabel(f) }}</span>
|
||||
<img v-if="files[f]" :src="files[f]!.url" class="s680-thumb" :alt="dermaFingerLabel(f)" />
|
||||
<label v-else class="s680-empty" :for="`s680-${f}`">+ 选图</label>
|
||||
<input :id="`s680-${f}`" type="file" :accept="ACCEPT" hidden @change="onPick(f, $event)" />
|
||||
<div v-if="files[f]" class="s680-ops">
|
||||
<span class="s680-size">{{ (files[f]!.size / 1024).toFixed(0) }}KB</span>
|
||||
<label class="btn small ghost" :for="`s680-${f}`">重传</label>
|
||||
<button type="button" class="btn small ghost" @click="clearFinger(f)">移除</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="errMsg" class="banner err">{{ errMsg }}</p>
|
||||
|
||||
<div class="btn-row" style="margin-top: 10px">
|
||||
<button type="button" class="btn" :disabled="!allReady || uploading" @click="upload">
|
||||
{{ uploading ? '上传中…' : allReady ? `⬆ 批量上传十指(${readyCount}/10)` : `等待十指就绪(${readyCount}/10)` }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 上传成功 → 判读引导 -->
|
||||
<div v-if="doneInfo" class="s680-done">
|
||||
<p class="banner ok" style="margin: 10px 0 8px">
|
||||
✅ 上传成功({{ doneInfo.record_id }})——请在天赋检测页按图录入纹型完成判读
|
||||
</p>
|
||||
<div class="btn-row">
|
||||
<button type="button" class="btn" @click="goDerma">→ 去天赋检测页录入纹型</button>
|
||||
</div>
|
||||
<p v-if="doneInfo.removed.length" class="hint" style="margin: 8px 0 0">
|
||||
磁盘纪律:已自动清理更旧图像集 {{ doneInfo.removed.join('、') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 最近上传(判读对照) -->
|
||||
<div class="s680-recent">
|
||||
<div class="section-head" style="margin: 6px 0">
|
||||
<h4 style="margin: 0">最近上传({{ uploads.length }}/3 套,判读对照用)</h4>
|
||||
<button type="button" class="btn small ghost" @click="loadUploads" :disabled="uploadsLoading">
|
||||
{{ uploadsLoading ? '…' : '↻ 刷新' }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="!uploads.length" class="hint" style="margin: 4px 0">尚未上传过</p>
|
||||
<div v-for="u in uploads" :key="u.record_id" class="s680-set">
|
||||
<div class="s680-setmeta">
|
||||
<b>{{ u.record_id }}</b>
|
||||
<span class="hint">{{ fmtTime(u.created_at) }} · 待判读</span>
|
||||
</div>
|
||||
<div class="s680-setimgs">
|
||||
<img
|
||||
v-for="f in DERMA_FINGER_IDS"
|
||||
:key="f"
|
||||
:src="dermaImageUrl(u.record_id, f)"
|
||||
:alt="dermaFingerLabel(f)"
|
||||
:title="dermaFingerLabel(f)"
|
||||
loading="lazy"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.s680 {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.card-inset {
|
||||
border: 1.5px dashed var(--line);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
background: #fbfcff;
|
||||
}
|
||||
|
||||
.s680-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.s680-ops {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.s680-gender {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.s680-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.s680-slot {
|
||||
border: 1.5px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 6px;
|
||||
background: #fff;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.s680-slot.filled {
|
||||
border-color: var(--ok);
|
||||
}
|
||||
|
||||
.s680-fname {
|
||||
font-size: 12px;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
|
||||
.s680-thumb,
|
||||
.s680-empty {
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 8px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.s680-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1.5px dashed var(--line);
|
||||
color: var(--ink-2);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.s680-empty:hover {
|
||||
border-color: var(--brand);
|
||||
color: var(--brand-deep);
|
||||
}
|
||||
|
||||
.s680-size {
|
||||
font-size: 11.5px;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
|
||||
.s680-recent {
|
||||
margin-top: 14px;
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.s680-set {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.s680-setmeta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin-bottom: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.s680-setimgs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.s680-setimgs img {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
object-fit: cover;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--line);
|
||||
cursor: zoom-in;
|
||||
}
|
||||
</style>
|
||||
+31
-1
@@ -1,5 +1,5 @@
|
||||
|
||||
import type { CheckinHeatmap, CheckinTask, CheckinToday, ConsultCloseFeed, ConsultListFeed, ConsultMetaFeed, ConsultPatchFeed, ConsultRecord, ConsultStartFeed, CopilotDraft, CopilotFeed, CopilotMessage, CrisisLogFeed, DermaCopy, DermaParentCommunication, DermaReport, DermaReportFeed, DermaSixPowers, DermaTemplateReportFeed, Diag2026SubmitResult, FamilyDetail, FamilyInfo, GrowthFeed, GrowthReport, GrowthReportFeed, IntakeFeed, IntakePortraitFeed, IntakeSubmitResult, OutboxItem, WeeklyReport, WeeklyReportFeed } from '../types'
|
||||
import type { CheckinHeatmap, CheckinTask, CheckinToday, ConsultCloseFeed, ConsultListFeed, ConsultMetaFeed, ConsultPatchFeed, ConsultRecord, ConsultStartFeed, CopilotDraft, CopilotFeed, CopilotMessage, CrisisLogFeed, DermaCopy, DermaParentCommunication, DermaReport, DermaReportFeed, DermaSixPowers, DermaTemplateReportFeed, DermaUploadSet, Diag2026SubmitResult, FamilyDetail, FamilyInfo, GrowthFeed, GrowthReport, GrowthReportFeed, IntakeFeed, IntakePortraitFeed, IntakeSubmitResult, OutboxItem, WeeklyReport, WeeklyReportFeed } from '../types'
|
||||
// 服务器地址:默认Xuan生产;登录页可改(localStorage 持久化)
|
||||
export const DEFAULT_SERVER_BASE = 'http://139.196.125.248:8787'
|
||||
export function getServerBase(): string {
|
||||
@@ -43,6 +43,11 @@ async function req<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
return data
|
||||
}
|
||||
|
||||
// S680 待判读图像集的单指图像地址(<img> 直连;服务端兼容模式免 token)
|
||||
export function dermaImageUrl(recordId: string, finger: string): string {
|
||||
return base() + `/api/derma/images/${encodeURIComponent(recordId)}/${finger}`
|
||||
}
|
||||
|
||||
export const api = {
|
||||
health: () => req<{ ok: boolean }>('/api/health'),
|
||||
login: (passcode: string) =>
|
||||
@@ -193,6 +198,31 @@ export const api = {
|
||||
req<DermaTemplateReportFeed>(
|
||||
`/api/derma/records/${encodeURIComponent(recordId)}/report?version=${version}`,
|
||||
),
|
||||
// ---------- S680 指纹图像上传(Windows 采集 → 平台上传 → 人工判读闭环) ----------
|
||||
// multipart 由浏览器生成 boundary,不可手动设 Content-Type(req() 固定 JSON 头,故走裸 fetch)
|
||||
dermaUpload: async (familySlug: string, form: FormData) => {
|
||||
const r = await fetch(base() + `/api/derma/upload/${encodeURIComponent(familySlug)}`, {
|
||||
method: 'POST',
|
||||
headers: { ...authHeaders() },
|
||||
body: form,
|
||||
})
|
||||
const data = (await r.json().catch(() => ({}))) as {
|
||||
ok?: boolean
|
||||
record_id: string
|
||||
capture_method: string
|
||||
files?: Record<string, string>
|
||||
image_urls?: Record<string, string>
|
||||
removed_sets?: string[]
|
||||
next_hint?: string
|
||||
error?: string
|
||||
}
|
||||
if (!r.ok) throw new Error(data?.error ?? `上传失败(${r.status})`)
|
||||
return data
|
||||
},
|
||||
dermaUploadList: (familySlug: string) =>
|
||||
req<{ ok: boolean; family: string; kept_sets: number; uploads: DermaUploadSet[] }>(
|
||||
`/api/derma/upload/${encodeURIComponent(familySlug)}`,
|
||||
),
|
||||
// ---------- I4B 深访建档 ----------
|
||||
postIntake: (familySlug: string, answers: unknown) =>
|
||||
req<IntakeSubmitResult>(`/api/intake/${encodeURIComponent(familySlug)}`, {
|
||||
|
||||
+12
-1
@@ -564,12 +564,13 @@ export const DERMA_PATTERNS = [
|
||||
{ key: 'composite_anomaly', code: 'X', alias: '', name: '复合纹', icon: '✳' },
|
||||
] as const
|
||||
|
||||
/** 采集方式(WP1 降级链口径:OTG 默认 → 捺印拍照 → 手工录入;ink_card_scan 为 legacy 值保留回显) */
|
||||
/** 采集方式(WP1 降级链口径:OTG 默认 → 捺印拍照 → 手工录入;ink_card_scan 为 legacy 值保留回显;s680_win_upload 为 S680 Windows 采集上传) */
|
||||
export const DERMA_CAPTURE_METHODS = [
|
||||
{ value: 'manual_entry', label: '手工录入' },
|
||||
{ value: 'phone_macro_camera', label: '捺印拍照' },
|
||||
{ value: 'otg_scanner', label: 'OTG 采集仪' },
|
||||
{ value: 'ink_card_scan', label: '油墨卡扫描' },
|
||||
{ value: 's680_win_upload', label: 'S680上传(Windows采集)' },
|
||||
] as const
|
||||
|
||||
export const DERMA_FINGER_IDS = [
|
||||
@@ -627,6 +628,16 @@ export interface DermaBrainRegion {
|
||||
asymmetry_flag: boolean
|
||||
}
|
||||
|
||||
// S680 待判读上传集(Windows 官方软件采集 → 平台上传;纹型由教练在天赋检测页按图人工录入)
|
||||
export interface DermaUploadSet {
|
||||
record_id: string
|
||||
created_at: string
|
||||
capture_method: string
|
||||
status: string
|
||||
files: Record<string, string>
|
||||
image_urls: Record<string, string>
|
||||
}
|
||||
|
||||
export interface DermaReport {
|
||||
ruleset_version: string
|
||||
schema_version: string
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { api } from '../lib/api'
|
||||
import DermaUpload from '../components/DermaUpload.vue'
|
||||
import { AGE_BAND_OPTIONS, CHANNEL_OPTIONS, CHILD_GENDER_OPTIONS, STAGES, ageBandLabel } from '../types'
|
||||
import type { FamilyInfo, GrowthFeed, WeeklyReport } from '../types'
|
||||
import type { ConsultRecord } from '../types'
|
||||
@@ -53,6 +54,9 @@ const flowing = ref('')
|
||||
const flowErr = ref('')
|
||||
const flowOk = ref('')
|
||||
|
||||
// S680 指纹图像上传入口(Windows 采集 → 平台上传 → 天赋检测页人工判读)
|
||||
const showS680 = ref(false)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadErr.value = ''
|
||||
@@ -445,7 +449,6 @@ const topImprove = computed(() => {
|
||||
多时点评估 + 打卡台账 → 六力曲线 / 坚持率 / 综合成长指数 / 家庭成长报告
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 咨询记录(I4C:1V1 十部曲留档入口 + 历史时间线) -->
|
||||
<div class="card">
|
||||
<div class="section-head" style="margin-bottom: 8px">
|
||||
@@ -521,6 +524,12 @@ const topImprove = computed(() => {
|
||||
</button>
|
||||
<button class="btn ghost" @click="router.push('/report')">查看示例报告</button>
|
||||
</div>
|
||||
<div class="btn-row" style="margin-top: 10px">
|
||||
<button class="btn ghost" @click="showS680 = !showS680">
|
||||
💻 S680指纹图像上传{{ showS680 ? '(收起)' : '' }}
|
||||
</button>
|
||||
</div>
|
||||
<DermaUpload v-if="showS680" :slug="slug" @close="showS680 = false" />
|
||||
</div>
|
||||
|
||||
<p class="notice">档案按家庭脱敏归档 · AI 不下诊断</p>
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# S680 指纹图像上传模式 —— DONE(feat/s680-upload)
|
||||
|
||||
> 任务书:S680任务书:S680指纹图像上传模式(Windows采集→平台上传→判读闭环)
|
||||
> 闭环:教练电脑 S680 官方软件(500DPI/40×40mm/USB2.0,SDK 仅 Windows)采集十指图像文件
|
||||
> → DermaUpload 十槽位上传 → 服务端落盘+建 `capture_method:"s680_win_upload"` 待判读记录
|
||||
> → 教练在天赋检测页按图人工录入纹型(App 不做 CV 自动识别,红线不变)→ 照常出报告
|
||||
|
||||
## 交付清单
|
||||
|
||||
| 层 | 文件 | 说明 |
|
||||
|---|---|---|
|
||||
| API | `server/src/api/routes-derma-upload.js`(新) | POST `/api/derma/upload/:familySlug`(multipart 十指)+ GET `/api/derma/upload/:familySlug`(待判读集列表)+ GET `/api/derma/images/:recordId/:finger`(单指图像) |
|
||||
| API | `server/src/api/app.js` | 追加 import + 注册一行(`registerDermaUploadRoutes`,`dermaImagesDir` 可注入,默认 `server/data/derma-images`) |
|
||||
| 存储 | `server/src/storage/db.js` | 迁移 `migrateDermaImagesRef`:derma_records 补列 `images_ref`(''=判读记录;非空=待判读图像集) |
|
||||
| 存储 | `server/src/storage/repo-derma.js` | insert 补 images_ref 默认 '';`latestByFamily`/`listMetaByFamily` 排除待判读(不顶掉 GET report/历史);新增 `listUploadsByFamily`/`deletePendingByRecordId` |
|
||||
| 引擎 | `server/src/engines/derma-engine.js` | `CAPTURE_METHODS` 追加 `s680_win_upload`(fingerprint-capture-options §6 第四来源) |
|
||||
| 前端 | `app/src/components/DermaUpload.vue`(新) | 十指上传槽位(选图/缩略预览/重传/移除)+ 性别 + 十指就绪批量上传 + 「去天赋检测页录入纹型」引导 + 最近 3 套图像对照 |
|
||||
| 前端 | `app/src/views/FamilyDetailView.vue` | 最小挂载:import + `showS680` ref + 快捷动作区一行按钮 + 组件标签(**未动 DermaView.vue**);顺手补 main 遗留的成长追踪卡片缺失 `</div>`(不补则构建必败) |
|
||||
| 前端 | `app/src/lib/api.ts` / `app/src/types.ts` | `dermaUpload`(FormData 裸 fetch,浏览器生成 boundary) / `dermaUploadList` / `dermaImageUrl`;`DermaUploadSet` 类型;采集方式枚举补 `s680_win_upload` 标签 |
|
||||
| 测试 | `server/test/test-derma-upload.js`(新)+ `test/index.js` 清单 + `helpers.js` 临时 imagesDir 隔离 | 5 用例见下 |
|
||||
|
||||
### 零依赖说明
|
||||
`@fastify/multipart` 不在依赖清单且任务禁装包 → multipart 用 `addContentTypeParser('multipart/form-data', {parseAs:'buffer', bodyLimit:12MB+10×2MB})` 收整包 + 自写 RFC7578 解析(`parseMultipart`,支持带引号 boundary/二进制/CRLF 剥离)。类型按魔数嗅探(PNG/JPG/BMP),不信任上传文件名与声明 Content-Type。
|
||||
|
||||
## 验收 1:测试全绿
|
||||
|
||||
`cd server && npm test` → **129 pass / 0 fail**(main 基线 124 + 新增 5,既有零破坏):
|
||||
- ✔ S680 上传全链路:multipart 十指 → 文件落盘 → capture_method=s680_win_upload 待判读记录(纹型/RC/ATD 全空、images_ref 指向目录、单指图像字节级回读)
|
||||
- ✔ 判读衔接:待判读不顶掉 GET report(404 待判/判读后 200);`s680_win_upload` 过 capture 校验照常出报告;历史不含待判读
|
||||
- ✔ 格式接纳:PNG/BMP/JPG 按魔数落对应扩展名(上传文件名全给错也能识别)
|
||||
- ✔ 校验拒绝:>2MB→400 / 非图像→400 / 缺指→400 / 未知指位→400 / 重复指位→400 / gender 缺失→400 / 家庭不存在→404 / 图像不存在→404
|
||||
- ✔ 磁盘纪律:第 4 套上传 → 最旧套目录+待判读 DB 行自动清,列表只回 3 套
|
||||
|
||||
## 验收 2:构建零报错
|
||||
|
||||
`cd app && npm ci && npm run build`(vue-tsc -b + vite build)→ ✓ built,无类型/模板错误。
|
||||
|
||||
## 验收 3:curl multipart 全链路(PORT=18787 冒烟实录)
|
||||
|
||||
```
|
||||
# ① 建档
|
||||
curl -X POST $B/api/families -d '{"slug":"smoke-s680",...}' → {"ok":true,...}
|
||||
# ② 十指 multipart 上传(-F finger_left_thumb=@… ×10 + -F gender=male)
|
||||
curl -X POST $B/api/derma/upload/smoke-s680 -F gender=male \
|
||||
-F finger_left_thumb=@left_thumb.png … -F finger_right_little=@right_little.png
|
||||
→ {"ok":true,"record_id":"DR-20261018-4812","capture_method":"s680_win_upload",
|
||||
"images_ref":"derma-images/smoke-s680/DR-20261018-4812","files":{十指→文件名},
|
||||
"image_urls":{…},"removed_sets":[],"kept_sets":3,
|
||||
"next_hint":"上传成功:请在天赋检测页按图录入纹型完成判读"}
|
||||
# ③ 图像回读:HTTP 200,content-type: image/png,字节头 8950 4e47(PNG)
|
||||
curl $B/api/derma/images/DR-20261018-4812/left_thumb
|
||||
# ④ 待判读不算报告
|
||||
curl $B/api/derma/report/smoke-s680 → 404 "尚无皮纹采集记录"
|
||||
# ⑤ 教练按图录入纹型(capture_method=s680_win_upload)→ 200 出报告
|
||||
curl -X POST $B/api/derma/capture/smoke-s680 -d '{gender,atd,fingers[十指纹型+rc],capture_method:"s680_win_upload"}'
|
||||
→ {"ok":true,"record_id":"DR-20261018-5953","report":{rules-v2 十三章…}}
|
||||
curl $B/api/derma/report/smoke-s680 → record_id=DR-20261018-5953,capture.method=s680_win_upload
|
||||
# ⑥ 第 4 套上传 → 最旧自动清
|
||||
→ "第4套 DR-20261018-2025 清理 ['DR-20261018-4812']";GET upload 列表仅余 3 套
|
||||
# ⑦ 拒绝路径
|
||||
>2MB → 400 "超过 2MB 上限(2097161 字节)";文本文件伪装 .png → 400 "魔数嗅探失败"
|
||||
```
|
||||
|
||||
## 验收 4:磁盘布局说明
|
||||
|
||||
```
|
||||
server/data/ # 既有 DATA_DIR(server/.gitignore /data 整体不入库)
|
||||
└── derma-images/ # imagesDir(buildApp 可注入,测试注入临时目录)
|
||||
└── {family_slug}/ # 目录名=safeDirName(slug)([^a-zA-Z0-9_-] 归一为 _,防穿越)
|
||||
├── DR-20260201-1234/ # 一套十指 = 目录名即待判读 record_id(mtime 排序做保留)
|
||||
│ ├── left_thumb.png # {finger}.{真实魔数扩展名}:png/bmp/jpg
|
||||
│ ├── left_index.bmp # (十指混合格式允许,逐指独立嗅探)
|
||||
│ └── … ×10(left_thumb…right_little)
|
||||
├── DR-20260305-5678/
|
||||
└── DR-20260409-9012/ # 同 family 永远只有最近 3 套;第 4 套上传即删最旧
|
||||
```
|
||||
|
||||
- DB 侧:`derma_records.images_ref = 'derma-images/{family}/{record_id}'`(判读记录恒为 '');
|
||||
待判读记录 payload 带 `status:"pending_judgment"` + `files` 映射,`report/copy = null`。
|
||||
- 清理联动:删目录同时 `DELETE … WHERE record_id=? AND images_ref != ''`(判读记录永不误删);
|
||||
被清套的图像 GET 返回 404「图像文件已清理(磁盘只保留最近 3 套)」。
|
||||
- 上限:2MB/指(魔数+大小双检);整包 bodyLimit 12MB+10×2MB(防默认 1MB 拦截整包)。
|
||||
|
||||
## 判读闭环工作流(教练视角)
|
||||
|
||||
1. 家庭详情页 → 快捷动作「💻 S680指纹图像上传」展开 DermaUpload;
|
||||
2. 选孩子性别 → 十指逐槽选图(本地缩略预览,可重传/移除)→ 10/10 就绪批量上传;
|
||||
3. 提示「请在天赋检测页按图录入纹型完成判读」→ 一键跳 `/derma?family=slug&new=1`;
|
||||
4. 录纹型时可回家庭详情页看「最近上传(3 套)」十指缩略图对照;
|
||||
5. 录完提交(采集方式可选手工录入或 s680_win_upload)→ 照常出 rules-v2 报告,待判读记录不进历史下拉。
|
||||
|
||||
## 风险与边界
|
||||
|
||||
- 未动 `DermaView.vue`(另一分支在改);前端只动 FamilyDetailView(按钮+组件标签)与 api/types 增量。
|
||||
- FamilyDetailView 顺手补 main 遗留的缺失 `</div>`(成长追踪卡未闭合,merge 残留;不补 build 必败,属必要修复)。
|
||||
- multipart 解析器为 RFC7578 标准子集(浏览器/curl 形态),未覆盖 preamble/8bit 传输等冷门形态。
|
||||
@@ -23,6 +23,7 @@ import { registerCopilotRoutes } from './routes-copilot.js'
|
||||
import { registerCheckinRoutes } from './routes-checkin.js'
|
||||
import { registerCrisisRoutes } from './routes-crisis.js'
|
||||
import { registerDermaRoutes } from './routes-derma.js'
|
||||
import { registerDermaUploadRoutes } from './routes-derma-upload.js'
|
||||
import { registerConsultRoutes } from './routes-consult.js'
|
||||
import { registerWeeklyRoutes } from './routes-weekly.js'
|
||||
import { registerDemoRoutes } from './routes-demo.js'
|
||||
@@ -39,6 +40,7 @@ export async function buildApp({
|
||||
requireToken = process.env.COACH_REQUIRE_TOKEN === '1',
|
||||
tokenTtlMs = TOKEN_TTL_MS,
|
||||
crisisLogFile,
|
||||
dermaImagesDir = path.join(DATA_DIR, 'derma-images'),
|
||||
distDir = path.join(SERVER_ROOT, '..', 'app', 'dist'),
|
||||
logger = true,
|
||||
} = {}) {
|
||||
@@ -121,6 +123,7 @@ export async function buildApp({
|
||||
registerCheckinRoutes(app, { repos })
|
||||
registerCrisisRoutes(app, { crisisLog })
|
||||
registerDermaRoutes(app, { repos })
|
||||
registerDermaUploadRoutes(app, { repos, imagesDir: dermaImagesDir })
|
||||
registerConsultRoutes(app, { repos })
|
||||
registerWeeklyRoutes(app, { repos })
|
||||
registerDemoRoutes(app, { db })
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
// routes-derma-upload —— S680 指纹图像上传(Windows 官方软件采集 → 平台上传 → 人工判读闭环)
|
||||
// 链路:POST multipart 十指图像(field=finger_left_thumb…finger_right_little,PNG/BMP/JPG ≤2MB/指)
|
||||
// → 落盘 data/derma-images/{family}/{record_id}/ → 建 capture_method=s680_win_upload 待判读记录
|
||||
// (payload.input.fingers 纹型/RC 留空,images_ref 指向目录)→ 教练在 DermaView 按图录入纹型照常出报告
|
||||
// 磁盘纪律:同 family 只保留最近 KEEP_SETS 套目录,更旧目录连同待判读记录自动清理
|
||||
// 采集抽象对齐 fingerprint-capture-options.md §6 第四来源;判读层不感知采集方式(App 不做 CV 自动识别)
|
||||
//
|
||||
// 零依赖说明:@fastify/multipart 不在依赖清单且本任务禁装包 → multipart 用
|
||||
// addContentTypeParser(parseAs:'buffer') 收整包 + 自写解析(浏览器/curl 的标准编码,见 parseMultipart)
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { FINGER_IDS, RULESET_VERSION } from '../engines/derma-engine.js'
|
||||
|
||||
const MAX_FILE_BYTES = 2 * 1024 * 1024 // 每指 ≤2MB
|
||||
const KEEP_SETS = 3 // 同 family 图像集保留套数(磁盘纪律)
|
||||
const S680_METHOD = 's680_win_upload'
|
||||
const MIME_BY_EXT = { png: 'image/png', bmp: 'image/bmp', jpg: 'image/jpeg' }
|
||||
// 整包上限:10 指×2MB + multipart 边界开销
|
||||
const BODY_LIMIT = 12 * 1024 * 1024 + 10 * MAX_FILE_BYTES
|
||||
|
||||
// S680 软件导出 PNG/BMP/JPG——按魔数嗅探定类型(不信任扩展名与声明 Content-Type)
|
||||
function sniffImage(buf) {
|
||||
if (buf.length >= 4 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return 'png'
|
||||
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpg'
|
||||
if (buf.length >= 2 && buf[0] === 0x42 && buf[1] === 0x4d) return 'bmp'
|
||||
return null
|
||||
}
|
||||
|
||||
// 待判读记录编号:与 routes-derma 的 DR- 口径一致(独立实现,避免跨路由文件耦合)
|
||||
function buildUploadRecordId() {
|
||||
const d = new Date()
|
||||
const date = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`
|
||||
return `DR-${date}-${String(Math.floor(1000 + Math.random() * 9000))}`
|
||||
}
|
||||
|
||||
// family slug 只作目录名(slug 由本系统生成,仍防御性收窄字符面防路径穿越)
|
||||
function safeDirName(s) {
|
||||
return String(s).replace(/[^a-zA-Z0-9_-]/g, '_')
|
||||
}
|
||||
|
||||
// multipart/form-data 解析(RFC 7578 子集:单文件/单值 part,name/filename 带引号——浏览器与 curl 标准形态)
|
||||
// 结构:preamble? (--boundary CRLF part)+ --boundary--
|
||||
// part = Content-Disposition 等头 CRLF CRLF data CRLF(data 尾 CRLF 属边界前缀,须剥掉)
|
||||
export function parseMultipart(buf, contentType) {
|
||||
const m = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(String(contentType ?? ''))
|
||||
const boundary = (m?.[1] ?? m?.[2] ?? '').trim()
|
||||
if (!boundary) throw new Error('Content-Type 缺少 boundary')
|
||||
const delim = Buffer.from(`--${boundary}`)
|
||||
const parts = []
|
||||
let pos = buf.indexOf(delim)
|
||||
while (pos !== -1) {
|
||||
let head = pos + delim.length
|
||||
if (buf[head] === 0x2d && buf[head + 1] === 0x2d) break // --boundary-- 终界
|
||||
if (buf[head] === 0x0d && buf[head + 1] === 0x0a) head += 2 // 边界后 CRLF
|
||||
const next = buf.indexOf(delim, head)
|
||||
if (next === -1) break
|
||||
let end = next
|
||||
if (buf[end - 2] === 0x0d && buf[end - 1] === 0x0a) end -= 2 // 剥 data 尾 CRLF
|
||||
if (end > head) parts.push(buf.slice(head, end))
|
||||
pos = next
|
||||
}
|
||||
const out = []
|
||||
for (const part of parts) {
|
||||
const split = part.indexOf('\r\n\r\n')
|
||||
if (split === -1) continue
|
||||
const headers = part.slice(0, split).toString('utf8')
|
||||
const data = part.slice(split + 4)
|
||||
// [\s;] 前缀锚定避免 name= 误吃 filename=(Content-Disposition: form-data; name="…"; filename="…")
|
||||
const disp = headers.split(/\r?\n/).find((l) => /^content-disposition:/i.test(l)) ?? ''
|
||||
const nameM = /[\s;]name="([^"]*)"|[\s;]name=([^;\s"]+)/i.exec(disp)
|
||||
const fileM = /[\s;]filename="([^"]*)"|[\s;]filename=([^;\s"]+)/i.exec(disp)
|
||||
if (!nameM) continue
|
||||
out.push({
|
||||
name: (nameM[1] ?? nameM[2] ?? '').trim(),
|
||||
filename: (fileM?.[1] ?? fileM?.[2] ?? '').trim(),
|
||||
data,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 磁盘纪律:按目录 mtime 降序保留最近 KEEP_SETS 套,其余删目录并联动删待判读 DB 行
|
||||
function cleanupOldSets(familyDir, derma) {
|
||||
if (!fs.existsSync(familyDir)) return []
|
||||
const sets = fs
|
||||
.readdirSync(familyDir, { withFileTypes: true })
|
||||
.filter((d) => d.isDirectory())
|
||||
.map((d) => {
|
||||
const p = path.join(familyDir, d.name)
|
||||
return { name: d.name, path: p, mtime: fs.statSync(p).mtimeMs }
|
||||
})
|
||||
.sort((a, b) => b.mtime - a.mtime || (a.name < b.name ? 1 : -1))
|
||||
const removed = []
|
||||
for (const s of sets.slice(KEEP_SETS)) {
|
||||
fs.rmSync(s.path, { recursive: true, force: true })
|
||||
derma.deletePendingByRecordId(s.name) // 目录名=record_id
|
||||
removed.push(s.name)
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
export function registerDermaUploadRoutes(app, { repos, imagesDir }) {
|
||||
const { derma, families } = repos
|
||||
|
||||
// multipart 整包收 Buffer(路由/解析器双 bodyLimit,防默认 1MB 拦截十指整包)
|
||||
app.addContentTypeParser('multipart/form-data', { parseAs: 'buffer', bodyLimit: BODY_LIMIT }, (_req, body, done) =>
|
||||
done(null, body),
|
||||
)
|
||||
|
||||
// 十指图像上传 → 落盘 + 待判读记录
|
||||
app.post('/api/derma/upload/:familySlug', { bodyLimit: BODY_LIMIT }, async (req, reply) => {
|
||||
const slug = req.params.familySlug
|
||||
if (!families.exists(slug)) return reply.code(404).send({ ok: false, error: `家庭 ${slug} 不存在,请先建档` })
|
||||
|
||||
let parts
|
||||
try {
|
||||
parts = parseMultipart(req.body, req.headers['content-type'])
|
||||
} catch (e) {
|
||||
return reply.code(400).send({ ok: false, error: `multipart 解析失败:${e.message}` })
|
||||
}
|
||||
|
||||
const errs = []
|
||||
const files = {} // finger → { ext, data }
|
||||
let gender = ''
|
||||
for (const p of parts) {
|
||||
if (!p.filename) {
|
||||
if (p.name === 'gender') gender = p.data.toString('utf8').trim()
|
||||
continue // 其余纯文本字段忽略(前端只附 gender)
|
||||
}
|
||||
if (!p.name.startsWith('finger_')) {
|
||||
errs.push(`未知上传字段 ${p.name}(十指字段名须为 finger_left_thumb…finger_right_little)`)
|
||||
continue
|
||||
}
|
||||
const finger = p.name.slice('finger_'.length)
|
||||
if (!FINGER_IDS.includes(finger)) {
|
||||
errs.push(`未知指位字段 ${p.name}`)
|
||||
continue
|
||||
}
|
||||
if (files[finger]) {
|
||||
errs.push(`${p.name} 重复上传`)
|
||||
continue
|
||||
}
|
||||
const ext = sniffImage(p.data)
|
||||
if (!ext) {
|
||||
errs.push(`${p.name} 不是 PNG/BMP/JPG 图像(魔数嗅探失败)`)
|
||||
continue
|
||||
}
|
||||
if (p.data.length > MAX_FILE_BYTES) {
|
||||
errs.push(`${p.name} 超过 2MB 上限(${p.data.length} 字节)`)
|
||||
continue
|
||||
}
|
||||
files[finger] = { ext, data: p.data }
|
||||
}
|
||||
for (const f of FINGER_IDS) {
|
||||
if (!files[f]) errs.push(`缺少 ${f} 图像(字段名 finger_${f})`)
|
||||
}
|
||||
if (gender !== 'male' && gender !== 'female') errs.push('gender 须为 male/female(表单文本字段)')
|
||||
if (errs.length) return reply.code(400).send({ ok: false, error: '指纹图像上传未通过校验', detail: errs })
|
||||
|
||||
const createdAt = new Date().toISOString()
|
||||
const familyDir = path.join(imagesDir, safeDirName(slug))
|
||||
// 落盘 + 建待判读记录(record_id 随机段 UNIQUE 碰撞时重试,对齐 routes-derma 口径)
|
||||
let recordId = buildUploadRecordId()
|
||||
let inserted = false
|
||||
for (let i = 0; i < 3 && !inserted; i++) {
|
||||
const dir = path.join(familyDir, recordId)
|
||||
const fileNames = Object.fromEntries(FINGER_IDS.map((f) => [f, `${f}.${files[f].ext}`]))
|
||||
const payload = {
|
||||
schema_version: 'derma-draft-v1',
|
||||
record_id: recordId,
|
||||
family_slug: slug,
|
||||
ruleset_version: RULESET_VERSION,
|
||||
gender,
|
||||
created_at: createdAt,
|
||||
status: 'pending_judgment', // 待判读:纹型/RC/ATD 留空,教练按图人工录入后由 /api/derma/capture 出正式报告
|
||||
capture: { method: S680_METHOD, collected_at: createdAt, notes: 'S680 光学采集仪(500DPI/40×40mm)Windows 端官方软件采集十指图像上传' },
|
||||
input: { gender, atd: null, arc: null, fingers: FINGER_IDS.map((f) => ({ finger: f, pattern: null, rc: null })) },
|
||||
files: fileNames,
|
||||
report: null,
|
||||
copy: null,
|
||||
}
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
for (const f of FINGER_IDS) fs.writeFileSync(path.join(dir, fileNames[f]), files[f].data)
|
||||
derma.insert({
|
||||
record_id: recordId,
|
||||
family_slug: slug,
|
||||
ruleset_version: RULESET_VERSION,
|
||||
gender,
|
||||
payload: JSON.stringify(payload),
|
||||
created_at: createdAt,
|
||||
images_ref: `derma-images/${slug}/${recordId}`,
|
||||
})
|
||||
inserted = true
|
||||
} catch (e) {
|
||||
fs.rmSync(dir, { recursive: true, force: true }) // 半成品目录不残留
|
||||
if (i === 2 || !/UNIQUE/.test(String(e))) throw e
|
||||
recordId = buildUploadRecordId()
|
||||
}
|
||||
}
|
||||
|
||||
const removed = cleanupOldSets(familyDir, derma)
|
||||
req.log.info({ record_id: recordId, family: slug, fingers: FINGER_IDS.length, removed_sets: removed.length }, 's680 upload stored')
|
||||
return {
|
||||
ok: true,
|
||||
record_id: recordId,
|
||||
family: slug,
|
||||
capture_method: S680_METHOD,
|
||||
images_ref: `derma-images/${slug}/${recordId}`,
|
||||
files: Object.fromEntries(FINGER_IDS.map((f) => [f, `${f}.${files[f].ext}`])),
|
||||
image_urls: Object.fromEntries(FINGER_IDS.map((f) => [f, `/api/derma/images/${recordId}/${f}`])),
|
||||
removed_sets: removed,
|
||||
kept_sets: KEEP_SETS,
|
||||
next_hint: '上传成功:请在天赋检测页按图录入纹型完成判读',
|
||||
}
|
||||
})
|
||||
|
||||
// 待判读图像集列表(判读时可回到上传组件对照图像)
|
||||
app.get('/api/derma/upload/:familySlug', async (req, reply) => {
|
||||
const slug = req.params.familySlug
|
||||
if (!families.exists(slug)) return reply.code(404).send({ ok: false, error: `家庭 ${slug} 不存在` })
|
||||
const uploads = derma.listUploadsByFamily(slug).map((row) => {
|
||||
const p = JSON.parse(row.payload)
|
||||
return {
|
||||
record_id: row.record_id,
|
||||
created_at: p.created_at ?? row.created_at,
|
||||
capture_method: p.capture?.method ?? S680_METHOD,
|
||||
status: p.status ?? 'pending_judgment',
|
||||
files: p.files ?? {},
|
||||
image_urls: Object.fromEntries(FINGER_IDS.filter((f) => p.files?.[f]).map((f) => [f, `/api/derma/images/${row.record_id}/${f}`])),
|
||||
}
|
||||
})
|
||||
return { ok: true, family: slug, kept_sets: KEEP_SETS, uploads }
|
||||
})
|
||||
|
||||
// 单指图像读取(待判读集判读对照用;文件名来自本服务写入的 payload,仍防御路径穿越)
|
||||
app.get('/api/derma/images/:recordId/:finger', async (req, reply) => {
|
||||
const recordId = String(req.params.recordId)
|
||||
const finger = String(req.params.finger)
|
||||
const row = derma.byRecordId(recordId)
|
||||
if (!row || !row.images_ref) return reply.code(404).send({ ok: false, error: `上传记录 ${recordId} 不存在` })
|
||||
if (!FINGER_IDS.includes(finger)) return reply.code(400).send({ ok: false, error: `未知指位 ${finger}` })
|
||||
const fileName = JSON.parse(row.payload)?.files?.[finger]
|
||||
if (!fileName || !/^[\w-]+\.(png|bmp|jpg)$/.test(fileName)) {
|
||||
return reply.code(404).send({ ok: false, error: `记录 ${recordId} 无 ${finger} 图像` })
|
||||
}
|
||||
const file = path.join(imagesDir, safeDirName(row.family_slug), recordId, fileName)
|
||||
if (!fs.existsSync(file)) return reply.code(404).send({ ok: false, error: `图像文件已清理(磁盘只保留最近 ${KEEP_SETS} 套)` })
|
||||
const ext = path.extname(fileName).slice(1)
|
||||
reply.header('content-type', MIME_BY_EXT[ext] ?? 'application/octet-stream')
|
||||
return reply.send(fs.readFileSync(file))
|
||||
})
|
||||
|
||||
app.log.info(
|
||||
'derma upload routes registered(POST /api/derma/upload/:slug + GET /api/derma/upload/:slug + GET /api/derma/images/:id/:finger,S680 Windows 采集上传闭环)',
|
||||
)
|
||||
}
|
||||
@@ -42,7 +42,7 @@ export const PATTERN_ALIASES = {
|
||||
}
|
||||
|
||||
// schema meta.device.method 枚举
|
||||
export const CAPTURE_METHODS = ['phone_macro_camera', 'otg_scanner', 'ink_card_scan', 'manual_entry']
|
||||
export const CAPTURE_METHODS = ['phone_macro_camera', 'otg_scanner', 'ink_card_scan', 'manual_entry', 's680_win_upload']
|
||||
|
||||
// W/L/A 三分法归并(维持 v1;v2 中仅作 R8 辅助线与沟通模式归类)
|
||||
const CLASS_OF_PATTERN = {
|
||||
|
||||
@@ -235,6 +235,14 @@ function migrateOutboxVersion(db) {
|
||||
}
|
||||
}
|
||||
|
||||
// S680 上传图像引用列(空=正常判读记录;非空=待判读图像集目录 derma-images/{family}/{record_id})
|
||||
function migrateDermaImagesRef(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(derma_records)').all().map((c) => c.name)
|
||||
if (!cols.includes('images_ref')) {
|
||||
db.prepare("ALTER TABLE derma_records ADD COLUMN images_ref TEXT NOT NULL DEFAULT ''").run()
|
||||
}
|
||||
}
|
||||
|
||||
export function openDb(dbPath) {
|
||||
const file = dbPath ? path.resolve(dbPath) : path.join(DATA_DIR, 'coach.db')
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true })
|
||||
@@ -244,5 +252,6 @@ export function openDb(dbPath) {
|
||||
migrateFamilies(db)
|
||||
migrateCrisisColumns(db)
|
||||
migrateOutboxVersion(db)
|
||||
migrateDermaImagesRef(db)
|
||||
return db
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
// repo-derma —— 皮纹采集记录仓储(M7:record_id 唯一,按家庭查最新/历史)
|
||||
// repo-derma —— 皮纹采集记录仓储(M7:record_id 唯一,按家庭查最新/历史;S680:images_ref 待判读图像集,
|
||||
// 报告链路只看 images_ref='' 的判读记录,待判读集走 listUploadsByFamily)
|
||||
export function createDermaRepo(db) {
|
||||
return {
|
||||
// images_ref 缺省 ''(正常判读记录);S680 上传记录显式传入目录引用
|
||||
insert: (r) =>
|
||||
db
|
||||
.prepare(`
|
||||
INSERT INTO derma_records (record_id, family_slug, ruleset_version, gender, payload, created_at)
|
||||
VALUES (@record_id, @family_slug, @ruleset_version, @gender, @payload, @created_at)
|
||||
INSERT INTO derma_records (record_id, family_slug, ruleset_version, gender, payload, created_at, images_ref)
|
||||
VALUES (@record_id, @family_slug, @ruleset_version, @gender, @payload, @created_at, @images_ref)
|
||||
`)
|
||||
.run(r),
|
||||
.run({ images_ref: '', ...r }),
|
||||
// 最新报告记录:排除 S680 待判读上传集(无报告数据,不得顶掉 GET report)
|
||||
latestByFamily: (slug) => {
|
||||
const row = db
|
||||
.prepare('SELECT * FROM derma_records WHERE family_slug = ? ORDER BY created_at DESC, id DESC LIMIT 1')
|
||||
.prepare("SELECT * FROM derma_records WHERE family_slug = ? AND images_ref = '' ORDER BY created_at DESC, id DESC LIMIT 1")
|
||||
.get(slug)
|
||||
return row ?? null
|
||||
},
|
||||
@@ -20,9 +23,20 @@ export function createDermaRepo(db) {
|
||||
: db.prepare('SELECT * FROM derma_records WHERE record_id = ?').get(recordId)
|
||||
return row ?? null
|
||||
},
|
||||
// 历史(报告下拉):同样只列判读记录
|
||||
listMetaByFamily: (slug) =>
|
||||
db
|
||||
.prepare('SELECT record_id, ruleset_version, gender, created_at FROM derma_records WHERE family_slug = ? ORDER BY created_at DESC, id DESC')
|
||||
.prepare("SELECT record_id, ruleset_version, gender, created_at FROM derma_records WHERE family_slug = ? AND images_ref = '' ORDER BY created_at DESC, id DESC")
|
||||
.all(slug),
|
||||
// S680 待判读上传集(磁盘纪律下最多保留 KEEP_SETS 套)
|
||||
listUploadsByFamily: (slug) =>
|
||||
db
|
||||
.prepare("SELECT * FROM derma_records WHERE family_slug = ? AND images_ref != '' ORDER BY created_at DESC, id DESC")
|
||||
.all(slug),
|
||||
// 磁盘清理联动:删待判读集目录时同步删其 DB 行(只删 images_ref 非空行,判读记录永不误删)
|
||||
deletePendingByRecordId: (recordId) =>
|
||||
db
|
||||
.prepare("DELETE FROM derma_records WHERE record_id = ? AND images_ref != ''")
|
||||
.run(recordId),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ export async function buildTestApp(overrides = {}) {
|
||||
secret: 'test-secret-fixture',
|
||||
passcode: 'AIBay666',
|
||||
crisisLogFile: path.join(dir, 'crisis-log.jsonl'),
|
||||
dermaImagesDir: path.join(dir, 'derma-images'), // S680 上传图像落盘进临时目录,不污染 server/data
|
||||
distDir: path.join(dir, 'no-dist'),
|
||||
logger: { level: 'silent' },
|
||||
...overrides,
|
||||
|
||||
@@ -4,6 +4,7 @@ import './test-consult.js'
|
||||
import './test-crisis.js'
|
||||
import './test-derma-plus.js'
|
||||
import './test-derma-report.js'
|
||||
import './test-derma-upload.js'
|
||||
import './test-derma.js'
|
||||
import './test-five.js'
|
||||
import './test-growth.js'
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
// test-derma-upload —— S680 指纹图像上传闭环(任务书 runs/2026-10-18-s680)
|
||||
// 覆盖:multipart 十指上传→落盘→待判读记录(capture_method=s680_win_upload)
|
||||
// → 与人工判读衔接(GET report 不被待判读顶掉,capture 后照常出报告)
|
||||
// → 格式/大小拒绝(>2MB、非图像、缺指、未知指位、gender 缺失 → 400;家庭不存在 → 404)
|
||||
// → 磁盘纪律(同 family 第 4 套上传 → 最旧套目录+待判读记录自动清)
|
||||
// 断言口径:fingerprint-capture-options.md §6 第四来源;判读层不感知采集方式
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { buildTestApp, createFamily } from './helpers.js'
|
||||
import { FINGER_IDS } from '../src/engines/derma-engine.js'
|
||||
|
||||
// ---------- 造数工具 ----------
|
||||
|
||||
// 1×1 真实 PNG / 极简 BMP、JPG 头(服务端只做魔数嗅探不解码)
|
||||
const TINY_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
)
|
||||
const TINY_BMP = Buffer.concat([Buffer.from('BM'), Buffer.alloc(54)])
|
||||
const TINY_JPG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff]), Buffer.alloc(16)])
|
||||
|
||||
// multipart 编码器(浏览器/curl 标准形态:name/filename 带引号 + CRLF 边界)
|
||||
// 文件字段传 { data: Buffer, filename },文本字段直接传字符串;可传 entries 数组以构造重复字段
|
||||
function mp(fields, opts = {}) {
|
||||
const b = opts.boundary ?? `----s680test${Math.random().toString(36).slice(2)}`
|
||||
const entries = Array.isArray(fields) ? fields : Object.entries(fields)
|
||||
const chunks = []
|
||||
for (const [name, v] of entries) {
|
||||
const isFile = !!v && typeof v === 'object' && Buffer.isBuffer(v.data)
|
||||
chunks.push(
|
||||
Buffer.from(
|
||||
`--${b}\r\nContent-Disposition: form-data; name="${name}"${
|
||||
isFile && v.filename ? `; filename="${v.filename}"` : ''
|
||||
}\r\n${isFile ? 'Content-Type: application/octet-stream\r\n' : ''}\r\n`,
|
||||
),
|
||||
)
|
||||
chunks.push(isFile ? v.data : Buffer.from(String(v)))
|
||||
chunks.push(Buffer.from('\r\n'))
|
||||
}
|
||||
chunks.push(Buffer.from(`--${b}--\r\n`))
|
||||
const boundaryHeader = opts.quoted ? `boundary="${b}"` : `boundary=${b}`
|
||||
return { payload: Buffer.concat(chunks), headers: { 'content-type': `multipart/form-data; ${boundaryHeader}` } }
|
||||
}
|
||||
|
||||
const file = (data, filename = 'finger.png') => ({ data, filename })
|
||||
|
||||
function tenFingers(buf = TINY_PNG, filename = 'finger.png') {
|
||||
return Object.fromEntries(FINGER_IDS.map((f) => [`finger_${f}`, file(buf, filename)]))
|
||||
}
|
||||
|
||||
async function uploadSet(app, slug, buf = TINY_PNG, opts = {}) {
|
||||
const { payload, headers } = mp({ gender: opts.gender ?? 'male', ...tenFingers(buf) }, opts)
|
||||
return app.inject({ method: 'POST', url: `/api/derma/upload/${slug}`, payload, headers })
|
||||
}
|
||||
|
||||
// 判读闭环用:最小合法 capture 体(对齐 test-derma captureBody 口径)
|
||||
function captureBody() {
|
||||
return {
|
||||
gender: 'male',
|
||||
atd: { left: 40, right: 42 },
|
||||
capture_method: 's680_win_upload',
|
||||
fingers: FINGER_IDS.map((f) => ({ finger: f, pattern: 'whorl_simple', rc: 12 })),
|
||||
}
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
|
||||
// ---------- 全链路:上传 → 落盘 → 待判读记录 → 判读衔接 ----------
|
||||
|
||||
test('S680 上传全链路:multipart 十指 → 文件落盘 → capture_method=s680_win_upload 待判读记录', async (t) => {
|
||||
const { app, db, dir, cleanup } = await buildTestApp()
|
||||
t.after(cleanup)
|
||||
const fam = await createFamily(app, { slug: 'fam-s680-a' })
|
||||
const imagesRoot = path.join(dir, 'derma-images')
|
||||
|
||||
// 带引号 boundary(浏览器实际发送形态之一)
|
||||
const { payload, headers } = mp({ gender: 'female', ...tenFingers() }, { quoted: true })
|
||||
const r = await app.inject({ method: 'POST', url: `/api/derma/upload/${fam.slug}`, payload, headers })
|
||||
assert.equal(r.statusCode, 200, r.body)
|
||||
const j = r.json()
|
||||
assert.equal(j.ok, true)
|
||||
assert.equal(j.capture_method, 's680_win_upload')
|
||||
assert.match(j.record_id, /^DR-\d{8}-\d{4}$/)
|
||||
assert.ok(j.next_hint.includes('天赋检测页'))
|
||||
|
||||
// 落盘布局:{imagesDir}/{family}/{record_id}/{finger}.{ext},十指 PNG 齐全
|
||||
for (const f of FINGER_IDS) {
|
||||
assert.ok(fs.existsSync(path.join(imagesRoot, fam.slug, j.record_id, `${f}.png`)), `落盘 ${f}.png`)
|
||||
assert.equal(j.files[f], `${f}.png`)
|
||||
}
|
||||
|
||||
// DB 待判读记录:images_ref 指向目录,纹型/RC/ATD 全留空
|
||||
const row = db.prepare('SELECT * FROM derma_records WHERE record_id = ?').get(j.record_id)
|
||||
assert.equal(row.family_slug, fam.slug)
|
||||
assert.equal(row.gender, 'female')
|
||||
assert.equal(row.images_ref, `derma-images/${fam.slug}/${j.record_id}`)
|
||||
const pl = JSON.parse(row.payload)
|
||||
assert.equal(pl.capture.method, 's680_win_upload')
|
||||
assert.equal(pl.status, 'pending_judgment')
|
||||
assert.equal(pl.input.atd, null)
|
||||
assert.ok(pl.input.fingers.every((x) => x.pattern === null && x.rc === null))
|
||||
assert.equal(pl.report, null)
|
||||
|
||||
// 单指图像读取:字节一致 + 正确 MIME
|
||||
const img = await app.inject({ method: 'GET', url: `/api/derma/images/${j.record_id}/left_thumb` })
|
||||
assert.equal(img.statusCode, 200)
|
||||
assert.equal(img.headers['content-type'], 'image/png')
|
||||
assert.ok(img.rawPayload.equals(TINY_PNG))
|
||||
|
||||
// 待判读列表:一套可查,含 image_urls
|
||||
const list = await app.inject({ method: 'GET', url: `/api/derma/upload/${fam.slug}` })
|
||||
assert.equal(list.statusCode, 200)
|
||||
const lj = list.json()
|
||||
assert.equal(lj.uploads.length, 1)
|
||||
assert.equal(lj.uploads[0].record_id, j.record_id)
|
||||
assert.equal(lj.uploads[0].capture_method, 's680_win_upload')
|
||||
assert.equal(lj.uploads[0].image_urls.right_little, `/api/derma/images/${j.record_id}/right_little`)
|
||||
})
|
||||
|
||||
test('判读衔接:待判读记录不顶掉 GET report;教练录入纹型后照常出报告(s680_win_upload 过 capture 校验)', async (t) => {
|
||||
const { app, cleanup } = await buildTestApp()
|
||||
t.after(cleanup)
|
||||
const fam = await createFamily(app, { slug: 'fam-s680-judge' })
|
||||
|
||||
// 上传前无报告 → 404
|
||||
const none = await app.inject({ method: 'GET', url: `/api/derma/report/${fam.slug}` })
|
||||
assert.equal(none.statusCode, 404)
|
||||
|
||||
const up = await uploadSet(app, fam.slug)
|
||||
assert.equal(up.statusCode, 200, up.body)
|
||||
const pendingId = up.json().record_id
|
||||
|
||||
// 待判读记录是唯一记录,但不得作为"报告"返回
|
||||
const before = await app.inject({ method: 'GET', url: `/api/derma/report/${fam.slug}` })
|
||||
assert.equal(before.statusCode, 404)
|
||||
|
||||
// 教练按图人工录入(capture_method=s680_win_upload 已进引擎枚举)→ 正常出报告
|
||||
const cap = await app.inject({ method: 'POST', url: `/api/derma/capture/${fam.slug}`, payload: captureBody() })
|
||||
assert.equal(cap.statusCode, 200, cap.body)
|
||||
const capj = cap.json()
|
||||
assert.equal(capj.ok, true)
|
||||
|
||||
const rep = await app.inject({ method: 'GET', url: `/api/derma/report/${fam.slug}` })
|
||||
assert.equal(rep.statusCode, 200)
|
||||
const rj = rep.json()
|
||||
assert.equal(rj.record_id, capj.record_id)
|
||||
assert.notEqual(rj.record_id, pendingId)
|
||||
assert.ok(rj.report.trc.total > 0)
|
||||
// 历史下拉不含待判读记录
|
||||
assert.ok(rj.history.every((h) => h.record_id !== pendingId))
|
||||
})
|
||||
|
||||
// ---------- 格式接纳 ----------
|
||||
|
||||
test('格式接纳:PNG/BMP/JPG 按魔数落对应扩展名(不信任上传文件名)', async (t) => {
|
||||
const { app, dir, cleanup } = await buildTestApp()
|
||||
t.after(cleanup)
|
||||
const fam = await createFamily(app, { slug: 'fam-s680-fmt' })
|
||||
const mixed = {}
|
||||
FINGER_IDS.forEach((f, i) => {
|
||||
mixed[`finger_${f}`] = file(i < 5 ? TINY_PNG : i < 8 ? TINY_BMP : TINY_JPG, `导出文件${i}.dat`) // 扩展名全部给错
|
||||
})
|
||||
const { payload, headers } = mp({ gender: 'male', ...mixed })
|
||||
const r = await app.inject({ method: 'POST', url: `/api/derma/upload/${fam.slug}`, payload, headers })
|
||||
assert.equal(r.statusCode, 200, r.body)
|
||||
const j = r.json()
|
||||
const setDir = path.join(dir, 'derma-images', fam.slug, j.record_id)
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const f = FINGER_IDS[i]
|
||||
const want = i < 5 ? 'png' : i < 8 ? 'bmp' : 'jpg'
|
||||
assert.ok(fs.existsSync(path.join(setDir, `${f}.${want}`)), `${f}.${want}`)
|
||||
}
|
||||
const bmp = await app.inject({ method: 'GET', url: `/api/derma/images/${j.record_id}/right_thumb` })
|
||||
assert.equal(bmp.headers['content-type'], 'image/bmp')
|
||||
const jpg = await app.inject({ method: 'GET', url: `/api/derma/images/${j.record_id}/right_little` })
|
||||
assert.equal(jpg.headers['content-type'], 'image/jpeg')
|
||||
})
|
||||
|
||||
// ---------- 校验拒绝 ----------
|
||||
|
||||
test('校验拒绝:>2MB → 400;非图像 → 400;缺指 → 400;未知/重复指位 → 400;gender 缺失 → 400;家庭不存在 → 404', async (t) => {
|
||||
const { app, cleanup } = await buildTestApp()
|
||||
t.after(cleanup)
|
||||
const fam = await createFamily(app, { slug: 'fam-s680-rej' })
|
||||
|
||||
// 超 2MB(PNG 魔数 + 填充,总 2MB+1B)
|
||||
const oversize = Buffer.concat([TINY_PNG, Buffer.alloc(2 * 1024 * 1024)])
|
||||
const over = await uploadSet(app, fam.slug, oversize)
|
||||
assert.equal(over.statusCode, 400)
|
||||
assert.ok(over.json().detail.some((e) => e.includes('2MB')))
|
||||
|
||||
// 非图像(文本文件,即使叫 .png)
|
||||
const notImage = await uploadSet(app, fam.slug, Buffer.from('hello s680 text file'))
|
||||
assert.equal(notImage.statusCode, 400)
|
||||
assert.ok(notImage.json().detail.some((e) => e.includes('PNG/BMP/JPG')))
|
||||
|
||||
// 缺一指(只传 9 指)
|
||||
const nine = Object.fromEntries(FINGER_IDS.slice(0, 9).map((f) => [`finger_${f}`, file(TINY_PNG)]))
|
||||
const miss = await app.inject({
|
||||
method: 'POST', url: `/api/derma/upload/${fam.slug}`,
|
||||
payload: mp({ gender: 'male', ...nine }).payload, headers: mp({ gender: 'male', ...nine }).headers,
|
||||
})
|
||||
assert.equal(miss.statusCode, 400)
|
||||
assert.ok(miss.json().detail.some((e) => e.includes('缺少')))
|
||||
|
||||
// 重复指位(十指 + left_thumb 再来一份 → entries 数组保留重复 key)
|
||||
const dup = mp([...Object.entries(tenFingers()), ['finger_left_thumb', file(TINY_PNG)]])
|
||||
const dupRes = await app.inject({ method: 'POST', url: `/api/derma/upload/${fam.slug}`, payload: dup.payload, headers: dup.headers })
|
||||
assert.equal(dupRes.statusCode, 400)
|
||||
assert.ok(dupRes.json().detail.some((e) => e.includes('重复')))
|
||||
const unknown = mp({ gender: 'male', ...tenFingers(), finger_left_big: file(TINY_PNG) })
|
||||
const unkRes = await app.inject({ method: 'POST', url: `/api/derma/upload/${fam.slug}`, payload: unknown.payload, headers: unknown.headers })
|
||||
assert.equal(unkRes.statusCode, 400)
|
||||
assert.ok(unkRes.json().detail.some((e) => e.includes('未知指位')))
|
||||
const noGender = mp(tenFingers())
|
||||
const ngRes = await app.inject({ method: 'POST', url: `/api/derma/upload/${fam.slug}`, payload: noGender.payload, headers: noGender.headers })
|
||||
assert.equal(ngRes.statusCode, 400)
|
||||
assert.ok(ngRes.json().detail.some((e) => e.includes('gender')))
|
||||
|
||||
// 家庭不存在 → 404;图像读取不存在 → 404
|
||||
const nf = await uploadSet(app, 'no-such-family')
|
||||
assert.equal(nf.statusCode, 404)
|
||||
const img404 = await app.inject({ method: 'GET', url: `/api/derma/images/DR-99999999-9999/left_thumb` })
|
||||
assert.equal(img404.statusCode, 404)
|
||||
})
|
||||
|
||||
// ---------- 磁盘纪律:保留最近 3 套 ----------
|
||||
|
||||
test('磁盘纪律:同 family 第 4 套上传 → 最旧套目录与待判读记录自动清理', async (t) => {
|
||||
const { app, db, dir, cleanup } = await buildTestApp()
|
||||
t.after(cleanup)
|
||||
const fam = await createFamily(app, { slug: 'fam-s680-keep3' })
|
||||
const familyDir = path.join(dir, 'derma-images', fam.slug)
|
||||
|
||||
const ids = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const r = await uploadSet(app, fam.slug)
|
||||
assert.equal(r.statusCode, 200, r.body)
|
||||
ids.push(r.json().record_id)
|
||||
if (i < 3) await sleep(25) // 目录 mtime 错开,保证排序稳定
|
||||
}
|
||||
|
||||
// 只剩 3 套:最旧 ids[0] 被清,最新 3 套在
|
||||
const sets = fs.readdirSync(familyDir)
|
||||
assert.equal(sets.length, 3)
|
||||
assert.ok(!sets.includes(ids[0]), '最旧套目录已删')
|
||||
for (const id of ids.slice(1)) assert.ok(sets.includes(id), `保留 ${id}`)
|
||||
|
||||
// 被清套的待判读 DB 行联动删除;最新 3 套行仍在
|
||||
assert.equal(db.prepare('SELECT * FROM derma_records WHERE record_id = ?').get(ids[0]), undefined)
|
||||
for (const id of ids.slice(1)) assert.ok(db.prepare('SELECT * FROM derma_records WHERE record_id = ?').get(id))
|
||||
|
||||
// 列表只回 3 套;被清套图像 404
|
||||
const list = await app.inject({ method: 'GET', url: `/api/derma/upload/${fam.slug}` })
|
||||
assert.equal(list.json().uploads.length, 3)
|
||||
assert.ok(list.json().uploads.every((u) => u.record_id !== ids[0]))
|
||||
const gone = await app.inject({ method: 'GET', url: `/api/derma/images/${ids[0]}/left_thumb` })
|
||||
assert.equal(gone.statusCode, 404)
|
||||
const keptImg = await app.inject({ method: 'GET', url: `/api/derma/images/${ids[3]}/left_thumb` })
|
||||
assert.equal(keptImg.statusCode, 200)
|
||||
})
|
||||
Reference in New Issue
Block a user