feat(qc): 修改记录同次提交合并节点并附件化展示 (#153) #154

Merged
cykj merged 2 commits from codex/issue-153-chg-group-fc14c4ae0ee7 into V2.0 2026-11-20 05:25:22 +00:00
7 changed files with 284 additions and 25 deletions

No files matched your search

+2
View File
@@ -449,6 +449,7 @@ class TaskCompleteWithResultBody(BaseModel):
third_party_attachments: Optional[str] = Field(None, alias="thirdPartyAttachments")
material_usages: Optional[List[Dict[str, Any]]] = Field(None, alias="materialUsages")
task_status: Optional[str] = Field(None, alias="taskStatus")
operate_batch_id: Optional[str] = Field(None, alias="operateBatchId")
@router.get("/qc-lab-test-items")
@@ -1438,6 +1439,7 @@ async def complete_task_with_result(
operator_user_name=str(user.get("nickName") or user.get("nick_name") or ""),
before=before,
after=after,
operate_batch_id=body.operate_batch_id,
)
db.commit()
db.refresh(obj)
@@ -144,12 +144,14 @@ def append_task_result_change_log(
before: Dict[str, Any],
after: Dict[str, Any],
operate_time: Optional[datetime] = None,
operate_batch_id: Optional[str] = None,
) -> BizQcTaskResultChangeLog:
"""追加一条检测结果保存留痕(不 commit)。无字段差异也写入。"""
now = operate_time or datetime.now()
changes = build_result_changes(before, after)
has_change = "1" if changes else "0"
name = _resolve_operator_name(db, user_id, operator_user_name)
batch_id = _norm_text(operate_batch_id) or None
obj = BizQcTaskResultChangeLog(
id=generate_uuid(),
task_id=task.id,
@@ -159,6 +161,7 @@ def append_task_result_change_log(
operate_time=now,
operator_user_id=user_id,
operator_user_name=name or None,
operate_batch_id=batch_id,
has_field_change=has_change,
changes_json=json.dumps(changes, ensure_ascii=False),
tenant_no=tenant_no,
@@ -194,6 +197,7 @@ def _row_to_dict(row: BizQcTaskResultChangeLog) -> Dict[str, Any]:
"operateTime": _fmt_dt(row.operate_time),
"operatorUserId": row.operator_user_id or "",
"operatorUserName": row.operator_user_name or "",
"operateBatchId": row.operate_batch_id or "",
"hasFieldChange": row.has_field_change == "1",
"changes": changes,
"createTime": _fmt_dt(row.create_time),
+1
View File
@@ -2407,6 +2407,7 @@ class BizQcTaskResultChangeLog(Base):
operate_time = Column(DateTime, nullable=False, comment="业务操作时间")
operator_user_id = Column(String(64), nullable=True, comment="操作人用户ID")
operator_user_name = Column(String(64), nullable=True, comment="操作人姓名快照")
operate_batch_id = Column(String(64), nullable=True, comment="同一次保存批次ID(多任务共用)")
has_field_change = Column(CHAR(1), nullable=False, default="0", comment="1有字段变更 0仅保存无变更")
changes_json = Column(Text, nullable=True, comment="变更明细JSON")
tenant_no = Column(String(64), nullable=False, default="zkxw", comment="租户编号")
@@ -0,0 +1,8 @@
-- 质检检测结果留痕:同一次批量保存共用 operate_batch_id(Issue #153)
-- 历史行可为空;前端对无批次号的旧数据做短时窗口合并兜底。
ALTER TABLE `biz_qc_task_result_change_log`
ADD COLUMN `operate_batch_id` varchar(64) DEFAULT NULL COMMENT '同一次保存批次ID(多任务共用)' AFTER `operator_user_name`;
ALTER TABLE `biz_qc_task_result_change_log`
ADD KEY `idx_qc_result_chg_batch` (`tenant_no`, `operate_batch_id`, `del_flag`);
+2
View File
@@ -51,6 +51,7 @@ export function fetchCompleteTaskWithResult(
remark?: string
thirdPartyAttachments?: string
taskStatus?: 'dzx' | 'jxz' | 'ywc'
operateBatchId?: string
materialUsages?: Array<{
requisitionUsageId: string
qty: number
@@ -83,6 +84,7 @@ export type QcTaskResultChangeLog = {
operateTime: string
operatorUserId?: string
operatorUserName?: string
operateBatchId?: string
hasFieldChange: boolean
changes: QcTaskResultChangeItem[]
createTime?: string
@@ -380,6 +380,11 @@
const thirdPartyAttachments = financeAttachmentsToUrlString(attachments.value)
const remarkVal = remark.value
// 同一次批量保存共用批次号,修改记录弹窗合并为一个时间线节点
const operateBatchId =
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
? crypto.randomUUID().replace(/-/g, '').toUpperCase()
: `BATCH${Date.now()}${Math.random().toString(16).slice(2, 10)}`.toUpperCase()
saving.value = true
const failures: string[] = []
let successCount = 0
@@ -399,7 +404,8 @@
})),
remark: remarkVal,
thirdPartyAttachments,
taskStatus: item.saveStatus
taskStatus: item.saveStatus,
operateBatchId
},
props.operateScope
)
@@ -14,39 +14,112 @@
>
<DialogFormBody :loading="loading" body-class="qc-result-chg-body">
<el-empty
v-if="!loading && !entries.length"
v-if="!loading && !timelineNodes.length"
description="暂无修改记录"
:image-size="72"
/>
<div v-else class="qc-result-chg-tl">
<div v-for="(entry, idx) in entries" :key="entry.id" class="qc-result-chg-tl__item">
<div
v-for="(node, idx) in timelineNodes"
:key="node.key"
class="qc-result-chg-tl__item"
>
<div class="qc-result-chg-tl__rail">
<span class="qc-result-chg-tl__dot" />
<span v-if="idx < entries.length - 1" class="qc-result-chg-tl__line" />
<span v-if="idx < timelineNodes.length - 1" class="qc-result-chg-tl__line" />
</div>
<div class="qc-result-chg-tl__content">
<div class="qc-result-chg-tl__meta">
{{ entry.operateTime || '—' }} · {{ entry.operatorUserName || '—' }}
<template v-if="showItemName && entry.itemName">
· {{ entry.itemName }}
{{ node.operateTime || '—' }} · {{ node.operatorUserName || '—' }}
<template v-if="node.entries.length > 1">
· 共 {{ node.entries.length }} 项
</template>
</div>
<template v-if="entry.hasFieldChange && entry.changes?.length">
<div v-if="node.sharedAttachment" class="qc-result-chg-tl__change">
<div class="qc-result-chg-tl__line-text">
{{ node.sharedAttachment.fieldLabel }}:
<template
v-if="
node.sharedAttachment.oldValue &&
node.sharedAttachment.oldValue !== node.sharedAttachment.newValue
"
>
已更新
</template>
<template v-else-if="!node.sharedAttachment.newValue">已清空</template>
</div>
<ProtocolAttachmentReadonly
v-if="attachmentFilesFromValue(node.sharedAttachment.newValue).length"
size="compact"
:files="attachmentFilesFromValue(node.sharedAttachment.newValue)"
@preview="onAttachmentPreview"
@download="onAttachmentDownload"
/>
<span
v-else-if="!node.sharedAttachment.newValue"
class="qc-result-chg-tl__line-text"
>—</span>
</div>
<div
v-for="entry in node.entries"
:key="entry.id"
class="qc-result-chg-tl__entry"
>
<div
v-for="(chg, cIdx) in entry.changes"
:key="`${entry.id}-${cIdx}`"
v-if="showItemName && entry.itemName"
class="qc-result-chg-tl__item-name"
>
{{ entry.itemName }}
</div>
<template v-if="visibleChanges(entry, node).length">
<div
v-for="(chg, cIdx) in visibleChanges(entry, node)"
:key="`${entry.id}-${cIdx}`"
class="qc-result-chg-tl__change"
>
<template v-if="isAttachmentChange(chg)">
<div class="qc-result-chg-tl__line-text">
{{ chg.fieldLabel }}:
<template v-if="chg.oldValue && chg.oldValue !== chg.newValue">
已更新
</template>
<template v-else-if="!chg.newValue">已清空</template>
</div>
<ProtocolAttachmentReadonly
v-if="attachmentFilesFromValue(chg.newValue).length"
size="compact"
:files="attachmentFilesFromValue(chg.newValue)"
@preview="onAttachmentPreview"
@download="onAttachmentDownload"
/>
<span
v-else-if="!chg.newValue"
class="qc-result-chg-tl__line-text"
>—</span>
</template>
<div v-else class="qc-result-chg-tl__line-text">
<template v-if="chg.oldValue">
{{ chg.fieldLabel }}:{{ chg.oldValue || '—' }} →
{{ chg.newValue || '—' }}
</template>
<template v-else>
{{ chg.fieldLabel }}:{{ chg.newValue || '—' }}
</template>
</div>
</div>
</template>
<div
v-else-if="!entry.hasFieldChange || !entry.changes?.length"
class="qc-result-chg-tl__line-text"
>
<template v-if="chg.oldValue">
{{ chg.fieldLabel }}:{{ chg.oldValue || '—' }} → {{ chg.newValue || '—' }}
</template>
<template v-else>
{{ chg.fieldLabel }}:{{ chg.newValue || '—' }}
</template>
保存操作(字段无变更)
</div>
</template>
<div v-else class="qc-result-chg-tl__line-text">保存操作(字段无变更)</div>
<div v-if="!entry.hasFieldChange" class="qc-result-chg-tl__note">
</div>
<div v-if="node.allNoFieldChange" class="qc-result-chg-tl__note">
即使未改值,点击保存也会记一条操作留痕
</div>
</div>
@@ -66,13 +139,33 @@
import { ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import DialogFormBody from '@/components/business/dialog-form-body/index.vue'
import ProtocolAttachmentReadonly from '@/views/cell-storage/protocol/ProtocolAttachmentReadonly.vue'
import { downloadAttachmentFile } from '@/utils/download-attachment'
import {
qcAttachmentFullUrl,
qcPreviewAttachment
} from './composables/useQcViewAttachmentHelpers'
import {
fetchQcTaskResultChangeLogsBatch,
type QcTaskResultChangeItem,
type QcTaskResultChangeLog
} from '@/api/qc-task-result'
defineOptions({ name: 'QcTaskResultChangeLogDialog' })
type TimelineNode = {
key: string
operateTime: string
operatorUserName: string
entries: QcTaskResultChangeLog[]
allNoFieldChange: boolean
/** 多任务同次提交且检测材料一致时,提到节点级只展示一次 */
sharedAttachment: QcTaskResultChangeItem | null
}
/** 无批次号的旧数据:同操作人且时间差 ≤15s 合并为一次提交 */
const LEGACY_GROUP_WINDOW_MS = 15_000
const props = withDefaults(
defineProps<{
visible: boolean
@@ -99,6 +192,8 @@
return suffix ? `修改记录 · ${suffix}` : '修改记录'
})
const timelineNodes = computed(() => groupChangeLogs(entries.value))
function onVisibleChange(v: boolean) {
emit('update:visible', v)
}
@@ -107,16 +202,138 @@
emit('update:visible', false)
}
function isAttachmentChange(chg: QcTaskResultChangeItem) {
return (chg.fieldKey || '') === 'attachments'
}
function pickSharedAttachment(rows: QcTaskResultChangeLog[]) {
if (rows.length < 2) return null
const attChanges = rows
.map((r) => (r.changes || []).find((c) => isAttachmentChange(c)))
.filter(Boolean) as QcTaskResultChangeItem[]
if (!attChanges.length || attChanges.length !== rows.length) return null
const first = attChanges[0]
const same = attChanges.every(
(c) => c.newValue === first.newValue && c.oldValue === first.oldValue
)
return same ? first : null
}
function visibleChanges(entry: QcTaskResultChangeLog, node: TimelineNode) {
const list = entry.changes || []
if (!node.sharedAttachment) return list
return list.filter((c) => !isAttachmentChange(c))
}
function attachmentFilesFromValue(raw: string | undefined) {
const text = String(raw || '').trim()
if (!text) return [] as Array<Record<string, unknown>>
return text
.split(',')
.map((u, i) => {
const url = u.trim()
if (!url) return null
const name = url.includes('/') ? url.split('/').pop() || `附件${i + 1}` : url
return {
id: `chg_att_${i}_${name}`,
fileUrl: url,
fileName: name
}
})
.filter(Boolean) as Array<Record<string, unknown>>
}
function onAttachmentPreview(file: Record<string, unknown>) {
qcPreviewAttachment(file)
}
function onAttachmentDownload(file: Record<string, unknown>) {
downloadAttachmentFile(file, { fullFileUrl: qcAttachmentFullUrl })
}
function parseOperateTimeMs(text: string | undefined) {
const s = String(text || '').trim()
if (!s) return NaN
const t = Date.parse(s.replace(/-/g, '/'))
return Number.isFinite(t) ? t : NaN
}
function groupChangeLogs(list: QcTaskResultChangeLog[]): TimelineNode[] {
const sorted = [...(list || [])].sort((a, b) => {
const tb = parseOperateTimeMs(b.operateTime)
const ta = parseOperateTimeMs(a.operateTime)
if (Number.isFinite(tb) && Number.isFinite(ta) && tb !== ta) return tb - ta
return String(b.id || '').localeCompare(String(a.id || ''))
})
const batchBuckets = new Map<string, QcTaskResultChangeLog[]>()
const orphans: QcTaskResultChangeLog[] = []
for (const row of sorted) {
const batch = String(row.operateBatchId || '').trim()
if (batch) {
const arr = batchBuckets.get(batch) || []
arr.push(row)
batchBuckets.set(batch, arr)
} else {
orphans.push(row)
}
}
const nodes: TimelineNode[] = []
for (const [batch, rows] of batchBuckets) {
nodes.push(toNode(`batch:${batch}`, rows))
}
// 旧数据兜底:按时间序贪心合并同操作人短窗口
const used = new Set<string>()
for (let i = 0; i < orphans.length; i++) {
const head = orphans[i]
if (used.has(head.id)) continue
const group = [head]
used.add(head.id)
const headTs = parseOperateTimeMs(head.operateTime)
const headOp = String(head.operatorUserId || head.operatorUserName || '')
for (let j = i + 1; j < orphans.length; j++) {
const cur = orphans[j]
if (used.has(cur.id)) continue
const curOp = String(cur.operatorUserId || cur.operatorUserName || '')
if (curOp !== headOp) continue
const curTs = parseOperateTimeMs(cur.operateTime)
if (!Number.isFinite(headTs) || !Number.isFinite(curTs)) continue
if (Math.abs(curTs - headTs) > LEGACY_GROUP_WINDOW_MS) continue
group.push(cur)
used.add(cur.id)
}
nodes.push(toNode(`legacy:${head.id}`, group))
}
return nodes.sort((a, b) => {
const tb = parseOperateTimeMs(b.operateTime)
const ta = parseOperateTimeMs(a.operateTime)
if (Number.isFinite(tb) && Number.isFinite(ta) && tb !== ta) return tb - ta
return a.key.localeCompare(b.key)
})
}
function toNode(key: string, rows: QcTaskResultChangeLog[]): TimelineNode {
const first = rows[0]
return {
key,
operateTime: first?.operateTime || '',
operatorUserName: first?.operatorUserName || '',
entries: rows,
allNoFieldChange: rows.every((r) => !r.hasFieldChange),
sharedAttachment: pickSharedAttachment(rows)
}
}
async function loadLogs() {
const seq = ++loadSeq
const ids = (props.taskIds || []).map((x) => (x || '').trim()).filter(Boolean)
loading.value = true
entries.value = []
try {
// 多任务统一走批量接口,避免路径被 /qc-tasks/{id} 误匹配
const list = ids.length
? await fetchQcTaskResultChangeLogsBatch(ids)
: []
const list = ids.length ? await fetchQcTaskResultChangeLogsBatch(ids) : []
if (seq !== loadSeq) return
entries.value = Array.isArray(list) ? list : []
} catch {
@@ -191,7 +408,26 @@
font-size: 12px;
font-weight: 600;
color: var(--mint-primary-dark, #059669);
margin-bottom: 6px;
margin-bottom: 8px;
}
.qc-result-chg-tl__entry {
margin-bottom: 10px;
&:last-child {
margin-bottom: 0;
}
}
.qc-result-chg-tl__item-name {
font-size: 13px;
font-weight: 600;
color: var(--mint-text, #1e293b);
margin-bottom: 4px;
}
.qc-result-chg-tl__change {
margin: 4px 0;
}
.qc-result-chg-tl__line-text {
@@ -202,7 +438,7 @@
}
.qc-result-chg-tl__note {
margin-top: 4px;
margin-top: 6px;
font-size: 12px;
color: var(--mint-text-muted, #334155);
}