mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-18 20:12:00 +00:00
Excel 导入改造期 2:配方引擎与确认向导——表从哪一行哪一列开始、哪些是合计、日期怎么补年份,都写进一份可校验的配方;首次导入经人确认,之后每期按配方重放并核对
配方语言(agentlab-recipe/2,新 recipe_types、recipe) - 封闭、不含正则、保存时静态校验:常量只能从表里的候选文字里选,占位符只能映射成空值,单位从固定词表里取 - 交叉表和列表两种版式;分段各自定位、不依赖先后顺序;合计按标签语义区间核对,关系恒等式、口径不同的声明都写在配方里 - 固定的解析器集合(parsers/2):全角、各类横线、千分位、月日写法宽容归一,规范写法存库、原文另记 执行器(新 xlsx_cells、recipe_engine) - 两遍读取逐行对账,每个非空格都要有去向(格子账);交叉表逆透视成长表,按统计期补年份并断言覆盖整期 - 合计行改作核对并另存一张表,不和明细混在一列;区域外文字、隐藏行列、合并单元格、空行之后的文字都单独报出 - STRICT 加主键写临时库;按锚点段记溯源,供后续证据下钻用;大表流式读取,扫描在 sheetData 处停止 校验与说明(新 recipe_checks、recipe_notes) - SQL 核对分通过、不一致、无法核对三种结果,失败分结构、数据质量、需确认三类;结构类直接拒收 - 数据质量类可以写理由接受,接受不改库、只改状态和说明 - 表的说明按核对结果生成、不含数字,经过数字检查;没核对过的不写「已核对」 起草(新 recipe_suggest、recipe_ai) - 先用规则起草:建议卡片加待确认问题(关系要不要登记、占位符表示什么) - 规则起草不完整时才提示 AI 兜底:界面先展示要发出的全部文字,用户同意才发;只发结构,数字、隐藏行列、遮罩列不发,公式先脱敏;同意绑定模型和服务方;AI 只写配方,有限次修订,记 token 和费用;截断单独识别 - 无论规则还是 AI 起草,都必须人工确认才能启用 导入流程(新 recipe_imports、recipe_confirm、recipe_diff、api/table_imports) - 暂存 → 起草 → 回答问题或改配方 → 试运行 → 勾确认项、写接受理由 → 确认并启用;接入期 1 的构建、导入记录、快照和运行固定版本 - 上传新一期按已确认的配方重放,不调用模型,出回执和差异卡,手动启用 - 改配方报破坏性变更(breaking:*)、单位变化、工作表改名的兜底,都要逐项勾选确认 前端导入向导(新 pages/import) - 原始网格(行列号、去向着色)、建议卡片、配方面板(表单,不露正则)、试运行回执、确认清单、差异卡、AI 起草的同意对话框
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
import type {
|
||||
AiPreview, CommitOut, CurrentRecipe, QuestionAnswer, Recipe, Staging,
|
||||
} from '../types'
|
||||
import type {
|
||||
Approval, AutofixResult, Conversation, ConversationDetail, ConversationTurn, CustomTool, DataSource, EvidenceGraph,
|
||||
EvidenceAudit, EvidenceJudgeResult, EvidenceSegmentDetail, GraphSpec, KbDocument, MemoryItem, Provider, PublishCheck, PublishLevel, ReviewResult, Run,
|
||||
@@ -552,6 +555,48 @@ export const api = {
|
||||
get<TableSchema>(`/datasources/${id}/schema?table=${encodeURIComponent(table)}`),
|
||||
},
|
||||
|
||||
/**
|
||||
* 按配方导入(期 2)。暂存区(staging)是一次还没提交的导入:起草、回答问题、改配方、试运行都在它上面做,
|
||||
* 提交(commit)成功之前不动数据源的当前版本。错误按 ApiError.code 分支(staging_closed、trial_required……)
|
||||
*/
|
||||
tableImports: {
|
||||
/** 选文件开始一次导入(首次,或同名的简单导入切换为按配方导入)。带字节进度 */
|
||||
stage: (file: File, body: { name: string; description?: string }, opts?: UploadOptions) => {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
form.append('name', body.name)
|
||||
form.append('description', body.description ?? '')
|
||||
return upload<Staging>('/datasources/imports/stage', form, opts)
|
||||
},
|
||||
get: (id: string) => get<Staging>(`/datasources/imports/${encodeURIComponent(id)}`),
|
||||
/** 已选的全部回答(服务端从起点配方按问题顺序重放)。needs_reason 的选项要带 reason */
|
||||
answers: (id: string, answers: Record<string, QuestionAnswer>) =>
|
||||
post<Staging>(`/datasources/imports/${encodeURIComponent(id)}/answers`, { answers }),
|
||||
/** 整份配方替换工作配方:有静态校验问题也照存,只是不能试运行;已选的回答清空 */
|
||||
putRecipe: (id: string, recipe: Recipe) =>
|
||||
put<Staging>(`/datasources/imports/${encodeURIComponent(id)}/recipe`, { recipe }),
|
||||
/** 将要发给模型的全文(同意框里给人看的就是这一份) */
|
||||
draftAiPreview: (id: string) => get<AiPreview>(`/datasources/imports/${encodeURIComponent(id)}/draft-ai/preview`),
|
||||
/** 用户同意后才调:preview_sha256 与服务端重算的不一致时回 409 ai_preview_stale */
|
||||
draftAi: (id: string, previewSha256: string) =>
|
||||
post<Staging>(`/datasources/imports/${encodeURIComponent(id)}/draft-ai`, { consent: true, preview_sha256: previewSha256 }),
|
||||
trial: (id: string, body: { context_inputs?: Record<string, { start: string; end: string }>; signed_by?: string | null } = {}) =>
|
||||
post<Staging>(`/datasources/imports/${encodeURIComponent(id)}/trial`, body),
|
||||
commit: (id: string, body: {
|
||||
trial_id: string; confirmations: string[]; acceptances: { check_id: string; reason: string }[]; signed_by?: string | null
|
||||
}) => post<CommitOut>(`/datasources/imports/${encodeURIComponent(id)}/commit`, body),
|
||||
discard: (id: string) => del(`/datasources/imports/${encodeURIComponent(id)}`),
|
||||
/** 上传新一期:按当前配方自动试运行,回来时已带回执和差异卡。带字节进度 */
|
||||
reupload: (sourceId: string, file: File, opts?: UploadOptions) => {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
return upload<Staging>(`/datasources/${encodeURIComponent(sourceId)}/reupload`, form, opts)
|
||||
},
|
||||
/** 修改配方(不换文件):用当前导入的原件、以当前配方为工作配方 */
|
||||
redraft: (sourceId: string) => post<Staging>(`/datasources/${encodeURIComponent(sourceId)}/redraft`, {}),
|
||||
recipe: (sourceId: string) => get<CurrentRecipe>(`/datasources/${encodeURIComponent(sourceId)}/recipe`),
|
||||
},
|
||||
|
||||
runs: {
|
||||
/**
|
||||
* status 可以给多个(逗号连接);q 按工作流名模糊匹配;before 是翻页游标
|
||||
|
||||
+352
-1
@@ -842,7 +842,9 @@ export const UPLOAD_TEXT = {
|
||||
// 交叉表、多块结构
|
||||
shapeTitle: '该表格不是一行一条记录的明细表',
|
||||
shapeLead: '检测到以下结构,默认不导入:',
|
||||
shapeRecipe: '这类表格需要按配方导入(指定表头、分段和合计行的处理方式),该功能将在后续版本提供。',
|
||||
shapeRecipe: '这类表格可以按配方导入:指定表头、分段和合计行的处理方式,试运行核对、逐条确认后再启用。',
|
||||
/** CSV 没有配方这条路(配方只认 Excel 的工作表结构) */
|
||||
shapeRecipeCsv: '按配方导入目前只支持 Excel(.xlsx)文件:可另存为 .xlsx 后再按配方导入。',
|
||||
shapeHeader: (row: number) => `如果表头不在第 ${row} 行,请取消后修改表头行号,再重新上传。`,
|
||||
/** 结构问题之外,预告的混合列:选按原样导入以后还要再选一次 */
|
||||
shapeMixedLead: '另外,以下各列以数字为主,但混有非数字的值。选择按原样导入后,还需要选择这些值的处理方式:',
|
||||
@@ -901,3 +903,352 @@ export const RAW_STATE_LABEL: Record<string, string> = {
|
||||
purged: '原件已清除',
|
||||
absent: '未保存原件',
|
||||
}
|
||||
|
||||
/**
|
||||
* 按配方导入(期 2):向导、原始网格、建议卡片、配方面板、试运行回执、确认清单、差异卡、AI 起草。
|
||||
* 后端返回的问题、确认项、核对标题是整句人话,界面原样显示;这里只放界面自己的文字和枚举的显示名。
|
||||
*
|
||||
* 配方面板里不出现「正则」一类字样:配方语言是封闭的,没有任何字段能写匹配规则
|
||||
*/
|
||||
export const RECIPE_TEXT = {
|
||||
// ---- 入口
|
||||
entry: '按配方导入',
|
||||
entryHint: '交叉表、分段表格按配方导入:起草配方、试运行核对,逐条确认后启用',
|
||||
reupload: '上传新一期',
|
||||
reuploadHint: '按已确认的配方导入新一期的文件:先试运行,看过回执和差异后再启用',
|
||||
redraft: '修改配方',
|
||||
redraftHint: '不换文件,修改当前配方后重新试运行',
|
||||
openStaging: '有未完成的导入',
|
||||
openStagingHint: '继续上次未完成的导入',
|
||||
// ---- 向导
|
||||
titleFirst: '按配方导入',
|
||||
titleNamed: (name: string) => `按配方导入「${name}」`,
|
||||
titleReupload: (name: string) => `上传新一期「${name}」`,
|
||||
titleRedraft: (name: string) => `修改配方「${name}」`,
|
||||
steps: { pick: '选择文件', draft: '起草配方', trial: '试运行', confirm: '确认启用', done: '完成' },
|
||||
pickReupload: '选择新一期的文件:将按当前配方试运行,回执和差异核对无误后再启用。',
|
||||
nameHint: '将用作工具名的一部分;启用之前不会创建数据源',
|
||||
nameLabel: '数据源名',
|
||||
nameInvalid: '须以小写字母开头,只能包含小写字母、数字和下划线',
|
||||
nameTakenDb: (name: string) => `「${name}」已被其他数据库用作标识,请更换名称`,
|
||||
descriptionLabel: '说明(供助手参考)',
|
||||
pickDrop: '拖入文件,或点击选择',
|
||||
/** 与选择框的 accept 一致 */
|
||||
pickFormats: '支持 Excel(.xlsx、.xlsm)',
|
||||
pickAria: '选择表格文件',
|
||||
pickWrongType: (name: string) => `「${name}」不是 Excel 文件:按配方导入只支持 .xlsx、.xlsm`,
|
||||
cancelUpload: '取消上传',
|
||||
cancel: '取消',
|
||||
close: '关闭',
|
||||
staging: '正在读取表格、起草配方',
|
||||
reuploading: '正在读取表格、按当前配方试运行',
|
||||
loading: '正在读取这次导入',
|
||||
discard: '放弃这次导入',
|
||||
discardTitle: '放弃这次导入?',
|
||||
discardConsequences: ['已起草的配方、回答和试运行结果都不保留', '数据源的当前版本不受影响'],
|
||||
discarded: '已放弃这次导入',
|
||||
closed: '这次导入已结束(过期或已放弃),请重新开始',
|
||||
rawMissing: '当前导入的原始文件已清除,无法直接修改配方:请用「上传新一期」带着文件进入修改',
|
||||
later: '稍后继续',
|
||||
laterHint: '关闭向导,进度已保存在服务端;可从卡片上的「有未完成的导入」继续',
|
||||
// ---- 起草
|
||||
trialRun: '试运行',
|
||||
trialRunning: '试运行中',
|
||||
trialBlocked: '配方有问题,修改后才能试运行',
|
||||
trialStale: '上次的试运行已失效(之后修改过配方或录入),请重新试运行',
|
||||
trialStaleConfirm: '上次的试运行已失效,不能据此启用:请回到配方重新试运行',
|
||||
partial: '仅检查了前 500 行,完整检查在试运行时进行',
|
||||
partialHint: '表格较大,起草时只检查了每张工作表的前 500 行;试运行会检查全部',
|
||||
draftIncomplete: '规则起草未能完成',
|
||||
cardsTitle: '建议',
|
||||
questionsTitle: '待确认',
|
||||
noCards: '没有需要说明的建议',
|
||||
reasonLabel: '理由(必填)',
|
||||
reasonPlaceholder: '说明为什么这样选',
|
||||
reasonSubmit: '提交',
|
||||
reasonRequired: '请填写理由',
|
||||
answering: '正在应用',
|
||||
suggested: (label: string) => `建议:${label}`,
|
||||
// ---- 网格
|
||||
gridLabel: '原始表格',
|
||||
legendTitle: '图例',
|
||||
unclaimed: '没有去处',
|
||||
hiddenCells: '隐藏的行列',
|
||||
gridTruncated: (n: string, total: string) => `仅显示前 ${n} 行,共 ${total} 行`,
|
||||
noGrid: '没有可显示的工作表',
|
||||
// ---- AI 起草
|
||||
aiOffer: '让 AI 起草(会把表格结构发给模型)',
|
||||
aiUnavailable: '未配置模型接入,无法使用 AI 起草(设置 → 模型接入)',
|
||||
aiConsentTitle: '发送表格结构给模型',
|
||||
aiConsentLead: (model: string) => `将把下面这段内容发送给「${model}」:工作表名称、表头和行标签等结构文字`
|
||||
+ '(写成文字的日期和统计期说明也会发送,如「8月1日」「统计时间范围:…」)、数字单元格和日期格式单元格的类型、'
|
||||
+ '合并区域、去掉了常量的公式形状、系统发现的关系。',
|
||||
aiConsentNot: '不会发送数字单元格的值、日期格式单元格里的日期、像数字的文字和隐藏行列的内容;'
|
||||
+ '其他文字只发字数,列表数据列只发个数统计、不发内容(每行最左一格的「合计」「小计」这类标签和占位符照发)。'
|
||||
+ '配方需要修订时,还会把配方的问题列表发给同一个模型,其中的这些内容同样已遮掉。',
|
||||
aiConsentAfter: 'AI 只起草配方,导入前仍需试运行并逐条确认。',
|
||||
aiPreviewLabel: (chars: string) => `将要发送的全文(${chars} 字)`,
|
||||
aiAgree: '同意并发送',
|
||||
aiPreviewing: '正在准备将要发送的内容',
|
||||
aiDrafting: 'AI 起草中',
|
||||
/** cost 是 formatCost 的结果(「$0.012」) */
|
||||
aiDone: (tokens: string, cost: string) => `AI 起草完成,用了 ${tokens} token(约 ${cost})`,
|
||||
aiStale: '表格内容或模型设置已变化,请重新查看将要发送的内容',
|
||||
// ---- 配方面板
|
||||
panel: '配方',
|
||||
panelHint: '每项修改都会立即保存并重新检查;有问题的字段旁会标出原因',
|
||||
panelProblems: '配方有以下问题',
|
||||
viewJson: '查看配方 JSON',
|
||||
hideJson: '收起配方 JSON',
|
||||
pasteJson: '粘贴配方',
|
||||
pasteLead: '粘贴一份完整的配方 JSON,保存后同样经过检查。',
|
||||
pasteSave: '保存配方',
|
||||
pasteInvalid: 'JSON 格式有误,未保存',
|
||||
pasteNotObject: '配方必须是一个 JSON 对象',
|
||||
saving: '正在保存',
|
||||
noRecipe: '还没有配方:请回答上面的问题,或粘贴一份配方',
|
||||
readonlyNote: '表单没有覆盖的字段只能通过粘贴配方修改',
|
||||
sheet: (name: string) => `工作表「${name}」`,
|
||||
table: (name: string) => `表「${name}」`,
|
||||
crosstab: '交叉表',
|
||||
listBlock: (id: string) => `列表「${id}」`,
|
||||
segment: (id: string) => `分段「${id}」`,
|
||||
derivedSegment: (id: string) => `合计段「${id}」`,
|
||||
tableName: '表名',
|
||||
columnName: '列名',
|
||||
unit: '单位',
|
||||
noUnit: '无单位',
|
||||
grain: '主键',
|
||||
grainHint: '用作主键的列(最多 4 列)',
|
||||
labels: '标签',
|
||||
totalLabels: '合计标签',
|
||||
addLabel: '添加',
|
||||
labelPlaceholder: '从表格中选择或输入',
|
||||
removeLabel: (label: string) => `移除标签「${label}」`,
|
||||
locateBy: '定位方式',
|
||||
sectionTitle: '分段标题',
|
||||
stopAtTotal: '遇到时段合计行时结束本段',
|
||||
dimName: '维度列名',
|
||||
dimParser: '标签写法',
|
||||
valueName: '值列名',
|
||||
constants: '常量列',
|
||||
constPick: '取值',
|
||||
deriveCols: '由时段派生的列',
|
||||
deriveRole: { start: '区间起点', end: '区间终点' } as Record<string, string>,
|
||||
keepDim: '合计项列名',
|
||||
keepAs: '原表合计另存为表',
|
||||
keepTable: '另存的表名',
|
||||
values: '数据区的值',
|
||||
valueType: '类型',
|
||||
placeholders: '占位符',
|
||||
placeholderText: '占位符文字',
|
||||
placeholderMeaning: '含义',
|
||||
placeholderStore: '一律存为空值',
|
||||
addPlaceholder: '添加占位符',
|
||||
removePlaceholder: (text: string) => `移除占位符「${text}」`,
|
||||
blank: '空格',
|
||||
textNumber: '文本写的数字',
|
||||
formula: '公式',
|
||||
period: '统计期',
|
||||
preferPrefix: '优先展示以此开头的格子',
|
||||
crossCheck: '与文件名里的日期核对',
|
||||
addPeriod: '从格子里解析统计期',
|
||||
noPeriod: '未配置统计期',
|
||||
axisChecks: '日期检查',
|
||||
axisChecksHint: '取消任一项,确认清单里会多出一条需确认的放宽',
|
||||
headerRows: '表头行数',
|
||||
afterTitle: '只在这行文字之后找表头',
|
||||
columns: '列',
|
||||
colHeader: '表头',
|
||||
colType: '类型',
|
||||
colStore: '存法',
|
||||
addColumn: '添加列',
|
||||
removeColumn: (name: string) => `移除列「${name}」`,
|
||||
extraColumns: '表头里多出的列',
|
||||
blankRows: '数据中间的空行',
|
||||
totalRow: '合计行',
|
||||
totalRowOn: '有合计行',
|
||||
totalLabelColumn: '合计标签所在的列',
|
||||
totalPick: '合计行以此开头',
|
||||
totalKeep: '原表合计另存为表(留空则只核对)',
|
||||
hiddenRows: '隐藏行',
|
||||
hiddenCols: '隐藏列',
|
||||
fallback: '工作表改名时',
|
||||
otherSheets: '配方没有列出的其他工作表',
|
||||
relations: '关系',
|
||||
relationRegister: '登记',
|
||||
relationDismiss: '不登记',
|
||||
relationReason: '不登记的理由(必填)',
|
||||
relationTotal: '合计列',
|
||||
relationParts: '组成列',
|
||||
relationNoCache: '请在建议卡片的问题里选择「登记」',
|
||||
notComparable: (a: string, b: string) => `「${a}」与「${b}」口径不同`,
|
||||
sumEq: (total: string, parts: string) => `${total} = ${parts}`,
|
||||
dismissed: (claims: string) => `不登记系统发现的关系 ${claims}`,
|
||||
// ---- 试运行回执
|
||||
receipt: '试运行回执',
|
||||
ledger: (n: string) => `单元格去向:非空单元格 ${n} 个`,
|
||||
ledgerAll: '全部有去处',
|
||||
ledgerUnclaimed: (n: string) => `其中 ${n} 个没有去处`,
|
||||
/** 格子账为空:配方里的工作表一张都没读到(如工作表改名后对不上),去向和两遍读取都无从谈起 */
|
||||
ledgerNone: '未读取到配方中的工作表,无法核对单元格去向',
|
||||
ledgerSheetsMissing: (n: string) => `配方中有 ${n} 张工作表未读取到,以上只计入已读取的工作表`,
|
||||
ledgerUnbalanced: (sum: string, read: string) => `各去向合计 ${sum} 个,与读取到的 ${read} 个不符`,
|
||||
passAgree: '两遍读取一致',
|
||||
passDiffer: (scan: string, read: string) => `两遍读取不一致:第一遍 ${scan} 个、第二遍 ${read} 个`,
|
||||
tables: '表与行数',
|
||||
rows: (n: string) => `${n} 行`,
|
||||
/** 拒收、需要录入时执行器没有写完(或根本没写库):只列表和列,不显示行数 */
|
||||
tablesUnwritten: '试运行没有完成写入,以下只列出表和列;行数以通过后的试运行为准',
|
||||
rowsUnwritten: '未写入',
|
||||
periodLine: (start: string, end: string) => `统计期:${start} 至 ${end}`,
|
||||
periodFromCells: (cells: string) => `取自 ${cells}`,
|
||||
periodHuman: (who: string) => `人工录入(${who})`,
|
||||
checks: '核对',
|
||||
notes: '说明预览',
|
||||
problems: '问题',
|
||||
outsideText: '区域外文字',
|
||||
placeholderCounts: '占位符',
|
||||
placeholderCount: (text: string, n: string) => `「${text}」${n} 格`,
|
||||
statusPassed: '试运行通过:请逐条确认后启用',
|
||||
statusNeedsDecision: '有核对未通过但可以接受:在确认清单里写明理由',
|
||||
statusNeedsInput: '无法从表格中确定统计期:请录入本期统计期',
|
||||
statusRejected: '试运行未通过:请修改配方或文件',
|
||||
backToRecipe: '修改配方',
|
||||
toConfirm: '下一步:逐条确认',
|
||||
backToReceipt: '返回回执',
|
||||
periodStart: '统计期起',
|
||||
periodEnd: '统计期止',
|
||||
periodSuggest: (start: string, end: string) => `文件名中的日期:${start} 至 ${end}`,
|
||||
periodUseSuggest: '填入',
|
||||
periodSubmit: '按此统计期试运行',
|
||||
periodInvalid: '请填写两个日期,且起点不晚于终点',
|
||||
// ---- 确认清单
|
||||
confirmTitle: '启用前请逐条确认',
|
||||
confirmLead: '以下各项需逐条勾选;可接受的核对须写明理由。',
|
||||
acceptTitle: '可接受的核对',
|
||||
acceptLabel: '接受理由(必填)',
|
||||
acceptPlaceholder: '说明为什么可以接受',
|
||||
signLabel: '署名',
|
||||
signNote: '署名(未认证)',
|
||||
commitFirst: '确认并启用',
|
||||
commitReupload: '启用',
|
||||
committing: '正在启用',
|
||||
commitBlocked: '请勾选全部必选的确认项,并为每条可接受的核对写明理由',
|
||||
/** 不必勾的确认项(ConfirmItem.required=false)旁的标注 */
|
||||
confirmOptional: '可选',
|
||||
missing: '这一项尚未确认',
|
||||
rerunTrial: '请重新试运行',
|
||||
baseChanged: '在你试运行之后,当前版本已被更新,请重新试运行',
|
||||
nameTaken: '该名称已被占用:请放弃这次导入,换一个名称后重新导入',
|
||||
// ---- 完成
|
||||
done: (name: string) => `已启用「${name}」`,
|
||||
doneUnchanged: (seq: string) => `与第 ${seq} 次导入相同,未新建版本`,
|
||||
doneReused: '内容与以前的某次导入相同,沿用了那次的数据文件',
|
||||
finish: '完成',
|
||||
// ---- 卡片上的配方信息
|
||||
recipeVersion: (seq: string) => `配方第 ${seq} 版`,
|
||||
recipeActivated: (when: string) => `${when}${/\d$/.test(when) ? ' ' : ''}启用`,
|
||||
recipeActivatedTitle: (when: string) => `当前配方于 ${when} 启用`,
|
||||
recipeSigned: (who: string) => `署名「${who}」(未认证)`,
|
||||
// ---- 差异卡
|
||||
diffTitle: '与上一期相比',
|
||||
/** 差异卡的 kind 不在 DIFF_KIND_LABEL 里时的通用名(不露键名) */
|
||||
diffKindOther: '其他变化',
|
||||
diffRequires: '需确认',
|
||||
diffNone: '与上一期相比没有需要说明的差异',
|
||||
sameAsImport: (seq: string) => `与第 ${seq} 次导入相同,无需重复导入`,
|
||||
} as const
|
||||
|
||||
/** 格子的去向(契约 Role):网格图例、回执里的格子账 */
|
||||
export const LEDGER_ROLE_LABEL: Record<string, string> = {
|
||||
value: '数据值',
|
||||
derived_value: '合计格',
|
||||
derived_label: '合计标签',
|
||||
col_header: '列表头',
|
||||
row_label: '行标签',
|
||||
section_title: '分段标题',
|
||||
context: '统计期',
|
||||
outside_text: '区域外文字',
|
||||
ignored_column: '忽略的列',
|
||||
hidden_excluded: '排除的隐藏行',
|
||||
total_label: '合计标签',
|
||||
total_value: '合计格',
|
||||
}
|
||||
|
||||
/** 核对结果的状态 */
|
||||
export const CHECK_STATUS_LABEL: Record<string, string> = {
|
||||
passed: '通过',
|
||||
mismatch: '不一致',
|
||||
unverifiable: '无法核对',
|
||||
info: '说明',
|
||||
}
|
||||
|
||||
/** 问题和核对的类别:结构问题不能接受,只能改配方或文件;数据质量可以写明理由后接受 */
|
||||
export const PROBLEM_CATEGORY_LABEL: Record<string, string> = {
|
||||
structure: '结构问题(需修改配方或文件)',
|
||||
data_quality: '数据质量(可写明理由后接受)',
|
||||
confirm: '需确认',
|
||||
input: '需要录入',
|
||||
recipe: '配方问题',
|
||||
info: '说明',
|
||||
}
|
||||
|
||||
/** 上传新一期的差异种类(recipe_diff 的 kind) */
|
||||
export const DIFF_KIND_LABEL: Record<string, string> = {
|
||||
period: '统计期',
|
||||
rows: '行数',
|
||||
placeholders: '占位符',
|
||||
checks: '核对结果',
|
||||
file_name: '文件名',
|
||||
full_calc: '打开时重算',
|
||||
context_text: '统计期的写法',
|
||||
context_source_added: '统计期来源',
|
||||
column_order: '列顺序',
|
||||
label_writing: '标签写法',
|
||||
header_writing: '表头写法',
|
||||
canon_values: '规范写法',
|
||||
row_order: '行顺序',
|
||||
block_order: '各块的先后',
|
||||
derived_form: '合计的形态',
|
||||
axis_form: '日期表头的形态',
|
||||
outside_added: '新增的区域外文字',
|
||||
outside_removed: '不再出现的区域外文字',
|
||||
outside_changed: '区域外文字有变化',
|
||||
outside_moved: '区域外文字挪了位置',
|
||||
ignored_columns: '忽略的列',
|
||||
hidden: '隐藏的行列',
|
||||
}
|
||||
|
||||
/**
|
||||
* 配方的起草方式(table_recipes.origin):卡片上「配方第 N 版 · 规则起草」。manual 是在配方面板里改过或
|
||||
* 粘贴的规则草稿,mixed 是 AI 草稿又经人改过
|
||||
*/
|
||||
export const RECIPE_ORIGIN_LABEL: Record<string, string> = {
|
||||
rules: '规则起草',
|
||||
ai: 'AI 起草',
|
||||
manual: '手工编辑',
|
||||
mixed: 'AI 起草后手工修改',
|
||||
}
|
||||
|
||||
/** 配方面板里各取值的显示名(封闭取值,界面不露英文枚举) */
|
||||
export const RECIPE_CHOICE_LABEL = {
|
||||
locateBy: { labels: '按标签', section_title: '按分段标题' } as Record<string, string>,
|
||||
dimParser: { hour_range: '时段(如 7-8)', text: '文字' } as Record<string, string>,
|
||||
valueType: { INTEGER: '整数', REAL: '小数' } as Record<string, string>,
|
||||
blankCross: { reject: '拒收', null: '存为空值(需确认)' } as Record<string, string>,
|
||||
blankList: { null: '存为空值', reject: '拒收' } as Record<string, string>,
|
||||
textNumber: { reject: '拒收', parse_thousands: '千分位写法按数字保存(需确认)' } as Record<string, string>,
|
||||
formulaCross: { reject: '拒收', accept_cached: '按保存值导入(需确认)' } as Record<string, string>,
|
||||
formulaList: { accept_cached: '按保存值导入', reject: '拒收' } as Record<string, string>,
|
||||
meaning: { 无数据: '无数据', 不适用: '不适用' } as Record<string, string>,
|
||||
hiddenRows: { reject_if_any: '有隐藏行时拒收', include: '照常导入', exclude: '跳过' } as Record<string, string>,
|
||||
hiddenCols: { reject_if_any: '有隐藏列时拒收', include: '照常导入' } as Record<string, string>,
|
||||
fallback: { only_visible_sheet: '用唯一有内容的可见工作表(需确认)', none: '必须同名' } as Record<string, string>,
|
||||
otherSheets: { confirm: '记入回执,需确认', reject: '拒收' } as Record<string, string>,
|
||||
extraColumns: { reject: '拒收', ignore: '忽略(需确认)' } as Record<string, string>,
|
||||
blankRows: { stop: '到此为止', skip: '跳过继续(需确认)' } as Record<string, string>,
|
||||
colType: { TEXT: '文字', INTEGER: '整数', REAL: '小数', DATE: '日期' } as Record<string, string>,
|
||||
colStore: { '': '默认', canonical: '规范写法', raw: '原文' } as Record<string, string>,
|
||||
axisChecks: { contiguous: '逐日连续', covers_context: '恰好覆盖统计期' } as Record<string, string>,
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useEffect, useId, useMemo, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import {
|
||||
AlertTriangle, ChevronRight, Database, EyeOff, FileSpreadsheet, Info, KeyRound, Lock, Plug, Plus, RefreshCw,
|
||||
AlertTriangle, ChevronRight, Database, EyeOff, FileSpreadsheet, Info, KeyRound, Layers, Lock, Plug, Plus, RefreshCw,
|
||||
Search, Table2, Upload, X,
|
||||
} from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { ApiError, api, uploadDecision } from '../api/client'
|
||||
import type { IntrospectPreview, TableSchema, UploadProgress } from '../api/client'
|
||||
import type { CurrentSnapshot, UploadDecision, UploadMixedColumn, UploadResult } from '../types'
|
||||
import type { CurrentSnapshot, DataSource, UploadDecision, UploadMixedColumn, UploadResult } from '../types'
|
||||
import { useCatalog, useOnReconnect } from '../store/catalog'
|
||||
import {
|
||||
confirmDialog, DeleteButton, EmptyState, ErrorState, Field, HealthPill, IconButton, Modal, promptDialog,
|
||||
@@ -20,8 +20,12 @@ import {
|
||||
import { checkHealth, forgetHealth, healthFromServer, setHealth, useHealth } from '../lib/health'
|
||||
import type { HealthRecord } from '../lib/health'
|
||||
import { workflowList, workflowsMentioning } from '../lib/mentions'
|
||||
import { RAW_STATE_LABEL, UPLOAD_CONVERSION_LABEL, UPLOAD_SHAPE_LABEL, UPLOAD_TEXT } from '../lib/terms'
|
||||
import {
|
||||
RAW_STATE_LABEL, RECIPE_ORIGIN_LABEL, RECIPE_TEXT, UPLOAD_CONVERSION_LABEL, UPLOAD_SHAPE_LABEL, UPLOAD_TEXT,
|
||||
} from '../lib/terms'
|
||||
import { useRunClock } from '../run/useRunClock'
|
||||
import { ImportWizard } from './import/ImportWizard'
|
||||
import type { WizardEntry } from './import/ImportWizard'
|
||||
|
||||
// ===========================================================================
|
||||
// 数据源
|
||||
@@ -70,6 +74,8 @@ export function DataSourcesTab({ view = 'databases' }: { view?: DataView }) {
|
||||
const [loadError, setLoadError] = useState<unknown>(null)
|
||||
const [editing, setEditing] = useState<any | null>(null)
|
||||
const [uploading, setUploading] = useState<{ name?: string } | null>(null)
|
||||
/** 按配方导入的向导(首次、上传新一期、修改配方、继续未完成的导入) */
|
||||
const [wizard, setWizard] = useState<WizardEntry | null>(null)
|
||||
const [kick, setKick] = useState<{ id: string; seq: number } | null>(null)
|
||||
const loadSeq = useRef(0)
|
||||
const hasRows = useRef(false)
|
||||
@@ -116,6 +122,9 @@ export function DataSourcesTab({ view = 'databases' }: { view?: DataView }) {
|
||||
title="表格"
|
||||
hint="上传 Excel / CSV 文件,每个工作表会转为一张可用 SQL 查询的表,数字可计算、可溯源。同名文件重新上传会直接替换数据,工具名不变。"
|
||||
>
|
||||
<button className="btn btn-sm" onClick={() => setWizard({ kind: 'new' })} title={RECIPE_TEXT.entryHint} data-recipe-entry>
|
||||
<Layers size={12} aria-hidden /> {RECIPE_TEXT.entry}
|
||||
</button>
|
||||
<button className="btn btn-primary btn-sm" onClick={() => setUploading({})}>
|
||||
<Upload size={12} /> 上传表格
|
||||
</button>
|
||||
@@ -171,6 +180,9 @@ export function DataSourcesTab({ view = 'databases' }: { view?: DataView }) {
|
||||
onRemoved={drop}
|
||||
onEdit={() => setEditing(row)}
|
||||
onReupload={() => setUploading({ name: row.name })}
|
||||
onRecipeReupload={() => setWizard({ kind: 'reupload', source: row })}
|
||||
onRedraft={() => setWizard({ kind: 'redraft', source: row })}
|
||||
onResume={() => row.open_staging && setWizard({ kind: 'resume', stagingId: row.open_staging.id, source: row })}
|
||||
kick={kick && kick.id === row.id ? kick.seq : 0}
|
||||
/>
|
||||
))}
|
||||
@@ -215,6 +227,27 @@ export function DataSourcesTab({ view = 'databases' }: { view?: DataView }) {
|
||||
syncCatalog()
|
||||
if (!tables) navigate('/data/tables', { replace: true })
|
||||
}}
|
||||
onRecipe={(file, name, description) => {
|
||||
// 交叉表决定页的「按配方导入」:带着同一个文件、名字和说明进向导,上传弹窗让位
|
||||
setUploading(null)
|
||||
setWizard({ kind: 'stage', file, name, description })
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{wizard && (
|
||||
<ImportWizard
|
||||
entry={wizard}
|
||||
// 同上传弹窗:手工登记的 SQLite 可能是还没迁移的早期上传,交给服务端判断
|
||||
taken={(rows ?? []).filter((r) => !isUploadedTable(r) && r.kind !== 'sqlite').map((r) => r.name)}
|
||||
onClose={() => setWizard(null)}
|
||||
onCommitted={(row) => {
|
||||
upsert(row)
|
||||
syncCatalog()
|
||||
if (!tables) navigate('/data/tables', { replace: true })
|
||||
}}
|
||||
// 暂存区开始、放弃、关掉:卡片上的「有未完成的导入」要跟上
|
||||
onChanged={() => void load()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -224,12 +257,16 @@ export function DataSourcesTab({ view = 'databases' }: { view?: DataView }) {
|
||||
/** 结构同步超过这么久就提示可能过期:库表会变,Copilot 照旧表写 SQL 只会报错 */
|
||||
const STALE_SCHEMA_MS = 7 * 24 * 3600_000
|
||||
|
||||
function SourceCard({ row, meta, onChange, onRemoved, onEdit, onReupload, kick }: {
|
||||
function SourceCard({ row, meta, onChange, onRemoved, onEdit, onReupload, onRecipeReupload, onRedraft, onResume, kick }: {
|
||||
row: any; meta?: any
|
||||
onChange: (row: any) => void
|
||||
onRemoved: (id: string) => void
|
||||
onEdit: () => void
|
||||
onReupload: () => void
|
||||
/** 按配方导入的源:上传新一期、修改配方;有未完成的导入时继续它 */
|
||||
onRecipeReupload: () => void
|
||||
onRedraft: () => void
|
||||
onResume: () => void
|
||||
/** 非 0 时自动点一次「探查结构」(新建后 toast 上的按钮) */
|
||||
kick: number
|
||||
}) {
|
||||
@@ -433,7 +470,19 @@ function SourceCard({ row, meta, onChange, onRemoved, onEdit, onReupload, kick }
|
||||
: <><RefreshCw size={11} aria-hidden /> 探查结构</>}
|
||||
</button>
|
||||
)}
|
||||
{uploaded
|
||||
{row.open_staging && (
|
||||
<button className="btn btn-sm" onClick={onResume} title={RECIPE_TEXT.openStagingHint} data-open-staging={row.open_staging.id}
|
||||
style={{ color: 'var(--warn)', borderColor: 'color-mix(in srgb, var(--warn) 45%, transparent)' }}>
|
||||
{RECIPE_TEXT.openStaging}
|
||||
</button>
|
||||
)}
|
||||
{uploaded && row.import_mode === 'recipe' ? (
|
||||
// 按配方导入的源:每月按已确认的配方重放,不走简单上传(服务端也会拒绝)
|
||||
<>
|
||||
<button className="btn btn-sm btn-ghost" onClick={onRecipeReupload} title={RECIPE_TEXT.reuploadHint}>{RECIPE_TEXT.reupload}</button>
|
||||
<button className="btn btn-sm btn-ghost" onClick={onRedraft} title={RECIPE_TEXT.redraftHint}>{RECIPE_TEXT.redraft}</button>
|
||||
</>
|
||||
) : uploaded
|
||||
? <button className="btn btn-sm btn-ghost" onClick={onReupload} title={UPLOAD_TEXT.reuploadHint}>{UPLOAD_TEXT.reupload}</button>
|
||||
: <button className="btn btn-sm btn-ghost" onClick={onEdit}>编辑</button>}
|
||||
<DeleteButton label={`删除数据源 ${row.name}`} onClick={() => void remove()} />
|
||||
@@ -579,6 +628,7 @@ function Address({ row, meta, uploaded }: { row: any; meta?: any; uploaded: bool
|
||||
<>
|
||||
<span>上传的表格{row.table_count ? ` · ${row.table_count} 张表` : ''}</span>
|
||||
{snap && <UploadVersion snap={snap} />}
|
||||
{row.import_mode === 'recipe' && row.current_recipe && <RecipeVersion recipe={row.current_recipe} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -617,6 +667,23 @@ function UploadVersion({ snap }: { snap: CurrentSnapshot }) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按配方导入的源当前用的是哪一版配方:第几版、怎么起草的、什么时候启用、谁署的名(署名未认证)。
|
||||
* 每月按配方重放,配方换了版本,引用它的报告口径可能跟着变,所以和当前版本写在同一处
|
||||
*/
|
||||
function RecipeVersion({ recipe }: { recipe: NonNullable<DataSource['current_recipe']> }) {
|
||||
const at = parseServerTime(recipe.activated_at)
|
||||
return (
|
||||
<span className="inline-flex min-w-0 flex-wrap items-baseline gap-x-1" data-current-recipe={recipe.id}
|
||||
title={at ? RECIPE_TEXT.recipeActivatedTitle(formatDateTime(recipe.activated_at)) : undefined}>
|
||||
<span className="tnum">{RECIPE_TEXT.recipeVersion(formatNumber(recipe.seq))}</span>
|
||||
<span>· {RECIPE_ORIGIN_LABEL[recipe.origin] ?? recipe.origin}</span>
|
||||
{at && <span className="tnum">· {RECIPE_TEXT.recipeActivated(formatRelative(recipe.activated_at))}</span>}
|
||||
{recipe.signed_by && <span className="break-all">· {RECIPE_TEXT.recipeSigned(recipe.signed_by)}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 一次最多画这么多行:上千个对象的库全画出来会卡,过滤一下就够用了 */
|
||||
const SCHEMA_ROWS = 300
|
||||
|
||||
@@ -1552,12 +1619,14 @@ const quoteList = (values: unknown[], max = 3) => values.slice(0, max).map((v) =
|
||||
* 只有后端给的两种(数字列混入非数字、交叉表或多块结构)。选「取消」回到表单:文件、名字、
|
||||
* 表头行号都还在——表头行号设错是这两种问题最常见的来由,改一下行号可能就不用选了
|
||||
*/
|
||||
function UploadDecisionBody({ decision, choices, headerRow, sheetNoun }: {
|
||||
function UploadDecisionBody({ decision, choices, headerRow, sheetNoun, onRecipe }: {
|
||||
decision: UploadDecision
|
||||
choices: UploadChoices
|
||||
headerRow: number
|
||||
/** 「工作表」;CSV 没有工作表,是「文件」 */
|
||||
sheetNoun: string
|
||||
/** 按配方导入(CSV 没有这条路:配方只认 Excel) */
|
||||
onRecipe?: () => void
|
||||
}) {
|
||||
if (decision.kind === 'mixed') {
|
||||
return (
|
||||
@@ -1601,7 +1670,14 @@ function UploadDecisionBody({ decision, choices, headerRow, sheetNoun }: {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs leading-relaxed text-dim" data-shape-recipe>{UPLOAD_TEXT.shapeRecipe}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded-lg border bg-bg px-2.5 py-2" data-shape-recipe>
|
||||
<p className="min-w-0 flex-1 text-xs leading-relaxed text-dim">{onRecipe ? UPLOAD_TEXT.shapeRecipe : UPLOAD_TEXT.shapeRecipeCsv}</p>
|
||||
{onRecipe && (
|
||||
<button type="button" className="btn btn-sm btn-primary shrink-0" onClick={onRecipe} data-shape-recipe-start>
|
||||
<Layers size={12} aria-hidden /> {RECIPE_TEXT.entry}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-2xs text-faint">{UPLOAD_TEXT.shapeHeader(headerRow)}</p>
|
||||
<ChosenLine choices={choices} />
|
||||
</div>
|
||||
@@ -1762,7 +1838,7 @@ function UploadNotes({ result }: { result: UploadResult }) {
|
||||
* 选(UploadDecisionBody),选完带着答案重传。答案跟着这一份文件和表头行号走,换文件、
|
||||
* 改行号就清掉,重新问
|
||||
*/
|
||||
function TableUploader({ initialName, taken, sqliteTaken, onClose, onImported }: {
|
||||
function TableUploader({ initialName, taken, sqliteTaken, onClose, onImported, onRecipe }: {
|
||||
initialName?: string
|
||||
/** 已经被数据库占用的名字(传表格只能就地替换表格,不能顶掉数据库) */
|
||||
taken: string[]
|
||||
@@ -1773,6 +1849,8 @@ function TableUploader({ initialName, taken, sqliteTaken, onClose, onImported }:
|
||||
sqliteTaken: string[]
|
||||
onClose: () => void
|
||||
onImported: (row: any) => void
|
||||
/** 交叉表决定页上选「按配方导入」:带着这份文件、名字和说明交给向导 */
|
||||
onRecipe: (file: File, name: string, description: string) => void
|
||||
}) {
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [name, setName] = useState(initialName ?? '')
|
||||
@@ -1917,7 +1995,8 @@ function TableUploader({ initialName, taken, sqliteTaken, onClose, onImported }:
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<UploadDecisionBody decision={decision} choices={choices} headerRow={headerRow} sheetNoun={sheetNoun} />
|
||||
<UploadDecisionBody decision={decision} choices={choices} headerRow={headerRow} sheetNoun={sheetNoun}
|
||||
onRecipe={file && sheetNoun === '工作表' ? () => onRecipe(file, name, description) : undefined} />
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useState } from 'react'
|
||||
import { AlertTriangle, Sparkles } from 'lucide-react'
|
||||
import { ApiError, api } from '../../api/client'
|
||||
import type { AiPreview, Staging } from '../../types'
|
||||
import { Modal, Spinner } from '../../components/ui'
|
||||
import { errorMessage } from '../../lib/errors'
|
||||
import { formatCost, formatNumber } from '../../lib/format'
|
||||
import { RECIPE_TEXT } from '../../lib/terms'
|
||||
|
||||
// ===========================================================================
|
||||
// AI 兜底起草:规则起草不完整时,经用户同意把表格结构(不含数字的值)发给模型起草配方。
|
||||
// 先取「将要发送的全文」给人看,同意才发;发的时候带上那份全文的 sha256,服务端重算对不上就拒绝
|
||||
// ===========================================================================
|
||||
|
||||
/**
|
||||
* 卡片区顶部的 AI 入口和结果。只在服务端说 offered 时出现(首次导入、规则草稿不完整);
|
||||
* 模型接入不可用时按钮置灰、写出原因。staging_closed 之类要关掉向导的错误交给 onError
|
||||
*/
|
||||
export function AiDraftOffer({ staging, busy, setBusy, onStaging, onError }: {
|
||||
staging: Staging
|
||||
busy: boolean
|
||||
setBusy: (v: boolean) => void
|
||||
onStaging: (s: Staging) => void
|
||||
/** 返回 true 表示已经处理(比如这次导入已结束、向导关了),这里不再显示 */
|
||||
onError: (e: unknown) => boolean
|
||||
}) {
|
||||
const [phase, setPhase] = useState<'idle' | 'previewing' | 'consent' | 'drafting'>('idle')
|
||||
const [preview, setPreview] = useState<AiPreview | null>(null)
|
||||
const [error, setError] = useState<{ message: string; next?: string } | null>(null)
|
||||
const ai = staging.ai
|
||||
const result = staging.ai_draft
|
||||
|
||||
const fail = (e: unknown) => {
|
||||
if (onError(e)) return
|
||||
const code = e instanceof ApiError ? e.code : undefined
|
||||
// 服务端的原话照写。ai_failed、ai_too_large 的原话里已经带了下一步(有没有工作配方,能做的事不一样:
|
||||
// 没有时配方面板里只能粘贴一份),界面不再另补;过期补一句重新查看
|
||||
if (code === 'ai_preview_stale') setError({ message: errorMessage(e), next: RECIPE_TEXT.aiStale })
|
||||
else setError({ message: errorMessage(e) })
|
||||
}
|
||||
|
||||
const open = async () => {
|
||||
setError(null)
|
||||
setPhase('previewing')
|
||||
setBusy(true)
|
||||
try {
|
||||
setPreview(await api.tableImports.draftAiPreview(staging.id))
|
||||
setPhase('consent')
|
||||
} catch (e) {
|
||||
setPhase('idle')
|
||||
fail(e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const send = async () => {
|
||||
if (!preview) return
|
||||
setPhase('drafting')
|
||||
setBusy(true)
|
||||
try {
|
||||
onStaging(await api.tableImports.draftAi(staging.id, preview.sha256))
|
||||
setPreview(null)
|
||||
setPhase('idle')
|
||||
} catch (e) {
|
||||
setPreview(null)
|
||||
setPhase('idle')
|
||||
fail(e)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const usage = result && result.draft && result.total_tokens != null
|
||||
? RECIPE_TEXT.aiDone(formatNumber(result.total_tokens), formatCost(result.cost_usd ?? 0))
|
||||
: null
|
||||
|
||||
if (!ai?.offered && !usage) return null
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
{ai?.offered && (
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-lg border px-3 py-2" data-ai-offer
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--copilot) 40%, var(--border))', background: 'color-mix(in srgb, var(--copilot) 6%, transparent)' }}>
|
||||
<button type="button" className="btn btn-sm" disabled={busy || !ai.available} onClick={() => void open()}
|
||||
aria-describedby={!ai.available ? 'ai-unavailable' : undefined}>
|
||||
{phase === 'previewing' || phase === 'drafting'
|
||||
? <Spinner size={11} />
|
||||
: <Sparkles size={12} className="text-[var(--copilot)]" aria-hidden />}
|
||||
{phase === 'drafting' ? RECIPE_TEXT.aiDrafting : phase === 'previewing' ? RECIPE_TEXT.aiPreviewing : RECIPE_TEXT.aiOffer}
|
||||
</button>
|
||||
{!ai.available && (
|
||||
<span id="ai-unavailable" className="min-w-0 flex-1 text-2xs leading-relaxed text-faint" data-ai-unavailable>
|
||||
{ai.reason || RECIPE_TEXT.aiUnavailable}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{usage && <p className="text-2xs text-dim" data-ai-usage>{usage}</p>}
|
||||
{error && (
|
||||
<div role="alert" className="flex gap-2 rounded-lg border px-3 py-2 text-xs leading-relaxed" data-ai-error
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--err) 35%, var(--border))', background: 'color-mix(in srgb, var(--err) 6%, transparent)' }}>
|
||||
<AlertTriangle size={13} className="mt-0.5 shrink-0 text-[var(--err)]" aria-hidden />
|
||||
<span>{error.message}{error.next && <span className="text-dim">({error.next})</span>}</span>
|
||||
</div>
|
||||
)}
|
||||
{phase === 'consent' && preview && (
|
||||
<AiConsentDialog preview={preview} model={preview.model || ai?.model || ''} busy={busy}
|
||||
onCancel={() => { setPreview(null); setPhase('idle') }} onAgree={() => void send()} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 同意框:说清发什么、不发什么,下面是将要发送的全文(等宽、可滚动)。取消不发任何请求 */
|
||||
function AiConsentDialog({ preview, model, busy, onCancel, onAgree }: {
|
||||
preview: AiPreview; model: string; busy: boolean; onCancel: () => void; onAgree: () => void
|
||||
}) {
|
||||
return (
|
||||
<Modal open onClose={onCancel} width={720} title={RECIPE_TEXT.aiConsentTitle}
|
||||
footer={
|
||||
<>
|
||||
<button className="btn" onClick={onCancel} data-autofocus>{RECIPE_TEXT.cancel}</button>
|
||||
<button className="btn btn-primary" disabled={busy} onClick={onAgree}>{RECIPE_TEXT.aiAgree}</button>
|
||||
</>
|
||||
}>
|
||||
<div className="space-y-2.5" data-ai-consent>
|
||||
<p className="text-xs leading-relaxed text-dim">{RECIPE_TEXT.aiConsentLead(model)}</p>
|
||||
<p className="text-xs font-medium leading-relaxed">{RECIPE_TEXT.aiConsentNot}</p>
|
||||
<p className="text-xs leading-relaxed text-dim">{RECIPE_TEXT.aiConsentAfter}</p>
|
||||
<div className="label">{RECIPE_TEXT.aiPreviewLabel(formatNumber(preview.chars ?? preview.text.length))}</div>
|
||||
<pre className="mono max-h-80 overflow-auto whitespace-pre-wrap rounded-lg border bg-bg p-2.5 text-2xs leading-relaxed" data-ai-preview
|
||||
tabIndex={0}>{preview.text}</pre>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { useEffect, useId, useMemo, useState } from 'react'
|
||||
import { AlertTriangle } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import type { CheckResult, ConfirmItem } from '../../types'
|
||||
import { Spinner } from '../../components/ui'
|
||||
import { localActor } from '../../lib/actor'
|
||||
import { PROBLEM_CATEGORY_LABEL, RECIPE_TEXT } from '../../lib/terms'
|
||||
import { CheckStatusChip } from './ImportReceipt'
|
||||
|
||||
// ===========================================================================
|
||||
// 启用前的确认清单:逐条勾选(不提供「全选」),可接受的核对逐条写理由,署名(未认证)。
|
||||
// 必勾的集合由服务端按试运行结果重算,少勾一项服务端照样拒绝(422 confirm_required)
|
||||
// ===========================================================================
|
||||
|
||||
/** 单位变化排最前(数量级变了,引用它的报告口径会变),其次是破坏性变更和差异卡里需确认的项 */
|
||||
function rank(id: string): number {
|
||||
if (id.startsWith('unit_changed:')) return 0
|
||||
if (id.startsWith('breaking:') || id === 'switch_from_simple') return 1
|
||||
if (id.startsWith('diff:')) return 2
|
||||
return 3
|
||||
}
|
||||
|
||||
export interface CommitBody {
|
||||
confirmations: string[]
|
||||
acceptances: { check_id: string; reason: string }[]
|
||||
signed_by: string | null
|
||||
}
|
||||
|
||||
export function ConfirmList({ items, checks, acceptable, reupload, busy, missing, error, onSubmit }: {
|
||||
items: ConfirmItem[]
|
||||
checks: CheckResult[]
|
||||
/** 可写理由接受、本次未通过的核对 id */
|
||||
acceptable: string[]
|
||||
/** 上传新一期:按钮写「启用」 */
|
||||
reupload: boolean
|
||||
busy: boolean
|
||||
/** 服务端说还没勾的项(422 confirm_required / acceptance_required 的 detail 里点名的) */
|
||||
missing: Set<string>
|
||||
error: string | null
|
||||
onSubmit: (body: CommitBody) => void
|
||||
}) {
|
||||
const sorted = useMemo(() => items.map((it, i) => ({ it, i }))
|
||||
.sort((a, b) => rank(a.it.id) - rank(b.it.id) || a.i - b.i).map((x) => x.it), [items])
|
||||
const [checked, setChecked] = useState<Set<string>>(() => new Set())
|
||||
const [reasons, setReasons] = useState<Record<string, string>>({})
|
||||
const [signer, setSigner] = useState(() => localActor() ?? '')
|
||||
const signId = useId()
|
||||
// 换了一次试运行(确认项变了):勾过的里面只留还在的
|
||||
useEffect(() => {
|
||||
setChecked((cur) => new Set([...cur].filter((id) => items.some((it) => it.id === id))))
|
||||
}, [items])
|
||||
|
||||
const required = sorted.filter((it) => it.required !== false)
|
||||
const accepts = acceptable.map((id) => ({ id, check: checks.find((c) => c.id === id) }))
|
||||
const allChecked = required.every((it) => checked.has(it.id))
|
||||
const allReasons = accepts.every(({ id }) => {
|
||||
const v = (reasons[id] ?? '').trim()
|
||||
return v.length > 0 && v.length <= 500
|
||||
})
|
||||
const ready = allChecked && allReasons && !busy
|
||||
|
||||
const submit = () => {
|
||||
if (!ready) return
|
||||
onSubmit({
|
||||
confirmations: sorted.filter((it) => checked.has(it.id)).map((it) => it.id),
|
||||
acceptances: accepts.map(({ id }) => ({ check_id: id, reason: reasons[id].trim() })),
|
||||
signed_by: signer.trim() || null,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3" data-confirm-list>
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold">{RECIPE_TEXT.confirmTitle}</h3>
|
||||
<p className="mt-0.5 text-2xs text-faint">{RECIPE_TEXT.confirmLead}</p>
|
||||
</div>
|
||||
{error && (
|
||||
<div role="alert" className="flex gap-2 rounded-lg border px-3 py-2 text-xs leading-relaxed" data-confirm-error
|
||||
style={{ borderColor: 'color-mix(in srgb, var(--err) 35%, var(--border))', background: 'color-mix(in srgb, var(--err) 6%, transparent)' }}>
|
||||
<AlertTriangle size={13} className="mt-0.5 shrink-0 text-[var(--err)]" aria-hidden />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
<ul className="space-y-1.5">
|
||||
{sorted.map((it) => {
|
||||
const miss = missing.has(it.id)
|
||||
return (
|
||||
<li key={it.id} data-confirm-item={it.id} data-required={it.required !== false} data-missing={miss || undefined}
|
||||
className={clsx('rounded-md border px-2.5 py-2 text-xs')}
|
||||
style={miss ? { borderColor: 'var(--err)' } : undefined}>
|
||||
<label className="flex cursor-pointer items-start gap-2">
|
||||
<input type="checkbox" className="mt-0.5" checked={checked.has(it.id)} disabled={busy}
|
||||
onChange={(e) => setChecked((cur) => {
|
||||
const next = new Set(cur)
|
||||
if (e.target.checked) next.add(it.id)
|
||||
else next.delete(it.id)
|
||||
return next
|
||||
})} />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="leading-relaxed">{it.label}</span>
|
||||
{it.required === false && <span className="ml-1.5 text-2xs text-faint" data-confirm-optional>{RECIPE_TEXT.confirmOptional}</span>}
|
||||
{it.detail && <span className="mt-0.5 block text-2xs leading-relaxed text-dim">{it.detail}</span>}
|
||||
{miss && <span className="mt-0.5 block text-2xs text-[var(--err)]">{RECIPE_TEXT.missing}</span>}
|
||||
</span>
|
||||
</label>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
{accepts.length > 0 && (
|
||||
<section className="space-y-1.5" data-acceptances>
|
||||
<h4 className="text-xs font-semibold">{RECIPE_TEXT.acceptTitle}</h4>
|
||||
{accepts.map(({ id, check }) => {
|
||||
const fieldId = `${signId}-accept-${id}`
|
||||
const miss = missing.has(id)
|
||||
return (
|
||||
<div key={id} className="space-y-1 rounded-md border px-2.5 py-2" data-acceptance={id} data-missing={miss || undefined}
|
||||
style={miss ? { borderColor: 'var(--err)' } : undefined}>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs">
|
||||
{check && <CheckStatusChip status={check.status} />}
|
||||
<span className="mono text-faint">{id}</span>
|
||||
<span className="min-w-0 flex-1">{check?.title ?? id}</span>
|
||||
</div>
|
||||
{check && <div className="text-2xs text-faint">{PROBLEM_CATEGORY_LABEL[check.category] ?? ''}</div>}
|
||||
<label className="label" htmlFor={fieldId}>{RECIPE_TEXT.acceptLabel}</label>
|
||||
<textarea id={fieldId} className="field text-xs" rows={2} maxLength={500} value={reasons[id] ?? ''} disabled={busy}
|
||||
placeholder={RECIPE_TEXT.acceptPlaceholder}
|
||||
onChange={(e) => setReasons((cur) => ({ ...cur, [id]: e.target.value }))} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
)}
|
||||
<div className="flex flex-wrap items-end gap-3 border-t pt-3">
|
||||
<div className="min-w-0">
|
||||
<label className="label" htmlFor={signId}>{RECIPE_TEXT.signLabel}</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input id={signId} className="field !w-48" value={signer} onChange={(e) => setSigner(e.target.value)} disabled={busy} />
|
||||
<span className="text-2xs text-faint" data-sign-note>{RECIPE_TEXT.signNote}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span className="flex-1" />
|
||||
{!ready && !busy && <span className="text-2xs text-faint">{RECIPE_TEXT.commitBlocked}</span>}
|
||||
<button type="button" className="btn btn-primary" disabled={!ready} onClick={submit} data-commit>
|
||||
{busy ? <><Spinner size={11} /> {RECIPE_TEXT.committing}</> : reupload ? RECIPE_TEXT.commitReupload : RECIPE_TEXT.commitFirst}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import { AlertTriangle, CheckCircle2, Info, XCircle } from 'lucide-react'
|
||||
import type { CheckResult, ImportProblem, TrialOut } from '../../types'
|
||||
import { formatNumber } from '../../lib/format'
|
||||
import { CHECK_STATUS_LABEL, LEDGER_ROLE_LABEL, PROBLEM_CATEGORY_LABEL, RECIPE_TEXT } from '../../lib/terms'
|
||||
import { roleStyle } from './SheetGrid'
|
||||
import { CellChips } from './SuggestionCards'
|
||||
|
||||
// ===========================================================================
|
||||
// 试运行回执:格子账、表与行数、统计期、核对、说明预览、问题。全部来自服务端的试运行结果,
|
||||
// 界面不做任何算术判断(核对在 SQL 里做完了),只把状态分清楚:通过 / 不一致 / 无法核对 / 说明
|
||||
// ===========================================================================
|
||||
|
||||
/** 核对状态的样式:四种一眼分得开(文字之外还有颜色和图标,色弱也能靠图标分) */
|
||||
const STATUS_STYLE: Record<string, { color: string; icon: typeof CheckCircle2 }> = {
|
||||
passed: { color: 'var(--ok)', icon: CheckCircle2 },
|
||||
mismatch: { color: 'var(--err)', icon: XCircle },
|
||||
unverifiable: { color: 'var(--warn)', icon: AlertTriangle },
|
||||
info: { color: 'var(--text-faint)', icon: Info },
|
||||
}
|
||||
|
||||
export function statusChipStyle(status: string): CSSProperties {
|
||||
const color = STATUS_STYLE[status]?.color ?? 'var(--text-faint)'
|
||||
return { color, borderColor: `color-mix(in srgb, ${color} 55%, transparent)`, background: `color-mix(in srgb, ${color} 10%, transparent)` }
|
||||
}
|
||||
|
||||
export function CheckStatusChip({ status }: { status: string }) {
|
||||
const Icon = STATUS_STYLE[status]?.icon ?? Info
|
||||
return (
|
||||
<span className="chip shrink-0" style={statusChipStyle(status)} data-check-status={status}>
|
||||
<Icon size={10} aria-hidden /> {CHECK_STATUS_LABEL[status] ?? status}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function CheckRow({ c, onFocus }: { c: CheckResult; onFocus: (cell: string) => void }) {
|
||||
const failedLine = c.status !== 'passed' && c.status !== 'info' && c.category !== 'info' ? PROBLEM_CATEGORY_LABEL[c.category] : ''
|
||||
// 「说明」类(如口径不同的 R2)的 failed 是「两边不相等的个数」,正是预期的结果,不是核对不一致:
|
||||
// 不写计数,只看服务端给的细节(「31 天中 0 天相等」)
|
||||
const counts = !!c.checked && c.status !== 'info'
|
||||
return (
|
||||
<li className="space-y-1 rounded-md border px-2.5 py-2" data-check={c.id} data-status={c.status}
|
||||
style={c.status === 'mismatch' ? { borderColor: 'color-mix(in srgb, var(--err) 40%, var(--border))' } : undefined}>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs">
|
||||
<CheckStatusChip status={c.status} />
|
||||
<span className="mono text-faint">{c.id}</span>
|
||||
<span className="min-w-0 flex-1">{c.title}</span>
|
||||
{counts && (
|
||||
<span className="tnum text-2xs text-faint" data-check-counts>
|
||||
{formatNumber(c.checked)}
|
||||
{c.failed ? ` / ${CHECK_STATUS_LABEL.mismatch} ${formatNumber(c.failed)}` : ''}
|
||||
{c.unverifiable ? ` / ${CHECK_STATUS_LABEL.unverifiable} ${formatNumber(c.unverifiable)}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{failedLine && <div className="text-2xs text-faint">{failedLine}</div>}
|
||||
{!!c.details?.length && (
|
||||
<ul className="space-y-0.5 text-2xs leading-relaxed text-dim">
|
||||
{c.details.slice(0, 6).map((d, i) => <li key={i}>{d}</li>)}
|
||||
</ul>
|
||||
)}
|
||||
<CellChips cells={c.cells} onFocus={onFocus} />
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** 问题列表:带类别和坐标,点坐标网格滚到那格 */
|
||||
export function ProblemList({ problems, onFocus }: { problems: ImportProblem[]; onFocus: (cell: string) => void }) {
|
||||
if (!problems.length) return null
|
||||
return (
|
||||
<ul className="space-y-1.5" data-problems>
|
||||
{problems.map((p, i) => {
|
||||
const tone = p.category === 'structure' || p.category === 'recipe' ? 'var(--err)'
|
||||
: p.category === 'data_quality' || p.category === 'input' ? 'var(--warn)' : 'var(--text-faint)'
|
||||
return (
|
||||
<li key={i} className="space-y-1 rounded-md border px-2.5 py-2 text-xs" data-problem={p.code} data-category={p.category}
|
||||
style={{ borderColor: `color-mix(in srgb, ${tone} 40%, var(--border))` }}>
|
||||
<div className="text-2xs" style={{ color: tone }}>{PROBLEM_CATEGORY_LABEL[p.category] ?? p.category}</div>
|
||||
<div className="leading-relaxed">{p.message}</div>
|
||||
<CellChips cells={p.cells} onFocus={onFocus} max={10} />
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
const STATUS_LINE: Record<string, string> = {
|
||||
passed: RECIPE_TEXT.statusPassed,
|
||||
needs_decision: RECIPE_TEXT.statusNeedsDecision,
|
||||
needs_input: RECIPE_TEXT.statusNeedsInput,
|
||||
rejected: RECIPE_TEXT.statusRejected,
|
||||
}
|
||||
|
||||
export function TrialStatusLine({ status }: { status: string }) {
|
||||
const color = status === 'passed' ? 'var(--ok)' : status === 'rejected' ? 'var(--err)' : 'var(--warn)'
|
||||
return (
|
||||
<div className="rounded-lg border px-3 py-2 text-xs font-medium" data-trial-status={status} role="status"
|
||||
style={{ color, borderColor: `color-mix(in srgb, ${color} 45%, var(--border))`, background: `color-mix(in srgb, ${color} 7%, transparent)` }}>
|
||||
{STATUS_LINE[status] ?? status}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Section({ title, children, attr }: { title: string; children: ReactNode; attr?: Record<string, string> }) {
|
||||
return (
|
||||
<section className="space-y-1.5" {...attr}>
|
||||
<h4 className="text-xs font-semibold">{title}</h4>
|
||||
{children}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 格子账能下哪些结论。执行器对找不到的工作表(sheet_missing)不记账,所以账是空的或缺了工作表时,
|
||||
* 「全部有去处」「两遍读取一致」都无从说起;各去向加起来和读到的个数对不上,也不能说「全部有去处」
|
||||
*/
|
||||
export function ledgerVerdict(trial: TrialOut, expectedSheets?: number) {
|
||||
const ledger = trial.receipt?.ledger ?? []
|
||||
const missingProblems = (trial.problems ?? []).filter((p) => p.code === 'sheet_missing').length
|
||||
const missing = Math.max(missingProblems, expectedSheets != null ? expectedSheets - ledger.length : 0)
|
||||
const total = ledger.reduce((n, s) => n + (s.nonempty_read ?? 0), 0)
|
||||
const unclaimed = ledger.reduce((n, s) => n + (s.unclaimed ?? 0), 0)
|
||||
const assigned = ledger.reduce((n, s) => n + Object.values(s.roles ?? {}).reduce((a, b) => a + b, 0), 0)
|
||||
const balanced = ledger.every((s) => Object.values(s.roles ?? {}).reduce((a, b) => a + b, 0) + (s.unclaimed ?? 0) === s.nonempty_read)
|
||||
const twoPass = ledger.every((s) => s.nonempty_scan === s.nonempty_read)
|
||||
const state: 'none' | 'partial' | 'complete' = !ledger.length ? 'none' : missing > 0 ? 'partial' : 'complete'
|
||||
return { ledger, state, missing, total, unclaimed, assigned, balanced, twoPass }
|
||||
}
|
||||
|
||||
export function ImportReceipt({ trial, expectedSheets, onFocusCell }: {
|
||||
trial: TrialOut
|
||||
/** 配方里有几张工作表:账里少了的就是没读到的 */
|
||||
expectedSheets?: number
|
||||
onFocusCell: (cell: string) => void
|
||||
}) {
|
||||
const r = trial.receipt ?? {}
|
||||
const { ledger, state, missing, total, unclaimed, assigned, balanced, twoPass } = ledgerVerdict(trial, expectedSheets)
|
||||
// 同一个说法(合计格、合计标签)的去向合在一起数
|
||||
const roles = new Map<string, { label: string; role: string; n: number }>()
|
||||
for (const s of ledger) {
|
||||
for (const [role, n] of Object.entries(s.roles ?? {})) {
|
||||
const label = LEDGER_ROLE_LABEL[role] ?? role
|
||||
const cur = roles.get(label)
|
||||
roles.set(label, { label, role: cur?.role ?? role, n: (cur?.n ?? 0) + n })
|
||||
}
|
||||
}
|
||||
const scanTotal = ledger.reduce((n, s) => n + (s.nonempty_scan ?? 0), 0)
|
||||
const period = r.period
|
||||
const notes = Object.entries(trial.notes ?? {})
|
||||
const placeholders = Object.entries(r.placeholders ?? {})
|
||||
const outside = r.outside_text ?? []
|
||||
// 拒收时执行器在结构问题上就停了(表可能只写了一半),需要录入时根本没写库:行数不能当真
|
||||
const written = trial.status === 'passed' || trial.status === 'needs_decision'
|
||||
|
||||
return (
|
||||
<div className="space-y-3" data-trial-receipt data-trial-id={trial.trial_id}>
|
||||
<Section title={RECIPE_TEXT.receipt}>
|
||||
<div className="space-y-1.5 rounded-lg border bg-bg px-3 py-2 text-xs" data-ledger data-ledger-state={state}>
|
||||
{state === 'none' ? (
|
||||
<div className="text-[var(--err)]">{RECIPE_TEXT.ledgerNone}</div>
|
||||
) : (
|
||||
<div>
|
||||
{RECIPE_TEXT.ledger(formatNumber(total))}
|
||||
{unclaimed
|
||||
? <>,<span className="text-[var(--err)]">{RECIPE_TEXT.ledgerUnclaimed(formatNumber(unclaimed))}</span></>
|
||||
: !balanced
|
||||
? <>,<span className="text-[var(--err)]">{RECIPE_TEXT.ledgerUnbalanced(formatNumber(assigned), formatNumber(total))}</span></>
|
||||
: state === 'complete' ? `,${RECIPE_TEXT.ledgerAll}` : ''}
|
||||
</div>
|
||||
)}
|
||||
{state === 'partial' && (
|
||||
<div className="text-[var(--err)]" data-ledger-missing={missing}>{RECIPE_TEXT.ledgerSheetsMissing(formatNumber(missing))}</div>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{[...roles.values()].map((x) => (
|
||||
<span key={x.label} className="chip" data-ledger-role={x.role}>
|
||||
<span className="inline-block h-2 w-2 rounded-sm" style={roleStyle(x.role)} aria-hidden />
|
||||
{x.label} <span className="tnum">{formatNumber(x.n)}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{/* 缺了工作表时,「两遍读取一致」只对读到的那几张成立,不写;不一致照写 */}
|
||||
{!twoPass ? (
|
||||
<div className="text-[var(--err)]" data-two-pass="differ">{RECIPE_TEXT.passDiffer(formatNumber(scanTotal), formatNumber(total))}</div>
|
||||
) : state === 'complete' && (
|
||||
<div className="text-faint" data-two-pass="agree">{RECIPE_TEXT.passAgree}</div>
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
{!!r.tables?.length && (
|
||||
<Section title={RECIPE_TEXT.tables} attr={{ 'data-receipt-tables': written ? '' : 'unwritten' }}>
|
||||
{!written && <p className="text-2xs text-faint" data-tables-unwritten>{RECIPE_TEXT.tablesUnwritten}</p>}
|
||||
<ul className="space-y-1">
|
||||
{r.tables.map((t) => (
|
||||
<li key={t.name} className="rounded-md border px-2.5 py-1.5 text-xs" data-receipt-table={t.name}
|
||||
data-rows={written ? t.rows : undefined}>
|
||||
<div className="flex flex-wrap items-baseline gap-x-2">
|
||||
<span className="font-medium">{t.name}</span>
|
||||
{written
|
||||
? <span className="tnum text-dim">{RECIPE_TEXT.rows(formatNumber(t.rows))}</span>
|
||||
: <span className="text-faint">{RECIPE_TEXT.rowsUnwritten}</span>}
|
||||
</div>
|
||||
<div className="mt-0.5 flex flex-wrap gap-1 text-2xs text-faint">
|
||||
{t.columns.map((c) => (
|
||||
<span key={c.name} className="chip" title={c.header ?? undefined}>
|
||||
{c.name}{c.unit ? `(${c.unit})` : ''}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{period && (
|
||||
<p className="text-xs text-dim" data-receipt-period>
|
||||
{RECIPE_TEXT.periodLine(period.start, period.end)}
|
||||
{period.source === 'human'
|
||||
? `,${RECIPE_TEXT.periodHuman(period.signed_by || RECIPE_TEXT.signNote)}`
|
||||
: period.cells?.length ? `,${RECIPE_TEXT.periodFromCells(period.cells.map((c) => c.slice(c.lastIndexOf('!') + 1)).join('、'))}` : ''}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{placeholders.length > 0 && (
|
||||
<p className="text-xs text-dim" data-receipt-placeholders>
|
||||
{RECIPE_TEXT.placeholderCounts}:{placeholders.map(([text, n]) => RECIPE_TEXT.placeholderCount(text, formatNumber(n))).join(',')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!!trial.problems?.length && (
|
||||
<Section title={RECIPE_TEXT.problems}>
|
||||
<ProblemList problems={trial.problems} onFocus={onFocusCell} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{!!trial.checks?.length && (
|
||||
<Section title={RECIPE_TEXT.checks}>
|
||||
<ul className="space-y-1.5" data-checks>
|
||||
{trial.checks.map((c) => <CheckRow key={c.id} c={c} onFocus={onFocusCell} />)}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{outside.length > 0 && (
|
||||
<Section title={RECIPE_TEXT.outsideText}>
|
||||
<ul className="space-y-1 text-xs" data-outside-texts>
|
||||
{outside.map((o) => {
|
||||
// cell 本来就带工作表名(「客流汇总!B3」,同问题的 cells);旧数据是纯 A1 时才补上 sheet
|
||||
const ref = o.cell.includes('!') ? o.cell : `${o.sheet}!${o.cell}`
|
||||
return (
|
||||
<li key={ref} className="flex items-baseline gap-2" data-outside-text={ref}>
|
||||
<CellChips cells={[ref]} onFocus={onFocusCell} />
|
||||
<span className="min-w-0 flex-1 break-all text-dim">{o.text}</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{notes.length > 0 && (
|
||||
<Section title={RECIPE_TEXT.notes}>
|
||||
<ul className="space-y-1.5" data-notes>
|
||||
{notes.map(([table, n]) => (
|
||||
<li key={table} className="rounded-md border px-2.5 py-1.5 text-xs" data-note={table}>
|
||||
<div className="font-medium">{table}</div>
|
||||
<p className="mt-0.5 leading-relaxed text-dim">{n.comment}</p>
|
||||
{Object.entries(n.columns ?? {}).map(([col, text]) => (
|
||||
<div key={col} className="text-2xs text-faint">{col}:{text}</div>
|
||||
))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { AlertTriangle, ChevronRight, FileSpreadsheet, Info, Upload } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import { ApiError, api } from '../../api/client'
|
||||
import type { UploadProgress } from '../../api/client'
|
||||
import type { CommitOut, DataSource, QuestionAnswer, Recipe, Staging } from '../../types'
|
||||
import { Field, Modal, Spinner, confirmDialog, toast } from '../../components/ui'
|
||||
import { localActor } from '../../lib/actor'
|
||||
import { errorMessage } from '../../lib/errors'
|
||||
import { formatBytes, formatDuration, formatNumber } from '../../lib/format'
|
||||
import { RECIPE_TEXT, UPLOAD_TEXT } from '../../lib/terms'
|
||||
import { useRunClock } from '../../run/useRunClock'
|
||||
import { UploadMeter } from '../DataSourcesTab'
|
||||
import { AiDraftOffer } from './AiDraftDialog'
|
||||
import { ConfirmList } from './ConfirmList'
|
||||
import type { CommitBody } from './ConfirmList'
|
||||
import { ImportReceipt, ProblemList, TrialStatusLine } from './ImportReceipt'
|
||||
import { RecipePanel } from './RecipePanel'
|
||||
import { ReuploadDiff } from './ReuploadDiff'
|
||||
import { SheetGrid, parseRef } from './SheetGrid'
|
||||
import type { GridFocus } from './SheetGrid'
|
||||
import { SuggestionCards } from './SuggestionCards'
|
||||
|
||||
// ===========================================================================
|
||||
// 按配方导入的向导:选文件 → 起草(网格 + 建议 + 配方面板)→ 试运行 → 逐条确认 → 启用。
|
||||
// 进度都在服务端的暂存区里:关掉向导不丢,从卡片上的「有未完成的导入」继续;提交成功之前
|
||||
// 不动数据源的当前版本
|
||||
// ===========================================================================
|
||||
|
||||
/** 从哪进来的 */
|
||||
export type WizardEntry =
|
||||
/** 表格标签页头部:在向导里选文件、填名字 */
|
||||
| { kind: 'new' }
|
||||
/** 上传弹窗的交叉表决定页:带着同一个文件、名字和说明直接开始 */
|
||||
| { kind: 'stage'; file: File; name: string; description: string }
|
||||
/** 卡片「上传新一期」:选文件后按当前配方试运行 */
|
||||
| { kind: 'reupload'; source: DataSource }
|
||||
/** 卡片「修改配方」:不换文件 */
|
||||
| { kind: 'redraft'; source: DataSource }
|
||||
/** 卡片「有未完成的导入」 */
|
||||
| { kind: 'resume'; stagingId: string; source?: DataSource }
|
||||
|
||||
type Phase = 'pick' | 'uploading' | 'loading' | 'work' | 'confirm' | 'done' | 'failed'
|
||||
type View = 'draft' | 'result'
|
||||
|
||||
const NAME_RE = /^[a-z][a-z0-9_]{0,40}$/
|
||||
/** 选择框收的扩展名,与 RECIPE_TEXT.pickFormats 的说法一致 */
|
||||
const PICK_ACCEPT = '.xlsx,.xlsm'
|
||||
const ENDED = new Set(['committed', 'discarded', 'expired'])
|
||||
|
||||
/** 文件名里的两个日期(「月报导出_2026-09-01_2026-09-30.xlsx」):只作统计期录入框的建议,服务端会再核对 */
|
||||
function periodFromFileName(name: string): { start: string; end: string } | null {
|
||||
const re = /(\d{4})\s*[-./年]\s*(\d{1,2})\s*[-./月]\s*(\d{1,2})\s*日?/g
|
||||
const found: string[] = []
|
||||
for (const m of name.matchAll(re)) {
|
||||
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]
|
||||
if (mo < 1 || mo > 12 || d < 1 || d > 31) continue
|
||||
found.push(`${y}-${String(mo).padStart(2, '0')}-${String(d).padStart(2, '0')}`)
|
||||
}
|
||||
return found.length >= 2 && found[0] <= found[1] ? { start: found[0], end: found[1] } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 标签候选:网格里标签列(有行标签、合计标签、分段标题的那几列)的文字,去掉已知是统计期、区域外文字、
|
||||
* 表头的格;还没有干跑过(没有区域标记)就取全部文字格
|
||||
*/
|
||||
function labelOptionsOf(staging: Staging | null): string[] {
|
||||
if (!staging) return []
|
||||
const LABEL_ROLES = ['row_label', 'derived_label', 'section_title', 'total_label']
|
||||
const out = new Set<string>()
|
||||
for (const grid of staging.grids ?? []) {
|
||||
const cols = new Set<number>()
|
||||
const other = new Set<string>()
|
||||
for (const m of staging.marks ?? []) {
|
||||
if (m.sheet !== grid.sheet) continue
|
||||
const range = parseRef(m.ref)
|
||||
if (!range) continue
|
||||
if (LABEL_ROLES.includes(m.role)) {
|
||||
for (let c = range.c1; c <= range.c2; c++) cols.add(c)
|
||||
} else if (range.c1 === range.c2 || range.r1 === range.r2) {
|
||||
// 标签列上的统计期、区域外文字、表头格:只可能是单格或一行一列的小区域,逐格记下排除
|
||||
for (let r = range.r1; r <= Math.min(range.r2, range.r1 + 2000); r++) {
|
||||
for (let c = range.c1; c <= Math.min(range.c2, range.c1 + 200); c++) other.add(`${r},${c}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [r, c, text, kind] of grid.cells) {
|
||||
if (kind !== 'text' || !String(text).trim()) continue
|
||||
if (cols.size && (!cols.has(c) || other.has(`${r},${c}`))) continue
|
||||
out.add(String(text).trim())
|
||||
}
|
||||
}
|
||||
return [...out].slice(0, 300)
|
||||
}
|
||||
|
||||
/** 回答原样发回:值,加上需要理由的选项的理由 */
|
||||
const asAnswer = (a: QuestionAnswer): QuestionAnswer => (a.reason ? { value: a.value, reason: a.reason } : { value: a.value })
|
||||
|
||||
const STEP_KEYS = ['pick', 'draft', 'trial', 'confirm', 'done'] as const
|
||||
|
||||
function Steps({ current, reupload }: { current: (typeof STEP_KEYS)[number]; reupload: boolean }) {
|
||||
const keys = reupload && current !== 'draft' ? STEP_KEYS.filter((k) => k !== 'draft') : STEP_KEYS
|
||||
const at = keys.indexOf(current as never)
|
||||
return (
|
||||
<ol className="flex flex-wrap items-center gap-1 text-2xs" data-wizard-steps aria-label={RECIPE_TEXT.titleFirst}>
|
||||
{keys.map((k, i) => (
|
||||
<li key={k} className="flex items-center gap-1" data-wizard-step={k} aria-current={k === current ? 'step' : undefined}>
|
||||
{i > 0 && <ChevronRight size={10} className="text-faint" aria-hidden />}
|
||||
<span className={clsx('rounded px-1.5 py-0.5',
|
||||
k === current ? 'bg-accent-soft text-fg' : i < at ? 'text-dim' : 'text-faint')}>
|
||||
{RECIPE_TEXT.steps[k]}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)
|
||||
}
|
||||
|
||||
function Notice({ tone, children, attr }: { tone: 'warn' | 'err' | 'info'; children: ReactNode; attr?: Record<string, string> }) {
|
||||
const color = tone === 'err' ? 'var(--err)' : tone === 'warn' ? 'var(--warn)' : 'var(--accent)'
|
||||
return (
|
||||
<div role={tone === 'info' ? 'status' : 'alert'} className="flex gap-2 rounded-lg border px-3 py-2 text-xs leading-relaxed" {...attr}
|
||||
style={{ borderColor: `color-mix(in srgb, ${color} 40%, var(--border))`, background: `color-mix(in srgb, ${color} 7%, transparent)` }}>
|
||||
{tone === 'info'
|
||||
? <Info size={13} className="mt-0.5 shrink-0" style={{ color }} aria-hidden />
|
||||
: <AlertTriangle size={13} className="mt-0.5 shrink-0" style={{ color }} aria-hidden />}
|
||||
<div className="min-w-0 flex-1">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 统计期录入:两个日期框,文件名里的区间作建议。日期是否合法、起点是否晚于终点,服务端还会再查 */
|
||||
function PeriodForm({ fileName, busy, error, onSubmit }: {
|
||||
fileName: string; busy: boolean; error: string | null; onSubmit: (start: string, end: string) => void
|
||||
}) {
|
||||
const suggest = useMemo(() => periodFromFileName(fileName), [fileName])
|
||||
const [start, setStart] = useState('')
|
||||
const [end, setEnd] = useState('')
|
||||
const valid = !!start && !!end && start <= end
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border bg-bg px-3 py-2.5" data-period-form>
|
||||
{suggest && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-2xs text-dim" data-period-suggest>
|
||||
{RECIPE_TEXT.periodSuggest(suggest.start, suggest.end)}
|
||||
<button type="button" className="btn btn-xs" onClick={() => { setStart(suggest.start); setEnd(suggest.end) }}>
|
||||
{RECIPE_TEXT.periodUseSuggest}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Field label={RECIPE_TEXT.periodStart}>
|
||||
{(p) => <input {...p} type="date" className="field" value={start} data-period-start onChange={(e) => setStart(e.target.value)} />}
|
||||
</Field>
|
||||
<Field label={RECIPE_TEXT.periodEnd}>
|
||||
{(p) => <input {...p} type="date" className="field" value={end} data-period-end onChange={(e) => setEnd(e.target.value)} />}
|
||||
</Field>
|
||||
</div>
|
||||
{error && <div className="text-2xs text-[var(--err)]" role="alert">{error}</div>}
|
||||
{!valid && (start || end) && <div className="text-2xs text-faint">{RECIPE_TEXT.periodInvalid}</div>}
|
||||
<button type="button" className="btn btn-sm btn-primary" disabled={!valid || busy} onClick={() => onSubmit(start, end)}>
|
||||
{busy ? <Spinner size={11} /> : null} {RECIPE_TEXT.periodSubmit}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ImportWizard({ entry, taken = [], onClose, onCommitted, onChanged }: {
|
||||
entry: WizardEntry
|
||||
/** 已被数据库占用的名字(新导入不能用) */
|
||||
taken?: string[]
|
||||
onClose: () => void
|
||||
/** 启用成功:新建或更新后的数据源 */
|
||||
onCommitted: (source: DataSource) => void
|
||||
/** 暂存区开始、放弃、结束:卡片上的「有未完成的导入」要跟着变 */
|
||||
onChanged?: () => void
|
||||
}) {
|
||||
const source = entry.kind === 'reupload' || entry.kind === 'redraft' ? entry.source : entry.kind === 'resume' ? entry.source : undefined
|
||||
const reuploadEntry = entry.kind === 'reupload'
|
||||
const [phase, setPhase] = useState<Phase>(entry.kind === 'new' || entry.kind === 'reupload' ? 'pick' : entry.kind === 'stage' ? 'uploading' : 'loading')
|
||||
const [view, setView] = useState<View>('draft')
|
||||
const [staging, setStaging] = useState<Staging | null>(null)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [notice, setNotice] = useState<{ tone: 'warn' | 'err' | 'info'; text: string; detail?: string } | null>(null)
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [focus, setFocus] = useState<GridFocus | null>(null)
|
||||
const [drawer, setDrawer] = useState(false)
|
||||
const [missing, setMissing] = useState<Set<string>>(new Set())
|
||||
const [confirmError, setConfirmError] = useState<string | null>(null)
|
||||
const [periodError, setPeriodError] = useState<string | null>(null)
|
||||
const [done, setDone] = useState<CommitOut | null>(null)
|
||||
// 选文件
|
||||
const [file, setFile] = useState<File | null>(entry.kind === 'stage' ? entry.file : null)
|
||||
const [name, setName] = useState(entry.kind === 'stage' ? entry.name : '')
|
||||
const [description, setDescription] = useState(entry.kind === 'stage' ? entry.description : '')
|
||||
const [nameRejected, setNameRejected] = useState<{ name: string; message: string } | null>(null)
|
||||
const [progress, setProgress] = useState<{ p: UploadProgress; sentAt?: number } | null>(null)
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const upload = useRef<{ abort: () => void; sent: boolean } | null>(null)
|
||||
const startedAt = useRef(0)
|
||||
const clock = useRunClock(phase === 'uploading' || !!busy)
|
||||
const started = useRef(false)
|
||||
|
||||
const focusCell = (cell: string) => setFocus({ cell, seq: Date.now() })
|
||||
|
||||
/** 暂存区已结束(过期或已放弃):说清楚、关掉向导。返回 true 表示处理了 */
|
||||
const guard = (e: unknown): boolean => {
|
||||
if (e instanceof ApiError && e.code === 'staging_closed') {
|
||||
toast.warn(RECIPE_TEXT.closed)
|
||||
onChanged?.()
|
||||
onClose()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const enter = (s: Staging) => {
|
||||
if (ENDED.has(s.status)) {
|
||||
toast.warn(RECIPE_TEXT.closed)
|
||||
onChanged?.()
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
setStaging(s)
|
||||
setView((s.status === 'trialed' || s.status === 'rejected') && s.trial ? 'result' : 'draft')
|
||||
setPhase('work')
|
||||
}
|
||||
|
||||
const refetch = async (id: string) => {
|
||||
try { setStaging(await api.tableImports.get(id)) } catch (e) { if (!guard(e)) toast.error(e) }
|
||||
}
|
||||
|
||||
/** 选中文件(点选或拖入):新导入拿文件名当默认数据源名,只留 ASCII;中文文件名清洗完可能什么都不剩,那就让用户自己填 */
|
||||
const pickFile = (f: File | null) => {
|
||||
// 拖进来的文件不经过选择框的 accept:不是 Excel 的在这里挡下,免得传完才被服务端拒收
|
||||
if (f && !PICK_ACCEPT.split(',').some((ext) => f.name.toLowerCase().endsWith(ext))) {
|
||||
toast.warn(RECIPE_TEXT.pickWrongType(f.name))
|
||||
return
|
||||
}
|
||||
setFile(f)
|
||||
if (f && !name && !reuploadEntry) {
|
||||
const slug = f.name.replace(/\.[^.]+$/, '').toLowerCase().replace(/[^a-z0-9_]+/g, '_').replace(/^_+|_+$/g, '')
|
||||
setName(/^[a-z]/.test(slug) ? slug.slice(0, 40) : '')
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 开始:上传 / 读取
|
||||
const sendFile = async () => {
|
||||
if (!file) return
|
||||
const isReupload = reuploadEntry && source
|
||||
if (!isReupload && (!name || !NAME_RE.test(name))) return
|
||||
const ctl = new AbortController()
|
||||
const handle = { abort: () => ctl.abort(), sent: false }
|
||||
upload.current = handle
|
||||
startedAt.current = Date.now()
|
||||
setProgress(null)
|
||||
setPhase('uploading')
|
||||
const opts = {
|
||||
signal: ctl.signal,
|
||||
onProgress: (p: UploadProgress) => {
|
||||
if (p.sent) handle.sent = true
|
||||
setProgress((cur) => ({ p, sentAt: cur?.sentAt ?? (p.sent ? Date.now() : undefined) }))
|
||||
},
|
||||
}
|
||||
try {
|
||||
const s = isReupload
|
||||
? await api.tableImports.reupload(source.id, file, opts)
|
||||
: await api.tableImports.stage(file, { name, description }, opts)
|
||||
onChanged?.()
|
||||
enter(s)
|
||||
} catch (e) {
|
||||
setPhase('pick')
|
||||
if (e instanceof DOMException && e.name === 'AbortError') { toast.info(UPLOAD_TEXT.cancelHint); return }
|
||||
const code = e instanceof ApiError ? e.code : undefined
|
||||
if (code && ['name_taken', 'name_invalid', 'recipe_source_exists'].includes(code)) setNameRejected({ name, message: errorMessage(e) })
|
||||
else toast.error(e)
|
||||
} finally {
|
||||
if (upload.current === handle) upload.current = null
|
||||
setProgress(null)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (started.current) return
|
||||
started.current = true
|
||||
if (entry.kind === 'stage') void sendFile()
|
||||
if (entry.kind === 'redraft') {
|
||||
void (async () => {
|
||||
try {
|
||||
enter(await api.tableImports.redraft(entry.source.id))
|
||||
onChanged?.()
|
||||
} catch (e) {
|
||||
setFailure(e instanceof ApiError && e.code === 'raw_missing' ? `${errorMessage(e)}(${RECIPE_TEXT.rawMissing})` : errorMessage(e))
|
||||
setPhase('failed')
|
||||
}
|
||||
})()
|
||||
}
|
||||
if (entry.kind === 'resume') {
|
||||
void (async () => {
|
||||
try { enter(await api.tableImports.get(entry.stagingId)) } catch (e) { setFailure(errorMessage(e)); setPhase('failed') }
|
||||
})()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const close = () => {
|
||||
if (upload.current && !upload.current.sent) upload.current.abort()
|
||||
if (staging) onChanged?.()
|
||||
onClose()
|
||||
}
|
||||
|
||||
// ---- 起草:回答、改配方、AI、试运行
|
||||
const answer = async (qid: string, a: QuestionAnswer): Promise<boolean> => {
|
||||
if (!staging) return false
|
||||
const answers: Record<string, QuestionAnswer> = {}
|
||||
for (const [k, v] of Object.entries(staging.answers ?? {})) answers[k] = asAnswer(v)
|
||||
answers[qid] = asAnswer(a)
|
||||
setBusy('answer')
|
||||
try {
|
||||
setStaging(await api.tableImports.answers(staging.id, answers))
|
||||
return true
|
||||
} catch (e) {
|
||||
if (!guard(e)) toast.error(e)
|
||||
return false
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
/** 存上了返回服务端存下的配方:配方面板以它为底接着发排在后面的修改 */
|
||||
const saveRecipe = async (recipe: Recipe): Promise<{ recipe: Recipe | null } | null> => {
|
||||
if (!staging) return null
|
||||
setBusy('recipe')
|
||||
try {
|
||||
const s = await api.tableImports.putRecipe(staging.id, recipe)
|
||||
setStaging(s)
|
||||
return { recipe: s.recipe }
|
||||
} catch (e) {
|
||||
if (!guard(e)) toast.error(e)
|
||||
return null
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const trial = async (context?: { start: string; end: string }) => {
|
||||
if (!staging) return
|
||||
setBusy('trial')
|
||||
setNotice(null)
|
||||
setPeriodError(null)
|
||||
try {
|
||||
const s = await api.tableImports.trial(staging.id, {
|
||||
...(context ? { context_inputs: { 统计期: context } } : {}), signed_by: localActor(),
|
||||
})
|
||||
setStaging(s)
|
||||
setView('result')
|
||||
setMissing(new Set())
|
||||
setConfirmError(null)
|
||||
} catch (e) {
|
||||
if (guard(e)) return
|
||||
const code = e instanceof ApiError ? e.code : undefined
|
||||
if (code === 'context_invalid' || code === 'context_not_needed') setPeriodError(errorMessage(e))
|
||||
else toast.error(e)
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 提交
|
||||
const commit = async (body: CommitBody) => {
|
||||
if (!staging?.trial) return
|
||||
setBusy('commit')
|
||||
setConfirmError(null)
|
||||
try {
|
||||
const out = await api.tableImports.commit(staging.id, { trial_id: staging.trial.trial_id, ...body })
|
||||
setDone(out)
|
||||
setPhase('done')
|
||||
onCommitted(out.source)
|
||||
} catch (e) {
|
||||
if (guard(e)) return
|
||||
const code = e instanceof ApiError ? e.code : undefined
|
||||
const message = errorMessage(e)
|
||||
if (code === 'confirm_required' || code === 'acceptance_required') {
|
||||
// 服务端在 detail 里点名缺的项:按 id 或文案认出来标红
|
||||
const ids = new Set<string>()
|
||||
for (const it of staging.trial.confirm_items ?? []) if (message.includes(it.id) || message.includes(it.label)) ids.add(it.id)
|
||||
for (const id of staging.trial.acceptable ?? []) if (message.includes(id)) ids.add(id)
|
||||
setMissing(ids)
|
||||
setConfirmError(message)
|
||||
} else if (code === 'trial_required' || code === 'trial_tampered' || code === 'base_changed' || code === 'name_taken') {
|
||||
// 试运行库已被消耗或作废:回到配方步骤重新试运行
|
||||
const text = code === 'base_changed' ? RECIPE_TEXT.baseChanged : code === 'name_taken' ? RECIPE_TEXT.nameTaken : RECIPE_TEXT.rerunTrial
|
||||
setNotice({ tone: 'warn', text, detail: message })
|
||||
setPhase('work')
|
||||
setView('draft')
|
||||
await refetch(staging.id)
|
||||
} else if (code === 'trial_not_passed') {
|
||||
setNotice({ tone: 'warn', text: message })
|
||||
setPhase('work')
|
||||
setView('result')
|
||||
} else {
|
||||
setConfirmError(message)
|
||||
}
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const discard = async () => {
|
||||
if (!staging) { close(); return }
|
||||
const ok = await confirmDialog({
|
||||
title: RECIPE_TEXT.discardTitle, danger: true, consequences: [...RECIPE_TEXT.discardConsequences], confirmLabel: RECIPE_TEXT.discard,
|
||||
})
|
||||
if (!ok) return
|
||||
setBusy('discard')
|
||||
try {
|
||||
await api.tableImports.discard(staging.id)
|
||||
toast.ok(RECIPE_TEXT.discarded)
|
||||
onChanged?.()
|
||||
onClose()
|
||||
} catch (e) {
|
||||
if (!guard(e)) toast.error(e)
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 标题
|
||||
const srcName = staging?.source?.name || source?.name || name
|
||||
const kind = staging?.kind ?? (entry.kind === 'reupload' ? 'reupload' : entry.kind === 'redraft' ? 'redraft' : 'first')
|
||||
const isReupload = kind === 'reupload'
|
||||
const title = kind === 'reupload' ? RECIPE_TEXT.titleReupload(srcName)
|
||||
: kind === 'redraft' ? RECIPE_TEXT.titleRedraft(srcName)
|
||||
: srcName ? RECIPE_TEXT.titleNamed(srcName) : RECIPE_TEXT.titleFirst
|
||||
const step: (typeof STEP_KEYS)[number] = phase === 'pick' || phase === 'uploading' ? 'pick'
|
||||
: phase === 'confirm' ? 'confirm' : phase === 'done' ? 'done' : view === 'result' ? 'trial' : 'draft'
|
||||
|
||||
const labelOptions = useMemo(() => labelOptionsOf(staging), [staging])
|
||||
const t = staging?.trial ?? null
|
||||
const trialStale = !!t && staging?.status === 'drafting'
|
||||
const canTrial = !!staging?.recipe && !staging.recipe_problems?.length && !busy
|
||||
|
||||
// ---- 正文
|
||||
let body: ReactNode = null
|
||||
let footer: ReactNode = null
|
||||
|
||||
if (phase === 'pick' || phase === 'uploading') {
|
||||
const nameError = reuploadEntry ? null
|
||||
: name && !NAME_RE.test(name) ? RECIPE_TEXT.nameInvalid
|
||||
: taken.includes(name) ? RECIPE_TEXT.nameTakenDb(name)
|
||||
: nameRejected && nameRejected.name === name ? nameRejected.message : null
|
||||
const uploading = phase === 'uploading'
|
||||
const sent = !!progress?.p.sent
|
||||
body = (
|
||||
<div className="space-y-3" data-wizard-pick>
|
||||
{reuploadEntry && <p className="text-xs leading-relaxed text-dim">{RECIPE_TEXT.pickReupload}</p>}
|
||||
{/* 同上传弹窗:拖进来的文件在这里接住(不接的话浏览器会直接打开或下载这个文件) */}
|
||||
<label className={clsx('flex flex-col items-center justify-center gap-1.5 rounded-lg border border-dashed px-4 py-5 text-center transition-colors',
|
||||
uploading ? 'opacity-60' : 'cursor-pointer',
|
||||
dragging ? 'border-[var(--accent)] bg-accent-soft' : !uploading && 'hover:border-[var(--border-strong)] hover:bg-hover')}
|
||||
data-wizard-drop
|
||||
onDragOver={(e) => { e.preventDefault(); if (!uploading) setDragging(true) }}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={(e) => { e.preventDefault(); setDragging(false); if (!uploading) pickFile(e.dataTransfer.files?.[0] ?? null) }}>
|
||||
<FileSpreadsheet size={20} className={file ? 'text-[var(--accent)]' : 'text-faint'} aria-hidden />
|
||||
{file
|
||||
? <span className="text-xs" data-wizard-file><span className="mono">{file.name}</span> <span className="tnum text-faint">· {formatBytes(file.size)}</span></span>
|
||||
: <span className="text-xs text-dim">{RECIPE_TEXT.pickDrop}</span>}
|
||||
<span className="text-2xs text-faint">{RECIPE_TEXT.pickFormats}</span>
|
||||
<input type="file" className="sr-only" accept={PICK_ACCEPT} aria-label={RECIPE_TEXT.pickAria} disabled={uploading}
|
||||
onChange={(e) => pickFile(e.target.files?.[0] ?? null)} />
|
||||
</label>
|
||||
<p className="flex gap-1.5 text-2xs leading-relaxed text-faint" data-raw-notice>
|
||||
<Info size={11} className="mt-0.5 shrink-0" aria-hidden />
|
||||
<span>{UPLOAD_TEXT.rawNotice}</span>
|
||||
</p>
|
||||
{uploading && (
|
||||
<div className="rounded-lg border bg-bg px-3 py-2 text-2xs" data-upload-progress>
|
||||
<UploadMeter progress={progress?.p ?? null} startedAt={startedAt.current || Date.now()} sentAt={progress?.sentAt}
|
||||
processing={reuploadEntry ? RECIPE_TEXT.reuploading : RECIPE_TEXT.staging} now={clock} />
|
||||
</div>
|
||||
)}
|
||||
{!reuploadEntry && (
|
||||
<>
|
||||
<Field label={RECIPE_TEXT.nameLabel} required error={nameError} hint={RECIPE_TEXT.nameHint}>
|
||||
{(p) => (
|
||||
<input {...p} className="field mono" value={name} placeholder="passenger_flow" autoComplete="off" spellCheck={false}
|
||||
disabled={uploading} onChange={(e) => setName(e.target.value)} data-wizard-name />
|
||||
)}
|
||||
</Field>
|
||||
<Field label={RECIPE_TEXT.descriptionLabel}>
|
||||
{(p) => <input {...p} className="field" value={description} disabled={uploading} onChange={(e) => setDescription(e.target.value)} />}
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
footer = (
|
||||
<>
|
||||
{uploading && !sent
|
||||
? <button className="btn" onClick={() => upload.current?.abort()}>{RECIPE_TEXT.cancelUpload}</button>
|
||||
: <button className="btn" onClick={close} disabled={uploading}>{RECIPE_TEXT.cancel}</button>}
|
||||
<button className="btn btn-primary tnum" disabled={uploading || !file || (!reuploadEntry && (!name || !!nameError))}
|
||||
onClick={() => void sendFile()} data-wizard-start>
|
||||
{uploading
|
||||
? <><Spinner size={11} /> {formatDuration(clock - startedAt.current)}</>
|
||||
: <><Upload size={12} aria-hidden /> {reuploadEntry ? RECIPE_TEXT.reupload : RECIPE_TEXT.entry}</>}
|
||||
</button>
|
||||
</>
|
||||
)
|
||||
} else if (phase === 'loading') {
|
||||
body = <div className="flex items-center justify-center gap-2 py-12 text-xs text-dim"><Spinner size={12} /> {RECIPE_TEXT.loading}</div>
|
||||
} else if (phase === 'failed') {
|
||||
body = <Notice tone="err" attr={{ 'data-wizard-failed': '' }}>{failure}</Notice>
|
||||
footer = <button className="btn" onClick={close}>{RECIPE_TEXT.close}</button>
|
||||
} else if (phase === 'done' && done) {
|
||||
const seq = t?.same_as_import?.seq
|
||||
body = (
|
||||
<div className="space-y-2 py-4 text-center" data-import-done={done.unchanged ? 'unchanged' : 'committed'}>
|
||||
<div className="text-sm font-medium">{RECIPE_TEXT.done(done.source?.name ?? srcName)}</div>
|
||||
{done.unchanged && seq != null && <p className="text-xs text-dim">{RECIPE_TEXT.doneUnchanged(formatNumber(seq))}</p>}
|
||||
{!done.unchanged && done.build_reused && <p className="text-xs text-faint">{RECIPE_TEXT.doneReused}</p>}
|
||||
</div>
|
||||
)
|
||||
footer = <button className="btn btn-primary" onClick={onClose} data-autofocus>{RECIPE_TEXT.finish}</button>
|
||||
} else if (staging && (phase === 'work' || phase === 'confirm')) {
|
||||
const problemsForGrid = view === 'result' && t ? t.problems ?? [] : staging.draft_problems ?? []
|
||||
let right: ReactNode
|
||||
if (phase === 'confirm' && t && !trialStale) {
|
||||
right = (
|
||||
<ConfirmList items={t.confirm_items ?? []} checks={t.checks ?? []} acceptable={t.acceptable ?? []} reupload={isReupload}
|
||||
busy={busy === 'commit'} missing={missing} error={confirmError} onSubmit={(b) => void commit(b)} />
|
||||
)
|
||||
} else if (view === 'result' && t) {
|
||||
right = (
|
||||
<div className="space-y-3">
|
||||
<TrialStatusLine status={t.status} />
|
||||
{trialStale && <Notice tone="warn" attr={{ 'data-trial-stale': 'result' }}>{RECIPE_TEXT.trialStaleConfirm}</Notice>}
|
||||
{t.status === 'needs_input' && (
|
||||
<PeriodForm fileName={staging.file?.name ?? ''} busy={busy === 'trial'} error={periodError}
|
||||
onSubmit={(start, end) => void trial({ start, end })} />
|
||||
)}
|
||||
{/* 拒收、需要录入时服务端有意不算差异(diff 为 null):不显示差异卡 */}
|
||||
{(Array.isArray(t.diff) || t.same_as_import) && <ReuploadDiff diff={t.diff} sameAsImport={t.same_as_import} />}
|
||||
<ImportReceipt trial={t} onFocusCell={focusCell}
|
||||
expectedSheets={Array.isArray(staging.recipe?.sheets) ? staging.recipe.sheets.length : undefined} />
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
const failures = staging.draft && !staging.draft.complete ? staging.draft.failures ?? [] : []
|
||||
right = (
|
||||
<div className="space-y-3">
|
||||
<AiDraftOffer staging={staging} busy={!!busy} setBusy={(v) => setBusy(v ? 'ai' : '')} onStaging={setStaging} onError={guard} />
|
||||
{failures.length > 0 && (
|
||||
<Notice tone="warn" attr={{ 'data-draft-failures': '' }}>
|
||||
<div className="font-medium">{RECIPE_TEXT.draftIncomplete}</div>
|
||||
<ul className="mt-0.5 list-disc pl-4 text-dim">{failures.map((f, i) => <li key={i}>{f}</li>)}</ul>
|
||||
</Notice>
|
||||
)}
|
||||
{staging.draft_partial && (
|
||||
<p className="text-2xs text-faint" data-draft-partial title={RECIPE_TEXT.partialHint}>{RECIPE_TEXT.partial}</p>
|
||||
)}
|
||||
{trialStale && <Notice tone="info" attr={{ 'data-trial-stale': '' }}>{RECIPE_TEXT.trialStale}</Notice>}
|
||||
<SuggestionCards cards={staging.cards ?? []} questions={staging.questions ?? []} answers={staging.answers ?? {}}
|
||||
busy={!!busy} applying={busy === 'answer'} onAnswer={answer} onFocusCell={focusCell} />
|
||||
{(staging.draft_problems ?? []).some((p) => p.category !== 'confirm') && (
|
||||
<section className="space-y-1.5">
|
||||
<h3 className="text-xs font-semibold">{RECIPE_TEXT.problems}</h3>
|
||||
<ProblemList problems={(staging.draft_problems ?? []).filter((p) => p.category !== 'confirm')} onFocus={focusCell} />
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
body = (
|
||||
<div className="space-y-3" data-import-wizard data-staging={staging.id} data-view={phase === 'confirm' ? 'confirm' : view}>
|
||||
<Steps current={step} reupload={isReupload} />
|
||||
{notice && (
|
||||
<Notice tone={notice.tone} attr={{ 'data-wizard-notice': '' }}>
|
||||
<div>{notice.text}</div>
|
||||
{notice.detail && notice.detail !== notice.text && <div className="mt-0.5 text-2xs text-dim">{notice.detail}</div>}
|
||||
</Notice>
|
||||
)}
|
||||
<div className="grid min-h-0 grid-cols-1 gap-3 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
|
||||
<SheetGrid grids={staging.grids ?? []} marks={staging.marks ?? []} problems={problemsForGrid}
|
||||
partial={view === 'draft' && staging.draft_partial} focus={focus} />
|
||||
<div className="min-h-0 overflow-y-auto pr-1" style={{ maxHeight: '60vh' }} data-wizard-side>{right}</div>
|
||||
</div>
|
||||
{view === 'draft' && phase === 'work' && (
|
||||
<section className="rounded-lg border" data-recipe-drawer>
|
||||
<button type="button" className="flex w-full items-center gap-1.5 px-3 py-2 text-xs font-medium hover:bg-hover"
|
||||
aria-expanded={drawer} onClick={() => setDrawer((v) => !v)} data-recipe-drawer-toggle>
|
||||
<ChevronRight size={12} className={clsx('transition-transform', drawer && 'rotate-90')} aria-hidden />
|
||||
{RECIPE_TEXT.panel}
|
||||
{!!staging.recipe_problems?.length && (
|
||||
<span className="chip" style={{ color: 'var(--err)', borderColor: 'var(--err)' }}>
|
||||
{formatNumber(staging.recipe_problems.length)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{drawer && (
|
||||
<div className="border-t p-3">
|
||||
<RecipePanel recipe={staging.recipe} problems={staging.recipe_problems ?? []} units={staging.units ?? []}
|
||||
candidates={staging.candidates ?? {}} labelOptions={labelOptions} saving={busy === 'recipe'}
|
||||
onSave={saveRecipe} />
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
const discardBtn = (
|
||||
<button className="btn btn-ghost mr-auto" onClick={() => void discard()} disabled={!!busy} data-wizard-discard>
|
||||
{RECIPE_TEXT.discard}
|
||||
</button>
|
||||
)
|
||||
if (phase === 'confirm') {
|
||||
footer = (
|
||||
<>
|
||||
{discardBtn}
|
||||
<button className="btn" onClick={() => setPhase('work')} disabled={busy === 'commit'}>{RECIPE_TEXT.backToReceipt}</button>
|
||||
</>
|
||||
)
|
||||
} else if (view === 'result' && t) {
|
||||
// 试运行已失效(之后改过配方或录入):不能拿它去确认、启用
|
||||
const next = (t.status === 'passed' || t.status === 'needs_decision') && !trialStale
|
||||
footer = (
|
||||
<>
|
||||
{discardBtn}
|
||||
<button className="btn" onClick={() => { setView('draft'); setDrawer(true); setNotice(null) }} disabled={!!busy} data-back-to-recipe>
|
||||
{RECIPE_TEXT.backToRecipe}
|
||||
</button>
|
||||
{next && (
|
||||
<button className="btn btn-primary" onClick={() => { setMissing(new Set()); setConfirmError(null); setPhase('confirm') }}
|
||||
disabled={!!busy} data-to-confirm>
|
||||
{RECIPE_TEXT.toConfirm}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
footer = (
|
||||
<>
|
||||
{discardBtn}
|
||||
{/* 新源在启用之前没有卡片,关掉就没有「有未完成的导入」可点:不给「稍后继续」 */}
|
||||
{staging.source?.exists && (
|
||||
<button className="btn" onClick={close} title={RECIPE_TEXT.laterHint}>{RECIPE_TEXT.later}</button>
|
||||
)}
|
||||
<button className="btn btn-primary tnum" disabled={!canTrial} onClick={() => void trial()} data-trial-run
|
||||
title={staging.recipe_problems?.length ? RECIPE_TEXT.trialBlocked : undefined}>
|
||||
{busy === 'trial' ? <><Spinner size={11} /> {RECIPE_TEXT.trialRunning}</> : RECIPE_TEXT.trialRun}
|
||||
</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={close} width={phase === 'pick' || phase === 'uploading' || phase === 'loading' || phase === 'failed' || phase === 'done' ? 560 : 1280}
|
||||
// 新源的导入关掉以后没有入口可以继续:和没保存的表单一样先问一句
|
||||
dirty={(phase === 'pick' && !!file) || (!!staging && !staging.source?.exists && (phase === 'work' || phase === 'confirm'))}
|
||||
title={title} footer={footer}>
|
||||
{body}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
import type { DiffItem } from '../../types'
|
||||
import { formatNumber } from '../../lib/format'
|
||||
import { DIFF_KIND_LABEL, RECIPE_TEXT } from '../../lib/terms'
|
||||
|
||||
// ===========================================================================
|
||||
// 差异卡:上传新一期与上一期相比变了什么。需确认的排在前面(它们同时是确认清单里的必勾项),
|
||||
// 其余只作说明。结构类变化不在这里——那种在试运行里就拒收了
|
||||
// ===========================================================================
|
||||
|
||||
export function ReuploadDiff({ diff, sameAsImport }: {
|
||||
/** null:没有可比的上一期,或者试运行拒收、需要录入(服务端有意不算差异),调用方此时不显示这张卡 */
|
||||
diff: DiffItem[] | null | undefined
|
||||
sameAsImport?: { id: string; seq: number } | null
|
||||
}) {
|
||||
const items = [...(diff ?? [])].sort((a, b) => Number(!!b.requires_confirm) - Number(!!a.requires_confirm))
|
||||
return (
|
||||
<section className="space-y-1.5 rounded-lg border bg-panel px-3 py-2" data-reupload-diff>
|
||||
<h4 className="text-xs font-semibold">{RECIPE_TEXT.diffTitle}</h4>
|
||||
{sameAsImport && (
|
||||
<p className="rounded-md border px-2.5 py-1.5 text-xs text-dim" data-same-as-import={sameAsImport.seq}>
|
||||
{RECIPE_TEXT.sameAsImport(formatNumber(sameAsImport.seq))}
|
||||
</p>
|
||||
)}
|
||||
{!items.length && !sameAsImport && <p className="text-xs text-faint">{RECIPE_TEXT.diffNone}</p>}
|
||||
{items.length > 0 && (
|
||||
<ul className="space-y-1">
|
||||
{items.map((d, i) => (
|
||||
<li key={`${d.kind}-${i}`} className="space-y-0.5 rounded-md border px-2.5 py-1.5 text-xs" data-diff={d.kind}
|
||||
data-requires-confirm={d.requires_confirm ? (d.confirm_id ?? '') : undefined}
|
||||
style={d.requires_confirm ? { borderColor: 'color-mix(in srgb, var(--warn) 45%, var(--border))' } : undefined}>
|
||||
<div className="flex flex-wrap items-baseline gap-x-2">
|
||||
{d.requires_confirm && <span className="chip" style={{ color: 'var(--warn)', borderColor: 'var(--warn)' }}>{RECIPE_TEXT.diffRequires}</span>}
|
||||
<span className="text-faint">{DIFF_KIND_LABEL[d.kind] ?? RECIPE_TEXT.diffKindOther}</span>
|
||||
<span className="min-w-0 flex-1">{d.label}</span>
|
||||
</div>
|
||||
{d.detail && <p className="text-2xs leading-relaxed text-dim">{d.detail}</p>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { CSSProperties } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import type { GridPreview, ImportProblem, RegionMark } from '../../types'
|
||||
import { Tabs } from '../../components/ui'
|
||||
import { formatNumber } from '../../lib/format'
|
||||
import { LEDGER_ROLE_LABEL, RECIPE_TEXT } from '../../lib/terms'
|
||||
|
||||
// ===========================================================================
|
||||
// 原始网格:按配方导入时左边那张表。只读——期 2 不能框选,区域只能经起草或配方面板改
|
||||
// ===========================================================================
|
||||
|
||||
/** 1 → A,27 → AA */
|
||||
export function colLetter(n: number): string {
|
||||
let s = ''
|
||||
let x = n
|
||||
while (x > 0) {
|
||||
const m = (x - 1) % 26
|
||||
s = String.fromCharCode(65 + m) + s
|
||||
x = Math.floor((x - 1) / 26)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
/** A → 1,AA → 27;不是列字母返回 0 */
|
||||
export function colNumber(letters: string): number {
|
||||
let n = 0
|
||||
for (const ch of letters.toUpperCase()) {
|
||||
const code = ch.charCodeAt(0)
|
||||
if (code < 65 || code > 90) return 0
|
||||
n = n * 26 + (code - 64)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
export interface CellRange { sheet: string | null; r1: number; c1: number; r2: number; c2: number }
|
||||
|
||||
/**
|
||||
* 「工作表!B5」「工作表!C5:AG7」「B5」→ 区域。工作表名可能带引号('客流 汇总'!B5),也可能自己含「!」,
|
||||
* 所以按最后一个「!」切。认不出返回 null
|
||||
*/
|
||||
export function parseRef(ref: string): CellRange | null {
|
||||
const at = ref.lastIndexOf('!')
|
||||
let sheet: string | null = at >= 0 ? ref.slice(0, at) : null
|
||||
if (sheet && sheet.length > 1 && sheet.startsWith("'") && sheet.endsWith("'")) sheet = sheet.slice(1, -1).replace(/''/g, "'")
|
||||
const body = (at >= 0 ? ref.slice(at + 1) : ref).replace(/\$/g, '')
|
||||
const m = /^([A-Za-z]{1,3})(\d{1,7})(?::([A-Za-z]{1,3})(\d{1,7}))?$/.exec(body.trim())
|
||||
if (!m) return null
|
||||
const c1 = colNumber(m[1])
|
||||
const r1 = Number(m[2])
|
||||
const c2 = m[3] ? colNumber(m[3]) : c1
|
||||
const r2 = m[4] ? Number(m[4]) : r1
|
||||
return { sheet, r1: Math.min(r1, r2), c1: Math.min(c1, c2), r2: Math.max(r1, r2), c2: Math.max(c1, c2) }
|
||||
}
|
||||
|
||||
export const cellName = (r: number, c: number) => `${colLetter(c)}${r}`
|
||||
|
||||
/**
|
||||
* 各去向的底色。只用已有的令牌混色:深浅两套主题下都跟着变,不另起一套色值。
|
||||
* 合计类(交叉表的合计段、列表的合计行)同色:图例里是同一个说法
|
||||
*/
|
||||
const TINT: Record<string, string> = {
|
||||
value: 'var(--accent)',
|
||||
derived_value: 'var(--warn)',
|
||||
total_value: 'var(--warn)',
|
||||
derived_label: 'var(--nt-metrics)',
|
||||
total_label: 'var(--nt-metrics)',
|
||||
col_header: 'var(--nt-tool)',
|
||||
row_label: 'var(--nt-agent)',
|
||||
section_title: 'var(--nt-branch)',
|
||||
context: 'var(--ok)',
|
||||
outside_text: 'var(--text-faint)',
|
||||
ignored_column: 'var(--st-unreached)',
|
||||
hidden_excluded: 'var(--st-unreached)',
|
||||
}
|
||||
|
||||
/** 网格格子和图例色块的样式 */
|
||||
export function roleStyle(role: string | undefined): CSSProperties | undefined {
|
||||
if (!role) return undefined
|
||||
if (role === 'unclaimed') {
|
||||
return {
|
||||
background: 'color-mix(in srgb, var(--err) 22%, transparent)',
|
||||
boxShadow: 'inset 0 0 0 1px color-mix(in srgb, var(--err) 70%, transparent)',
|
||||
}
|
||||
}
|
||||
const tint = TINT[role]
|
||||
return tint ? { background: `color-mix(in srgb, ${tint} 20%, transparent)` } : undefined
|
||||
}
|
||||
|
||||
/** 这些问题的格子就是「没有去处」的格子(执行器的区域标记不含未认领的格,由问题的 cells 指出) */
|
||||
const UNCLAIMED_CODES = new Set([
|
||||
'cell_unclaimed', 'row_unclaimed', 'row_without_label', 'outside_number', 'axis_extra_cells', 'rows_after_stop',
|
||||
])
|
||||
|
||||
/** 网格最多画这么多行:再多浏览器就卡了,预览本身也只给前面一部分 */
|
||||
const MAX_ROWS = 600
|
||||
|
||||
/** 区域在显示的行列里展开成格子键「行,列」;只走显示出来的行列,C5:XFD1048576 这种不会卡住 */
|
||||
function expand(range: CellRange, rows: number[], cols: number[], out: (key: string) => void) {
|
||||
const rs = rows.filter((r) => r >= range.r1 && r <= range.r2)
|
||||
const cs = cols.filter((c) => c >= range.c1 && c <= range.c2)
|
||||
for (const r of rs) for (const c of cs) out(`${r},${c}`)
|
||||
}
|
||||
|
||||
function axisOf(grid: GridPreview): { rows: number[]; cols: number[] } {
|
||||
if (grid.rows?.length && grid.cols?.length) return { rows: grid.rows.slice(0, MAX_ROWS), cols: grid.cols }
|
||||
const b = grid.bounds ? parseRef(grid.bounds) : null
|
||||
if (b) {
|
||||
const rows: number[] = []
|
||||
const cols: number[] = []
|
||||
for (let r = b.r1; r <= Math.min(b.r2, b.r1 + MAX_ROWS - 1); r++) rows.push(r)
|
||||
for (let c = b.c1; c <= b.c2; c++) cols.push(c)
|
||||
return { rows, cols }
|
||||
}
|
||||
// 没有边界:按格子自己拼
|
||||
const rs = new Set<number>()
|
||||
const cs = new Set<number>()
|
||||
for (const [r, c] of grid.cells) { rs.add(r); cs.add(c) }
|
||||
return { rows: [...rs].sort((a, b) => a - b).slice(0, MAX_ROWS), cols: [...cs].sort((a, b) => a - b) }
|
||||
}
|
||||
|
||||
interface SheetModel {
|
||||
rows: number[]
|
||||
cols: number[]
|
||||
cells: Map<string, { text: string; kind: string }>
|
||||
roles: Map<string, string>
|
||||
spans: Map<string, { rs: number; cs: number }>
|
||||
covered: Set<string>
|
||||
hiddenRows: Set<number>
|
||||
hiddenCols: Set<number>
|
||||
}
|
||||
|
||||
function buildModel(grid: GridPreview, marks: RegionMark[], problems: ImportProblem[], partial: boolean): SheetModel {
|
||||
const { rows, cols } = axisOf(grid)
|
||||
const cells = new Map<string, { text: string; kind: string }>()
|
||||
for (const [r, c, text, kind] of grid.cells) cells.set(`${r},${c}`, { text: String(text ?? ''), kind: String(kind ?? 'text') })
|
||||
const roles = new Map<string, string>()
|
||||
const own = marks.filter((m) => m.sheet === grid.sheet)
|
||||
for (const m of own) {
|
||||
const range = parseRef(m.ref)
|
||||
if (range) expand(range, rows, cols, (k) => { if (cells.has(k)) roles.set(k, m.role) })
|
||||
}
|
||||
// 没有去处:问题里点名的格,加上(完整干跑过时)区域标记没覆盖到的非空格。部分干跑只看了前面几百行,
|
||||
// 窗口外的格本来就没有标记,不能一概标红
|
||||
const flagged = new Set<string>()
|
||||
for (const p of problems) {
|
||||
if (!UNCLAIMED_CODES.has(p.code)) continue
|
||||
for (const ref of p.cells ?? []) {
|
||||
const range = parseRef(ref)
|
||||
if (range && (range.sheet == null || range.sheet === grid.sheet)) expand(range, rows, cols, (k) => flagged.add(k))
|
||||
}
|
||||
}
|
||||
const exhaustive = own.length > 0 && !partial
|
||||
for (const k of cells.keys()) {
|
||||
if (roles.has(k)) continue
|
||||
if (flagged.has(k) || exhaustive) roles.set(k, 'unclaimed')
|
||||
}
|
||||
// 合并区:左上格跨行跨列,其余格不画。跨度按显示出来的行列数(中间有截掉的行时不会错位)
|
||||
const spans = new Map<string, { rs: number; cs: number }>()
|
||||
const covered = new Set<string>()
|
||||
const rowIndex = new Map(rows.map((r, i) => [r, i]))
|
||||
const colIndex = new Map(cols.map((c, i) => [c, i]))
|
||||
for (const ref of grid.merges ?? []) {
|
||||
const range = parseRef(ref)
|
||||
if (!range || !rowIndex.has(range.r1) || !colIndex.has(range.c1)) continue
|
||||
const rs = rows.filter((r) => r >= range.r1 && r <= range.r2).length
|
||||
const cs = cols.filter((c) => c >= range.c1 && c <= range.c2).length
|
||||
if (rs * cs <= 1) continue
|
||||
spans.set(`${range.r1},${range.c1}`, { rs, cs })
|
||||
expand(range, rows, cols, (k) => { if (k !== `${range.r1},${range.c1}`) covered.add(k) })
|
||||
}
|
||||
return {
|
||||
rows, cols, cells, roles, spans, covered,
|
||||
hiddenRows: new Set(grid.hidden_rows ?? []), hiddenCols: new Set(grid.hidden_cols ?? []),
|
||||
}
|
||||
}
|
||||
|
||||
/** 要滚到的格子:seq 每次点击都变,同一格点两次也会再滚一次 */
|
||||
export interface GridFocus { cell: string; seq: number }
|
||||
|
||||
export function SheetGrid({ grids, marks, problems, partial = false, focus }: {
|
||||
grids: GridPreview[]
|
||||
marks: RegionMark[]
|
||||
/** 最近一次干跑或试运行的问题:其中点名的格标「没有去处」 */
|
||||
problems: ImportProblem[]
|
||||
partial?: boolean
|
||||
focus?: GridFocus | null
|
||||
}) {
|
||||
const [active, setActive] = useState(grids[0]?.sheet ?? '')
|
||||
const [flash, setFlash] = useState<string | null>(null)
|
||||
const boxRef = useRef<HTMLDivElement>(null)
|
||||
const grid = grids.find((g) => g.sheet === active) ?? grids[0]
|
||||
|
||||
useEffect(() => {
|
||||
if (grids.length && !grids.some((g) => g.sheet === active)) setActive(grids[0].sheet)
|
||||
}, [grids, active])
|
||||
|
||||
const model = useMemo(() => (grid ? buildModel(grid, marks, problems, partial) : null), [grid, marks, problems, partial])
|
||||
|
||||
// 点了问题、卡片里的坐标:切到那张工作表,把那格滚到中间,闪一下。切表要等下一次渲染才有那一格,
|
||||
// 所以分两步:这里记下要去哪,下面的 effect 在画好之后再滚
|
||||
const [pending, setPending] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (!focus) return
|
||||
const range = parseRef(focus.cell)
|
||||
if (!range) return
|
||||
if (range.sheet && grids.some((g) => g.sheet === range.sheet)) setActive(range.sheet)
|
||||
setPending(cellName(range.r1, range.c1))
|
||||
// 只在点击(seq 变化)时滚
|
||||
}, [focus?.seq])
|
||||
useEffect(() => {
|
||||
if (!pending) return
|
||||
const el = boxRef.current?.querySelector<HTMLElement>(`[data-cell="${pending}"]`)
|
||||
el?.scrollIntoView({ block: 'center', inline: 'center' })
|
||||
setFlash(pending)
|
||||
setPending(null)
|
||||
}, [pending, grid?.sheet])
|
||||
useEffect(() => {
|
||||
if (!flash) return
|
||||
const timer = setTimeout(() => setFlash(null), 1600)
|
||||
return () => clearTimeout(timer)
|
||||
}, [flash, focus?.seq])
|
||||
|
||||
if (!grid || !model) {
|
||||
return <div className="rounded-lg border px-3 py-6 text-center text-xs text-faint" data-sheet-grid>{RECIPE_TEXT.noGrid}</div>
|
||||
}
|
||||
|
||||
const legend = new Map<string, string>()
|
||||
for (const role of model.roles.values()) {
|
||||
const label = role === 'unclaimed' ? RECIPE_TEXT.unclaimed : LEDGER_ROLE_LABEL[role]
|
||||
if (label && ![...legend.values()].includes(label)) legend.set(role, label)
|
||||
}
|
||||
const hasHidden = model.hiddenRows.size > 0 || model.hiddenCols.size > 0
|
||||
const shownRows = model.rows.length
|
||||
const totalRows = grid.total_rows ?? shownRows
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-col gap-2" data-sheet-grid data-sheet={grid.sheet}>
|
||||
{grids.length > 1 && (
|
||||
<Tabs tabs={grids.map((g) => ({ key: g.sheet, label: g.sheet }))} active={grid.sheet} onChange={setActive}
|
||||
label={RECIPE_TEXT.gridLabel} />
|
||||
)}
|
||||
<div ref={boxRef} className="min-h-0 overflow-auto rounded-lg border bg-bg" style={{ maxHeight: '52vh' }}
|
||||
role="region" aria-label={`${RECIPE_TEXT.gridLabel}:${grid.sheet}`} tabIndex={0}>
|
||||
<table className="border-separate border-spacing-0 text-2xs">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="sticky left-0 top-0 z-20 border-b border-r bg-panel px-1" aria-hidden />
|
||||
{model.cols.map((c) => (
|
||||
<th key={c} scope="col" data-col-header={colLetter(c)}
|
||||
className={clsx('sticky top-0 z-10 border-b border-r bg-panel px-1 font-normal text-faint mono',
|
||||
model.hiddenCols.has(c) && 'opacity-60')}>
|
||||
{colLetter(c)}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{model.rows.map((r) => (
|
||||
<tr key={r}>
|
||||
<th scope="row" data-row-header={r}
|
||||
className={clsx('sticky left-0 z-10 border-b border-r bg-panel px-1 text-right font-normal text-faint tnum',
|
||||
model.hiddenRows.has(r) && 'opacity-60')}>
|
||||
{r}
|
||||
</th>
|
||||
{model.cols.map((c) => {
|
||||
const key = `${r},${c}`
|
||||
if (model.covered.has(key)) return null
|
||||
const name = cellName(r, c)
|
||||
const cell = model.cells.get(key)
|
||||
const role = model.roles.get(key)
|
||||
const span = model.spans.get(key)
|
||||
const hidden = model.hiddenRows.has(r) || model.hiddenCols.has(c)
|
||||
const formula = grid.formulas?.[name]
|
||||
const label = role === 'unclaimed' ? RECIPE_TEXT.unclaimed : role ? LEDGER_ROLE_LABEL[role] : ''
|
||||
const title = cell
|
||||
? [`${name}${label ? ` · ${label}` : ''}${hidden ? ` · ${RECIPE_TEXT.hiddenCells}` : ''}`, cell.text, formula]
|
||||
.filter(Boolean).join('\n')
|
||||
: undefined
|
||||
return (
|
||||
<td key={c} data-cell={name} data-role={role} data-hidden={hidden || undefined}
|
||||
rowSpan={span?.rs} colSpan={span?.cs} title={title}
|
||||
className={clsx(
|
||||
'h-6 max-w-[9rem] truncate border-b border-r px-1.5',
|
||||
cell?.kind === 'number' || cell?.kind?.startsWith('formula') ? 'text-right tnum' : 'text-left',
|
||||
hidden && 'opacity-50',
|
||||
flash === name && 'outline outline-2 outline-[var(--accent)]',
|
||||
)}
|
||||
style={{
|
||||
...roleStyle(role),
|
||||
...(hidden && !role ? { background: 'color-mix(in srgb, var(--st-unreached) 18%, transparent)' } : null),
|
||||
minWidth: span ? undefined : '3.5rem',
|
||||
}}>
|
||||
{cell?.text}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-2xs text-dim" data-grid-legend aria-label={RECIPE_TEXT.legendTitle}>
|
||||
{[...legend.entries()].map(([role, label]) => (
|
||||
<span key={role} className="inline-flex items-center gap-1" data-legend={role}>
|
||||
<span className="inline-block h-2.5 w-2.5 rounded-sm border" style={roleStyle(role)} aria-hidden />
|
||||
{label}
|
||||
</span>
|
||||
))}
|
||||
{hasHidden && (
|
||||
<span className="inline-flex items-center gap-1" data-legend="hidden">
|
||||
<span className="inline-block h-2.5 w-2.5 rounded-sm border opacity-50"
|
||||
style={{ background: 'color-mix(in srgb, var(--st-unreached) 18%, transparent)' }} aria-hidden />
|
||||
{RECIPE_TEXT.hiddenCells}
|
||||
</span>
|
||||
)}
|
||||
{(grid.truncated || totalRows > shownRows) && (
|
||||
<span className="text-faint">{RECIPE_TEXT.gridTruncated(formatNumber(shownRows), formatNumber(totalRows))}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { Lightbulb } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
import type { Card, Question, QuestionAnswer } from '../../types'
|
||||
import { Spinner } from '../../components/ui'
|
||||
import { RECIPE_TEXT } from '../../lib/terms'
|
||||
|
||||
// ===========================================================================
|
||||
// 建议卡片与待确认问题:起草器给的每条建议一句理由、指向网格上的格子;问题只有封闭的选项,
|
||||
// 选了哪一项发给服务端,由服务端按选项改配方(界面自己不改配方)
|
||||
// ===========================================================================
|
||||
|
||||
/** 格子坐标的小按钮:点了网格滚到那一格 */
|
||||
export function CellChips({ cells, onFocus, max = 6 }: { cells?: string[]; onFocus: (cell: string) => void; max?: number }) {
|
||||
if (!cells?.length) return null
|
||||
return (
|
||||
<span className="inline-flex flex-wrap items-center gap-1" data-cells>
|
||||
{cells.slice(0, max).map((c) => (
|
||||
<button key={c} type="button" className="chip mono hover:border-[var(--accent)] hover:text-fg" data-cell-ref={c}
|
||||
onClick={() => onFocus(c)} title={c}>
|
||||
{c.includes('!') ? c.slice(c.lastIndexOf('!') + 1) : c}
|
||||
</button>
|
||||
))}
|
||||
{cells.length > max && <span className="text-2xs text-faint">+{cells.length - max}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个问题:单选,**没有默认选中**(起草器的建议只写在旁边,不替人选)。选需要理由的选项(如「不登记」)
|
||||
* 时先出理由框,写了理由点「提交」才发;普通选项选了就发。已选的按服务端存的回答回显
|
||||
*/
|
||||
function QuestionItem({ q, answer, busy, onAnswer }: {
|
||||
q: Question; answer?: QuestionAnswer; busy: boolean; onAnswer: (qid: string, a: QuestionAnswer) => Promise<boolean>
|
||||
}) {
|
||||
const name = useId()
|
||||
const [pending, setPending] = useState<string | null>(null)
|
||||
const [reason, setReason] = useState(answer?.reason ?? '')
|
||||
// 服务端的回答变了(刷新、改了配方清空了):放下没提交的那一项
|
||||
useEffect(() => { setPending(null); setReason(answer?.reason ?? '') }, [answer?.value, answer?.reason])
|
||||
const chosen = pending ?? answer?.value ?? null
|
||||
const needsReason = q.options.find((o) => o.value === chosen)?.needs_reason
|
||||
const suggested = q.default ? q.options.find((o) => o.value === q.default)?.label : null
|
||||
return (
|
||||
<fieldset className="space-y-1.5 rounded-md border bg-bg px-2.5 py-2" data-question={q.id}>
|
||||
<legend className="px-1 text-xs font-medium">{q.text}</legend>
|
||||
<div role="radiogroup" aria-label={q.text} className="flex flex-wrap gap-x-4 gap-y-1">
|
||||
{q.options.map((o) => (
|
||||
<label key={o.value} className={clsx('inline-flex items-center gap-1.5 text-xs', busy ? 'cursor-wait' : 'cursor-pointer')}
|
||||
data-option={o.value}>
|
||||
<input type="radio" name={name} value={o.value} checked={chosen === o.value} disabled={busy}
|
||||
onChange={() => {
|
||||
// 先按选中画(等服务端回来才勾上,点了像没反应);没发成功就退回服务端存的那一项
|
||||
setPending(o.value)
|
||||
if (o.needs_reason) return
|
||||
void onAnswer(q.id, { value: o.value }).then((ok) => { if (!ok) setPending(null) })
|
||||
}} />
|
||||
{o.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{suggested && !chosen && <p className="text-2xs text-faint" data-question-suggested={q.default}>{RECIPE_TEXT.suggested(suggested)}</p>}
|
||||
{needsReason && (
|
||||
<div className="space-y-1" data-question-reason>
|
||||
<label className="label" htmlFor={`${name}-reason`}>{RECIPE_TEXT.reasonLabel}</label>
|
||||
<div className="flex items-start gap-2">
|
||||
<textarea id={`${name}-reason`} className="field text-xs" rows={2} maxLength={200} value={reason}
|
||||
placeholder={RECIPE_TEXT.reasonPlaceholder} disabled={busy}
|
||||
onChange={(e) => setReason(e.target.value)} />
|
||||
<button type="button" className="btn btn-sm shrink-0" disabled={busy || !reason.trim()}
|
||||
title={!reason.trim() ? RECIPE_TEXT.reasonRequired : undefined}
|
||||
onClick={() => onAnswer(q.id, { value: chosen!, reason: reason.trim() })}>
|
||||
{RECIPE_TEXT.reasonSubmit}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
export function SuggestionCards({ cards, questions, answers, busy, applying = false, onAnswer, onFocusCell }: {
|
||||
cards: Card[]
|
||||
questions: Question[]
|
||||
answers: Record<string, QuestionAnswer>
|
||||
busy: boolean
|
||||
/** 刚选的回答正在服务端应用(重新起草、干跑):大表要等几秒,标出来免得以为没反应 */
|
||||
applying?: boolean
|
||||
/** 返回是否发成功 */
|
||||
onAnswer: (qid: string, a: QuestionAnswer) => Promise<boolean>
|
||||
onFocusCell: (cell: string) => void
|
||||
}) {
|
||||
const byId = new Map(questions.map((q) => [q.id, q]))
|
||||
const linked = new Set(cards.map((c) => c.question).filter(Boolean) as string[])
|
||||
const loose = questions.filter((q) => !linked.has(q.id))
|
||||
return (
|
||||
<div className="space-y-3" data-suggestions>
|
||||
<section className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-xs font-semibold">{RECIPE_TEXT.cardsTitle}</h3>
|
||||
{applying && (
|
||||
<span className="inline-flex items-center gap-1 text-2xs text-faint" role="status" data-answer-applying>
|
||||
<Spinner size={10} /> {RECIPE_TEXT.answering}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{!cards.length && <p className="text-xs text-faint">{RECIPE_TEXT.noCards}</p>}
|
||||
<ol className="space-y-2">
|
||||
{cards.map((c) => {
|
||||
const q = c.question ? byId.get(c.question) : undefined
|
||||
return (
|
||||
<li key={c.id} className="space-y-1.5 rounded-lg border bg-panel px-3 py-2" data-suggestion-card={c.id}>
|
||||
<div className="flex items-start gap-2">
|
||||
<Lightbulb size={12} className="mt-0.5 shrink-0 text-[var(--warn)]" aria-hidden />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs font-medium">{c.title}</div>
|
||||
<p className="mt-0.5 text-2xs leading-relaxed text-dim" data-card-reason>{c.reason}</p>
|
||||
</div>
|
||||
</div>
|
||||
<CellChips cells={c.cells} onFocus={onFocusCell} />
|
||||
{q && <QuestionItem q={q} answer={answers[q.id]} busy={busy} onAnswer={onAnswer} />}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</section>
|
||||
{loose.length > 0 && (
|
||||
<section className="space-y-2">
|
||||
<h3 className="text-xs font-semibold">{RECIPE_TEXT.questionsTitle}</h3>
|
||||
{loose.map((q) => <QuestionItem key={q.id} q={q} answer={answers[q.id]} busy={busy} onAnswer={onAnswer} />)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -234,6 +234,12 @@ export interface DataSource extends ServerHealth {
|
||||
origin?: 'upload' | 'manual' | (string & {})
|
||||
/** 上传表格当前启用的版本。手工登记的源恒为 null */
|
||||
current_snapshot?: CurrentSnapshot | null
|
||||
/** simple 简单导入;recipe 按配方导入;手工登记的源为 null。老后端没有这个字段 */
|
||||
import_mode?: 'simple' | 'recipe' | null
|
||||
/** 按配方导入的源当前启用的配方 */
|
||||
current_recipe?: { id: string; seq: number; origin: string; activated_at: string | null; signed_by: string | null } | null
|
||||
/** 这个源最近一个未结束的导入(按配方导入的暂存区) */
|
||||
open_staging?: { id: string; kind: ImportStagingKind; status: ImportStagingStatus; created_at: string } | null
|
||||
}
|
||||
|
||||
/** 上传表格当前启用的版本(DataSource.current_snapshot) */
|
||||
@@ -331,6 +337,315 @@ export interface UploadResult {
|
||||
tables: UploadedTable[]
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 按配方导入(期 2:/api/datasources/imports/*、/{id}/reupload|redraft|recipe)
|
||||
// 字段与后端 recipe_types.py 的 dataclass 同名;后端多出来的字段界面不认也不报错
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** first 首次导入;reupload 上传新一期;redraft 修改配方(不换文件);switch 从简单导入切换 */
|
||||
export type ImportStagingKind = 'first' | 'reupload' | 'redraft' | 'switch' | (string & {})
|
||||
export type ImportStagingStatus = 'drafting' | 'trialed' | 'rejected' | 'committed' | 'discarded' | 'expired' | (string & {})
|
||||
|
||||
/**
|
||||
* 配方 JSON(agentlab-recipe/2)。结构由服务端的静态校验把关,界面只按已知字段读写,所以这里是宽松类型:
|
||||
* 表单改哪个字段就按路径写哪个字段,整份经 PUT recipe 交给服务端
|
||||
*/
|
||||
export type Recipe = Record<string, any>
|
||||
|
||||
/** 配方静态校验的问题:path 是 JSON Pointer(如 /tables/0/units/客流),message 是整句人话 */
|
||||
export interface RecipeProblem {
|
||||
path: string
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/** structure 结构问题;data_quality 数据质量;confirm 需确认;input 需要录入;recipe 配方不合法 */
|
||||
export type ImportProblemCategory = 'structure' | 'data_quality' | 'confirm' | 'input' | 'recipe' | (string & {})
|
||||
|
||||
/** 干跑、试运行的问题(契约 Problem)。cells 是「工作表!A1」或「工作表!A1:B2」,最多 20 个 */
|
||||
export interface ImportProblem {
|
||||
code: string
|
||||
category: ImportProblemCategory
|
||||
message: string
|
||||
cells?: string[]
|
||||
fix?: string | null
|
||||
}
|
||||
|
||||
export type CheckStatus = 'passed' | 'mismatch' | 'unverifiable' | 'info' | (string & {})
|
||||
|
||||
/** 一条核对的结果(契约 CheckResult)。acceptable:可以写理由接受 */
|
||||
export interface CheckResult {
|
||||
id: string
|
||||
kind: string
|
||||
title: string
|
||||
status: CheckStatus
|
||||
category: 'structure' | 'data_quality' | 'info' | (string & {})
|
||||
checked?: number
|
||||
failed?: number
|
||||
unverifiable?: number
|
||||
sql?: string | null
|
||||
params?: unknown[]
|
||||
details?: string[]
|
||||
cells?: string[]
|
||||
acceptable?: boolean
|
||||
reasons?: Record<string, number>
|
||||
}
|
||||
|
||||
/** 启用前要逐条勾选的一项(契约 ConfirmItem;id 的取值见 P2-SPEC 7.5) */
|
||||
export interface ConfirmItem {
|
||||
id: string
|
||||
label: string
|
||||
detail?: string
|
||||
required?: boolean
|
||||
source?: string
|
||||
}
|
||||
|
||||
/** 上传新一期与上一期相比的一条差异(契约 DiffItem) */
|
||||
export interface DiffItem {
|
||||
kind: string
|
||||
label: string
|
||||
detail?: string
|
||||
requires_confirm?: boolean
|
||||
confirm_id?: string | null
|
||||
}
|
||||
|
||||
/** 建议卡片:一条建议加一句理由,指向网格上的格子 */
|
||||
export interface Card {
|
||||
id: string
|
||||
title: string
|
||||
reason: string
|
||||
cells?: string[]
|
||||
/** 对应的待确认问题(Question.id) */
|
||||
question?: string | null
|
||||
}
|
||||
|
||||
export interface QuestionOption {
|
||||
value: string
|
||||
label: string
|
||||
/** 选它时必须写理由(如「不登记」) */
|
||||
needs_reason?: boolean
|
||||
}
|
||||
|
||||
/** 待确认问题:只有封闭的选项;选项对配方的修改由服务端应用,界面只发选了哪一项 */
|
||||
export interface Question {
|
||||
id: string
|
||||
text: string
|
||||
options: QuestionOption[]
|
||||
default?: string | null
|
||||
}
|
||||
|
||||
/** 已选的回答(StagingOut.answers 的值) */
|
||||
export interface QuestionAnswer {
|
||||
value: string
|
||||
reason?: string | null
|
||||
}
|
||||
|
||||
/** 规则或 AI 起草的结果(契约 Draft,不含给模型看的那份原因) */
|
||||
export interface Draft {
|
||||
recipe: Recipe | null
|
||||
complete: boolean
|
||||
origin: 'rules' | 'ai' | (string & {})
|
||||
cards?: Card[]
|
||||
questions?: Question[]
|
||||
failures?: string[]
|
||||
}
|
||||
|
||||
/** 一次模型调用的用量 */
|
||||
export interface AiUsage {
|
||||
model: string
|
||||
input_tokens: number
|
||||
output_tokens: number
|
||||
cost_usd: number
|
||||
ok: boolean
|
||||
at: string
|
||||
attempt?: number
|
||||
}
|
||||
|
||||
/** 一张可见工作表的原始网格预览 */
|
||||
export interface GridPreview {
|
||||
sheet: string
|
||||
bounds: string | null
|
||||
total_rows?: number
|
||||
total_cols?: number
|
||||
/** 预览只取了前面的部分 */
|
||||
truncated?: boolean
|
||||
rows?: number[]
|
||||
cols?: number[]
|
||||
/** [行, 列, 显示文字, 种类];种类:text / number / date / bool / error / formula / formula_uncached */
|
||||
cells: [number, number, string, string][]
|
||||
/** A1 → 公式原文 */
|
||||
formulas?: Record<string, string>
|
||||
merges?: string[]
|
||||
hidden_rows?: number[]
|
||||
hidden_cols?: number[]
|
||||
}
|
||||
|
||||
/** 格子的去向(契约 Role),按区域给出 */
|
||||
export interface RegionMark {
|
||||
sheet: string
|
||||
role: string
|
||||
ref: string
|
||||
}
|
||||
|
||||
/** 格子账:每张工作表的非空格和各去向的个数 */
|
||||
export interface LedgerSheet {
|
||||
sheet: string
|
||||
nonempty_scan: number
|
||||
nonempty_read: number
|
||||
roles?: Record<string, number>
|
||||
unclaimed?: number
|
||||
}
|
||||
|
||||
export interface ReceiptTable {
|
||||
name: string
|
||||
sheet: string
|
||||
kind: 'data' | 'reported_total' | (string & {})
|
||||
columns: { name: string; type: string; header?: string | null; unit?: string | null; role?: string }[]
|
||||
grain: string[]
|
||||
rows: number
|
||||
sources?: string[]
|
||||
}
|
||||
|
||||
export interface PeriodOut {
|
||||
start: string
|
||||
end: string
|
||||
source: 'cells' | 'human' | (string & {})
|
||||
cells?: string[]
|
||||
signed_by?: string | null
|
||||
texts?: Record<string, string>
|
||||
annotated?: Record<string, string>
|
||||
}
|
||||
|
||||
export interface OutsideText {
|
||||
sheet: string
|
||||
/** 带工作表名的坐标「工作表!A1」(与问题的 cells 同一写法) */
|
||||
cell: string
|
||||
text: string
|
||||
kind: 'text' | 'text_digits' | (string & {})
|
||||
period_source?: boolean
|
||||
}
|
||||
|
||||
/** 试运行回执(Extraction 去掉问题和核对之后给界面看的部分) */
|
||||
export interface TrialReceipt {
|
||||
ledger?: LedgerSheet[]
|
||||
tables?: ReceiptTable[]
|
||||
period?: PeriodOut | null
|
||||
placeholders?: Record<string, number>
|
||||
outside_text?: OutsideText[]
|
||||
canonicalized_total?: number
|
||||
blank_rows_skipped?: number
|
||||
formula_cells_accepted?: number
|
||||
full_calc_on_load?: boolean
|
||||
db_sha256?: string
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
/** passed 通过;needs_input 需要录入统计期;needs_decision 有可接受的核对待写理由;rejected 拒收 */
|
||||
export type TrialStatus = 'passed' | 'needs_input' | 'needs_decision' | 'rejected' | (string & {})
|
||||
|
||||
/** 最近一次试运行(StagingOut.trial) */
|
||||
export interface TrialOut {
|
||||
trial_id: string
|
||||
status: TrialStatus
|
||||
receipt: TrialReceipt
|
||||
problems: ImportProblem[]
|
||||
checks: CheckResult[]
|
||||
confirm_items: ConfirmItem[]
|
||||
/** 可以写理由接受、本次未通过的核对 id */
|
||||
acceptable: string[]
|
||||
/** 表 → 说明预览 */
|
||||
notes?: Record<string, { comment: string; columns?: Record<string, string> }>
|
||||
diff?: DiffItem[] | null
|
||||
same_as_import?: { id: string; seq: number } | null
|
||||
base_snapshot_id?: string | null
|
||||
}
|
||||
|
||||
/** AI 起草的结果摘要 */
|
||||
export interface AiDraftSummary {
|
||||
draft: Draft | null
|
||||
usage?: AiUsage[]
|
||||
attempts?: number
|
||||
total_tokens?: number
|
||||
cost_usd?: number
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
/** 暂存区(一次未提交的按配方导入):GET /imports/{id} 等接口的返回 */
|
||||
export interface Staging {
|
||||
id: string
|
||||
kind: ImportStagingKind
|
||||
status: ImportStagingStatus
|
||||
source: { id: string; name: string; exists: boolean; import_mode: 'simple' | 'recipe' | null }
|
||||
file: { name: string; size: number; sha256_prefix: string }
|
||||
sheets?: {
|
||||
name: string; state: string; bounds: string | null; nonempty: number; merged?: number
|
||||
formulas?: number; formulas_uncached?: number; hidden_rows?: number; hidden_cols?: number
|
||||
}[]
|
||||
skipped_sheets?: { sheet: string; state: string }[]
|
||||
full_calc_on_load?: boolean
|
||||
grids: GridPreview[]
|
||||
draft: Draft | null
|
||||
ai_draft: AiDraftSummary | null
|
||||
/** offered:这次导入提供 AI 起草入口;available:模型接入可用 */
|
||||
ai: { offered: boolean; available: boolean; reason?: string; model?: string; provider?: string }
|
||||
ai_consents?: { signed_by: string | null; at: string; model: string; compressed_sha256: string; chars: number }[]
|
||||
recipe: Recipe | null
|
||||
recipe_origin?: string | null
|
||||
recipe_problems: RecipeProblem[]
|
||||
answers: Record<string, QuestionAnswer>
|
||||
cards: Card[]
|
||||
questions: Question[]
|
||||
draft_problems: ImportProblem[]
|
||||
/** 干跑只检查了每张工作表的前若干行 */
|
||||
draft_partial: boolean
|
||||
/** 分段标题原文 → 常量可选的词 */
|
||||
candidates: Record<string, string[]>
|
||||
/** 单位词表 */
|
||||
units: string[]
|
||||
marks: RegionMark[]
|
||||
trial: TrialOut | null
|
||||
context_inputs?: Record<string, { start: string; end: string; signed_by?: string | null }>
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
expires_at?: string
|
||||
}
|
||||
|
||||
/** GET draft-ai/preview:将要发给模型的压缩表示原文 */
|
||||
export interface AiPreview {
|
||||
text: string
|
||||
chars: number
|
||||
/** 同意令牌:绑定全文、接入名和模型 id,POST draft-ai 原样带回(三者任一变了服务端回 409 ai_preview_stale) */
|
||||
sha256: string
|
||||
/** 全文本身的 sha256(留痕用) */
|
||||
text_sha256?: string
|
||||
model: string
|
||||
provider: string
|
||||
}
|
||||
|
||||
/** POST imports/{id}/commit 的返回 */
|
||||
export interface CommitOut {
|
||||
source: DataSource
|
||||
import_id: string
|
||||
snapshot_id: string
|
||||
build_id: string
|
||||
recipe_id: string
|
||||
build_reused: boolean
|
||||
/** 与某次导入完全相同,未新建版本 */
|
||||
unchanged: boolean
|
||||
}
|
||||
|
||||
/** GET /{source_id}/recipe:当前启用的配方(补全了默认值) */
|
||||
export interface CurrentRecipe {
|
||||
recipe_id: string
|
||||
seq: number
|
||||
origin: string
|
||||
recipe: Recipe
|
||||
recipe_sha256: string
|
||||
confirmations: { id: string; label: string; at: string }[]
|
||||
signed_by: string | null
|
||||
activated_at: string | null
|
||||
}
|
||||
|
||||
/** 自定义工具(GET /api/custom-tools 的一行;POST / PATCH 的返回同形) */
|
||||
export interface CustomTool {
|
||||
id: string
|
||||
|
||||
Reference in New Issue
Block a user