commit c7264cc50d9d77f5534bfc0e7802cc4999cde52a Author: GEEKi Date: Mon Nov 16 18:25:21 2026 +0800 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7656b67 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Whitelist: the repository holds only source code and what the build needs. +# Everything at the root is ignored unless re-included below (logs, backups, +# legacy SQL dumps, extracted images, sample documents, temp output, .vs). +/* +!/.gitignore +!/Leiren.Erp.slnx +!/src/ +!/deploy/ +!/docs/ +!/migration/ + +# Build output and IDE state +bin/ +obj/ +.vs/ +*.user + +# Local runtime data: SQLite databases, uploaded files, scratch output +src/**/data/ +src/**/temp/ +*.db +*.db-shm +*.db-wal +*.log + +# Docs: keep the markdown, not prototype pages +/docs/* +!/docs/*.md diff --git a/Leiren.Erp.slnx b/Leiren.Erp.slnx new file mode 100644 index 0000000..32c6bd9 --- /dev/null +++ b/Leiren.Erp.slnx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/deploy/windows/appsettings.Production.example.json b/deploy/windows/appsettings.Production.example.json new file mode 100644 index 0000000..8cc7d4b --- /dev/null +++ b/deploy/windows/appsettings.Production.example.json @@ -0,0 +1,28 @@ +{ + "Urls": "http://*:5118", + "AllowedHosts": "*", + "Database": { + "Provider": "PostgreSql" + }, + "ConnectionStrings": { + "Default": "Host=127.0.0.1;Port=5432;Database=leiren_erp;Username=leiren_erp;Password=CHANGE_ME_VIA_ENVIRONMENT" + }, + "HealthChecks": { + "DatabaseTimeout": "00:00:05" + }, + "FileStorage": { + "RootPath": "D:\\LeirenErpData\\storage", + "MaxFileSizeBytes": 52428800, + "AllowedExtensions": [ + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".txt", ".csv", ".zip", ".rar", ".7z" + ] + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/deploy/windows/backup.example.json b/deploy/windows/backup.example.json new file mode 100644 index 0000000..867fc3a --- /dev/null +++ b/deploy/windows/backup.example.json @@ -0,0 +1,18 @@ +{ + "Sources": [ + { + "Name": "FileStorage", + "Path": "D:\\LeirenErpData\\storage" + }, + { + "Name": "Templates", + "Path": "D:\\LeirenErpData\\templates" + } + ], + "DestinationPath": "E:\\LeirenErpBackups", + "IncludeDatabase": true, + "DatabaseProvider": "PostgreSql", + "DatabaseConnectionString": "", + "PgDumpPath": "C:\\Program Files\\PostgreSQL\\17\\bin\\pg_dump.exe", + "AllowEmpty": false +} diff --git a/docs/01-总体业务流程设计.md b/docs/01-总体业务流程设计.md new file mode 100644 index 0000000..f1e1430 --- /dev/null +++ b/docs/01-总体业务流程设计.md @@ -0,0 +1,359 @@ +# 简化 ERP 总体业务流程设计 + +## 1. 目标 + +系统服务于小企业内部订单、采购、出货、报关和供应商开票流程。核心原则: + +- 以客户销售订单为主线。 +- 产品资料只维护一次,后续流程自动带出。 +- 每次实际出货形成一个独立的出货批次和单证包。 +- 客户 SKU、客户产品名只属于订单明细,不建立长期客户产品映射。 +- 无独立审核人员,资料采用 `Draft -> Publish` 发布机制。 +- 已生成业务单据保存数据快照,不受后续主档修改影响。 + +## 2. 主流程 + +```text +客户 PO 原文件 + -> 客户订单录入/导入 + -> 订单明细匹配内部货号 + -> 订单确认 + -> 采购拆解 + -> 按供应商生成采购合同 + -> 采购完货并确认实际包装数据 + -> 建立出货批次 + -> 从订单选择本次出货数量 + -> 确认箱数、毛净重、尺寸、CBM、集装箱 + -> 确认报关资料 + -> 生成报关单证包 + -> 按客户模板生成 CI/PL + -> 生成供应商开票通知及购销合同 + -> 登记供应商发票 + -> 转财务 +``` + +## 3. 核心业务对象 + +```text +客户 +供应商 +产品 +销售订单 +销售订单明细 +采购任务 +采购合同 +到货/完货确认 +出货批次 +出货明细 +集装箱 +报关资料 +客户 CI +客户 PL +供应商开票通知 +供应商购销合同 +文件模板 +附件 +操作日志 +``` + +关键关系: + +```text +销售订单明细 + ├── 多个采购任务 + ├── 多个出货批次 + └── 多套生成单据 +``` + +## 4. 客户订单 + +客户提供的文件可能包含客户 PO、客户 SKU、客户英文描述、数量、箱数、价格、交期、装运方式、港口、HS 编码、箱规等信息。 + +订单明细必须同时保存: + +| 字段 | 用途 | +|---|---| +| 内部货号 | 内部采购、订单跟踪和产品识别 | +| 客户 SKU | 原样显示在客户单证中,仅属于当前订单 | +| 客户产品名 Override | 覆盖产品默认英文名,仅属于当前订单 | +| 产品主档英文品名 | 无 Override 时的默认值 | +| 订单数量 | 客户订购数量 | +| 客户单价 | 客户订单/CI 使用 | +| 客户装箱率 | 客户提供的订单数据 | +| 客户备注 | 原始要求 | +| 原始 PO 文件 | 用于核对和追溯 | + +客户单证名称规则: + +```text +订单明细.客户产品名 Override 非空 -> 使用 Override +否则 -> 使用产品主档英文品名 +``` + +客户 SKU 不进入产品主档,不建立客户 SKU 与内部货号的长期映射。 + +## 5. 采购拆解 + +一个销售产品可以整体采购,也可以拆成主体、配件、包装和加工项目,由不同供应商分别完成。 + +采购任务至少保存: + +- 销售订单及订单明细 +- 采购内容 +- 部件或产品 +- 供应商 +- 数量和单位 +- 单价、币种、含税标志、税率 +- 交期 +- 采购要求 +- 包装/质量要求 + +系统可以根据产品 BOM 自动生成采购任务,采购人员可以修改供应商、数量、价格、税率、采购内容,或临时增加采购项目。 + +生成采购任务/采购合同后,价格和关键资料复制为单据快照。 + +## 6. 采购合同 + +采购合同样本中的主要内容: + +- 甲乙方信息 +- 客户订单号 +- 合同编号、签约时间、完货时间 +- 付款条件 +- 客户 SKU、产品描述、材料要求 +- 数量、含税单价、装箱数、金额 +- 合同条款 +- 盖章及签字位置 + +合同生成后不随产品或供应商主档变化。修改合同应生成新版本或作废后重新生成。 + +## 7. 到货与实际包装 + +产品主档中的包装信息只是默认/预计数据。采购完货或出货前必须记录本次实际数据: + +- 已采购数量、已到货数量 +- 实际装箱率、箱数 +- 实际外箱长宽高 +- 实际单箱毛重、净重 +- 实际总毛重、净重、CBM +- 包装照片和异常说明 + +报关单证和客户 PL 应使用本次出货的实际数据。 + +## 8. 出货批次 + +一个销售订单可以拆成多个出货批次。每个批次保存: + +- 批次编号 +- 关联订单和客户 +- 船期、截关日期、ETD、ETA +- 起运港、目的港 +- 货代 +- 集装箱号、柜型、封条号 +- 提单号、船名航次 +- 出货明细 + +出货明细保存: + +- 订单明细和内部货号 +- 客户 SKU、客户产品名 +- 出货数量和单位 +- 箱数 +- 实际外箱尺寸 +- 毛重、净重、CBM +- 客户单价和金额 +- 报关单价和金额 +- HS 编码、报关品名、申报要素 +- 原产国、目的国、境内货源地、征免信息 + +出货批次确认后,关键数据应锁定;如果修改,必须提示会影响哪些已生成单据。 + +## 9. 报关资料 + +报关资料由产品默认资料、订单数据和本次出货数据组成,并在生成前提供确认页面。 + +产品默认资料: + +- HS 编码 +- 中文/英文报关品名 +- 报关单位 +- 申报要素 +- 原产国 +- 境内货源地 +- 包装种类 + +本次出货资料: + +- 报关数量、单位 +- 报关单价、金额、币制 +- 贸易方式、征免性质 +- 箱数、毛净重、CBM +- 集装箱、提单、船名航次 +- 出口日期、申报日期 + +输出: + +- 报关发票 +- 报关装箱单 +- 报关外销合同 +- 报关单录入数据 + +系统生成文件时自行计算合计,不依赖模板中的 Excel 公式,避免 `#REF!` 等错误。 + +## 10. 客户 CI/PL 与占位符模板 + +客户可以自行设计 XLSX 模板,不要求系统预先固定版式。 + +模板中使用双大括号包围占位符,例如: + +```text +{{InvoiceNo}} +{{CustomerName}} +{{CustomerAddress}} +{{CustomerPO}} +{{ProductDescription}} +{{Quantity}} +{{CartonCount}} +{{GrossWeight}} +{{NetWeight}} +{{TotalCBM}} +``` + +模板导入系统后,系统扫描所有工作表和单元格,提取全部 `{{...}}` 内容,显示占位符清单。用户逐项选择该占位符对应的业务字段。 + +系统保存: + +- 模板文件 +- 模板版本 +- 占位符原文 +- 对应业务字段 +- 格式化方式:日期、数字、小数位、币种 +- 是否为明细行字段 + +建议占位符名称由用户自行决定;名称只用于模板显示,真正的数据来源由用户在导入模板后选择。 + +### 模板生成规则 + +- 普通占位符替换为单值,例如 `{{InvoiceNo}}`。 +- 同一个占位符可以在多个单元格重复使用。 +- 一个单元格中可以包含多个占位符。 +- 未配置的占位符禁止生成文件,并显示缺失映射。 +- 明细行占位符放在同一行,系统按出货明细复制该行。 +- 合计字段由系统重新计算,不依赖 Excel 公式。 +- 模板版本和字段映射固定后,历史生成文件不受模板后续修改影响。 + +CI 可能包含: + +- 买卖双方及地址 +- Invoice No.、日期、运输方式 +- 起运地、目的地 +- PO、Item、描述、数量、单价、金额 +- 制造商、材料、付款条款 +- 佣金、货代费用、银行资料 + +PL 可能包含: + +- PO、Item、描述 +- PCS、Cartons +- 毛重、净重 +- 长宽高、CBM +- 集装箱/封条号 +- 总箱数、总毛重、总净重、总 CBM + +## 11. 供应商开票 + +出货确认后,按供应商生成开票资料。一个出货批次可以对应多个供应商开票通知。 + +开票通知包含: + +- 外销发票号 +- 采购合同号 +- 供应商和开票抬头 +- 地址、电话、开户银行、账号、税号、海关代码 +- 品名、数量、规范中文单位 +- 含税单价、含税金额 +- 开票要求、合同/出库单盖章要求 +- 联系人及寄送地址 + +供应商购销合同还包括不含税金额、增值税额、含税金额、质量/技术要求、交货、包装、结算、税务和知识产权条款。 + +发票状态: + +```text +未生成 -> 已通知供应商 -> 等待发票 -> 已收到发票 -> 已交财务 -> 已完成 +``` + +## 12. 单证版本与数据快照 + +单据状态: + +```text +Draft -> Generated -> Confirmed -> Exported + └-> Voided +``` + +以下业务单据生成时必须保存快照: + +- 销售订单 +- 采购任务 +- 采购合同 +- 出货明细 +- 报关资料 +- 客户 CI/PL +- 供应商开票资料 + +修改关键出货数据时,系统提示会影响的文件,并要求重新生成新版本;不直接覆盖已导出的文件。 + +## 13. 多账户与组合权限 + +系统采用“用户 + 权限项”的组合授权模型,不把用户限制为单一角色。 + +每个用户可以独立勾选或分配多个模块和操作权限,例如: + +| 用户 | 可访问模块 | 可执行操作 | +|---|---|---| +| 张三 | 订单、采购 | 查看、新增、修改、确认、导出 | +| 李四 | 订单、出货、客户单证 | 查看、修改、生成、导出 | +| 王五 | 报关 | 查看、修改、确认、生成、导出 | +| 赵六 | 开票、财务 | 查看、修改、登记、导出 | + +权限至少包括: + +- 模块访问:客户、供应商、产品、订单、采购、出货、报关、客户 CI/PL、开票、财务、附件、查询报表、系统设置 +- 操作权限:查看、新增、修改、发布、停用、确认、生成、导出、作废、删除草稿 + +角色或权限组可以作为可选的权限打包工具,例如“采购常用权限”,但角色不是用户授权的唯一来源。用户可以: + +- 直接拥有单项权限 +- 同时加入多个权限组 +- 在权限组基础上追加个人权限 +- 不加入任何权限组而单独配置权限 + +最终有效权限为用户直接权限与所属权限组权限的并集。没有明确授权的模块和操作默认拒绝。管理员也必须通过权限项访问管理模块,不能用代码内置“万能角色”绕过授权。 + +所有关键操作记录操作人、时间、对象、权限来源和前后变化。停用用户后立即禁止登录;权限变化在下一次请求鉴权时生效。 + +## 14. 技术部署 + +- 服务端:ASP.NET Core Web API,.NET 11,Windows Server +- 客户端:WPF,.NET 11,MVVM +- 开发和验收数据库:SQLite,通过 EF Core 访问 +- 生产数据库:PostgreSQL,通过 EF Core 访问 +- 附件和模板:服务器集中存储 +- 客户端通过 API 访问服务端,不直接连接数据库 + +## 15. 第一阶段范围 + +- 用户、角色和权限 +- 客户、供应商、产品资料 +- 产品 BOM、供应商报价 +- 客户订单手工录入和 Excel 导入 +- 采购拆解和采购合同 +- 到货及实际包装确认 +- 出货批次和集装箱装箱 +- 报关资料和报关单证 +- 客户 CI/PL 两类以上模板 +- 供应商开票通知和购销合同 +- 附件、版本、操作日志 + +第一阶段暂不实现复杂总账、供应商门户、自动海关接口、自由报表设计器和完整库存管理。 diff --git a/docs/02-产品与样品库设计.md b/docs/02-产品与样品库设计.md new file mode 100644 index 0000000..8c0bad1 --- /dev/null +++ b/docs/02-产品与样品库设计.md @@ -0,0 +1,374 @@ +# 产品库详细设计 + +## 1. 设计原则 + +- 产品是内部长期主档;客户 SKU 和客户产品名不进入产品主档。 +- 产品资料采用 `Draft -> Publish -> Disabled`,不设置独立审核人。 +- 保存草稿和发布是两个不同操作。 +- 已发布产品编辑时生成新的 Draft 版本,不直接改写历史版本。 +- 产品包装、报关、供应商价格和 BOM 分区维护。 +- 订单、采购合同、出货和报关单据保存产品数据快照。 +- 已使用的资料不能删除,只能停用;未引用的草稿才允许删除。 + +产品和零件统一在产品库维护。本系统不包含产品实物/样品管理:不维护样品编号、版本、类型、来源、数量、存放位置、保管人、借出归还或样品确认等信息,也不建立样品实体、接口或页面。产品图片和确认文件等资料通过产品附件功能管理,与样品无关。 + +## 2. 产品状态 + +```text +Draft + -> Publish +Published + -> Disable +Disabled +``` + +| 状态 | 规则 | +|---|---| +| Draft | 可继续编辑;默认不能进入正式订单、采购和报关流程 | +| Published | 可用于订单、采购、出货和单证 | +| Disabled | 禁止新业务使用,历史业务可查看 | + +### 操作 + +草稿:保存、发布、删除草稿。 + +已发布:编辑新版本、停用、查看历史版本。 + +已停用:查看历史版本;如需恢复,建立新 Draft 后重新 Publish。 + +## 3. 发布检查 + +发布不需要其他人审核,但系统自动检查资料。 + +### 基础发布条件 + +- 内部货号 +- 中文品名 +- 英文品名 +- 产品分类 +- 产品类型 +- 计量单位 + +### 采购使用检查 + +- 至少一个有效供应商,或明确允许采购时临时指定 +- 采购要求已填写,或明确无要求 + +### 出货使用检查 + +- 装箱率 +- 默认外箱长宽高 +- 单箱毛重 +- 单箱净重 + +### 报关使用检查 + +- HS 编码 +- 中文报关品名 +- 英文报关品名 +- 报关单位 +- 申报要素 + +发布失败时显示缺失字段。不同业务阶段按用途检查,不要求创建产品时一次填写全部资料。 + +## 4. 产品主档 + +### 基本资料 + +| 字段 | 说明 | +|---|---| +| 内部货号 | 公司内部唯一编号;支持手工输入,必须唯一 | +| 中文品名 | 内部中文名称 | +| 英文品名 | 默认英文名称;客户单证可被订单 Override 覆盖 | +| 产品分类 | 玩具、包装、配件等 | +| 产品类型 | 成品、部件、包装材料、其他 | +| 计量单位 | PCS、SET、BOX、KG 等 | +| 产品尺寸 | 长、宽、高和单位 | +| 产品描述 | 内部综合说明 | +| 采购要求 | 给采购和工厂看的要求 | +| 质量要求 | 验货和质量控制要求 | +| 默认产地 | 默认中国或具体地区 | +| 备注 | 其他说明 | + +产品不保存客户 SKU、客户产品名或客户长期映射关系。 + +## 5. 产品包装资料 + +产品包装资料是默认/预估资料,实际订单和出货可以覆盖。 + +### 单品包装 + +- 单品长、宽、高及单位 +- 单品净重、毛重 +- 单品包装方式 + +### 外箱包装 + +- 装箱率 +- 外箱长、宽、高及单位 +- 单箱净重、毛重 +- 外箱材质 +- 外箱包装说明 +- 默认箱数计算方式 + +默认计算: + +```text +预计箱数 = 向上取整(订单数量 / 装箱率) +单箱 CBM = 长 × 宽 × 高 / 1,000,000 +预计总 CBM = 预计箱数 × 单箱 CBM +预计总毛重 = 预计箱数 × 单箱毛重 +预计总净重 = 预计箱数 × 单箱净重 +``` + +### 包装方案 + +一个产品允许多个包装方案,例如普通出口箱、半托包装、客户指定包装。产品设置默认方案;订单选择方案时复制为订单包装快照。 + +## 6. 报关资料 + +报关资料独立于基本资料维护: + +- HS 编码 +- 中文报关品名 +- 英文报关品名 +- 报关单位 +- 申报要素 +- 原产国 +- 境内货源地 +- 征免性质默认值 +- 包装种类 +- 监管条件 +- 检验检疫类别 +- 报关备注 + +第一版的申报要素可以保存为多行文本,同时保留原始文本。后续如需要标准化,再拆为材质、用途、品牌、型号等字段。 + +HS 编码、报关品名和申报要素应保留修改历史。已用于历史报关的版本不能被当前资料覆盖。 + +## 7. 产品、零件、供应商与价格 + +产品库必须保存产品与供应商的完整关系,不把供应商只放在采购单中。 + +关系模型: + +```text +产品 + ├── 供应商 A ── 多个历史报价 + ├── 供应商 B ── 多个历史报价 + └── BOM 零件 + ├── 零件 1 ── 供应商 C、供应商 D ── 各自报价 + └── 零件 2 ── 供应商 E ── 多个历史报价 +``` + +一个产品可以: + +- 由一个供应商整体供货 +- 由多个供应商分别供货 +- 由主体、配件、包装和加工项目组成 +- 某个零件由一个或多个供应商供货 +- 每个供应商使用不同的产品/零件货号、要求、交期和报价 + +### 产品或零件供应商关系 + +每条关系至少保存: + +- 产品或零件 +- 供应商 +- 供应商产品名称 +- 供应商产品货号 +- 采购内容类型:成品、主体、配件、包装、加工 +- 是否默认供应商 +- 供应商要求 +- 最小采购量 +- 交期 +- 启用状态 + +独立管理的零件应建立独立产品主档。这样该零件可以被多个成品复用,并且在零件自身的产品页面维护多个供应商和报价。 + +### 供应商价格 + +同一产品/零件与同一供应商允许存在多个价格版本: + +- 单价 +- 币种 +- 计价单位 +- 含税/未税 +- 税率:0%、3%、6%、9%、13% 等 +- 最小起订量 +- 生效日期 +- 失效日期 +- 价格备注 + +价格必须保留历史。生成采购任务或采购合同时,复制当时生效的供应商关系和价格快照,后续价格变化不影响已生成单据。 + +## 8. 产品 BOM/配件 + +一个产品可以没有 BOM,也可以包含主体、配件、包装和加工项目。 + +BOM 明细字段: + +- 主产品 +- 部件名称 +- 部件类型:主体、配件、包装、加工 +- 部件内部货号,可为空 +- 每套用量 +- 计量单位 +- 默认供应商,可为空 +- 采购要求 +- 是否必须 +- 显示/合同排序 +- 启用状态 + +需要独立采购、报价、复用或独立管理的部件建立独立产品,例如说明书、彩盒、外箱、桌垫。只属于单个产品的简单要求可直接写在 BOM 明细中。 + +BOM 可以自动生成采购任务,但采购人员必须能够修改、删除某一拆解项或临时新增采购项目。 + +## 9. 产品图片和附件 + +一个产品支持多个附件: + +- 产品正面图 +- 包装图、彩盒图、外箱图 +- 结构图、设计稿、规格书 +- 检验报告 +- 客户确认文件 +- 供应商报价文件 + +附件元数据: + +- 文件名、类型、用途 +- 上传人、上传时间 +- 当前版本标记 +- 备注 + +产品详情页显示第一张图片作为封面,所有附件集中管理。 + +## 10. 产品版本 + +已发布产品编辑时,不直接修改当前版本,而是建立新的 Draft: + +```text +产品 P-001 + ├── V1 Published + └── V2 Draft +``` + +V2 发布前: + +- 新订单继续使用 V1 +- V2 可继续编辑 + +V2 发布后: + +- 新订单使用 V2 +- 已有订单继续使用订单创建/确认时的快照 +- V1 保留为历史版本 + +界面不要求用户理解复杂版本模型,只显示当前版本、状态、编辑新版本和历史版本。 + +## 11. 修改日志 + +记录: + +- 修改字段 +- 修改前值 +- 修改后值 +- 修改人 +- 修改时间 +- 修改原因 + +以下关键字段修改建议要求填写原因: + +- HS 编码 +- 报关品名 +- 报关单位 +- 装箱率 +- 外箱尺寸 +- 毛重、净重 +- 默认供应商 + +## 12. 页面设计 + +### 产品列表 + +显示:状态、内部货号、中文品名、英文品名、分类、默认供应商、HS 编码。 + +筛选:货号、名称、分类、状态、供应商、HS 编码、资料完整度。 + +操作:新增产品、批量导入、导出、查看停用产品、资料完整性检查。 + +### 产品详情 + +标签页: + +```text +基本资料 +包装资料 +采购供应商 +配件/BOM +报关资料 +图片/附件 +修改记录 +``` + +产品详情不包含产品实物/样品管理;本系统不提供样品登记、借出、归还或确认功能。 + +## 13. 建议数据结构 + +```text +Product + ProductId, InternalCode, ChineseName, EnglishName, + CategoryId, ProductType, UnitId, Status, + CurrentVersionId, PurchaseRequirement, QualityRequirement, Remark + +ProductVersion + ProductId, VersionNo, Status, PublishedAt, PublishedBy, + EffectiveFrom, EffectiveTo + +ProductPackaging + ProductVersionId, SchemeName, PackingRate, + CartonLength, CartonWidth, CartonHeight, DimensionUnit, + CartonGrossWeight, CartonNetWeight, IsDefault + +ProductCustoms + ProductVersionId, HsCode, CustomsChineseName, + CustomsEnglishName, CustomsUnit, DeclarationElements, + Origin, SourceArea, PackagingType + +ProductSupplier + ProductVersionId, SupplierId, SupplierProductCode, + SupplierProductName, PurchaseType, IsDefault, + Requirement, MinimumQuantity, LeadDays, Status + +ProductSupplierPrice + ProductSupplierId, Currency, UnitPrice, PricingUnit, + TaxIncluded, TaxRate, EffectiveFrom, EffectiveTo, Remark + +ProductBomItem + ProductVersionId, ComponentProductId, ComponentName, + ComponentType, QuantityPerProduct, UnitId, + Requirement, IsRequired, SortOrder, Status + +``` + +产品零件如果建立为独立产品,则通过该零件自己的 `ProductSupplier` 和 `ProductSupplierPrice` 维护多个供应商及报价。BOM 只保存零件组成关系,不把供应商限制为一个。 + +图片、附件、操作日志使用统一附件和审计表。 + +## 14. 第一版范围 + +第一版实现: + +1. 产品基本资料 +2. 产品包装方案 +3. 报关资料 +4. 供应商和历史价格 +5. 产品 BOM/配件及零件供应商 +6. 产品图片和附件 +7. 产品 Draft/Publish/Disabled +8. 产品版本和修改日志 +9. 资料完整性检查 +10. 产品批量导入/导出 + +第一版暂不实现完整仓库库存、条码扫描、供应商门户、自动图片识别和复杂审批流。 diff --git a/docs/03-数据库迁移与导入设计.md b/docs/03-数据库迁移与导入设计.md new file mode 100644 index 0000000..8f9ce3a --- /dev/null +++ b/docs/03-数据库迁移与导入设计.md @@ -0,0 +1,418 @@ +# 数据库迁移与导入设计 + +## 1. 数据源范围 + +旧 ERP 数据提取只使用仓库中的 UTF-16 SQL 导出文件: + +```text +bak/ps_tr.sql +bak/ps_tr_mail.sql +bak/ps_tr_pic.sql +``` + +这些文件包含 `CREATE TABLE`、字段定义和 `INSERT` 数据。迁移程序直接解析 SQL 文件,不恢复 `.bak`,不连接旧 SQL Server,也不把 `.bak` 作为后续步骤。 + +`.bak` 文件不属于本次数据提取路径。它们只作为原始备份文件保留,不在开发、迁移、验收或上线流程中使用。 + +从 SQL 文件已经识别出与本 ERP 流程直接相关的旧表: + +| 旧表 | 初步业务含义 | 已观察到的字段/关系 | +|---|---|---| +| `yp_hh` | 产品货号主档 | `ypid`、`hh`、中文/英文品名、单位、产品尺寸、装箱率、外箱尺寸、毛净重、报关字段 | +| `khxx` | 客户 | 客户编号、中文/英文名称、附件/图片字段 | +| `gysxx` | 供应商 | 供应商编号、名称、地址、联系人、银行/税务及附件字段 | +| `order_main` | 客户订单主表 | 订单 ID、客户、合同号、PO、订单日期、交期、币种、装运信息 | +| `order_hh` | 客户订单明细 | 订单 ID、产品 ID、数量、单价、金额、箱规、装箱数、尺寸及交期字段 | +| `maker_order_main/detail` | 供应商采购合同及明细 | 供应商、合同号、交期、币种、数量、单价、金额、包装和要求字段 | +| `invoice/invoice_detail` | 出货/报关发票及明细 | 客户、发票号、箱数、毛重、CBM、产品、数量、报关数量和金额字段 | +| `yp_zj`、`yp_jg`、`yp_glgx` | 产品部件/加工/关联关系候选表 | 产品与部件、加工项目、关系数量及要求字段 | +| `Documents`、`relate_files_data` | 文件元数据/附件候选表 | 文件编号、名称、业务对象、类型、哈希/内容关联字段 | + +历史产品图片核查结论(`ps_tr_pic.sql` 实测):该文件 95 张表只有 7 张有 INSERT;业务图片表自身的图片列无真实字节(`yp_pic_hh.pic`/`clzb_pic.pic` 为 `NULL`,`html_attach_data.filedata`/`relate_files_data.file_image` 为空 `0x`)。真实字节在 `blob_hash.hash_blob`(17 行、1,830,748 字节、6 PNG + 11 JPEG,`file_type` 全为 `NULL`,已验证 `hash_value` = `hash_blob` 的 SHA-1)。产品图片经 `yp_pic_hh.ypid -> yp_hh.ypid`、`yp_pic_hh.hash_value -> blob_hash.hash_value` 关联,5 行全部命中(4 个不同哈希),可真实导入;`execute` 已按此导入为 `product` 的 `product-photo` 附件(文件写入服务器文件存储、数据库只存 `FileAttachment` 元数据),无法恢复的行逐行进入迁移错误报告,不臆造图片。详见 `migration/README.md`「历史产品图片」。 + +## 2. SQL 文件解析范围 + +解析器必须支持: + +1. UTF-16 SQL 文件读取。 +2. `CREATE TABLE` 字段定义解析。 +3. `INSERT [dbo].[table] ([column...]) VALUES (...)` 解析。 +4. `N'中文字符串'`、普通字符串、`NULL`、数字和 `CAST(...)`。 +5. SQL 字符串中的换行、逗号和单引号转义。 +6. `GO` 批次分隔。 +7. `SET IDENTITY_INSERT`,但不依赖其执行。 +8. 大文件逐行或分块解析,不把全部文件复制成多个内存副本。 + +解析结果必须保留: + +- 源文件 +- 源表 +- 源列 +- 源主键或候选主键 +- 原始值 +- 转换后的标准值 +- 解析错误位置 + +静态脚本中已经能看到真实业务字段,例如产品的 `ypid/hh/pm/pm_e/dw/box_i/box_m/box_o`,订单的 `ddid/khid/po`,订单明细的 `ypid/sl/dj/je`,采购合同明细的 `gysid/sl/dj/je`,以及发票明细的 `invoice_id/qty/ctns/cbm`。 + +## 3. 数据库选型 + +新 ERP 使用 EF Core: + +- 开发和实际交互验收使用 SQLite。 +- 生产使用 PostgreSQL。 +- 业务代码只依赖 EF Core 和通用关系模型。 +- 迁移解析器先写入 SQLite 做验证,再写入生产 PostgreSQL。 +- 不使用 PostgreSQL 专用 SQL。 +- 申报要素、模板参数和旧字段使用文本或 EF Core 可兼容的 JSON 字符串。 +- 附件不放数据库大字段,使用服务器文件存储,数据库保存元数据。 + +MongoDB 不作为主业务库。 + +## 4. 新系统数据库边界 + +新数据库只承载新 ERP 的有效业务模型,旧 SQL 文件先进入 `legacy` 导入区,再经过映射写入正式表: + +```text +legacy_* 原始导入区,保留源文件、源表、源主键、原始值 +core_* 客户、供应商、产品、用户等主数据 +sales_* 客户订单及明细 +purchase_* 采购拆解、采购合同、到货 +shipping_* 出货批次、集装箱、出货明细 +customs_* 报关数据 +billing_* 供应商开票通知和发票状态 +document_* 文件、模板和生成版本 +audit_* 操作日志和迁移日志 +``` + +导入程序不得直接把旧表写入正式业务表。所有数据必须通过 `source_file + source_table + source_key` 追溯回来源。 + + +## 5. 建议正式表 + +### 5.1 基础资料 + +```text +core_company +core_user +core_role +core_user_role +core_customer +core_supplier +core_product +core_product_version +core_product_packaging +core_product_customs +core_product_supplier +core_product_supplier_price +core_product_bom_item +core_category +core_unit +``` + +### 5.2 订单与采购 + +```text +sales_order +sales_order_line +sales_order_line_packaging_snapshot +purchase_task +purchase_task_line +purchase_contract +purchase_contract_version +purchase_receipt +purchase_receipt_line +``` + +### 5.3 出货与报关 + +```text +shipping_batch +shipping_container +shipping_line +shipping_line_packaging_snapshot +customs_declaration +customs_declaration_line +``` + +### 5.4 单证与开票 + +```text +document_template +document_template_version +document_file +document_generation +document_generation_item +billing_notice +billing_notice_line +supplier_invoice +``` + +### 5.5 附件和迁移 + +```text +file_attachment +audit_log +legacy_source_record +legacy_id_map +migration_run +migration_error +``` + +## 6. 核心表关键字段 + +以下字段定义使用逻辑类型,实际由 EF Core provider 映射:`uuid` 映射为 `Guid`,`datetime` 映射为 UTC 时间,`json_text` 映射为字符串。为保证 SQLite 开发环境可运行,正式表不依赖 PostgreSQL 专用类型。 + +### `core_product` + +```text +id uuid primary key +internal_code varchar(100) unique not null +status varchar(20) not null -- draft/published/disabled +current_version_id uuid null +created_at timestamptz not null +created_by uuid not null +``` + +### `core_product_version` + +```text +id uuid primary key +product_id uuid not null +version_no integer not null +status varchar(20) not null -- draft/published/disabled +chinese_name varchar(300) not null +english_name varchar(500) not null +category_id uuid null +product_type varchar(30) not null +unit_code varchar(30) not null +product_size jsonb null +purchase_requirement text null +quality_requirement text null +remark text null +published_at timestamptz null +published_by uuid null +unique(product_id, version_no) +``` + +### `core_product_packaging` + +```text +id uuid primary key +product_version_id uuid not null +scheme_name varchar(100) not null +is_default boolean not null default false +packing_rate numeric(18,6) null +carton_length numeric(18,6) null +carton_width numeric(18,6) null +carton_height numeric(18,6) null +dimension_unit varchar(20) null +carton_gross_weight numeric(18,6) null +carton_net_weight numeric(18,6) null +weight_unit varchar(20) null +packaging_note text null +``` + +### `core_product_customs` + +```text +id uuid primary key +product_version_id uuid not null +hs_code varchar(30) null +customs_chinese_name varchar(300) null +customs_english_name varchar(500) null +customs_unit varchar(30) null +declaration_elements text null +origin_country varchar(100) null +source_area varchar(200) null +packaging_type varchar(100) null +extra jsonb null +``` + +### `sales_order` 和 `sales_order_line` + +订单明细中保留客户字段,不建立客户 SKU 主数据: + +```text +sales_order +------------ +id uuid primary key +order_no varchar(100) unique not null +customer_id uuid not null +customer_po_no varchar(200) null +order_date date null +delivery_date date null +currency_code varchar(10) null +status varchar(30) not null +original_file_id uuid null + +sales_order_line +---------------- +id uuid primary key +sales_order_id uuid not null +line_no integer not null +product_id uuid not null +product_version_id uuid not null +customer_sku varchar(200) null +customer_product_name_override varchar(500) null +quantity numeric(18,6) not null +unit_code varchar(30) not null +customer_unit_price numeric(18,6) null +customer_amount numeric(18,6) null +customer_packing_rate numeric(18,6) null +customer_requirement text null +product_snapshot jsonb not null +unique(sales_order_id, line_no) +``` + +`product_snapshot` 保存订单生成时的产品名称、包装和报关默认值;客户 SKU 和 Override 直接保存在订单明细。 + +### `shipping_line` + +```text +id uuid primary key +shipping_batch_id uuid not null +sales_order_line_id uuid not null +quantity numeric(18,6) not null +unit_code varchar(30) not null +carton_count numeric(18,6) null +gross_weight numeric(18,6) null +net_weight numeric(18,6) null +carton_length numeric(18,6) null +carton_width numeric(18,6) null +carton_height numeric(18,6) null +cbm numeric(18,6) null +customer_unit_price numeric(18,6) null +customer_amount numeric(18,6) null +customs_unit_price numeric(18,6) null +customs_amount numeric(18,6) null +customs_snapshot jsonb not null +``` + +### `legacy_source_record` 和 `legacy_id_map` + +```text +legacy_source_record +-------------------- +id bigserial primary key +migration_run_id uuid not null +source_database varchar(128) not null +source_schema varchar(128) not null +source_table varchar(128) not null +source_key varchar(500) not null +source_payload jsonb not null +source_hash char(64) not null +unique(source_database, source_schema, source_table, source_key) + +legacy_id_map +------------- +id bigserial primary key +source_record_id bigint not null +source_entity varchar(100) not null +target_id uuid not null +unique(source_record_id, source_entity) +``` + +## 7. 导入程序设计 + +建立独立的 `.NET 11` 控制台工具: + +```text +src/ + Erp.Migration.Cli/ + Erp.Migration.SqlFile/ + Erp.Migration.Mapping/ + Erp.Migration.EfCore/ + Erp.Migration.Reporting/ +``` + +职责: + +- `SqlFile`:流式读取 UTF-16 SQL 文件,解析表结构和 INSERT 数据。 +- `Mapping`:把旧表行映射到标准中间模型。 +- `EfCore`:使用 EF Core 写入 SQLite 或 PostgreSQL。 +- `Reporting`:生成读取数、成功数、跳过数、错误数和未映射报告。 +- `Cli`:控制源文件、批次、目标数据库和 dry-run。 + +建议使用: + +- `System.IO` 流式读取大文件。 +- `System.Text.Json` 保存原始行和扩展字段。 +- EF Core SQLite provider 写入开发/验收数据库。 +- EF Core PostgreSQL provider 写入生产数据库。 +- `CsvHelper` 或 JSON 输出报告。 + +## 8. 导入阶段 + +```text +0. 检查源 SQL 文件和目标数据库 +1. 解析 CREATE TABLE 和 INSERT +2. 保存原始行到 legacy_source_record +3. 清洗字符串、日期、金额、单位和空值 +4. 建立源文件/表/主键到新 UUID 的映射 +5. 导入客户、供应商、分类、单位 +6. 导入产品和产品版本 +7. 导入供应商价格及 BOM +8. 导入订单和订单明细 +9. 导入采购、出货、报关、附件 +10. 运行一致性检查 +11. 输出迁移报告 +12. 使用 SQLite 完成真实交互抽样 +13. 生产切换时使用同一批次导入 PostgreSQL +``` + +## 9. 映射规则 + +实际旧表结构确认前,不写死字段名。映射采用配置文件: + +```yaml +source: + database: ps_tr + table: legacy_table_name + key: old_id +mapping: + internal_code: [product_code, item_no, art_no] + chinese_name: [cn_name, product_name_cn] + english_name: [en_name, product_name_en, description] + quantity: [qty, quantity, amount] +transform: + trim_strings: true + empty_to_null: true + date_system: excel_serial_if_numeric +``` + +一个旧字段映射多个候选列时,按优先级读取第一个非空值,并在报告中记录来源列。 + +## 10. 幂等、错误和数据安全 + +- 每次导入有 `migration_run` 编号。 +- 原始行使用源库、表、主键唯一约束,重复执行不重复导入。 +- 清洗失败的行写入 `migration_error`,不静默跳过。 +- 金额使用 `numeric`,不使用浮点类型。 +- 日期明确记录时区和来源格式。 +- 导入程序不删除目标数据,修正采用新批次或显式回滚。 +- 默认 dry-run,只生成报告,不写正式业务表。 +- 数据库密码只从环境变量或 Windows Credential Manager 读取。 +- 原始附件和敏感客户数据不进入 Git。 + +## 11. 必须验证的业务规则 + +导入完成后检查: + +- 订单号是否唯一。 +- 订单明细数量是否非负。 +- 采购数量、到货数量、出货数量关系是否合理。 +- 供应商、客户和产品引用是否存在。 +- 产品货号、客户订单号、采购合同号是否有重复。 +- 金额是否满足数量 × 单价,允许记录原始金额和差异。 +- 出货总箱数、毛重、净重、CBM 是否与单证原数据一致。 +- 图片和邮件是否能关联到原业务记录。 +- 无法映射的旧表和字段是否有报告。 + +## 12. 当前结论 + +旧 ERP 数据提取路径已经确定为三个 UTF-16 SQL 文件。迁移程序直接解析 `CREATE TABLE` 和 `INSERT`,不恢复 `.bak`,不连接旧 SQL Server。 + +SQL 文件中的 `INSERT` 语句计数为:`yp_hh` 110、`khxx` 5、`gysxx` 25、`order_main` 3、`order_hh` 1、`maker_order_main` 5、`maker_order_hh` 5、`invoice` 1、`invoice_detail` 1。该数字是 INSERT 语句数,不等于最终可靠行数;解析器必须以实际解析结果和错误报告为准。 + +SQLite 用于开发和真实交互抽样,生产数据导入使用 PostgreSQL。`.bak` 不属于本项目的数据提取、迁移、验收或上线流程。 diff --git a/docs/04-系统架构与技术设计.md b/docs/04-系统架构与技术设计.md new file mode 100644 index 0000000..756b1d6 --- /dev/null +++ b/docs/04-系统架构与技术设计.md @@ -0,0 +1,810 @@ +# ERP 系统架构与技术设计 + +## 1. 设计目标 + +系统面向小企业内部 Windows 局域网使用,核心目标: + +- 客户端简单、页面少、按待办推动流程。 +- 所有业务数据集中在服务器,客户端不直接连接数据库。 +- 订单、采购、出货、报关和开票共享同一套数据。 +- 单证从统一业务数据生成,避免手工复制造成不一致。 +- 支持多账户和按用户组合配置的模块/操作权限、操作日志和附件。 +- 开发和验收默认使用 SQLite;生产部署使用 PostgreSQL,业务代码通过 EF Core 保持两者兼容。 +- 先做模块化单体,不提前拆分微服务。 + +## 2. 总体架构 + +```text ++-------------------+ HTTPS/HTTP +-------------------------+ +| WPF 客户端 | <--------------------> | ASP.NET Core API | +| 业务/采购/报关/财务 | | .NET 11 | ++-------------------+ +-----------+-------------+ + | + +------------------------------+------------------+ + | | + +-------v--------+ +-------v--------+ + | EF Core 数据访问 | | 文件存储 | + | SQLite 开发/验收 | | 附件/模板/导出 | + | PostgreSQL 生产 | | | +``` + +服务端操作系统不作为业务代码依赖。初始部署可以使用 Windows Server,后续可以迁移到 Linux: + +- ERP API:Windows Service 或 Linux `systemd` 服务 +- PostgreSQL:生产环境 Windows 服务或独立数据库服务器 +- SQLite:开发、实际交互验收和迁移 dry-run +- 文件目录:服务器本地磁盘、NAS 或兼容对象存储 +- WPF 客户端:Windows 客户端电脑 + +客户端只访问 API,不允许直接访问数据库。 + +## 3. 采用模块化单体 + +第一版采用一个 API 进程和一个数据库,不拆分微服务。 + +原因: + +- 团队规模小,部署简单。 +- 订单到单证的事务边界集中。 +- 不需要消息队列、服务发现和分布式事务。 +- 后续可以按模块拆分,但现在不为未来复杂度付成本。 + +模块边界: + +```text +Identity 用户、角色、权限、登录 +- Catalog 产品、包装、报关、供应商价格和 BOM +Sales 客户订单、订单明细、客户 PO 附件 +Purchase 采购拆解、采购合同、到货/完货 +Shipping 出货批次、集装箱、装箱明细 +Customs 报关资料和报关单证 +Documents 模板、字段映射、文件生成、版本 +Billing 供应商开票通知、发票登记 +Files 附件、文件版本、下载权限 +Audit 操作日志、数据变更、迁移记录 +``` + +模块之间通过应用服务调用,不直接互相修改数据库表。跨模块操作使用明确的命令,例如: + +```text +ConfirmSalesOrder +CreatePurchaseTasks +ConfirmPurchaseCompletion +CreateShippingBatch +ConfirmShippingBatch +GenerateCustomsDocuments +GenerateCustomerDocuments +CreateBillingNotices +``` + +## 4. 后端项目结构 + +建议解决方案: + +```text +src/ + Leiren.Erp.Api/ + Controllers/ + Middleware/ + Program.cs + + Leiren.Erp.Application/ + Identity/ + MasterData/ + Catalog/ + Sales/ + Purchase/ + Shipping/ + Customs/ + Documents/ + Billing/ + Files/ + Audit/ + Common/ + + Leiren.Erp.Domain/ + Entities/ + ValueObjects/ + Enums/ + Rules/ + + Leiren.Erp.Infrastructure/ + Persistence/ + Authentication/ + FileStorage/ + DocumentGeneration/ + BackgroundJobs/ + Logging/ + + Leiren.Erp.Contracts/ + Requests/ + Responses/ + Enums/ + + Leiren.Erp.Migration/ + SqlServer/ + Mapping/ + Postgres/ + Reporting/ +``` + +### 各层职责 + +#### `Domain` + +保存实体、状态、值对象和业务不变量。不得依赖数据库、HTTP 或 WPF。 + +#### `Application` + +实现用例和事务边界。负责权限检查、状态迁移、快照生成和领域规则调用。 + +#### `Infrastructure` +实现 EF Core 数据访问、文件系统、模板生成、日志和后台任务。 + +#### `Contracts` + +保存 API 请求/响应模型。禁止直接把 EF Core 实体作为 API 返回值。 + +#### `Api` + +只负责 HTTP、认证、异常转换、参数验证和 OpenAPI。 + +#### `Migration` +独立命令行程序,不加载 WPF 和业务 UI。流式读取 UTF-16 SQL 文件,使用 EF Core 写入 SQLite 或 PostgreSQL。 + +## 5. 客户端项目结构 + +```text +src/ + Leiren.Erp.Client/ + App.xaml + Shell/ + Login/ + Dashboard/ + Sales/ + Purchase/ + Shipping/ + Customs/ + Billing/ + Catalog/ + Settings/ + Shared/ + + Leiren.Erp.Client.Infrastructure/ + ApiClient/ + Authentication/ + LocalSettings/ + FileDownload/ +``` + +客户端技术: + +- WPF +- MVVM +- `CommunityToolkit.Mvvm` +- `HttpClientFactory` +- `System.Text.Json` +- 本地不保存业务数据库 + +页面设计: + +- 左侧模块导航。 +- 首页显示当前用户待办和异常。 +- 列表页统一筛选、分页、导出。 +- 详情页使用标签页减少一次性字段数量。 +- 保存和发布按钮明确分开。 +- 生成文件后显示文件版本、生成时间和生成者。 + +### 客户端壳原型 + +快速原型位于 `docs/client-shell.html`,用于锁定 WPF 的页面结构、导航名称和信息层级,不作为生产前端代码。 + +WPF 必须按原型实现以下固定结构: + +```text +主窗口 +├── 左侧导航 +│ ├── 首页 +│ ├── 客户订单 +│ ├── 采购 +│ ├── 出货 +│ ├── 报关与单证 +│ ├── 供应商开票 +│ ├── 产品库 +│ ├── 客户 +│ ├── 供应商 +│ ├── 附件 +│ └── 系统设置 +├── 顶部用户区 +└── 内容区 + ├── 页面标题 + ├── 操作按钮 + ├── 数据卡片或筛选栏 + └── 列表/详情 +``` + +前端实现规则: + +- 只显示当前用户有权限的导航项和按钮。 +- 页面标题直接说明当前功能,不写欢迎语、解释性长句或营销文案。 +- 数据卡片只展示可操作的数量,不放装饰性插图。 +- 列表优先显示业务编号、客户/供应商、日期、状态和负责人。 +- 详情页使用固定标签页;字段按业务录入顺序排列。 +- 所有保存、确认、生成、导出按钮放在页面右上角或表格上方。 +- 危险操作使用“作废”“停用”等明确文字,不使用仅靠颜色表达的图标。 +- 无数据时显示“暂无数据”和下一步操作,不显示无意义说明。 +- 禁止在生产界面保留原型占位数据、演示数字和无实际用途的提示条。 + +前端验收: + +1. 登录一个只有采购权限的用户,导航中不出现报关、财务和系统管理入口。 +2. 打开订单列表,能完成搜索、筛选、打开详情和返回列表。 +3. 在详情页完成保存、确认和生成文件,按钮状态与服务端结果一致。 +4. 列表、详情、错误提示和确认对话框不包含欢迎语、营销文案或装饰性说明。 + +## 6. API 设计 + +采用 REST API,写操作使用命令式端点,避免客户端直接修改状态字段。 + +示例: + +```text +POST /api/auth/login +POST /api/auth/refresh +POST /api/auth/logout + +GET /api/products +POST /api/products/drafts +PUT /api/products/{id}/draft +POST /api/products/{id}/publish +POST /api/products/{id}/disable + +GET /api/sales-orders +POST /api/sales-orders +POST /api/sales-orders/{id}/confirm + +POST /api/sales-orders/{id}/purchase-tasks +POST /api/shipping-batches +POST /api/shipping-batches/{id}/confirm +POST /api/shipping-batches/{id}/documents/generate + +GET /api/files/{id}/download +POST /api/files +``` + +写操作返回: + +```json +{ + "id": "uuid", + "status": "published", + "version": 3, + "updatedAt": "2026-11-13T10:00:00Z" +} +``` + +错误统一使用 RFC 7807 Problem Details,包含: + +- `type` +- `title` +- `status` +- `code` +- `detail` +- `traceId` +- 字段级验证错误 + +列表接口统一支持: + +```text +page +pageSize +sort +search +filters +``` + +禁止返回无限制全表数据。 + +## 7. 认证与授权 + +### 登录 + +- 用户名 + 密码。 +- 密码只保存不可逆哈希,不保存明文。 +- 默认使用 ASP.NET Core 的安全密码哈希器;生产环境可升级为 Argon2id。 +- 连续失败次数和锁定时间写入登录审计。 + +### Token + +推荐: + +- 短期 access token,约 30 分钟。 +- 长期 refresh token,服务端保存哈希,支持撤销。 +- 客户端只保存在 Windows Credential Manager,不写普通配置文件。 + +局域网部署也建议使用 HTTPS。服务器使用内部证书,客户端安装企业根证书或指定可信证书。 + +### 权限模型 + +权限采用 `module:action`,并以用户为最终授权主体: + +```text +catalog:product:view +catalog:product:edit +catalog:product:publish +sales:order:confirm +purchase:contract:generate +shipping:batch:confirm +customs:document:generate +billing:invoice:receive +file:download +admin:user:manage +``` + +系统支持三种授权来源: + +1. 用户直接权限。 +2. 可复用的权限组权限。 +3. 多个权限组叠加后的权限。 + +角色/权限组只是权限集合,不是互斥身份,也不是用户必须选择的唯一角色。最终有效权限为用户直接权限与所有所属权限组权限的并集;未明确授予的权限默认拒绝。用户可以只访问一个模块,也可以跨多个模块组合权限,例如“订单查看 + 采购编辑 + 出货导出”。 + +权限组可预置“采购权限”“报关权限”等常用组合,但管理员可以对每个用户追加或移除单项权限。权限判断必须在 API 和应用服务执行,客户端隐藏菜单不能代替服务端授权。 + +### 身份与授权数据 + +`identity` schema 至少包含: + +```text +identity_user +identity_permission +identity_user_permission +identity_permission_group +identity_permission_group_item +identity_user_permission_group +identity_refresh_token +``` + +权限变更记录审计日志,并在下一次请求鉴权时生效。停用用户立即禁止登录。权限检查同时覆盖模块访问、具体操作和文件下载。 + +## 8. 状态与发布规则 + +产品、模板和业务单据: + +```text +Draft -> Published -> Disabled +``` + +订单、采购、出货和开票使用各自有限状态机。状态修改必须由应用服务执行,禁止 API 直接接受任意状态值。 + +重要规则: + +- 已发布主档编辑产生新的 Draft 版本。 +- 已确认出货批次不能静默修改。 +- 已导出文件不覆盖,重新生成产生新文件版本。 +- 已被业务引用的数据不能删除,只能停用或作废。 +- 每个状态转换记录操作者、时间和原因。 + +数据库访问统一使用 EF Core。 + +- 开发和交互验收:SQLite 文件数据库。 +- 生产部署:PostgreSQL。 +- API、应用服务和业务实体不直接依赖具体数据库提供程序。 +- 只使用 SQLite 与 PostgreSQL 都支持的字段和约束;生产专用能力必须有明确替代方案。 + +### Schema 分区 + +```text +identity +master +catalog +sales +purchase +shipping +customs +documents +billing +files +audit +legacy +``` + +### 通用字段 + +业务表按需要使用: + +```text +id uuid primary key +created_at datetime not null +created_by uuid not null +updated_at datetime not null +updated_by uuid not null +row_version integer not null +``` + +`row_version` 用于乐观并发控制。客户端提交修改时携带读取时版本,版本不一致返回冲突,不覆盖他人修改。 + +### 约束 + +- 业务编号唯一。 +- 数量、价格、重量和税率使用 EF Core `decimal`,由数据库映射为适合提供程序的精确数值类型;不使用浮点计算金额。 +- 外键默认不级联删除业务数据。 +- 关键金额字段不依赖客户端计算,服务端重新计算并校验。 +- 时间统一存 UTC,界面按公司时区显示。 + +## 10. 文件与模板 + +文件内容不放数据库大字段,保存到服务器文件存储;数据库只保存文件元数据。 + +文件路径由 `IFileStorage` 抽象管理,不在业务代码中拼接 Windows 路径。默认文件系统实现的逻辑目录: + +```text +{root}/files/{year}/{entity}/{id}/{file-id}-{safe-name} +{root}/templates/{template-id}/{version}/... +{root}/generated/{year}/{document-id}/... +``` + +Windows 示例根目录: + +```text +D:\LeirenErpData +``` + +Linux 示例根目录: + +```text +/var/lib/leiren-erp +``` + +数据库保存: + +- 文件 ID +- 原始文件名 +- 存储路径或对象键 +- MIME 类型 +- 文件大小 +- SHA-256 +- 关联业务对象 +- 上传人和时间 +- 是否当前版本 + +客户端下载文件必须经过 API 权限检查,不能直接暴露共享目录。 + +### 文件安全 + +- 文件名不直接拼接用户输入路径。 +- 限制允许的文件扩展名和大小。 +- 上传后计算 SHA-256。 +- Office/PDF 文件保存原始文件,不执行宏。 +- 生成文件和上传文件分开目录。 +- 定期备份数据库和文件目录,备份必须可恢复验证。 + +## 11. 单证生成 + +模板生成采用简单的 XLSX 占位符替换,不制作自由报表设计器。 + +```text +业务数据快照 + -> 模板版本 + -> 扫描 {{...}} 占位符 + -> 读取已保存的字段映射 + -> 计算合计 + -> 替换单元格文字 + -> 按明细行复制模板行 + -> 生成 XLSX + -> 可选转换 PDF + -> 保存 document_generation 和 document_file +``` + +模板规则: + +- 用户自行设计 XLSX 文件并导入系统。 +- 系统扫描所有工作表和单元格中的 `{{...}}` 占位符。 +- 用户在导入页面把每个占位符选择为一个业务字段。 +- 占位符名称不要求使用固定英文名称,例如 `{{客户名称}}`、`{{InvoiceNo}}` 都可以。 +- 普通占位符替换单值;同一占位符可以在多个单元格使用;一个单元格可以有多个占位符。 +- 明细行中的占位符使用统一的明细字段,系统复制该行生成所有明细。 +- 未映射占位符禁止生成文件,并显示占位符名称。 +- 日期、金额、数量和币种格式在映射中配置。 +- 生成时固定模板版本、字段映射和业务数据快照。 + +模板版本至少保存: + +```text +template_id +customer_id +document_type +version_no +source_file_id +placeholder_mapping +status +``` + +实现优先使用 ClosedXML 或 Open XML SDK。只替换单元格文字,不调用 Excel COM;复杂公式不作为数据来源,合计由服务端计算。 + +## 12. 后台任务 + +第一版不引入 RabbitMQ、Kafka 等消息系统。 + +使用 EF Core 兼容的数据库任务表和 ASP.NET Core `BackgroundService`;开发/验收使用 SQLite,生产使用 PostgreSQL。 + +```text +document_job +---------------- +id +job_type +payload +status +attempt_count +available_at +started_at +finished_at +error +``` + +适合后台执行: + +- 大文件生成 +- 批量单证生成 +- PDF 转换 +- 数据导入 +- 附件校验 +- 迁移报告 + +任务必须可重试且幂等。用户界面显示任务状态,不长时间阻塞 HTTP 请求。 + +## 13. 日志与审计 + +### 技术日志 + +记录: + +- API 请求耗时 +- traceId +- 异常堆栈 +- 后台任务失败 +- 数据库连接异常 + +技术日志使用结构化日志,按日期滚动,保留期限可配置。 + +### 业务审计 + +记录: + +- 用户 +- 操作类型 +- 实体类型和 ID +- 操作前值/后值或差异 +- IP/客户端信息 +- 时间 +- 原因 + +密码、token 和敏感凭据不得进入日志。客户文件内容不写入普通日志。 + +## 14. 部署与备份 + +### 服务安装 + +服务端采用可跨平台部署的 ASP.NET Core 发布方式: + +```text +Windows: + LeirenErp.Api -> Windows Service + PostgreSQL -> Windows Service + +Linux: + LeirenErp.Api -> systemd service + PostgreSQL -> systemd service +``` + +业务代码不得依赖: + +- Windows 注册表 +- Windows 专用路径格式 +- IIS 专用 API +- Windows 用户登录状态 +- 仅 Windows 可用的 Office COM 自动化 + +配置通过环境变量或外部配置文件注入。敏感配置不写入客户端安装包。 + +开发和交互验收使用 SQLite;生产环境使用 PostgreSQL。生产 PostgreSQL 是否使用 Docker 由部署环境决定,不作为应用依赖。 + +### Linux 迁移要求 + +- 使用 `Path.Combine` 或 `IFileStorage`,禁止手写反斜杠路径。 +- 文件名进行平台无关清理,禁止依赖大小写不敏感。 +- 连接字符串、时区和文件根目录均配置化。 +- PDF 转换使用服务器安装的 LibreOffice headless 或跨平台商业组件。 +- 不调用 Excel COM;XLSX 生成必须使用 Open XML/ClosedXML 等库。 +- 日志输出 stdout/结构化文件,由 Windows Event Log 或 Linux journald 收集。 +- 安装脚本分别提供 PowerShell 和 shell/systemd 版本。 + +### 网络 + +- API 仅开放局域网端口。 +- PostgreSQL 只允许 API 服务器访问。 +- Windows 使用 Windows Firewall;Linux 使用 `firewalld` 或 `ufw`。 +- 管理员接口不暴露到公网。 + +### 备份 + +至少包括: + +- PostgreSQL 定时逻辑/物理备份 +- 文件目录增量备份 +- 模板目录备份 +- 配置和证书备份 + +备份策略不能只保存备份文件,必须定期在隔离环境执行恢复演练。 + +## 15. 开发里程碑与验收规则 + +每个里程碑都必须先完成可运行的实际交互,再进入下一个里程碑。验收使用 SQLite、真实文件和真实 WPF 客户端操作,不使用 Mock API、Mock 数据库或只验证函数返回值的测试。生产发布前再使用 PostgreSQL 做一次同样的关键场景验收。 + +### M0:可运行骨架 + +实现: + +- API、WPF 客户端和 SQLite 可以启动。 +- EF Core 迁移可以创建必要表。 +- 客户端可以配置 API 地址。 +- 统一异常提示和日志目录可用。 + +验收: + +1. 在一台 Windows 机器启动 API、SQLite 和客户端。 +2. 客户端能连接 API;API 无法连接数据库时显示明确错误。 +3. 创建一个空数据库后执行 EF Core 迁移,迁移可重复执行且不破坏已有数据。 +4. API 返回错误时,客户端显示业务错误,不显示未处理异常窗口。 + +### M1:账户、组合权限和基础资料 + +实现: + +- 用户登录、停用和密码修改。 +- 用户直接权限。 +- 权限组权限。 +- 用户加入多个权限组。 +- 客户、供应商和基础单位。 +- 产品草稿、发布、停用。 +- 产品供应商、零件/BOM 和供应商历史报价。 +- 本系统不包含产品实物/样品管理,不提供样品实体、接口或页面。 + +验收: + +1. 建立三个用户,分别只授权订单、采购、报关模块。 +2. 一个用户同时拥有“订单查看 + 采购修改 + 出货导出”,客户端只显示允许的菜单和按钮。 +3. 使用无权限用户直接调用 API,API 返回 403;仅隐藏菜单不算通过。 +4. 产品可以包含多个 BOM 零件;同一个零件可以关联多个供应商;每个供应商可以保存不同币种、税率、含税状态和历史价格。 +5. 发布产品时缺少业务必需字段,界面显示缺失字段;发布成功后订单可以选择该产品。 +6. 已被业务引用的产品不能删除,只能停用。 + +### M2:客户订单和采购 + +实现: + +- 客户订单手工录入。 +- PO Excel 导入和原始 PO 附件。 +- 订单明细保存客户 SKU、客户描述覆盖值、数量、装箱率和备注。 +- 订单确认。 +- 根据 BOM 生成采购任务。 +- 采购人员调整供应商、数量、价格、税率和采购内容。 +- 采购合同生成和导出。 +- 到货/完货确认及实际包装数据。 + +验收: + +1. 新建一个包含至少两个产品的订单,并上传真实 PO 文件。 +2. 导入一份真实 Excel,导入失败行必须显示行号和原因,不能静默跳过。 +3. 一个产品拆成主体和两个零件,系统生成不同供应商的采购任务。 +4. 修改一个采购任务的供应商和价格后生成采购合同,合同显示修改后的值。 +5. 修改产品主档供应商价格后,已生成采购合同内容不变。 +6. 录入实际箱数、外箱尺寸、毛重和净重后,订单页面显示采购完成/待出货状态。 + +### M3:出货、报关和客户单证 + +实现: + +- 出货批次和集装箱。 +- 从订单选择本次出货数量,允许一个订单分批出货。 +- 实际箱数、尺寸、CBM、毛重和净重。 +- 报关资料确认。 +- 报关发票、装箱单、外销合同。 +- 客户 CI/PL 占位符模板导入、占位符扫描和字段映射。 + +验收: + +1. 一个订单拆成两个出货批次,两个批次数量之和不得超过订单数量。 +2. 出货明细使用本次实际包装数据,不直接重新读取当前产品默认值。 +3. 确认出货批次后,普通编辑不能覆盖关键数据。 +4. 导入用户自制 XLSX,系统列出所有 `{{...}}` 占位符。 +5. 用户为每个占位符选择业务字段后,生成可打开的 XLSX;产品明细、箱数、重量和合计与页面一致。 +6. 未映射占位符禁止生成,并显示缺失的占位符名称。 + +### M4:供应商开票与财务交接 + +实现: + +- 按供应商生成开票通知。 +- 生成开票用购销合同。 +- 登记供应商发票。 +- 发票状态流转。 +- 订单工作台显示开票完成情况。 + +验收: + +1. 一个出货批次关联两个供应商时,生成两份独立开票通知。 +2. 开票通知中的供应商、采购合同、数量、单价、税率和金额与采购/出货数据一致。 +3. 发票状态只能按规定顺序流转,非法操作显示原因。 +4. 供应商发票登记后,订单工作台能看到待处理和已完成状态。 + +### M5:迁移、备份和上线 + +实现: + +- 解析 `bak/ps_tr*.sql` 的表结构和 INSERT 数据。 +- 原始旧数据进入 `legacy` 区。 +- 客户、供应商、产品、订单、采购合同和出货数据映射到正式表。 +- 导入报告、错误报告和重复执行保护。 +- PostgreSQL、附件和模板备份。 +- Windows 服务部署。 + +验收: + +1. 对复制的 SQL 文件执行 dry-run,不修改正式业务表。 +2. 报告显示每张源表的读取数、成功数、跳过数和错误数。 +3. 同一批次重复执行不会产生重复客户、产品、订单或合同。 +4. 无法关联的产品、客户、供应商和订单明细进入错误报告,不能静默丢失。 +5. 从 SQL 文件导入后的 SQLite 数据库中,能启动系统并打开一个迁移后的订单及其附件。 +6. 新用户能登录,权限、订单、产品和生成文件均可实际操作。 + +### 里程碑完成规则 + +- 验收清单全部通过才算完成。 +- 发现阻塞问题时只修复当前里程碑,不顺手加入未验收功能。 +- 每个里程碑保留一份真实操作记录和生成文件。 +- 任何未完成项进入下一里程碑清单,不用空实现、假数据或 TODO 冒充完成。 + +## 16. 简化工程规则 + +- 先完成业务闭环,再增加抽象。 +- 允许模块之间直接调用;不要为了“解耦”创建大量接口、工厂、事件和通用基类。 +- 优先使用简单函数和清晰的数据结构;只有确实需要共享状态或生命周期时才定义类。 +- API、应用服务和数据库查询可以适度耦合,避免仿照 Java 的多层包装。 +- 一个功能只保留一个实现,不建立兼容层、空实现或未来扩展占位。 +- 业务规则在服务端集中实现;客户端只负责展示、输入和调用命令。 +- 不做完整库存、复杂审批、自由报表、供应商门户和公网访问。 +- 只有发现真实问题并且需要防止回归时才新增单元测试。 +- 单元测试必须针对真实缺陷或明确边界;禁止测试 Mock、代码结构、简单属性访问、按钮转发或“只是不抛异常”。 +- 默认使用真实 SQLite、真实 API、真实 WPF 客户端和真实文件进行交互验收。 +- 每个里程碑只运行覆盖当前验收场景的最窄检查,不运行无关的大型测试套件。 +- 注释只在解释“为什么必须这样做”时编写;不要注释代码正在执行的动作。没有必要时不写注释。 +- 可以使用 subagent 完成边界清晰的实现任务,但 subagent 不负责最终验收。 +- 主 agent 必须检查 subagent 的修改,启动真实环境并按里程碑清单完成实际交互验收;未经过主 agent 验收只能标记为待验收。 +## 17. 关键技术决策 + +| 项目 | 决策 | +|---|---| +| 主数据库 | 开发/验收使用 SQLite;生产使用 PostgreSQL | +| 后端 | ASP.NET Core Web API,.NET 11 | +| 客户端 | WPF,.NET 11,MVVM | +| 部署 | Windows Server 或 Linux;API 使用 Windows Service 或 systemd | +| 数据访问 | EF Core;不引入 Dapper | +| 文件 | 服务器文件系统 + 数据库文件元数据 | +| 认证 | access token + refresh token,HTTPS | +| 任务 | 数据库任务表 + BackgroundService;开发和验收使用 SQLite | +| 单证 | Excel 模板渲染,XLSX 优先,PDF 后处理 | +| 架构 | 模块化单体,不做微服务 | +| 旧数据 | SQL Server 只读读取,PostgreSQL 分层导入 | +| 删除策略 | 业务数据不物理删除,使用停用/作废 | +| 并发 | `row_version` 乐观并发控制 | + +## 18. 暂不实现 + +- 微服务和消息队列。 +- 移动端和网页端。 +- 复杂工作流引擎。 +- 完整财务总账。 +- 复杂库存和仓库条码系统。 +- 公网访问。 +- 自由报表设计器。 diff --git a/docs/05-部署与备份运维.md b/docs/05-部署与备份运维.md new file mode 100644 index 0000000..abb72a5 --- /dev/null +++ b/docs/05-部署与备份运维.md @@ -0,0 +1,105 @@ +# 部署与备份运维 + +本文覆盖 M5 基础:数据库选择、健康检查、NSSM 进程托管,以及文件/模板/数据库备份。开发和本地验收继续使用 SQLite,生产使用 PostgreSQL;业务代码不依赖具体数据库。 + +## 1. 数据库选择 + +配置项(`appsettings.json`、环境专属配置或环境变量三选一注入,优先级由 ASP.NET Core 配置系统决定): + +| 配置 | 说明 | +|---|---| +| `Database:Provider` | `Sqlite`(默认,未配置时也是 SQLite)或 `PostgreSql`(接受 `Postgres`/`Npgsql` 别名)。其他值直接使启动失败,不会静默回退 SQLite。 | +| `ConnectionStrings:Default` | 当前提供程序的连接字符串。SQLite 缺省时使用内容根目录下 `data/leiren-dev.db`,相对路径按内容根目录解析。PostgreSQL 缺失、格式错误或缺少 `Host`/`Database` 时启动失败,且错误信息不回显连接字符串(避免泄露密码)。 | +| `FileStorage:RootPath` | 服务器文件根目录。附件、上传的单证模板和生成文件都在此目录下,数据库只存元数据。 | +| `HealthChecks:DatabaseTimeout` | 就绪检查的数据库连接超时,默认 5 秒。 | + +生产连接字符串优先通过服务账户的环境变量注入,不要把真实密码写进发布包或版本控制: + +```powershell +# 仅示例变量名;实际由服务运行账户的环境提供 +ConnectionStrings__Default = Host=127.0.0.1;Port=5432;Database=leiren_erp;Username=leiren_erp;Password=... +Database__Provider = PostgreSql +``` + +PostgreSQL 侧准备(管理员在数据库服务器上执行,应用不自动建库/建用户): + +```sql +CREATE USER leiren_erp WITH PASSWORD '...'; +CREATE DATABASE leiren_erp OWNER leiren_erp; +``` + +当前仓库尚无 EF Core 迁移,API 首次启动会用 `EnsureCreated` 建表;一旦引入首个迁移,启动自动切换为 `Migrate`。PostgreSQL 只允许 API 服务器访问(防火墙/安全组与 `pg_hba.conf` 同时限制)。 + +## 2. 健康与就绪检查 + +| 端点 | 含义 | 失败表现 | +|---|---|---| +| `GET /health/live` | 进程存活探针,只证明进程能响应。 | 进程挂死时无响应。 | +| `GET /health`、`GET /health/ready` | 就绪探针:打开真实数据库连接(带超时),并验证文件存储根目录存在且可写(写入后立即删除探针文件)。 | 任一项不健康返回 HTTP 503,逐项给出 `name/status/durationMs/description`; healthy 返回 200。响应不包含连接字符串、密码或服务器路径。 | + +两个端点都无需登录,负载均衡和服务监控应使用 `/health/ready`,不要用 `/health/live` 代替业务就绪判断。 + +## 3. NSSM 进程托管 + +生产环境不使用 Windows Service Host。使用 NSSM 将 ASP.NET Core API 作为普通进程托管。 + +```powershell +dotnet publish src/Leiren.Erp.Api -c Release -o C:\LeirenErp\Api +nssm install LeirenErpApi C:\Program Files\dotnet\dotnet.exe +nssm set LeirenErpApi AppParameters "C:\LeirenErp\Api\Leiren.Erp.Api.dll --urls http://0.0.0.0:5118" +nssm set LeirenErpApi AppDirectory C:\LeirenErp\Api +nssm set LeirenErpApi AppEnvironmentExtra "ASPNETCORE_ENVIRONMENT=Production" "Database__Provider=PostgreSql" +nssm set LeirenErpApi AppExit Default Restart +nssm set LeirenErpApi AppStdout C:\LeirenErp\Logs\api.out.log +nssm set LeirenErpApi AppStderr C:\LeirenErp\Logs\api.err.log +nssm start LeirenErpApi +``` + +NSSM 配置完成后必须检查 `GET /health/ready` 返回 `200`。停止或删除进程不会删除数据库、附件和备份目录。 + +网络:API 只开放局域网端口,管理接口不对公网暴露。 +## 4. 备份(文件、模板与数据库) + +备份工具 `Leiren.Erp.Backup` 把配置的每个源目录(含文件存储、独立模板目录)连同可选数据库备份复制到带时间戳的备份目录,逐文件计算 SHA-256 写入 `manifest.json`,并在宣布完成前把已写文件重新哈希自校验。任何失败(源目录缺失、目录互相包含、空备份、pg_dump 失败、校验不一致)都以非零退出码结束并删除该次未完成目录,不会冒充成功。 + +```powershell +dotnet publish src/Leiren.Erp.Backup -c Release -o C:\LeirenErp\Tools + +# 先 dry-run:只枚举并哈希源文件,不写任何东西 +C:\LeirenErp\Tools\Leiren.Erp.Backup.exe backup --config C:\LeirenErp\Config\backup.json --dry-run + +# 正式备份 +C:\LeirenErp\Tools\Leiren.Erp.Backup.exe backup --config C:\LeirenErp\Config\backup.json + +# 校验已有备份(逐文件比对大小与 SHA-256) +C:\LeirenErp\Tools\Leiren.Erp.Backup.exe verify --backup E:\LeirenErpBackups\20261113T020000Z-xxxxxxxx +``` + +配置示例见 `deploy/windows/backup.example.json`: + +- `Sources[]`:`Name`(仅字母/数字/`-`/`_`/`.`,用作备份内文件夹名)+ `Path`。源目录不存在会直接失败,不跳过。经 API 上传的单证模板保存在文件存储根目录下,已随 `FileStorage` 源覆盖;只有模板另行存放时才保留 `Templates` 源(目录需真实存在)。 +- `DestinationPath`:备份根目录,不能位于任何源目录之内、也不能包含源目录。 +- `IncludeDatabase` + `DatabaseProvider` + `DatabaseConnectionString`:SQLite 使用在线备份 API 做一致性副本;PostgreSQL 调用 `pg_dump --format=custom`,密码只通过 `PGPASSWORD` 环境传递,不进进程参数。`pg_dump` 不存在或退出码非零即失败。连接字符串也可改用环境变量 `LEIREN_ERP_CONNECTION_STRING` 注入(参数/配置文件优先)。 +- `AllowEmpty`:默认 `false`,源为空且无数据库时拒绝生成空备份。 + +每次备份目录结构: + +```text +// + manifest.json # 备份编号、时间、每个文件的源/相对路径/大小/SHA-256、数据库条目 + files/<源名>/... # 按原相对路径保存的文件与模板 + database/leiren-erp.dump | leiren-erp.sqlite # 仅 IncludeDatabase 时 +``` + +定时备份使用任务计划程序或现有运维平台调用 `Leiren.Erp.Backup`,必须保留工具退出码;失败不得打印成功。 + +## 5. 恢复与演练 + +备份“生成成功”不等于可恢复,至少每季度在隔离环境演练一次: + +1. 对备份目录先跑 `verify`,失败则该备份不可用,换更早的备份并记录。 +2. PostgreSQL:在隔离实例上用 `pg_restore` 恢复 `database/leiren-erp.dump`;SQLite:停 API 后用备份的 `leiren-erp.sqlite` 替换数据文件。 +3. 把 `files/<源名>/` 内容按原相对路径还原到文件存储/模板根目录,不要改名。 +4. 用隔离配置启动 API,确认 `/health/ready` 为 200,并登录抽查一个订单及其附件、一个模板和一份生成文件。 + +演练结果(日期、备份编号、校验结论、恢复耗时)记录在运维日志中。 diff --git a/docs/启动文档.md b/docs/启动文档.md new file mode 100644 index 0000000..a785fe8 --- /dev/null +++ b/docs/启动文档.md @@ -0,0 +1,484 @@ +# Leiren ERP 启动文档 + +## 1. 当前仓库状态 + +当前仓库处于设计和原型阶段,包含: + +- `docs/01-总体业务流程设计.md`:总体业务流程 +- `docs/02-产品与样品库设计.md`:产品、零件、供应商和报价设计 +- `docs/03-数据库迁移与导入设计.md`:旧 ERP 数据迁移设计 +- `docs/04-系统架构与技术设计.md`:后端、WPF 客户端、数据库和里程碑 +- `docs/client-shell.html`:WPF 客户端壳的 HTML 参考原型 +- `migration/README.md`:迁移工具约定 +- `订单流程涉及单据文件/`:真实业务单据样本 +- `bak/`:旧 ERP SQL Server 备份和 SQL 导出文件 + +目前没有可直接运行的 API、WPF 客户端或数据库工程。 + +## 2. 查看客户端壳原型 + +### 方式 A:直接打开 + +在 Windows 文件管理器中双击: + +```text +docs/client-shell.html +``` + +### 方式 B:使用本地静态服务器 + +在仓库根目录打开 PowerShell: + +```powershell +python -m http.server 8080 --directory docs +``` + +浏览器打开: + +```text +http://127.0.0.1:8080/client-shell.html +``` + +停止服务: + +```text +Ctrl+C +``` + +HTML 原型只用于确认页面结构、导航名称和信息层级,不连接数据库,也不实现真实业务操作。 + +## 3. 目标开发环境 + +### 必需 + +- Windows +- .NET 11 SDK +- Visual Studio 2022 或 JetBrains Rider +- Git + +### 开发数据库 + +- SQLite +- 通过 EF Core 访问 +- 数据库文件放在本地开发目录,不提交到 Git + +### 生产数据库 + +- PostgreSQL +- 通过 EF Core PostgreSQL provider 访问 +- WPF 客户端不直接连接数据库 + +### 文件和单证 + +- 开发阶段使用本地文件目录 +- 生产阶段使用服务器文件目录 +- Excel 使用 Open XML SDK 或 ClosedXML +- 不使用 Excel COM 自动化 + +## 4. 目标解决方案 + +建议解决方案结构: + +```text +src/ + Leiren.Erp.Api/ + Leiren.Erp.Client/ + Leiren.Erp.Domain/ + Leiren.Erp.Application/ + Leiren.Erp.Infrastructure/ + Leiren.Erp.Migration/ +``` + +第一版不要拆分微服务,也不要增加独立消息队列服务。 + +如果项目尚未创建,先创建最小可运行结构: + +```powershell +dotnet new sln -n Leiren.Erp +dotnet new webapi -n Leiren.Erp.Api -f net11.0 +dotnet new wpf -n Leiren.Erp.Client -f net11.0 +dotnet sln Leiren.Erp.sln add .\src\Leiren.Erp.Api\Leiren.Erp.Api.csproj +dotnet sln Leiren.Erp.sln add .\src\Leiren.Erp.Client\Leiren.Erp.Client.csproj +``` + +实际创建项目时,以已安装 SDK 支持的目标框架为准。 + +## 5. EF Core 数据库配置 + +开发环境使用 SQLite: + +```text +Database: .\data\leiren-dev.db +Provider: Microsoft.EntityFrameworkCore.Sqlite +``` + +生产环境使用 PostgreSQL: + +```text +Provider: Npgsql.EntityFrameworkCore.PostgreSQL +``` + +业务代码必须使用 EF Core 的通用关系模型。不得在业务逻辑中直接写 PostgreSQL 专用 SQL,避免开发环境和生产环境行为不一致。 + +典型配置分离: + +```text +appsettings.Development.json -> SQLite +appsettings.Production.json -> PostgreSQL +``` + +数据库密码不得写入 Git,不得写入 WPF 客户端安装包。 + +## 6. Subagent 使用规则 + +开发任务可以分配给 subagent,但 subagent 只负责一个边界清晰的实现任务,例如一个 API 模块、一个 WPF 页面或一个迁移解析步骤。 + +主 agent 必须负责最终验收: + +1. 检查 subagent 修改的文件和实际差异。 +2. 阅读关键代码,确认实现没有超出任务范围。 +3. 启动真实 API、SQLite 和 WPF 客户端。 +4. 按当前里程碑验收规则执行真实交互。 +5. 发现问题后由主 agent 决定修复方式,不能把 subagent 自己的“已完成”当作验收结果。 + +subagent 不得自行宣布功能验收通过。没有主 agent 的实际验收,任务只能标记为“待验收”。 + +## 7. 启动顺序 + +### 开发阶段 + +1. 启动 API。 +2. API 使用 SQLite 数据库。 +3. 执行 EF Core 数据库迁移。 +4. 启动 WPF 客户端。 +5. 使用真实客户端操作验证功能。 + +推荐启动检查: + +```powershell +dotnet restore +dotnet build +``` + +启动 API: + +```powershell +dotnet run --project .\src\Leiren.Erp.Api +``` + +启动 WPF: + +```powershell +dotnet run --project .\src\Leiren.Erp.Client +``` + +如果解决方案尚未包含数据库迁移命令,不要创建假的迁移脚本;先完成 EF Core `DbContext` 和第一条真实迁移。 + +## 8. 第一阶段启动验收 + +### M0 验收 + +以下操作必须使用真实 SQLite、真实 API 和真实 WPF 客户端完成: + +1. 创建空 SQLite 数据库。 +2. 执行 EF Core 迁移。 +3. 启动 API。 +4. 启动 WPF 客户端。 +5. 登录一个真实创建的用户。 +6. API 连接失败时,客户端显示明确错误。 +7. API 返回业务错误时,客户端显示错误信息,不弹出未处理异常窗口。 +8. 关闭并重新启动 API 后,SQLite 中的数据仍然存在。 + +### M1 验收 + +1. 创建三个用户。 +2. 分别授权订单、采购和报关模块。 +3. 验证用户只能看到自己的模块。 +4. 直接调用无权限 API,确认返回 `403`。 +5. 创建一个产品。 +6. 为产品添加两个零件。 +7. 为同一个零件添加两个供应商。 +8. 为两个供应商分别保存不同报价和税率。 +9. 发布产品。 +10. 在订单页面选择已发布产品。 + +## 9. 真实交互测试规则 + +默认不写单元测试。 + +只有发现真实缺陷,并且需要防止回归时,才新增测试。新增测试必须说明: + +- 真实问题是什么 +- 用户如何遇到问题 +- 测试防止哪一次回归 +- 为什么实际交互验收不足以覆盖该问题 + +禁止编写以下测试: + +- Mock API 测试 +- Mock 数据库测试 +- 只测试属性读写 +- 只测试按钮转发 +- 只测试方法不抛异常 +- 只验证代码行被执行 +- 只验证控件数量或 XAML 文本 + +## 10. 编码规则 + +- 优先使用简单函数和直接数据结构。 +- 不为每个方法创建接口。 +- 不为了“解耦”增加大量工厂、事件、适配器和通用基类。 +- 允许模块之间适度耦合。 +- 业务规则集中在 API,WPF 只负责输入、显示和调用。 +- 注释只写“为什么必须这样做”,不写“代码正在做什么”。 +- 没有必要时不写注释。 +- 不写空实现、假数据、无效 fallback 或 TODO 占位。 +- 一个功能只保留一个实现。 + +## 11. 注意事项 + +- WPF 客户端不直接访问 SQLite 或 PostgreSQL。 +- 生产环境不使用开发 SQLite 数据库。 +- 真实单据模板先用仓库中的文件验证;新模板使用 `{{占位符}}`,导入后由用户完成字段映射,不要先写死模板单元格坐标。 +- 旧 ERP 数据只从 `bak/ps_tr.sql`、`bak/ps_tr_mail.sql` 和 `bak/ps_tr_pic.sql` 提取;不恢复、不解析、不使用 `.bak`。 + +## 12. 当前开发状态 + +已完成: + +- .NET 11 分层解决方案、API、WPF 客户端和迁移 CLI 骨架 +- SQLite EF Core 开发数据库 +- 用户初始化、登录、Bearer Session、角色和模块权限 +- 产品、零件、供应商报价和产品发布 +- 客户、销售订单和订单确认 +- 采购任务、采购合同、到货和实际包装 +- 出货批次、集装箱和出货实际数据快照 +- 报关资料和单证包元数据版本 +- 供应商开票通知、发票登记和开票合同快照 +- 附件元数据、版本、服务器文件存储和下载 +- 旧 ERP UTF-16 SQL 文件检查/快照 CLI +- WPF 登录、产品库、客户、订单和采购页面 + +当前开发验收命令: + +```powershell +dotnet build .\Leiren.Erp.slnx +dotnet run --project .\src\Leiren.Erp.Api --urls http://127.0.0.1:5118 +dotnet run --project .\src\Leiren.Erp.Migration -- inspect --source-file .\bak\ps_tr.sql +dotnet run --project .\src\Leiren.Erp.Client +``` + +开发数据库位置: + +```text +src/Leiren.Erp.Api/data/leiren-dev.db +``` + +该目录不应提交到 Git。生产环境必须配置 PostgreSQL 连接字符串和服务器文件存储目录。 + +## 13. M2 开发状态 + +已完成 M2 客户订单和采购功能: + +- PO Excel 通过表头识别导入,不依赖固定单元格坐标。 +- 导入预览返回工作表行号、错误原因、缺失表头和无效数据。 +- 失败行不会静默跳过,也不会创建草稿订单。 +- 有效 PO 可以创建草稿订单,并将原始 PO 保存到附件版本系统。 +- 采购合同可导出为真实 XLSX 文件。 +- 合同导出使用采购合同自身快照,不重新读取产品或供应商当前报价。 +- 合同重新导出产生新的附件版本。 +- 销售订单详情和采购页面显示采购完成、待出货、部分出货和已完成状态。 +- 工作台状态从订单、采购任务、到货和出货数据实时计算,不保存重复状态字段。 + +M2 验收使用临时 SQLite 数据库完成: + +```text +创建完整业务表结构 +创建管理员 +登录 API +访问销售订单列表 +访问采购任务列表 +``` + +已有开发数据库如果创建于 M1 之前,需要先执行正式 EF Core migration 或重新创建开发数据库;不得在生产数据库上删除旧数据代替迁移。 + +## 14. M3 开发状态 + +已完成客户 CI/PL 单证基础能力: + +- XLSX 模板上传和真实文件保存。 +- 遍历所有工作表扫描 `{{占位符}}`。 +- 返回占位符名称、工作表、单元格位置和明细行信息。 +- 支持模板版本和模板附件版本。 +- 支持业务字段映射配置。 +- 映射字段使用受限业务字段目录,不接受任意表达式。 +- 生成前校验所有占位符,未映射字段全部返回并禁止生成。 +- 生成后的模板映射自动锁定,修改必须上传新版本模板。 +- 基于确认后的出货批次快照生成 CI/PL XLSX。 +- 明细行按出货明细复制。 +- 合计由系统重新计算,不依赖模板公式。 +- 生成文件保存到附件版本系统。 +- 未确认出货批次禁止生成客户单证。 + +M3 模板接口: + +```text +POST /api/document-templates/upload +POST /api/document-templates/{fileId}/versions +GET /api/document-templates/{fileId}/scan +GET /api/document-templates/fields +POST /api/document-templates/mapping-profiles +POST /api/shipping-batches/{id}/documents/ci-pl +``` + +使用仓库中的旧 Excel 模板进行扫描时,如果模板没有 `{{...}}` 占位符,接口会明确返回 400,不会创建无效模板记录。 + +## 15. M4/M5 开发状态 + +M4 财务交接已完成: + +- 一个出货批次按供应商拆分独立开票通知。 +- 开票通知保存供应商、采购合同、数量、单价、税率和金额快照。 +- 发票状态必须按 `Received -> HandedToFinance -> Completed` 顺序流转。 +- 非法状态变更返回业务错误原因。 +- 订单工作台显示每个供应商的开票状态、通知数、发票数、已开票金额和待开票金额。 + +M5 迁移和上线基础已完成: + +- `ps_tr.sql`、`ps_tr_mail.sql`、`ps_tr_pic.sql` 的 UTF-16 解析。 +- `legacy_*` 暂存表和批次哈希。 +- dry-run 不修改正式业务表。 +- 已知客户、产品、订单和采购合同的正式表映射。 +- 无法映射数据进入错误表,不静默丢失。 +- 重复批次拒绝再次导入。 +- SQLite/PostgreSQL 显式数据库提供者选择。 +- 文件和模板目录备份。 +- SHA-256 备份清单和备份校验。 +- PostgreSQL 使用 `pg_dump`。 +- `/health/live`、`/health`、`/health/ready`。 +- NSSM 进程托管和 `/health/ready` 就绪检查。 + +备份 dry-run 示例: + +```powershell +dotnet run --project .\src\Leiren.Erp.Backup -- backup --dry-run ` + --source docs=docs ` + --destination temp/m5-backups +``` + +## 16. 产品库补充能力 + +- 本系统不包含产品实物/样品管理,不提供样品登记、借出、归还、确认、库存或样品附件引用功能,产品库不维护样品记录。 +- 产品详情提供资料完整度检查。 +- 产品发布只阻塞必要基础字段,采购、出货、报关字段作为待补齐提示。 +- 产品变更记录按产品版本追加保存,不能修改或删除。 +- 产品详情提供历史记录和变更字段。 +- 产品库主界面是列表优先布局:左侧显示可搜索、可筛选和可键盘操作的产品列表,右侧显示当前产品快速预览,不在列表区域嵌入编辑器。 +- 产品列表按 `product-photo` 附件类别加载当前版本图片缩略图;没有图片时保持空缩略图,不生成假图片。 +- 产品、部件和部件供应商报价分别使用独立编辑窗口,列表双击或回车只打开对应编辑窗口。 +- 产品详情右侧预览提供部件和部件供应商报价列表,新增、编辑、删除操作均通过真实 API 完成。 +- WPF 客户端配置保存在 `%LOCALAPPDATA%\LeirenErp\settings.ini`,不再读取 `LEIREN_API_BASE_URL` 环境变量;`ApiBaseUrl` 可直接在 `[Client]` 段修改。 +- “保持登录”使用服务端持久化 refresh token,客户端只在 INI 中保存 Windows 当前用户 DPAPI 保护后的令牌。登录成功后 refresh token 会轮换保存,退出登录会撤销服务端令牌。 + +## 17. 主数据与权限客户端 + +- 供应商主数据支持编码、名称、联系人、税号、默认币种、税率和停用。 +- 供应商被报价、采购或开票引用后禁止硬删除。 +- 采购合同和采购任务保存供应商快照,不因主数据后续修改而改变历史。 +- 系统设置提供用户、角色、模块权限和直接权限管理。 +- 非管理员访问系统设置显示服务器返回的 403 权限错误。 +- 管理员可以创建用户、启用/停用用户、分配角色、模块和直接权限。 +- 客户端不显示密码哈希。 + +## 18. 首页工作台 + +- 首页通过 `/api/dashboard` 加载真实业务汇总。 +- 展示客户订单、采购任务、采购合同、出货批次、报关单、供应商开票通知和产品状态数量。 +- 汇总按服务端状态枚举返回,即使数量为零也保留状态项。 +- 首页需要 `dashboard:view` 权限,客户端支持刷新和错误显示。 + +## 19. 功能验证记录 + +- 使用全新 SQLite 数据库完成 97 次真实 HTTP 调用的端到端验证。 +- 验证链路覆盖:客户、供应商、产品、报价、销售订单、采购任务、采购合同、到货、出货、报关、CI/PL、供应商开票、发票、附件、权限和首页汇总。 +- 验证结果:成功响应 200/201;预期的权限、状态和数据校验错误返回 400/401/403/404/409。 +- 真实 XLSX 采购合同导出、CI/PL 模板扫描映射生成、PO 导入和附件下载均已验证。 +- 复杂总账、完整仓库库存、供应商门户、自动海关接口和自由报表设计器仍属于第一阶段明确排除范围。 + +## 20. 真实生产数据测试实例 + +测试实例可以与开发数据库完全隔离: + +```powershell +$env:ConnectionStrings__Default = "Data Source=D:\repo\leiren-erp\temp\production-rerun-20261114\data\test.db" +$env:FileStorage__RootPath = "D:\repo\leiren-erp\temp\production-rerun-20261114\storage" +dotnet run --project src/Leiren.Erp.Api --urls http://127.0.0.1:5128 +``` + +本次真实迁移使用 `bak/ps_tr.sql`、`bak/ps_tr_mail.sql` 和 `bak/ps_tr_pic.sql`,共读取 271828 行,正式映射 146 行,未映射 2 行。已导入客户 3 条、供应商 25 条、产品 110 条、销售订单 1 条、采购任务 3 条、采购合同 3 条。未映射的 1 条出口发票及 1 条出口发票明细因当前系统没有对应的正式出口发票实体,仍保存在 `legacy_*` 暂存表和迁移报告中。 + +测试账号:`erp-tester` / `ErpTest2026!`。 + +产品库采用资源管理器式列表,支持搜索、状态/分类/类型筛选、排序、分组、键盘选择和右侧详情。 + +产品、客户、供应商、销售订单、用户和角色的新建操作均打开各自业务向导,取消不会写入数据,只有向导成功提交后才创建记录。 + +## 21. 采购订单向导 + +- 从“新建采购订单”进入时,第一步是采购订单(销售订单)列表;选择订单后才进入创建模式。 +- 从订单卡片(“进入采购”)或采购任务卡片(“查看拆解”)进入时直接打开创建模式页,步骤条不显示第一步。 +- 创建模式页标题为“选择采购方式”,只读显示当前订单,再选择“新建采购方案”或“复用历史方案”。 +- 新建方案第二步按订单产品列出全部启用配件;每个配件只列出已报价的供应商,组合框旁的“编辑”直接维护该配件的供应商报价。 +- 复用历史方案第二步只列出同一产品在其他订单中的历史采购任务,选中后沿用当时的供应商、单价和税率。 +- 生成采购任务时提交每个配件的供应商与价格;同一订单明细已有任务时跳过,不重复生成。 +- 采购页(左侧栏“采购”,其下缩进子项“采购合同”)是一个按客户订单分组的列表:订单号、客户 PO 和采购状态在订单行,下面按产品 → 部件列出供应商和数量;产品只有一个采购项时合并成一行;未生成方案时供应商显示 TBD。 +- 列表上方提供搜索(订单号、PO、客户、产品、部件、供应商)、状态筛选(待生成采购方案 / 待导出采购合同 / 待到货确认 / 已完成)和排序(订单日期、订单号、客户 PO、采购状态)。 +- 采购状态由订单的未取消采购任务推导:无任务=待生成采购方案;有任务但未全部进入已确认合同=待导出采购合同;任务都在已确认合同内=待到货确认;任务全部完成=已完成。 +- 订单行的“处理”按采购状态跳转:待生成→采购订单向导,待导出→采购合同页面(搜索框自动填入该订单的客户 PO),待到货确认→到货确认向导;已完成不显示处理按钮。 +- 待导出采购合同且全部任务都还没进合同时,订单行显示“修改采购单”:重新打开采购订单向导,不显示创建模式步骤,直接按原方案预填供应商与报价,保存后覆盖原采购任务。 +- 客户订单、采购、采购合同、出货与报关、供应商开票页面使用同一布局:顶部筛选卡(搜索 / 状态 / 排序),下方一个列表卡,不再在列表卡内重复页面标题;分组下的明细行统一向右缩进,状态标签垂直居中。页头只显示页面标题,不再显示英文眉题和说明文字。搜索在停止输入 400ms 后自动执行,回车立即执行。 +- 客户订单列表中草稿订单显示“确认订单”,二次确认后调用 `POST /api/sales-orders/{id}/confirm`;服务端校验失败(例如产品未发布)时在左侧栏提示原因。 +- 左侧“采购合同”页面按客户订单分组:已有采购方案但仍有任务未生成合同的订单立即显示一行“尚未生成合同”和“生成合同”按钮;草稿合同显示“修改 / 确认”,修改只改合同头信息并使版本号 +1;“确认”先打开预览窗口,预览中确认后再弹出二次确认,确认后合同锁定并保存导出文件,按钮变为“导出”(即下载)。页面顶部不提供“生成采购合同”按钮。 +- 合同预览使用 `GET /api/purchase-contracts/{id}/export/preview` 取回与导出相同的 XLSX,客户端用 ExcelRenderer(NuGet `ExcelRenderer`,SkiaSharp 渲染,不依赖 Excel/LibreOffice/WebView2)把工作表渲染成一张完整图片;字体使用 Windows 自带等线(`Deng.ttf` / `Dengb.ttf`)。默认缩放到适应窗口,单击放大到 100% 并保持点击位置,按住拖动平移,再次单击恢复适应窗口。 +- 生成采购合同向导只列出尚未进入合同的采购任务:按供应商新建合同并确认履约条件;不生成下载文件。 +- 采购合同导出在采购合同页面按合同执行,使用 `src/Leiren.Erp.Api/templates/purchase-contract.xlsx`(由 `订单流程涉及单据文件/采购合同样本.xlsx` 改造,配置项 `PurchaseContract:TemplatePath`)。模板占位符写在单元格内,明细行按 `{{...}}` 所在行复制并填充,合并单元格与行高随之复制;表头、合计、签约日期同步替换。 +- 到货登记按最终成品(订单明细)进行,不选择零件:每个成品填写本次到货数量(默认待到数量,可部分到货,填 0 表示本次未到)、到货日期,并确认外箱尺寸(长宽高 cm,必填)、装箱率或箱数、单箱毛重 / 净重(必填),已按产品包装资料预填。提交时该成品的每个采购任务按比例登记到货,外箱数据只记在成品 / 主体任务(没有时取第一项)的到货记录上,箱数按成品数量计算。 +- 成品已到货数量 = 订单数量 × 各采购任务到货比例的最小值(最慢的零件决定成品数量);出货数量累计不能超过该数量。 +- 主窗口不显示顶部工具栏;左侧栏底部显示当前用户的显示名称和账号,点击后弹出菜单,“退出登录”在菜单内;操作结果提示也显示在该区域。 +- 登录是独立窗口,启动时在主窗口之前弹出;勾选“保持登录”且 refresh token 仍有效时自动登录,不弹出登录窗口。退出登录会隐藏主窗口并重新弹出登录窗口(保留用户名和“保持登录”选择),关闭登录窗口即退出程序。 +- 向导窗口只显示标题和步骤,不再显示副标题、提示文字和右上角重复的关闭按钮(使用窗口自带关闭)。 +- 图标统一使用系统已安装的 Segoe Fluent Icons 字体(Windows 10 回退到 Segoe MDL2 Assets,码位相同),字体不随程序分发;代码中的图标常量在 `Controls/FluentIcons.cs`。 +- 全局控件样式在 `App.xaml`(按钮、输入框、表格、主操作按钮 `PrimaryAction`);产品与供应商、客户资料、供应商资料、系统设置页面套用与业务页面相同的深色页头(`Controls/PageFrame.cs`),同样只显示页面标题。 +- 客户订单页的草稿订单可“修改”(打开订单向导并带入全部订单信息和明细,保存走 `PUT /api/sales-orders/{id}`)或“删除”(二次确认后 `DELETE /api/sales-orders/{id}`,只允许草稿)。 +- 修改采购单时点“编辑”打开该供应商针对此部件的报价并带出全部已存内容;该供应商还没有报价时以采购单中的价格、币种、单位、税率预填一份新报价。内容类型、产品类型、部件类型在界面上显示中文。 + +## 22. 出货与报关 + +- 出货与报关页面只显示真实数据:已确认订单中成品已到货但未装箱的产品(待装箱),以及出货批次(待确认出货 / 已出货 / 已取消),按客户订单分组,顶部提供搜索、出货状态筛选和排序。 +- `GET /api/shipping-batches/ready-orders` 返回可装箱订单:每个订单明细的订单数量、成品已到数量、已装箱数量、可出货数量,以及最近一次到货登记的外箱数据(没有时取产品包装资料)。 +- “装箱”向导:选择订单(同一客户、同一币种的多个订单可一起勾选拼柜;从订单行或今日概览待办进入时跳过此步,直接装箱该订单)→ 选择标准集装箱(20GP / 40GP / 40HQ / 45HQ,按内径和最大载重)并填写各订单产品的本次出货数量(不出货填 0)→ 出货信息(起运港、目的港必填,默认取第一个出货订单)→ 确认装箱。每柜可装箱数取 6 种统一摆放方向中能装最多的一种,再按单箱毛重受载重上限约束;系统按订单号顺序逐柜装货,每箱占 1/(该产品每柜可装箱数)个柜,柜内剩余空间由下一个产品 / 订单继续填满,放不下的部分进入下一柜,并显示每个柜装了哪些订单的哪些产品及箱数。 +- 完成后创建草稿出货批次:集装箱按分配结果生成(柜号暂为 `40HQ-01` 形式,备注“柜号待补”),每条出货明细按 `ContainerNo` 归属到对应集装箱,一个产品跨柜时按整箱拆成多条明细。出货明细可以来自同一客户、同一币种的任意已确认订单(服务端校验),批次的订单号 / PO 显示为全部订单(如 `SC-TEST-02 / SC-TEST-03`),按订单筛选批次时包含拼柜批次。草稿批次行可“柜号”(补录集装箱号和封条号,留空则保持待补)、“确认出货”(锁定报关快照;仍有待补柜号时二次提醒)或“取消”(产品回到待装箱);已出货批次显示“报关资料”和“生成单证”。 +- “报关资料”:没有有效报关资料时自动按出货批次生成草稿;报关品名、HS 编码、申报要素、原产国、境内货源地、征免、报关单位按同一产品(内部货号)最近一次已确认报关单预填,没有历史时取产品资料;监管方式、征免性质沿用该客户最近一次报关单。草稿可修改表头(报关单号、发票编号、出口 / 申报日期、监管方式、征免性质、备注)和每项明细(含数量、单价)并保存;“确认报关单”二次确认后锁定。已确认的报关资料只能作废,作废后重新打开生成新版本。 +- 报关单证(报关发票、报关装箱单、报关外销合同、报关单数据)从已确认的报关资料取数:数量、单位、单价、金额、HS 编码和报关品名等以报关资料为准;未确认报关资料时拒绝生成。客户 CI / PL 仍按出货明细生成。 +- “生成单证”向导:选择已确认出货的批次(从批次行进入时跳过)→ 多选单证模板(按类型分组,只有字段全部映射的报关 / 客户单证模板可勾选;其他客户的专用模板不显示)→ 确认生成。进入时按批次客户自动勾选:每种单证优先勾选该客户专用的最新模板,没有时勾选最新的通用模板,可再调整。每份单证调用 `POST /api/shipping-batches/{id}/documents/generate` 生成并存入附件版本,生成后选择文件夹一次保存全部文件。 +- “开票通知”(已出货批次):填写发票抬头、地址、电话、开户银行、帐号、税号、海关代码、寄件地址、联系人、签订地点(按上一份开票通知预填),调用 `POST /api/billing/notices/generate-from-shipping-batch`,每个供应商生成一份开票通知和开票用购销合同。开票内容取自已确认的报关资料:品名、单位与报关单一致;一个产品由多个供应商供货(主体、配件、包装)时,报关数量按各供应商本次出货部分的含税采购金额比例拆分(整数数量按最大余数法分配,且每家至少 1),各供应商数量合计等于报关数量,金额为各自的含税采购金额,单价 = 金额 / 数量。未确认报关资料时拒绝生成;外销发票号为空时取报关资料的发票编号。 + +## 23. 供应商开票单据 + +- “供应商开票”页按出货批次分组,顶部显示待确认、待收票和已收票金额。流程:草稿开票通知可“编辑”(发票抬头、联系人、寄件地址等表头资料)→ 批次“分配数量”(每个报关品名由一个或多个供应商开票,数量合计必须等于报关数量,金额为各供应商含税金额,单价自动计算;“全部给它”把该品名全部数量和金额分给一个供应商;某供应商所有品名都为 0 时其开票通知作废;`PUT /api/billing/notices/shipping-batches/{batchId}/allocation`)→ 批次“确认开票”(两次确认后锁定并发给供应商,`POST /api/billing/notices/shipping-batches/{batchId}/confirm`)→ 每个供应商“登记发票”(发票号码、开票日期、含税金额和税率,自动拆分不含税金额和税额)→ “完成”。每份开票通知都可“导出单据”:选择文件夹后保存开票通知书和开票用产品购销合同两份 xlsx(`GET /api/billing/notices/{id}/documents/SupplierInvoiceNotice|SupplierBillingContract`)。 +- 付款管理页在统计卡片下方显示两张图表:近 6 个月应付(按应付日期)与已付(按付款日期)的月度柱状图,以及各供应商待付款金额排行;图表随搜索、供应商和日期筛选变化,按金额最大的币种统计。 +- 两种单据走模板系统:模板类型“开票通知”“开票购销合同”(数据来自开票通知,使用内置占位符,无需映射),优先使用“单证模板”中最近导入的该类型模板,没有时使用 `src/Leiren.Erp.Api/templates/billing/` 下的内置模板(按 `订单流程涉及单据文件/出货后给供应商的开票通知和开票用购销合同.pdf` 的版式制作,开发库已导入)。预览测试选择一份开票通知作为测试数据。 +- 内置占位符:表头 `NoticeNo`、`NoticeDate`、`ExportInvoiceNo`、`ContractNo`、`SignedPlace`、`SignedDate`、`SupplierName/Contact/Phone/Fax/Address`、`InvoiceTitle*`、`MailingAddress`、`ContactName`、`Buyer*`、`Seller*`、合计 `TotalQuantity`、`TotalAmountIncludingTax`、`TotalAmountExcludingTax`、`TotalTaxAmount`、`TotalAmountInWords`(大写金额,如“陆万陆仟贰佰壹拾壹元贰角”)、`TotalAmountText`(千分位金额);明细 `LineNumber`、`ProductName`、`Specification`、`Quantity`、`Unit`、`TaxIncludedUnitPrice`、`TaxExcludingUnitPrice`、`AmountIncludingTax`、`AmountExcludingTax`、`TaxAmount`、`TaxRate`。表头占位符也可以放在明细行中(如每行重复的外销发票号)。 + +## 24. 单证模板编辑器 + +- 左侧“单证模板”页面列出全部已导入模板(每个模板的当前版本),顶部提供搜索、模板类型筛选和排序;按类型分组显示文件、版本、导入人、占位符数量和状态(已可用 / 待映射 N 项 / 待识别 N 项 / 已锁定)。 +- 模板类型(`GET /api/document-templates/kinds`):报关发票、报关装箱单、报关外销合同、报关单数据、客户 CI、客户 PL(数据来自出货批次,需要字段映射),采购合同(数据来自采购合同),开票通知、开票购销合同(数据来自开票通知);后三种使用内置占位符名,无需映射。导入时类型必选,服务端拒绝其他类型和没有 `{{...}}` 占位符的文件。 +- 导入出货批次类模板时可选“适用客户”(默认通用),客户专用模板在列表中显示客户名,生成单证时按批次客户自动勾选;新版本沿用原模板的客户。 +- “导入模板”上传 .xlsx;“新版本”为同一模板上传新文件,类型不变。出货批次类模板导入后直接打开字段映射。 +- “字段映射”为每个占位符选择业务字段(表头 / 明细 / 合计)。选了明细字段的占位符所在行按出货明细逐行复制;新版本自动带入上一版本同名占位符的映射,再按同名业务字段补全。已用于生成单证的版本映射锁定,只能上传新版本调整。 +- “预览测试”选择测试数据(出货批次或采购合同)后调用 `POST /api/document-templates/{versionId}/preview`,服务端按当前映射渲染(未映射的占位符保持原样),客户端用 ExcelRenderer 真实渲染显示,可另存为 xlsx;不保存任何数据。 +- 采购合同导出优先使用最近导入的采购合同模板,没有导入时才使用 `PurchaseContract:TemplatePath` 配置的模板文件。 +- 报关单证模板源自 `订单流程涉及单据文件/报关资料输入.xlsx` 的 4 个工作表,已拆成 4 个模板文件放在 `src/Leiren.Erp.Api/templates/customs/`:`报关装箱单.xlsx`、`报关发票.xlsx`、`报关单.xlsx`(每项 3 行:品名 / 申报要素 / 币制)、`报关外销合同.xlsx`。原表中的示例数据和跨表公式已替换为占位符,占位符名与业务字段同名,导入时选对应类型即可一一映射。开发库已导入这 4 个模板。 +- 报关相关业务字段:表头 `InvoiceNo`(发票编号,空则用出货批次号)、`CustomerAddress`、`OrderDate`、`ExportDate`、`DeclarationDate`、`TradeMode`、`ExemptionNature`、`CurrencyNameZh`;明细 `CustomsNameZh`、`CustomsNameEn`、`DeclarationElements`、`OriginCountry`、`DomesticSourcePlace`、`ExemptionInfo`、`LineCurrencyZh`。 + diff --git a/migration/README.md b/migration/README.md new file mode 100644 index 0000000..cf67968 --- /dev/null +++ b/migration/README.md @@ -0,0 +1,73 @@ +# ERP 数据迁移程序 + +## 当前状态 + +迁移程序只读取仓库中的 UTF-16 SQL 文件: + +```text +bak/ps_tr.sql +bak/ps_tr_mail.sql +bak/ps_tr_pic.sql +``` + +迁移程序直接解析 `CREATE TABLE` 和 `INSERT`。不恢复 `.bak`,不连接旧 SQL Server,也不把 `.bak` 作为迁移步骤。 + +## 目标运行方式 + +```text +UTF-16 SQL 文件 + | + v +.NET 11 Migration CLI + | + +--> SQLite 开发/验收数据库 + +--> PostgreSQL 生产数据库 + +--> legacy 原始区和正式业务表 + +--> migration_run / migration_error + +--> 脱敏迁移报告 +``` + +迁移程序和业务 API 使用 EF Core;SQL 文件使用流式解析。目标数据库使用 EF Core SQLite provider 或 PostgreSQL provider。 + +## 已实现命令(`src/Leiren.Erp.Migration`) + +```text +Leiren.Erp.Migration inspect --source-file bak/ps_tr.sql --output report.json [--staging-output staging.jsonl] +Leiren.Erp.Migration import --source-file bak/ps_tr.sql --dry-run --output report.json [--staging-output staging.jsonl] +Leiren.Erp.Migration import --source-dir bak --dry-run --output combined-report.json +Leiren.Erp.Migration inspect-all [--source-dir bak] [--output combined-report.json] [--staging-output staging.jsonl] +Leiren.Erp.Migration execute --source-dir bak --target-db erp.db [--batch-id ] [--output report.json] [--file-storage ] +Leiren.Erp.Migration execute --source-file bak/ps_tr.sql --target-db erp.db [--batch-id ] [--output report.json] [--file-storage ] +``` + +- 只接受 `ps_tr.sql`、`ps_tr_mail.sql`、`ps_tr_pic.sql` 三个文件名;`.bak` 明确拒绝。 +- 流式解析安全子集:`CREATE TABLE` 字段定义、`ALTER TABLE ... PRIMARY KEY`、`INSERT ... VALUES`(`NULL`、`N'...'`/普通字符串、数字、`0x...` 二进制、`CAST`/`CONVERT`)、`GO`、`SET`/`USE`。 +- 不在子集内的语句计入报告的 `unsupportedStatements`,解析失败的行计入 `parseErrors`(含源文件、表、行、列),都不静默丢弃或导入。 +- 二进制字面量不保留内容,只记录字节数和 SHA-256。 +- 每张源表在报告中均有 `readRows`(读取)、`successRows`(成功暂存)、`skippedRows`(同表同源主键重复而跳过)、`errorRows`(解析失败 + 未映射)、`mappedRows`、`unmappedRows`、`stagingOnlyRows` 和 `mappingStatus`。 +- dry-run(`inspect` / `import --dry-run`)从不打开目标数据库、不修改正式业务表;`--staging-output` 仅在显式指定时写 JSONL 暂存文件(源文件/表/主键或显式 `__row:<序号>` 回退键、源列、原始值、标准值)。 +- `execute` 是唯一写库命令:先把全部解析行写入 `legacy_source_row`(批次 `legacy_import_batch`、错误 `legacy_import_error`、映射 `legacy_id_map`,均为迁移专用暂存表),再按依赖顺序将已知表映射到正式表:`khxx -> Customer`、`yp_hh -> Product`、`order_main -> SalesOrder`、`order_hh -> SalesOrderLine`、`maker_order_main -> PurchaseContract`。 +- 无正式供应商主档实体,`gysxx` 供应商行只保留在 legacy 暂存区并逐行写入未映射报告(其名称仍会被解析到采购合同上);`maker_order_hh` 无正式合同明细实体、`invoice/invoice_detail` 无正式映射,同样逐行报告未映射,不静默丢弃。未文档化表只进 legacy 暂存区(`stagingOnlyRows`)。 +- 重复保护:批次键为显式 `--batch-id` 或三个源文件内容 SHA-256;同批次重复 `execute` 直接返回退出码 4 且不写任何数据。`legacy_source_row` 对 `(source_file, source_schema, source_table, source_key)` 全局唯一,跨批次重复行跳过;正式表按客户编码/产品货号/订单号/合同号及 `legacy_id_map` 查重,不重复创建。 +- 退出码:0 成功,1 I/O 失败,2 用法/源文件校验失败,3 有行解析失败,4 重复批次(未写入),5 有未映射行(详见报告与 `legacy_import_error`)。 + +## 历史产品图片(ps_tr_pic.sql,已核查并实现) + +核查证据(2026-11-14 实测 `bak/ps_tr_pic.sql`,UTF-16,约 7.5 MB): + +- 共定义 95 张表,但只有 7 张表有 INSERT:`DDLEvents`(66)、`DDLEvents_detail`(262)、`blob_hash`(17)、`clzb_pic`(8)、`html_attach_data`(11)、`relate_files_data`(13)、`yp_pic_hh`(5);其余 `*_pic` 表只有表结构、无数据行。 +- 各业务图片表自身的图片列在导出中均无真实字节:`yp_pic_hh.pic`、`clzb_pic.pic` 全部为 `NULL`,`html_attach_data.filedata`、`relate_files_data.file_image` 全部为 `0x`(空)。 +- 真实图片字节集中在 `blob_hash.hash_blob`:17 行、合计 1,830,748 字节,其中 6 行为 PNG(魔数 `89 50 4E 47`)、11 行为 JPEG(魔数 `FF D8 FF`);`blob_hash.file_type` 全为 `NULL`,格式只能按魔数识别。已逐行验证 `hash_value` 等于该行 `hash_blob` 的 SHA-1(大写十六进制),17/17 一致。 +- 产品图片关联:`yp_pic_hh.ypid` 对应产品主档 `yp_hh.ypid`(5 行的 ypid 均能在 `ps_tr.sql` 的 `yp_hh` 中找到);每行 `pic=NULL`,但 `hash_value` 全部能在 `blob_hash` 中命中(4 个不同哈希,其中 1 个被 2 个产品共用),均为 JPEG。因此产品图片**可以**从 SQL 导入,不是只有元数据。 + +`execute` 正式流程(批次内包含 `ps_tr_pic.sql` 时)在普通正式映射之后执行产品图片导入:按 `yp_pic_hh.ypid -> 已映射 Product`、`hash_value -> blob_hash.hash_blob` 恢复真实字节,经 `LocalFileStorage` 写入文件存储(`--file-storage` 指定根目录,未指定时为目标数据库同目录的 `storage/`),并创建 `FileAttachment(OwnerType=product, OwnerId=产品Id, Category=product-photo, UploadedBy=legacy-migration)`;同时在 `legacy_id_map` 记录 `ProductPhoto` 映射。暂存解析器仍只保留二进制长度/SHA-256,图片字节由导入阶段对 `ps_tr_pic.sql` 做第二遍定向提取,不进入暂存 JSON。 + +不静默丢失:报告顶层 `productImages{status,ypPicHhRows,blobHashRows,imported,skippedDuplicate,unmapped,evidence}` 与 `formalImport.byTable.yp_pic_hh` 给出计数;无法导入的行逐行写入 `legacy_import_error` 并进入未映射计数(退出码 5),错误码为 `PRODUCT_IMAGE_MISSING_YPID`、`PRODUCT_IMAGE_PRODUCT_UNMAPPED`、`PRODUCT_IMAGE_BLOB_NOT_FOUND`、`PRODUCT_IMAGE_EMPTY`、`PRODUCT_IMAGE_FORMAT_UNRECOGNIZED`(含前 12 字节十六进制证据)、`PRODUCT_IMAGE_WRITE_FAILED`。批次未包含 `ps_tr_pic.sql` 时 `productImages.status=source-file-not-in-batch`,不读取批次外文件。同一图片(同产品 + 同 SHA-256)重复执行不会重复建附件。其余图片表(如 `clzb_pic`)无正式业务主档映射,仍只进 legacy 暂存并计数,不臆造归属。 + +## 实现边界 + +- 使用流式读取解析 UTF-16 SQL 文件,不把全文件复制成多个内存副本(映射评估仅保留已知业务表的键集合与轻量行摘要)。 +- `execute` 目标库为 SQLite 文件(开发/验收);PostgreSQL 生产导入不在本命令内臆造连接方式。 +- 使用 `System.Text.Json` 保存旧表原始行(`payload_json`)及行内容 SHA-256(`source_hash`)。 +- 金额、重量、尺寸和数量使用 `decimal` 精确数值;超过正式表长度上限或引用缺失的行进入未映射报告,不截断、不臆造。 +- 附件/图片/邮件表只做 legacy 暂存与计数;产品图片例外,按上文在 `execute` 中经 `blob_hash` 恢复并导入为 `product-photo` 附件,其他图片/附件二进制内容不迁移(解析器只保留字节数与 SHA-256)。 diff --git a/src/Leiren.Erp.Api/AuthorizationEndpoints.cs b/src/Leiren.Erp.Api/AuthorizationEndpoints.cs new file mode 100644 index 0000000..66e533d --- /dev/null +++ b/src/Leiren.Erp.Api/AuthorizationEndpoints.cs @@ -0,0 +1,95 @@ +using System.Collections.Concurrent; +using Leiren.Erp.Application.Identity; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.AspNetCore.Identity; + +namespace Leiren.Erp.Api; + +public static class AuthorizationEndpoints +{ + public static IEndpointRouteBuilder MapAuthorizationEndpoints( + this IEndpointRouteBuilder app, + ConcurrentDictionary sessions, + PasswordHasher passwordHasher) + { + var group = app.MapGroup("/api/admin"); + + // Every admin route requires admin:manage, checked against the database per request. + group.AddEndpointFilter(async (context, next) => + { + var denied = await BearerAuthorization.AuthorizeAsync( + context.HttpContext, sessions, "admin:manage", context.HttpContext.RequestAborted); + return denied ?? await next(context); + }); + + group.MapGet("/modules", (IdentityService service) => Results.Ok(service.ListModules())); + + group.MapGet("/permissions", (IdentityService service) => Results.Ok(service.ListPermissions())); + + group.MapGet("/roles", (IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListRolesAsync(ct)))); + + group.MapPost("/roles", (CreateRoleRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => + { + var role = await service.CreateRoleAsync(request, ct); + return Results.Created($"/api/admin/roles/{role.Id}", role); + })); + + group.MapPut("/roles/{id:guid}/permissions", (Guid id, UpdateRolePermissionsRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateRolePermissionsAsync(id, request, ct)))); + + group.MapGet("/users", (int? page, int? pageSize, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListUsersAsync(page ?? 1, pageSize ?? 100, ct)))); + + group.MapPost("/users", (CreateUserRequest? request, IdentityService service, CancellationToken ct) => + Handle(async () => + { + if (request is null || string.IsNullOrWhiteSpace(request.Password)) + return Results.ValidationProblem(new Dictionary { ["password"] = ["密码不能为空。"] }); + // Hash here with the same hasher login uses; the service persists only the hash. + var placeholder = new AppUser { UserName = request.UserName?.Trim() ?? string.Empty, DisplayName = request.DisplayName?.Trim() ?? string.Empty, PasswordHash = string.Empty }; + var hash = passwordHasher.HashPassword(placeholder, request.Password); + var user = await service.CreateUserAsync(request, hash, ct); + return Results.Created($"/api/admin/users/{user.Id}", user); + })); + + group.MapGet("/users/{id:guid}", (Guid id, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetUserAsync(id, ct)))); + + group.MapPut("/users/{id:guid}/roles", (Guid id, AssignRolesRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AssignRolesAsync(id, request, ct)))); + + group.MapPut("/users/{id:guid}/modules", (Guid id, AssignModulesRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AssignModulesAsync(id, request, ct)))); + + group.MapPut("/users/{id:guid}/permissions", (Guid id, AssignPermissionsRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AssignPermissionsAsync(id, request, ct)))); + + group.MapPut("/users/{id:guid}/active", (Guid id, SetUserActiveRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.SetUserActiveAsync(id, request.IsActive, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (IdentityValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (IdentityNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (IdentityConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/BearerAuthorization.cs b/src/Leiren.Erp.Api/BearerAuthorization.cs new file mode 100644 index 0000000..9c3ba09 --- /dev/null +++ b/src/Leiren.Erp.Api/BearerAuthorization.cs @@ -0,0 +1,127 @@ +using System.Collections.Concurrent; +using Leiren.Erp.Application.Identity; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Api; + +/// +/// Server-side bearer authorization. Every protected request re-reads the user and +/// effective permissions from the database, so role/permission changes and user +/// deactivation take effect on the next request. +/// +public static class BearerAuthorization +{ + public static bool TryGetUserId(HttpContext context, ConcurrentDictionary sessions, out Guid userId) + { + userId = Guid.Empty; + if (!context.Request.Headers.TryGetValue("Authorization", out var authorization) || + !authorization.ToString().StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + var token = authorization.ToString()["Bearer ".Length..].Trim(); + return token.Length > 0 && sessions.TryGetValue(token, out userId); + } + + /// Returns null when authorized; otherwise the 401/403 result to return. + public static async Task AuthorizeAsync( + HttpContext context, + ConcurrentDictionary sessions, + string requiredPermission, + CancellationToken cancellationToken = default) + { + if (!TryGetUserId(context, sessions, out var userId)) + { + return Unauthorized(); + } + + var database = context.RequestServices.GetRequiredService(); + var user = await database.Users.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == userId, cancellationToken); + if (user is null) return Unauthorized(); + if (!user.IsActive) return Forbidden("用户已停用。"); + + var identity = context.RequestServices.GetRequiredService(); + return await identity.HasPermissionAsync(user.Id, requiredPermission, cancellationToken) + ? null + : Forbidden($"缺少权限:{requiredPermission}"); + } + + public static async Task GetCurrentUserAsync( + HttpContext context, + ConcurrentDictionary sessions, + CancellationToken cancellationToken = default) + { + if (!TryGetUserId(context, sessions, out var userId)) return null; + var database = context.RequestServices.GetRequiredService(); + var user = await database.Users.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == userId, cancellationToken); + return user is { IsActive: true } ? user : null; + } + + public static IResult Unauthorized() => Results.Problem( + title: "未登录", + detail: "缺少或无效的登录凭据。", + statusCode: StatusCodes.Status401Unauthorized); + + public static IResult Forbidden(string detail) => Results.Problem( + title: "无权限", + detail: detail, + statusCode: StatusCodes.Status403Forbidden); + + /// Permission required for a business route, or null when the route is not authorization-protected here. + public static string? RequiredPermissionFor(HttpRequest request) + { + var path = request.Path.Value ?? string.Empty; + var method = request.Method; + + string ActionFor(string module, params (string Suffix, string Action)[] special) + { + foreach (var (suffix, action) in special) + { + if (path.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) return $"{module}:{action}"; + } + return method switch + { + "GET" => $"{module}:view", + "DELETE" => $"{module}:delete", + _ => $"{module}:edit", + }; + } + + if (path.StartsWith("/api/dashboard", StringComparison.OrdinalIgnoreCase)) return "dashboard:view"; + if (path.StartsWith("/api/admin", StringComparison.OrdinalIgnoreCase)) return "admin:manage"; + if (path.StartsWith("/api/products", StringComparison.OrdinalIgnoreCase)) + return ActionFor("catalog", ("/publish", "publish"), ("/disable", "disable")); + if (path.StartsWith("/api/customers", StringComparison.OrdinalIgnoreCase)) return ActionFor("customers"); + if (path.StartsWith("/api/suppliers", StringComparison.OrdinalIgnoreCase)) return ActionFor("suppliers"); + if (path.StartsWith("/api/sales-orders", StringComparison.OrdinalIgnoreCase)) + return ActionFor("sales", ("/confirm", "confirm"), ("/cancel", "void")); + if (path.StartsWith("/api/purchase-tasks", StringComparison.OrdinalIgnoreCase) || + path.StartsWith("/api/purchase-contracts", StringComparison.OrdinalIgnoreCase) || + path.StartsWith("/api/purchases", StringComparison.OrdinalIgnoreCase)) + return ActionFor("purchase", ("/confirm", "confirm"), ("/void", "void"), ("/generate-from-sales-order", "generate"), ("/export", "export")); + if (path.StartsWith("/api/shipping", StringComparison.OrdinalIgnoreCase)) + return ActionFor("shipping", ("/confirm", "confirm"), ("/void", "void")); + if (path.StartsWith("/api/customs", StringComparison.OrdinalIgnoreCase)) + return ActionFor("customs", ("/confirm", "confirm")); + if (path.StartsWith("/api/billing", StringComparison.OrdinalIgnoreCase) || + path.StartsWith("/api/invoices", StringComparison.OrdinalIgnoreCase)) + return ActionFor("billing", ("/confirm", "confirm"), ("/generate-from-shipping-batch", "generate"), ("/hand-to-finance", "confirm"), ("/complete", "confirm"), ("/void", "delete")); + // Supplier payables belong to the billing/finance permission group; paying needs confirm rights. + if (path.StartsWith("/api/payables", StringComparison.OrdinalIgnoreCase)) + return ActionFor("billing", ("/pay", "confirm")); + if (path.StartsWith("/api/document-templates", StringComparison.OrdinalIgnoreCase)) + return path.Contains("/mapping", StringComparison.OrdinalIgnoreCase) || + path.EndsWith("/fields", StringComparison.OrdinalIgnoreCase) || + path.EndsWith("/validate", StringComparison.OrdinalIgnoreCase) + ? ActionFor("customs") + : ActionFor("files"); + if (path.StartsWith("/api/files", StringComparison.OrdinalIgnoreCase)) + return ActionFor("files", ("/download", "download")); + return null; + } +} diff --git a/src/Leiren.Erp.Api/BillingEndpoints.cs b/src/Leiren.Erp.Api/BillingEndpoints.cs new file mode 100644 index 0000000..33f9ae5 --- /dev/null +++ b/src/Leiren.Erp.Api/BillingEndpoints.cs @@ -0,0 +1,122 @@ +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class BillingEndpoints +{ + public static IEndpointRouteBuilder MapBillingEndpoints(this IEndpointRouteBuilder app) + { + var notices = app.MapGroup("/api/billing/notices"); + + notices.MapGet("/", (Guid? shippingBatchId, Guid? purchaseContractId, Guid? supplierId, string? status, + string? search, int? page, int? pageSize, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListNoticesAsync( + shippingBatchId, purchaseContractId, supplierId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + notices.MapGet("/{id:guid}", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetNoticeAsync(id, ct)))); + + notices.MapPost("/", (CreateSupplierInvoiceNoticeRequest request, BillingService service, CancellationToken ct) => + Handle(async () => + { + var created = await service.CreateNoticeAsync(request, ct); + return Results.Created($"/api/billing/notices/{created.Id}", created); + })); + + // One notice per supplier from a confirmed shipping batch. + notices.MapPost("/generate-from-shipping-batch", (GenerateBillingNoticesRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GenerateFromShippingBatchAsync(request, ct)))); + + notices.MapPut("/{id:guid}", (Guid id, UpdateSupplierInvoiceNoticeRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateNoticeAsync(id, request, ct)))); + + notices.MapPost("/{id:guid}/notify", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.NotifyAsync(id, ct)))); + + notices.MapPost("/{id:guid}/await-invoice", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AwaitInvoiceAsync(id, ct)))); + + notices.MapPost("/{id:guid}/void", (Guid id, VoidBillingRequest? request, BillingService service, CancellationToken ct) => + Handle(async () => + { + await service.VoidNoticeAsync(id, request, ct); + return Results.NoContent(); + })); + + notices.MapGet("/{id:guid}/contract", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetBillingContractAsync(id, ct)))); + + notices.MapPut("/{id:guid}/contract", (Guid id, UpdateSupplierBillingContractRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateBillingContractAsync(id, request, ct)))); + + // documentKind: SupplierInvoiceNotice (开票通知) or SupplierBillingContract (开票购销合同). + notices.MapGet("/{id:guid}/documents/{documentKind}", (Guid id, string documentKind, BillingDocumentExportService service, CancellationToken ct) => + Handle(async () => + { + var (bytes, fileName) = await service.RenderAsync(id, documentKind, ct); + return Results.File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); + })); + + // Batch level: split quantities between the batch's suppliers, then confirm all notices at once. + notices.MapPut("/shipping-batches/{batchId:guid}/allocation", (Guid batchId, ReallocateBillingRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ReallocateBatchAsync(batchId, request, ct)))); + notices.MapPost("/shipping-batches/{batchId:guid}/confirm", (Guid batchId, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmBatchAsync(batchId, ct)))); + + notices.MapPost("/{id:guid}/invoices", (Guid id, RegisterSupplierInvoiceRequest request, BillingService service, CancellationToken ct) => + Handle(async () => + { + var created = await service.RegisterInvoiceAsync(id, request, ct); + return Results.Created($"/api/billing/invoices/{created.Id}", created); + })); + + var invoices = app.MapGroup("/api/billing/invoices"); + + invoices.MapGet("/", (Guid? noticeId, string? status, string? search, int? page, int? pageSize, + BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListInvoicesAsync(noticeId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + invoices.MapGet("/{id:guid}", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetInvoiceAsync(id, ct)))); + + invoices.MapPost("/{id:guid}/hand-to-finance", (Guid id, HandSupplierInvoiceToFinanceRequest? request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.HandInvoiceToFinanceAsync(id, request, ct)))); + + invoices.MapPost("/{id:guid}/complete", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.CompleteInvoiceAsync(id, ct)))); + + invoices.MapPost("/{id:guid}/void", (Guid id, VoidBillingRequest? request, BillingService service, CancellationToken ct) => + Handle(async () => + { + await service.VoidInvoiceAsync(id, request, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (BillingValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (BillingNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (BillingConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/CatalogEndpoints.cs b/src/Leiren.Erp.Api/CatalogEndpoints.cs new file mode 100644 index 0000000..7b3a0a3 --- /dev/null +++ b/src/Leiren.Erp.Api/CatalogEndpoints.cs @@ -0,0 +1,141 @@ +using System.Collections.Concurrent; +using Leiren.Erp.Application.Catalog; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class CatalogEndpoints +{ + public static IEndpointRouteBuilder MapCatalogEndpoints( + this IEndpointRouteBuilder app, ConcurrentDictionary sessions) + { + var group = app.MapGroup("/api/products"); + + group.MapGet("/", (string? search, string? status, int? page, int? pageSize, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, status, page ?? 1, pageSize ?? 50, ct)))); + + group.MapGet("/{id:guid}", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + group.MapGet("/{id:guid}/history", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListHistoryAsync(id, ct)))); + + group.MapGet("/{id:guid}/completeness", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetCompletenessAsync(id, ct)))); + + group.MapPost("/drafts", (SaveProductDraftRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + var product = await service.CreateDraftAsync(request, ct, actor.UserId, actor.UserName); + return Results.Created($"/api/products/{product.Id}", product); + })); + + group.MapPut("/{id:guid}/draft", (Guid id, SaveProductDraftRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.UpdateDraftAsync(id, request, ct, actor.UserId, actor.UserName)); + })); + + group.MapPost("/{id:guid}/publish", (Guid id, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.PublishAsync(id, ct, actor.UserId, actor.UserName)); + })); + + group.MapPost("/{id:guid}/disable", (Guid id, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.DisableAsync(id, ct, actor.UserId, actor.UserName)); + })); + + group.MapDelete("/{id:guid}", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteDraftAsync(id, ct); + return Results.NoContent(); + })); + + group.MapPost("/{id:guid}/parts", (Guid id, SaveProductPartRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + var part = await service.AddPartAsync(id, request, ct, actor.UserId, actor.UserName); + return Results.Created($"/api/products/{id}/parts/{part.Id}", part); + })); + + group.MapPut("/{id:guid}/parts/{partId:guid}", (Guid id, Guid partId, SaveProductPartRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.UpdatePartAsync(id, partId, request, ct, actor.UserId, actor.UserName)); + })); + + group.MapDelete("/{id:guid}/parts/{partId:guid}", (Guid id, Guid partId, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + await service.DeletePartAsync(id, partId, ct, actor.UserId, actor.UserName); + return Results.NoContent(); + })); + + group.MapPost("/{id:guid}/quotes", (Guid id, CreateSupplierQuoteRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + var quote = await service.AddQuoteAsync(id, request, ct, actor.UserId, actor.UserName); + return Results.Created($"/api/products/{id}/quotes/{quote.Id}", quote); + })); + + group.MapPut("/{id:guid}/quotes/{quoteId:guid}", (Guid id, Guid quoteId, CreateSupplierQuoteRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.UpdateQuoteAsync(id, quoteId, request, ct, actor.UserId, actor.UserName)); + })); + + group.MapDelete("/{id:guid}/quotes/{quoteId:guid}", (Guid id, Guid quoteId, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + await service.DeleteQuoteAsync(id, quoteId, ct, actor.UserId, actor.UserName); + return Results.NoContent(); + })); + + return app; + } + + private static async Task<(Guid? UserId, string? UserName)> ActorAsync( + HttpContext http, ConcurrentDictionary sessions, CancellationToken ct) + { + var user = await BearerAuthorization.GetCurrentUserAsync(http, sessions, ct); + return user is null ? (null, null) : (user.Id, $"{user.DisplayName} ({user.UserName})"); + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CatalogValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CatalogNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CatalogConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs b/src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs new file mode 100644 index 0000000..21a4c9b --- /dev/null +++ b/src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs @@ -0,0 +1,52 @@ +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class CiPlDocumentEndpoints +{ + public static IEndpointRouteBuilder MapCiPlDocumentEndpoints(this IEndpointRouteBuilder app) + { + var documents = app.MapGroup("/api/shipping-batches/{shippingBatchId:guid}/documents"); + + // Generates one customs or customer document from a mapped template version. + documents.MapPost("/generate", (Guid shippingBatchId, GenerateCiPlDocumentRequest request, CiPlDocumentGenerationService service, CancellationToken ct) => + Handle(async () => + { + var result = await service.GenerateAsync(shippingBatchId, request, ct); + return Results.Created( + $"/api/shipping-batches/{shippingBatchId}/documents/{result.Document.Id}", result); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CustomsValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (DocumentTemplateValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CustomsNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CustomsConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/CustomsEndpoints.cs b/src/Leiren.Erp.Api/CustomsEndpoints.cs new file mode 100644 index 0000000..df2441b --- /dev/null +++ b/src/Leiren.Erp.Api/CustomsEndpoints.cs @@ -0,0 +1,94 @@ +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class CustomsEndpoints +{ + public static IEndpointRouteBuilder MapCustomsEndpoints(this IEndpointRouteBuilder app) + { + var customs = app.MapGroup("/api/customs"); + + customs.MapGet("/", (string? search, string? status, Guid? shippingBatchId, int? page, int? pageSize, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, status, shippingBatchId, page ?? 1, pageSize ?? 50, ct)))); + + customs.MapGet("/{id:guid}", (Guid id, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + customs.MapPost("/", (CreateCustomsDeclarationRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => + { + var declaration = await service.CreateFromShippingBatchAsync(request, ct); + return Results.Created($"/api/customs/{declaration.Id}", declaration); + })); + + customs.MapPut("/{id:guid}", (Guid id, UpdateCustomsDeclarationRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateAsync(id, request, ct)))); + + customs.MapPost("/{id:guid}/confirm", (Guid id, ConfirmCustomsDeclarationRequest? request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmAsync(id, request, ct)))); + + customs.MapPost("/{id:guid}/void", (Guid id, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.VoidAsync(id, ct)))); + + customs.MapGet("/{id:guid}/documents", (Guid id, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListDocumentsForCustomsAsync(id, ct)))); + + customs.MapPost("/{id:guid}/documents", (Guid id, GenerateCustomsDocumentPackageRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => + { + var package = await service.GenerateForCustomsAsync(id, request, ct); + return Results.Created($"/api/shipping-batches/{package.ShippingBatchId}/documents/{package.Id}", package); + })); + + var documents = app.MapGroup("/api/shipping-batches/{shippingBatchId:guid}/documents"); + + documents.MapGet("/", (Guid shippingBatchId, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListDocumentsAsync(shippingBatchId, ct)))); + + documents.MapGet("/{documentId:guid}", (Guid shippingBatchId, Guid documentId, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetDocumentAsync(shippingBatchId, documentId, ct)))); + + documents.MapPost("/", (Guid shippingBatchId, GenerateDocumentPackageRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => + { + var package = await service.GenerateDocumentAsync(shippingBatchId, request, ct); + return Results.Created($"/api/shipping-batches/{shippingBatchId}/documents/{package.Id}", package); + })); + + documents.MapPost("/{documentId:guid}/confirm", (Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmDocumentAsync(shippingBatchId, documentId, request, ct)))); + + documents.MapPost("/{documentId:guid}/export", (Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ExportDocumentAsync(shippingBatchId, documentId, request, ct)))); + + documents.MapPost("/{documentId:guid}/void", (Guid shippingBatchId, Guid documentId, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.VoidDocumentAsync(shippingBatchId, documentId, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CustomsValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CustomsNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CustomsConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/DashboardEndpoints.cs b/src/Leiren.Erp.Api/DashboardEndpoints.cs new file mode 100644 index 0000000..27cb691 --- /dev/null +++ b/src/Leiren.Erp.Api/DashboardEndpoints.cs @@ -0,0 +1,14 @@ +using Leiren.Erp.Application.Dashboard; + +namespace Leiren.Erp.Api; + +public static class DashboardEndpoints +{ + public static IEndpointRouteBuilder MapDashboardEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/api/dashboard", async (DashboardService service, CancellationToken ct) => + Results.Ok(await service.GetSummaryAsync(ct))); + + return app; + } +} diff --git a/src/Leiren.Erp.Api/DocumentTemplateEndpoints.cs b/src/Leiren.Erp.Api/DocumentTemplateEndpoints.cs new file mode 100644 index 0000000..4d778ad --- /dev/null +++ b/src/Leiren.Erp.Api/DocumentTemplateEndpoints.cs @@ -0,0 +1,115 @@ +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; + +namespace Leiren.Erp.Api; + +public static class DocumentTemplateEndpoints +{ + public static IEndpointRouteBuilder MapDocumentTemplateEndpoints(this IEndpointRouteBuilder app) + { + var templates = app.MapGroup("/api/document-templates"); + + // multipart/form-data: file (required, real .xlsx), name, documentKind, + // customerId, uploadedBy, uploadedByUserId. The workbook is scanned + // before it is stored through Files; a template without placeholders + // is rejected and nothing is persisted. + templates.MapPost("/upload", (HttpRequest request, DocumentTemplateService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + await using var content = file.OpenReadStream(); + var created = await service.UploadAsync( + content, file.FileName, file.ContentType, + new DocumentTemplateUploadOptions( + FormValue(form, "name"), + FormValue(form, "documentKind"), + ParseGuid(FormValue(form, "customerId"), "customerId"), + FormValue(form, "uploadedBy"), + ParseGuid(FormValue(form, "uploadedByUserId"), "uploadedByUserId")), ct); + return Results.Created($"/api/document-templates/{created.SourceFileId}/scan", created); + })).DisableAntiforgery(); + + templates.MapPost("/{fileId:guid}/versions", (Guid fileId, HttpRequest request, DocumentTemplateService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + await using var content = file.OpenReadStream(); + var created = await service.UploadNewVersionAsync( + fileId, content, file.FileName, file.ContentType, + new DocumentTemplateUploadOptions( + FormValue(form, "name"), + FormValue(form, "documentKind"), + ParseGuid(FormValue(form, "customerId"), "customerId"), + FormValue(form, "uploadedBy"), + ParseGuid(FormValue(form, "uploadedByUserId"), "uploadedByUserId")), ct); + return Results.Created($"/api/document-templates/{created.SourceFileId}/scan", created); + })).DisableAntiforgery(); + + templates.MapGet("/{fileId:guid}/scan", (Guid fileId, DocumentTemplateService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ScanStoredAsync(fileId, ct)))); + + return app; + } + + private static async Task ReadFormAsync(HttpRequest request, CancellationToken ct) + { + if (!request.HasFormContentType) + throw new DocumentTemplateValidationException("file", "上传必须使用 multipart/form-data。"); + return await request.ReadFormAsync(ct); + } + + private static IFormFile RequireFile(IFormCollection form) + { + var file = form.Files.GetFile("file") ?? form.Files.FirstOrDefault(); + if (file is null || file.Length == 0 && string.IsNullOrWhiteSpace(file.FileName)) + throw new DocumentTemplateValidationException("file", "请选择要上传的 .xlsx 模板文件。"); + return file; + } + + private static string? FormValue(IFormCollection form, string key) + => form.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value.ToString()) + ? value.ToString().Trim() + : null; + + private static Guid? ParseGuid(string? value, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (!Guid.TryParse(value, out var parsed) || parsed == Guid.Empty) + throw new DocumentTemplateValidationException(field, "标识无效。"); + return parsed; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (DocumentTemplateValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FilesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidDataException ex) + { + return Results.Problem(title: "文件无效", detail: ex.Message, statusCode: StatusCodes.Status413PayloadTooLarge); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/DocumentTemplateMappingEndpoints.cs b/src/Leiren.Erp.Api/DocumentTemplateMappingEndpoints.cs new file mode 100644 index 0000000..907f259 --- /dev/null +++ b/src/Leiren.Erp.Api/DocumentTemplateMappingEndpoints.cs @@ -0,0 +1,104 @@ +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +/// +/// Versioned placeholder-to-business-field mapping CRUD for scanned XLSX +/// document templates. {templateVersionId} is the immutable template +/// version id (scanned template file version) from the template upload/scan +/// endpoints. Once a document package is generated from a version, every +/// mutation of its mappings is refused (409); upload a new template version +/// to change mappings. +/// +public static class DocumentTemplateMappingEndpoints +{ + public static IEndpointRouteBuilder MapDocumentTemplateMappingEndpoints(this IEndpointRouteBuilder app) + { + var templates = app.MapGroup("/api/document-templates"); + + templates.MapGet("/", (DocumentTemplateCatalogService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(ct)))); + + templates.MapGet("/kinds", (DocumentTemplateCatalogService service) => + Handle(() => Task.FromResult(Results.Ok(service.ListKinds())))); + + // Renders the template against chosen test data; nothing is stored. + templates.MapPost("/{templateVersionId:guid}/preview", (Guid templateVersionId, PreviewDocumentTemplateRequest request, DocumentTemplateCatalogService service, CancellationToken ct) => + Handle(async () => + { + var (bytes, fileName) = await service.PreviewAsync(templateVersionId, request, ct); + return Results.File(bytes, CiPlDocumentGenerationService.ContentType, fileName); + })); + + templates.MapGet("/fields", (DocumentTemplateMappingService service) => + Handle(() => Task.FromResult(Results.Ok(service.ListFields())))); + + templates.MapGet("/mapping-profiles", (Guid? templateId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListProfilesAsync(templateId, ct)))); + + templates.MapPost("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, CreateDocumentTemplateMappingProfileRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => + { + var profile = await service.CreateProfileAsync(templateVersionId, request, ct); + return Results.Created($"/api/document-templates/{templateVersionId}/mapping-profile", profile); + })); + + templates.MapGet("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetProfileAsync(templateVersionId, ct)))); + + templates.MapPut("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, UpdateDocumentTemplateMappingProfileRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateProfileAsync(templateVersionId, request, ct)))); + + templates.MapDelete("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteProfileAsync(templateVersionId, ct); + return Results.NoContent(); + })); + + templates.MapPost("/{templateVersionId:guid}/mappings", (Guid templateVersionId, SaveDocumentTemplateFieldMappingRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AddMappingAsync(templateVersionId, request, ct)))); + + templates.MapPut("/{templateVersionId:guid}/mappings", (Guid templateVersionId, ReplaceDocumentTemplateFieldMappingsRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ReplaceMappingsAsync(templateVersionId, request, ct)))); + + templates.MapPost("/{templateVersionId:guid}/mappings/copy-from", (Guid templateVersionId, CopyDocumentTemplateMappingsRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.CopyMappingsAsync(templateVersionId, request, ct)))); + + templates.MapPut("/{templateVersionId:guid}/mappings/{mappingId:guid}", (Guid templateVersionId, Guid mappingId, SaveDocumentTemplateFieldMappingRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateMappingAsync(templateVersionId, mappingId, request, ct)))); + + templates.MapDelete("/{templateVersionId:guid}/mappings/{mappingId:guid}", (Guid templateVersionId, Guid mappingId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.DeleteMappingAsync(templateVersionId, mappingId, ct)))); + + templates.MapPost("/{templateVersionId:guid}/validate", (Guid templateVersionId, ValidateDocumentTemplateRequest? request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ValidateAsync(templateVersionId, request?.Placeholders, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CustomsValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CustomsNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CustomsConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/FileEndpoints.cs b/src/Leiren.Erp.Api/FileEndpoints.cs new file mode 100644 index 0000000..6ed3e03 --- /dev/null +++ b/src/Leiren.Erp.Api/FileEndpoints.cs @@ -0,0 +1,129 @@ +using Leiren.Erp.Application.Files; + +namespace Leiren.Erp.Api; + +public static class FileEndpoints +{ + public static IEndpointRouteBuilder MapFileEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api/files"); + + group.MapGet("/", (string? ownerType, Guid? ownerId, string? category, string? search, + bool? currentOnly, int? page, int? pageSize, FileService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync( + ownerType, ownerId, category, search, currentOnly ?? false, page ?? 1, pageSize ?? 50, ct)))); + + group.MapGet("/{id:guid}", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + group.MapGet("/{id:guid}/versions", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListVersionsAsync(id, ct)))); + + group.MapGet("/{id:guid}/download", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => + { + var download = await service.OpenDownloadAsync(id, ct); + // Results.File owns and disposes the stream. + return Results.File(download.Content, download.File.ContentType, + download.File.OriginalFileName, enableRangeProcessing: true); + })); + + group.MapPost("/", (HttpRequest request, FileService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + Guid? uploadedByUserId = Guid.TryParse(FormValue(form, "uploadedByUserId"), out var parsed) ? parsed : null; + await using var content = file.OpenReadStream(); + var created = await service.UploadAsync(new UploadFileCommand( + FormValue(form, "ownerType"), + ParseGuid(FormValue(form, "ownerId"), "ownerId"), + FormValue(form, "category"), + FormValue(form, "description"), + file.FileName, + file.ContentType, + content, + uploadedByUserId, + FormValue(form, "uploadedBy")), ct); + return Results.Created($"/api/files/{created.Id}", created); + })).DisableAntiforgery(); + + group.MapPost("/{id:guid}/versions", (Guid id, HttpRequest request, FileService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + Guid? uploadedByUserId = Guid.TryParse(FormValue(form, "uploadedByUserId"), out var parsed) ? parsed : null; + await using var content = file.OpenReadStream(); + var created = await service.UploadNewVersionAsync( + id, content, file.FileName, file.ContentType, + FormValue(form, "category"), FormValue(form, "description"), + uploadedByUserId, FormValue(form, "uploadedBy"), ct); + return Results.Created($"/api/files/{created.Id}", created); + })).DisableAntiforgery(); + + group.MapDelete("/{id:guid}", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task ReadFormAsync(HttpRequest request, CancellationToken ct) + { + if (!request.HasFormContentType) + throw new FilesValidationException("file", "上传必须使用 multipart/form-data。"); + return await request.ReadFormAsync(ct); + } + + private static IFormFile RequireFile(IFormCollection form) + { + var file = form.Files.GetFile("file") ?? form.Files.FirstOrDefault(); + if (file is null || file.Length == 0 && string.IsNullOrWhiteSpace(file.FileName)) + throw new FilesValidationException("file", "请选择要上传的文件。"); + return file; + } + + private static string? FormValue(IFormCollection form, string key) + => form.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value.ToString()) + ? value.ToString() + : null; + + private static Guid ParseGuid(string? value, string field) + { + if (!Guid.TryParse(value, out var parsed) || parsed == Guid.Empty) + throw new FilesValidationException(field, "所属业务对象标识无效。"); + return parsed; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FilesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidDataException ex) + { + return Results.Problem(title: "文件无效", detail: ex.Message, statusCode: StatusCodes.Status413PayloadTooLarge); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/FinanceEndpoints.cs b/src/Leiren.Erp.Api/FinanceEndpoints.cs new file mode 100644 index 0000000..338e6c3 --- /dev/null +++ b/src/Leiren.Erp.Api/FinanceEndpoints.cs @@ -0,0 +1,40 @@ +using Leiren.Erp.Application.Finance; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class FinanceEndpoints +{ + public static IEndpointRouteBuilder MapFinanceEndpoints(this IEndpointRouteBuilder app) + { + var payables = app.MapGroup("/api/payables"); + + payables.MapGet("/", (PayableService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(ct)))); + + payables.MapPost("/{id:guid}/pay", (Guid id, PaySupplierPayableRequest request, PayableService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.PayAsync(id, request, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (FinanceValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FinanceNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FinanceConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/HealthEndpoints.cs b/src/Leiren.Erp.Api/HealthEndpoints.cs new file mode 100644 index 0000000..76d0221 --- /dev/null +++ b/src/Leiren.Erp.Api/HealthEndpoints.cs @@ -0,0 +1,129 @@ +using System.Diagnostics; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Api; + +public sealed record HealthCheckResult(string Name, string Status, long DurationMs, string? Description); + +public sealed record HealthReport(string Status, string Provider, DateTimeOffset CheckedAtUtc, IReadOnlyList Checks); + +/// +/// Real liveness/readiness probes. +/// /health/live only proves the process responds. +/// /health and /health/ready open a database connection and probe that the +/// configured file-storage root exists and is writable; any failed check +/// yields 503 with per-check detail (no connection strings, passwords or +/// server paths are exposed). +/// +public static class HealthEndpoints +{ + private static readonly TimeSpan DefaultDatabaseTimeout = TimeSpan.FromSeconds(5); + + public static IEndpointRouteBuilder MapErpHealthEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/health/live", () => Results.Ok(new + { + status = "ok", + checkedAtUtc = DateTimeOffset.UtcNow, + })); + + app.MapGet("/health", RunReadinessAsync); + app.MapGet("/health/ready", RunReadinessAsync); + return app; + } + + private static async Task RunReadinessAsync(HttpContext context, ErpDbContext database) + { + var configuration = context.RequestServices.GetRequiredService(); + var timeout = DefaultDatabaseTimeout; + if (TimeSpan.TryParse(configuration["HealthChecks:DatabaseTimeout"], out var configured) && configured > TimeSpan.Zero) + { + timeout = configured; + } + + var checks = new List + { + await CheckDatabaseAsync(database, timeout, context.RequestAborted), + CheckFileStorage(context.RequestServices.GetRequiredService()), + }; + + var healthy = checks.All(x => x.Status == "healthy"); + var provider = database.Database.ProviderName ?? "unknown"; + var report = new HealthReport( + healthy ? "ok" : "unhealthy", + provider, + DateTimeOffset.UtcNow, + checks); + return Results.Json(report, statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable); + } + + private static async Task CheckDatabaseAsync( + ErpDbContext database, TimeSpan timeout, CancellationToken requestAborted) + { + var stopwatch = Stopwatch.StartNew(); + try + { + using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(requestAborted); + timeoutSource.CancelAfter(timeout); + var canConnect = await database.Database.CanConnectAsync(timeoutSource.Token); + stopwatch.Stop(); + return canConnect + ? new HealthCheckResult("database", "healthy", stopwatch.ElapsedMilliseconds, "数据库连接可用。") + : new HealthCheckResult("database", "unhealthy", stopwatch.ElapsedMilliseconds, "数据库连接不可用。"); + } + catch (OperationCanceledException) when (!requestAborted.IsCancellationRequested) + { + stopwatch.Stop(); + return new HealthCheckResult("database", "unhealthy", stopwatch.ElapsedMilliseconds, + $"数据库连接在 {timeout.TotalSeconds:0} 秒内未完成。"); + } + catch (Exception ex) + { + stopwatch.Stop(); + // Exception type only: messages may contain hosts or credentials. + return new HealthCheckResult("database", "unhealthy", stopwatch.ElapsedMilliseconds, + $"数据库连接失败({ex.GetType().Name})。"); + } + } + + private static HealthCheckResult CheckFileStorage(FileStorageOptions options) + { + var stopwatch = Stopwatch.StartNew(); + string? probePath = null; + try + { + if (string.IsNullOrWhiteSpace(options.RootPath) || !Directory.Exists(options.RootPath)) + { + stopwatch.Stop(); + return new HealthCheckResult("fileStorage", "unhealthy", stopwatch.ElapsedMilliseconds, "文件存储根目录不存在。"); + } + + probePath = Path.Combine(options.RootPath, ".health-probe-" + Guid.NewGuid().ToString("N")); + using (var stream = new FileStream(probePath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + stream.WriteByte(0); + stream.Flush(); + } + + File.Delete(probePath); + probePath = null; + stopwatch.Stop(); + return new HealthCheckResult("fileStorage", "healthy", stopwatch.ElapsedMilliseconds, "文件存储根目录可写。"); + } + catch (Exception ex) + { + stopwatch.Stop(); + return new HealthCheckResult("fileStorage", "unhealthy", stopwatch.ElapsedMilliseconds, + $"文件存储根目录不可写({ex.GetType().Name})。"); + } + finally + { + if (probePath is not null) + { + try { File.Delete(probePath); } catch { /* probe cleanup is best effort */ } + } + } + } +} diff --git a/src/Leiren.Erp.Api/Leiren.Erp.Api.csproj b/src/Leiren.Erp.Api/Leiren.Erp.Api.csproj new file mode 100644 index 0000000..fd2bcce --- /dev/null +++ b/src/Leiren.Erp.Api/Leiren.Erp.Api.csproj @@ -0,0 +1,28 @@ + + + + net11.0 + enable + enable + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + + + diff --git a/src/Leiren.Erp.Api/Leiren.Erp.Api.http b/src/Leiren.Erp.Api/Leiren.Erp.Api.http new file mode 100644 index 0000000..5c3931c --- /dev/null +++ b/src/Leiren.Erp.Api/Leiren.Erp.Api.http @@ -0,0 +1,54 @@ +@Leiren.Erp.Api_HostAddress = http://localhost:5118 + +GET {{Leiren.Erp.Api_HostAddress}}/health +Accept: application/json + +### + +# Only succeeds while no user exists. +POST {{Leiren.Erp.Api_HostAddress}}/api/auth/bootstrap +Content-Type: application/json + +{ + "userName": "admin", + "displayName": "管理员", + "password": "change-me" +} + +### + +POST {{Leiren.Erp.Api_HostAddress}}/api/auth/login +Content-Type: application/json + +{ + "userName": "admin", + "password": "change-me" +} + +### + +# Replace with the accessToken returned by login. +GET {{Leiren.Erp.Api_HostAddress}}/api/auth/me +Authorization: Bearer +Accept: application/json + +### + +POST {{Leiren.Erp.Api_HostAddress}}/api/products/drafts +Content-Type: application/json + +{ + "internalSku": "P-001", + "nameZh": "示例产品", + "nameEn": "Example Product", + "category": "玩具", + "productType": "Finished", + "unit": "PCS", + "packingRate": 12, + "hsCode": "950300" +} + +### + +GET {{Leiren.Erp.Api_HostAddress}}/api/products?status=Draft +Accept: application/json diff --git a/src/Leiren.Erp.Api/MasterDataEndpoints.cs b/src/Leiren.Erp.Api/MasterDataEndpoints.cs new file mode 100644 index 0000000..8787392 --- /dev/null +++ b/src/Leiren.Erp.Api/MasterDataEndpoints.cs @@ -0,0 +1,64 @@ +using Leiren.Erp.Application.MasterData; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class MasterDataEndpoints +{ + public static IEndpointRouteBuilder MapMasterDataEndpoints(this IEndpointRouteBuilder app) + { + var suppliers = app.MapGroup("/api/suppliers"); + + suppliers.MapGet("/", (string? search, bool? isActive, int? page, int? pageSize, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, isActive, page ?? 1, pageSize ?? 50, ct)))); + + suppliers.MapGet("/{id:guid}", (Guid id, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + suppliers.MapPost("/", (SaveSupplierRequest request, SupplierService service, CancellationToken ct) => + Handle(async () => + { + var supplier = await service.CreateAsync(request, ct); + return Results.Created($"/api/suppliers/{supplier.Id}", supplier); + })); + + suppliers.MapPut("/{id:guid}", (Guid id, SaveSupplierRequest request, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateAsync(id, request, ct)))); + + suppliers.MapPost("/{id:guid}/deactivate", (Guid id, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.DeactivateAsync(id, ct)))); + + suppliers.MapDelete("/{id:guid}", (Guid id, SupplierService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (MasterDataValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (MasterDataNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (MasterDataConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/Program.cs b/src/Leiren.Erp.Api/Program.cs new file mode 100644 index 0000000..0bc4275 --- /dev/null +++ b/src/Leiren.Erp.Api/Program.cs @@ -0,0 +1,398 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using Leiren.Erp.Api; +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Application.Catalog; +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Application.Dashboard; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Finance; +using Leiren.Erp.Application.Identity; +using Leiren.Erp.Application.MasterData; +using Leiren.Erp.Application.Purchasing; +using Leiren.Erp.Application.Sales; +using Leiren.Erp.Application.Shipping; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Infrastructure.Files; +using Leiren.Erp.Infrastructure.Persistence; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; + +var builder = WebApplication.CreateBuilder(args); + + +// Database provider is selected by configuration: Sqlite (development/local +// acceptance, the default) or PostgreSql (production). Unknown providers and +// malformed PostgreSQL connection strings fail startup explicitly. +var database = ErpDatabaseConfiguration.Resolve( + builder.Configuration["Database:Provider"], + builder.Configuration.GetConnectionString("Default"), + builder.Environment.ContentRootPath); + +builder.Services.AddProblemDetails(); +builder.Services.AddErpDbContext(database); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +// File content lives on the server filesystem under FileStorage:RootPath +// (relative to the content root); the database stores only metadata. +var fileStorageOptions = new FileStorageOptions(); +builder.Configuration.GetSection("FileStorage").Bind(fileStorageOptions); +if (!Path.IsPathFullyQualified(fileStorageOptions.RootPath)) +{ + fileStorageOptions.RootPath = Path.GetFullPath( + Path.Combine(builder.Environment.ContentRootPath, fileStorageOptions.RootPath)); +} +Directory.CreateDirectory(fileStorageOptions.RootPath); +builder.Services.AddSingleton(fileStorageOptions); + +// Purchase-contract exports render the contract snapshot into this XLSX +// template. A missing file fails the export with an explicit message. +var contractTemplatePath = builder.Configuration["PurchaseContract:TemplatePath"]; +if (string.IsNullOrWhiteSpace(contractTemplatePath)) + contractTemplatePath = Path.Combine("templates", "purchase-contract.xlsx"); +if (!Path.IsPathFullyQualified(contractTemplatePath)) +{ + contractTemplatePath = Path.GetFullPath( + Path.Combine(builder.Environment.ContentRootPath, contractTemplatePath)); +} +builder.Services.AddSingleton(new PurchaseContractTemplateOptions(contractTemplatePath)); +// Built-in 开票通知 / 开票购销合同 templates; an imported template of the same type wins. +string ContentPath(string relative) => Path.GetFullPath(Path.Combine(builder.Environment.ContentRootPath, relative)); +builder.Services.AddSingleton(new BillingTemplateOptions( + ContentPath(Path.Combine("templates", "billing", "开票通知.xlsx")), + ContentPath(Path.Combine("templates", "billing", "开票购销合同.xlsx")))); +builder.Services.AddScoped(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddOpenApi(); + +var app = builder.Build(); + +app.UseExceptionHandler(); +app.UseStatusCodePages(); + +using (var scope = app.Services.CreateScope()) +{ + var dbContext = scope.ServiceProvider.GetRequiredService(); + // This repository has no EF Core migrations yet, so EnsureCreated creates the + // development schema. Once a first migration is added, Migrate takes over. + if (dbContext.Database.GetMigrations().Any()) + { + await dbContext.Database.MigrateAsync(); + } + else + { + await dbContext.Database.EnsureCreatedAsync(); + } + await IdentitySchemaInitializer.EnsureCreatedAsync(dbContext); + await RefreshSessionSchemaInitializer.EnsureCreatedAsync(dbContext); + await SupplierPayableSchemaInitializer.EnsureCreatedAsync(dbContext); + await CustomsSchemaInitializer.EnsureCreatedAsync(dbContext); + // Contracts confirmed before payables existed still owe their suppliers. + await scope.ServiceProvider.GetRequiredService().BackfillAsync(); + var identityService = scope.ServiceProvider.GetRequiredService(); + var firstUser = await dbContext.Users.OrderBy(x => x.Id).FirstOrDefaultAsync(); + var adminRole = await dbContext.Roles.SingleOrDefaultAsync(x => x.Code == "admin"); + if (firstUser is not null && adminRole is not null && + !await dbContext.UserRoles.AnyAsync(x => x.UserId == firstUser.Id)) + { + dbContext.UserRoles.Add(new UserRole { UserId = firstUser.Id, RoleId = adminRole.Id }); + await dbContext.SaveChangesAsync(); + } +} + +app.Logger.LogInformation("Database ready: {DatabaseTarget}", database.DisplayTarget); + +if (app.Environment.IsDevelopment()) +{ + app.MapOpenApi(); +} + +var passwordHasher = new PasswordHasher(); +var sessions = new ConcurrentDictionary(StringComparer.Ordinal); + +// Access tokens stay in the in-memory session dictionary (existing behavior). +// Refresh tokens are random, persisted only as SHA-256 hashes, and rotated on +// every refresh so a used refresh token can never be replayed. +Func createAccessToken = userId => +{ + var accessToken = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + sessions[accessToken] = userId; + return accessToken; +}; +Func hashRefreshToken = static token => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); +Func createRefreshSession = userId => +{ + var refreshToken = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); + var now = DateTimeOffset.UtcNow; + var session = new RefreshSession + { + UserId = userId, + TokenHash = hashRefreshToken(refreshToken), + CreatedAt = now, + ExpiresAt = now.AddDays(30) + }; + return (refreshToken, session); +}; + +app.MapErpHealthEndpoints(); + +// Server-side authorization for business routes: 401 without a valid bearer +// token, 403 when the user's effective permissions do not include the route's +// required permission. Permissions are re-read from the database per request. +app.Use(async (context, next) => +{ + var required = BearerAuthorization.RequiredPermissionFor(context.Request); + if (required is null) + { + await next(); + return; + } + + var denied = await BearerAuthorization.AuthorizeAsync(context, sessions, required, context.RequestAborted); + if (denied is not null) + { + await denied.ExecuteAsync(context); + return; + } + + await next(); +}); +app.MapAuthorizationEndpoints(sessions, passwordHasher); +app.MapCatalogEndpoints(sessions); +app.MapSalesOrderEndpoints(); +app.MapSalesOrderImportEndpoints(); +app.MapPurchasingEndpoints(); +app.MapShippingEndpoints(); +app.MapFinanceEndpoints(); +app.MapBillingEndpoints(); +app.MapFileEndpoints(); +app.MapCustomsEndpoints(); +app.MapDocumentTemplateEndpoints(); +app.MapDocumentTemplateMappingEndpoints(); +app.MapCiPlDocumentEndpoints(); +app.MapMasterDataEndpoints(); +app.MapDashboardEndpoints(); + +app.MapPost("/api/auth/bootstrap", async (BootstrapRequest? request, ErpDbContext database, IdentityService identity, CancellationToken cancellationToken) => +{ + if (request is null || + string.IsNullOrWhiteSpace(request.UserName) || + string.IsNullOrWhiteSpace(request.DisplayName) || + string.IsNullOrWhiteSpace(request.Password)) + { + return Results.ValidationProblem(new Dictionary + { + ["user"] = ["用户名、显示名称和密码均不能为空。"] + }); + } + + if (await database.Users.AnyAsync(cancellationToken)) + { + return Results.Problem( + title: "初始化已完成", + detail: "系统已经存在用户,不能重复初始化。", + statusCode: StatusCodes.Status409Conflict); + } + + var user = new AppUser + { + UserName = request.UserName.Trim(), + DisplayName = request.DisplayName.Trim(), + PasswordHash = string.Empty + }; + user.PasswordHash = passwordHasher.HashPassword(user, request.Password); + + database.Users.Add(user); + try + { + await database.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + return Results.Problem( + title: "初始化已完成", + detail: "系统已经存在用户,不能重复初始化。", + statusCode: StatusCodes.Status409Conflict); + } + + await identity.EnsureAuthorizationCatalogAsync(cancellationToken); + await identity.AssignRoleToUserAsync(user.Id, "admin", cancellationToken); + return Results.Created($"/api/auth/users/{user.Id}", new { user.Id, user.UserName, user.DisplayName, Roles = new[] { "admin" } }); +}); + +app.MapPost("/api/auth/login", async (LoginRequest? request, ErpDbContext database, CancellationToken cancellationToken) => +{ + if (request is null || + string.IsNullOrWhiteSpace(request.UserName) || + string.IsNullOrWhiteSpace(request.Password)) + { + return Results.ValidationProblem(new Dictionary + { + ["credentials"] = ["用户名和密码均不能为空。"] + }); + } + + var user = await database.Users.SingleOrDefaultAsync( + x => x.UserName == request.UserName.Trim(), cancellationToken); + + var passwordValid = false; + if (user is not null) + { + try + { + passwordValid = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, request.Password) + is PasswordVerificationResult.Success or PasswordVerificationResult.SuccessRehashNeeded; + } + catch (FormatException) + { + passwordValid = false; + } + } + + if (user is null || !passwordValid) + { + return Results.Problem( + title: "登录失败", + detail: "用户名或密码不正确。", + statusCode: StatusCodes.Status401Unauthorized); + } + + + if (!user.IsActive) + { + return Results.Problem( + title: "用户已停用", + detail: "该用户已被停用,不能登录。", + statusCode: StatusCodes.Status403Forbidden); + } + var accessToken = createAccessToken(user.Id); + var (refreshToken, refreshSession) = createRefreshSession(user.Id); + database.RefreshSessions.Add(refreshSession); + await database.SaveChangesAsync(cancellationToken); + return Results.Ok(new AuthResponse(user.Id, user.UserName, user.DisplayName, accessToken, refreshToken)); +}); + +app.MapPost("/api/auth/refresh", async (RefreshTokenRequest? request, ErpDbContext database, CancellationToken cancellationToken) => +{ + if (request is null || string.IsNullOrWhiteSpace(request.RefreshToken)) + { + return Results.ValidationProblem(new Dictionary + { + ["refreshToken"] = ["刷新凭据不能为空。"] + }); + } + + static IResult InvalidRefresh() => Results.Problem( + title: "刷新失败", + detail: "刷新凭据无效或已过期,请重新登录。", + statusCode: StatusCodes.Status401Unauthorized); + + var tokenHash = hashRefreshToken(request.RefreshToken.Trim()); + var session = await database.RefreshSessions.SingleOrDefaultAsync( + x => x.TokenHash == tokenHash, cancellationToken); + if (session is null || session.RevokedAt is not null || session.ExpiresAt <= DateTimeOffset.UtcNow) + { + return InvalidRefresh(); + } + + var user = await database.Users.SingleOrDefaultAsync(x => x.Id == session.UserId, cancellationToken); + if (user is null || !user.IsActive) + { + session.RevokedAt = DateTimeOffset.UtcNow; + await database.SaveChangesAsync(cancellationToken); + return InvalidRefresh(); + } + + // Rotation: the presented token is revoked and replaced in the same save. + session.RevokedAt = DateTimeOffset.UtcNow; + var (newRefreshToken, newSession) = createRefreshSession(user.Id); + database.RefreshSessions.Add(newSession); + var newAccessToken = createAccessToken(user.Id); + await database.SaveChangesAsync(cancellationToken); + return Results.Ok(new AuthResponse(user.Id, user.UserName, user.DisplayName, newAccessToken, newRefreshToken)); +}); + +app.MapPost("/api/auth/logout", async (RefreshTokenRequest? request, ErpDbContext database, CancellationToken cancellationToken) => +{ + if (request is null || string.IsNullOrWhiteSpace(request.RefreshToken)) + { + return Results.ValidationProblem(new Dictionary + { + ["refreshToken"] = ["刷新凭据不能为空。"] + }); + } + + var tokenHash = hashRefreshToken(request.RefreshToken.Trim()); + var session = await database.RefreshSessions.SingleOrDefaultAsync( + x => x.TokenHash == tokenHash, cancellationToken); + if (session is not null && session.RevokedAt is null) + { + session.RevokedAt = DateTimeOffset.UtcNow; + await database.SaveChangesAsync(cancellationToken); + } + + return Results.NoContent(); +}); + +app.MapGet("/api/auth/me", async (HttpRequest request, ErpDbContext database, IdentityService identity, CancellationToken cancellationToken) => +{ + static IResult Unauthorized() => Results.Problem( + title: "未登录", + detail: "缺少或无效的登录凭据。", + statusCode: StatusCodes.Status401Unauthorized); + + if (!request.Headers.TryGetValue("Authorization", out var authorization) || + !authorization.ToString().StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + return Unauthorized(); + } + + var token = authorization.ToString()["Bearer ".Length..].Trim(); + if (token.Length == 0 || !sessions.TryGetValue(token, out var userId)) + { + return Unauthorized(); + } + + var user = await database.Users.SingleOrDefaultAsync(x => x.Id == userId, cancellationToken); + if (user is null || !user.IsActive) + { + return Unauthorized(); + } + + var profile = await identity.GetUserAsync(user.Id, cancellationToken); + return Results.Ok(new { user.Id, user.UserName, user.DisplayName, profile.IsActive, profile.Roles, profile.Modules, profile.Permissions }); +}); + +app.Run(); diff --git a/src/Leiren.Erp.Api/Properties/launchSettings.json b/src/Leiren.Erp.Api/Properties/launchSettings.json new file mode 100644 index 0000000..d00ec73 --- /dev/null +++ b/src/Leiren.Erp.Api/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5118", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/Leiren.Erp.Api/PurchasingEndpoints.cs b/src/Leiren.Erp.Api/PurchasingEndpoints.cs new file mode 100644 index 0000000..58fb43f --- /dev/null +++ b/src/Leiren.Erp.Api/PurchasingEndpoints.cs @@ -0,0 +1,128 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Purchasing; + +namespace Leiren.Erp.Api; + +public static class PurchasingEndpoints +{ + public static IEndpointRouteBuilder MapPurchasingEndpoints(this IEndpointRouteBuilder app) + { + var tasks = app.MapGroup("/api/purchase-tasks"); + + tasks.MapGet("/", (Guid? salesOrderId, Guid? purchaseContractId, string? status, string? search, + int? page, int? pageSize, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListTasksAsync( + salesOrderId, purchaseContractId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + tasks.MapGet("/{id:guid}", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetTaskAsync(id, ct)))); + + tasks.MapGet("/overview", (PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetOverviewAsync(ct)))); + + tasks.MapPost("/", (CreatePurchaseTaskRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + var task = await service.CreateTaskAsync(request, ct); + return Results.Created($"/api/purchase-tasks/{task.Id}", task); + })); + + // Explicit cross-module command: derive tasks from a confirmed sales order. + tasks.MapPost("/generate-from-sales-order", (GeneratePurchaseTasksRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GenerateFromSalesOrderAsync(request, ct)))); + + tasks.MapPut("/{id:guid}", (Guid id, UpdatePurchaseTaskRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateTaskAsync(id, request, ct)))); + + tasks.MapPost("/{id:guid}/cancel", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + await service.CancelTaskAsync(id, ct); + return Results.NoContent(); + })); + + tasks.MapPost("/{id:guid}/arrivals", (Guid id, RecordPurchaseArrivalRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + var arrival = await service.RecordArrivalAsync(id, request, ct); + return Results.Created($"/api/purchase-tasks/{id}/arrivals/{arrival.Id}", arrival); + })); + + var contracts = app.MapGroup("/api/purchase-contracts"); + + contracts.MapGet("/", (string? status, string? search, int? page, int? pageSize, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListContractsAsync(status, search, page ?? 1, pageSize ?? 50, ct)))); + + contracts.MapGet("/{id:guid}", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetContractAsync(id, ct)))); + + contracts.MapPost("/", (CreatePurchaseContractRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + var contract = await service.CreateContractAsync(request, ct); + return Results.Created($"/api/purchase-contracts/{contract.Id}", contract); + })); + + contracts.MapPut("/{id:guid}", (Guid id, UpdatePurchaseContractRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateContractAsync(id, request, ct)))); + + contracts.MapPost("/{id:guid}/confirm", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmContractAsync(id, ct)))); + + contracts.MapPost("/{id:guid}/export", (Guid id, PurchaseContractExportService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ExportAsync(id, ct)))); + + contracts.MapGet("/{id:guid}/export/preview", (Guid id, PurchaseContractExportService service, CancellationToken ct) => + Handle(async () => + { + var (bytes, fileName) = await service.PreviewAsync(id, ct); + return Results.File(bytes, PurchaseContractExportService.ContentType, fileName); + })); + + contracts.MapPost("/{id:guid}/void", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + await service.VoidContractAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (PurchasingValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (PurchasingNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (PurchasingConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FilesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/SalesOrderEndpoints.cs b/src/Leiren.Erp.Api/SalesOrderEndpoints.cs new file mode 100644 index 0000000..d28b911 --- /dev/null +++ b/src/Leiren.Erp.Api/SalesOrderEndpoints.cs @@ -0,0 +1,85 @@ +using Leiren.Erp.Application.Sales; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class SalesOrderEndpoints +{ + public static IEndpointRouteBuilder MapSalesOrderEndpoints(this IEndpointRouteBuilder app) + { + var customers = app.MapGroup("/api/customers"); + + customers.MapGet("/", (string? search, bool? isActive, int? page, int? pageSize, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListCustomersAsync(search, isActive, page ?? 1, pageSize ?? 50, ct)))); + + customers.MapGet("/{id:guid}", (Guid id, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetCustomerAsync(id, ct)))); + + customers.MapPost("/", (SaveCustomerRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => + { + var customer = await service.CreateCustomerAsync(request, ct); + return Results.Created($"/api/customers/{customer.Id}", customer); + })); + + customers.MapPut("/{id:guid}", (Guid id, SaveCustomerRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateCustomerAsync(id, request, ct)))); + + var orders = app.MapGroup("/api/sales-orders"); + + orders.MapGet("/", (string? search, string? status, Guid? customerId, int? page, int? pageSize, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, status, customerId, page ?? 1, pageSize ?? 50, ct)))); + + orders.MapGet("/{id:guid}", (Guid id, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + orders.MapPost("/", (SaveSalesOrderRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => + { + var order = await service.CreateAsync(request, ct); + return Results.Created($"/api/sales-orders/{order.Id}", order); + })); + + orders.MapPut("/{id:guid}", (Guid id, SaveSalesOrderRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateAsync(id, request, ct)))); + + orders.MapPost("/{id:guid}/confirm", (Guid id, ConfirmSalesOrderRequest? request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmAsync(id, request, ct)))); + + orders.MapPost("/{id:guid}/cancel", (Guid id, CancelSalesOrderRequest? request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.CancelAsync(id, request, ct)))); + + orders.MapDelete("/{id:guid}", (Guid id, SalesOrderService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (SalesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (SalesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (SalesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/SalesOrderImportEndpoints.cs b/src/Leiren.Erp.Api/SalesOrderImportEndpoints.cs new file mode 100644 index 0000000..8f6e15f --- /dev/null +++ b/src/Leiren.Erp.Api/SalesOrderImportEndpoints.cs @@ -0,0 +1,119 @@ +using System.Globalization; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Sales; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class SalesOrderImportEndpoints +{ + public static IEndpointRouteBuilder MapSalesOrderImportEndpoints(this IEndpointRouteBuilder app) + { + var orders = app.MapGroup("/api/sales-orders"); + + // multipart/form-data: + // file (required, real .xlsx), customerId, customerPoNumber, orderNumber, + // orderDate, requiredDeliveryDate, currency, transportMode, loadingPort, + // destinationPort, destinationCountry, tradeTerm, paymentTerms, + // shippingNote, remark, sheetName, createDraft, attachOriginal, uploadedBy + // Without createDraft this is a pure preview: nothing is persisted and + // every bad row is reported with its worksheet row number. With + // createDraft a Draft order is created only when all rows are valid; + // attachOriginal additionally stores the uploaded file as the order's + // original PO through FileService. + orders.MapPost("/import-po", (HttpRequest request, PoExcelImportService service, CancellationToken ct) => + Handle(async () => + { + if (!request.HasFormContentType) + throw new SalesValidationException("file", "PO 导入必须使用 multipart/form-data 上传 .xlsx 文件。"); + + var form = await request.ReadFormAsync(ct); + var file = form.Files.GetFile("file") ?? form.Files.FirstOrDefault(); + if (file is null || file.Length == 0) + throw new SalesValidationException("file", "请选择要导入的 PO Excel 文件。"); + + await using var content = file.OpenReadStream(); + var result = await service.ImportAsync(content, file.FileName, file.ContentType, new PoExcelImportOptions( + CustomerId: ParseGuid(FormValue(form, "customerId")), + CustomerPoNumber: FormValue(form, "customerPoNumber"), + OrderNumber: FormValue(form, "orderNumber"), + OrderDate: ParseDate(FormValue(form, "orderDate"), "orderDate"), + RequiredDeliveryDate: ParseDate(FormValue(form, "requiredDeliveryDate"), "requiredDeliveryDate"), + Currency: FormValue(form, "currency"), + TransportMode: FormValue(form, "transportMode"), + LoadingPort: FormValue(form, "loadingPort"), + DestinationPort: FormValue(form, "destinationPort"), + DestinationCountry: FormValue(form, "destinationCountry"), + TradeTerm: FormValue(form, "tradeTerm"), + PaymentTerms: FormValue(form, "paymentTerms"), + ShippingNote: FormValue(form, "shippingNote"), + Remark: FormValue(form, "remark"), + SheetName: FormValue(form, "sheetName"), + CreateDraft: ParseBool(FormValue(form, "createDraft")), + AttachOriginal: ParseBool(FormValue(form, "attachOriginal") ?? FormValue(form, "saveOriginalPo")), + UploadedBy: FormValue(form, "uploadedBy")), ct); + + return result.CreatedOrder is { } order + ? Results.Created($"/api/sales-orders/{order.Id}", result) + : Results.Ok(result); + })).DisableAntiforgery(); + + return app; + } + + private static string? FormValue(IFormCollection form, string key) + => form.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value.ToString()) + ? value.ToString().Trim() + : null; + + private static Guid? ParseGuid(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (!Guid.TryParse(value, out var parsed)) + throw new SalesValidationException("customerId", "customerId 不是有效的标识。"); + return parsed; + } + + private static bool ParseBool(string? value) + => bool.TryParse(value, out var parsed) && parsed; + + private static DateOnly? ParseDate(string? value, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (DateOnly.TryParseExact(value.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + return date; + throw new SalesValidationException(field, $"{field} 必须为 yyyy-MM-dd 格式。"); + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (SalesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (SalesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (SalesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidDataException ex) + { + return Results.Problem(title: "文件无效", detail: ex.Message, statusCode: StatusCodes.Status400BadRequest); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/ShippingEndpoints.cs b/src/Leiren.Erp.Api/ShippingEndpoints.cs new file mode 100644 index 0000000..7da052f --- /dev/null +++ b/src/Leiren.Erp.Api/ShippingEndpoints.cs @@ -0,0 +1,87 @@ +using Leiren.Erp.Application.Shipping; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class ShippingEndpoints +{ + public static IEndpointRouteBuilder MapShippingEndpoints(this IEndpointRouteBuilder app) + { + var batches = app.MapGroup("/api/shipping-batches"); + + batches.MapGet("/", (Guid? salesOrderId, string? status, string? search, + int? page, int? pageSize, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListBatchesAsync( + salesOrderId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + batches.MapGet("/ready-orders", (ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListReadyOrdersAsync(ct)))); + + batches.MapGet("/{id:guid}", (Guid id, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetBatchAsync(id, ct)))); + + batches.MapPost("/", (CreateShippingBatchRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => + { + var batch = await service.CreateBatchAsync(request, ct); + return Results.Created($"/api/shipping-batches/{batch.Id}", batch); + })); + + batches.MapPut("/{id:guid}", (Guid id, UpdateShippingBatchRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateBatchAsync(id, request, ct)))); + + batches.MapPost("/{id:guid}/confirm", (Guid id, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmBatchAsync(id, confirmedBy: null, ct)))); + + batches.MapPost("/{id:guid}/cancel", (Guid id, CancelShippingBatchRequest? request, ShippingService service, CancellationToken ct) => + Handle(async () => + { + await service.CancelBatchAsync(id, request?.Reason, ct); + return Results.NoContent(); + })); + + batches.MapPost("/{id:guid}/containers", (Guid id, SaveShippingContainerRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AddContainerAsync(id, request, ct)))); + + batches.MapPut("/{id:guid}/containers/{containerId:guid}", (Guid id, Guid containerId, SaveShippingContainerRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateContainerAsync(id, containerId, request, ct)))); + + batches.MapDelete("/{id:guid}/containers/{containerId:guid}", (Guid id, Guid containerId, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.RemoveContainerAsync(id, containerId, ct)))); + + batches.MapPost("/{id:guid}/lines", (Guid id, SaveShipmentLineRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AddLineAsync(id, request, ct)))); + + batches.MapPut("/{id:guid}/lines/{lineId:guid}", (Guid id, Guid lineId, SaveShipmentLineRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateLineAsync(id, lineId, request, ct)))); + + batches.MapDelete("/{id:guid}/lines/{lineId:guid}", (Guid id, Guid lineId, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.RemoveLineAsync(id, lineId, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (ShippingValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (ShippingNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (ShippingConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/appsettings.Development.json b/src/Leiren.Erp.Api/appsettings.Development.json new file mode 100644 index 0000000..c5d74a5 --- /dev/null +++ b/src/Leiren.Erp.Api/appsettings.Development.json @@ -0,0 +1,14 @@ +{ + "ConnectionStrings": { + "Default": "Data Source=data/leiren-dev.db" + }, + "Database": { + "Provider": "Sqlite" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/src/Leiren.Erp.Api/appsettings.json b/src/Leiren.Erp.Api/appsettings.json new file mode 100644 index 0000000..d57caa6 --- /dev/null +++ b/src/Leiren.Erp.Api/appsettings.json @@ -0,0 +1,27 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Database": { + "Provider": "Sqlite" + }, + "HealthChecks": { + "DatabaseTimeout": "00:00:05" + }, + "PurchaseContract": { + "TemplatePath": "templates/purchase-contract.xlsx" + }, + "FileStorage": { + "RootPath": "data/storage", + "MaxFileSizeBytes": 52428800, + "AllowedExtensions": [ + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".txt", ".csv", ".zip", ".rar", ".7z" + ] + } +} diff --git a/src/Leiren.Erp.Api/templates/billing/开票购销合同.xlsx b/src/Leiren.Erp.Api/templates/billing/开票购销合同.xlsx new file mode 100644 index 0000000..2d12136 Binary files /dev/null and b/src/Leiren.Erp.Api/templates/billing/开票购销合同.xlsx differ diff --git a/src/Leiren.Erp.Api/templates/billing/开票通知.xlsx b/src/Leiren.Erp.Api/templates/billing/开票通知.xlsx new file mode 100644 index 0000000..63431a6 Binary files /dev/null and b/src/Leiren.Erp.Api/templates/billing/开票通知.xlsx differ diff --git a/src/Leiren.Erp.Api/templates/customs/报关单.xlsx b/src/Leiren.Erp.Api/templates/customs/报关单.xlsx new file mode 100644 index 0000000..ef7cd83 Binary files /dev/null and b/src/Leiren.Erp.Api/templates/customs/报关单.xlsx differ diff --git a/src/Leiren.Erp.Api/templates/customs/报关发票.xlsx b/src/Leiren.Erp.Api/templates/customs/报关发票.xlsx new file mode 100644 index 0000000..4814100 Binary files /dev/null and b/src/Leiren.Erp.Api/templates/customs/报关发票.xlsx differ diff --git a/src/Leiren.Erp.Api/templates/customs/报关外销合同.xlsx b/src/Leiren.Erp.Api/templates/customs/报关外销合同.xlsx new file mode 100644 index 0000000..6972365 Binary files /dev/null and b/src/Leiren.Erp.Api/templates/customs/报关外销合同.xlsx differ diff --git a/src/Leiren.Erp.Api/templates/customs/报关装箱单.xlsx b/src/Leiren.Erp.Api/templates/customs/报关装箱单.xlsx new file mode 100644 index 0000000..c86a9cb Binary files /dev/null and b/src/Leiren.Erp.Api/templates/customs/报关装箱单.xlsx differ diff --git a/src/Leiren.Erp.Api/templates/purchase-contract.xlsx b/src/Leiren.Erp.Api/templates/purchase-contract.xlsx new file mode 100644 index 0000000..fc918d2 Binary files /dev/null and b/src/Leiren.Erp.Api/templates/purchase-contract.xlsx differ diff --git a/src/Leiren.Erp.Application/Billing/BillingDocumentExportService.cs b/src/Leiren.Erp.Application/Billing/BillingDocumentExportService.cs new file mode 100644 index 0000000..f384035 --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/BillingDocumentExportService.cs @@ -0,0 +1,77 @@ +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Billing; + +/// Absolute paths of the built-in 开票通知 / 开票购销合同 templates. +public sealed record BillingTemplateOptions(string NoticeTemplatePath, string ContractTemplatePath); + +/// +/// Renders a supplier notice's 开票通知书 or 开票用产品购销合同 as XLSX. +/// The most recently imported template of that type (template editor) wins; +/// without one the configured built-in template is used. Nothing is stored. +/// +public sealed class BillingDocumentExportService(IBillingDbContext db, FileService files, BillingTemplateOptions options) +{ + public async Task<(byte[] Bytes, string FileName)> RenderAsync(Guid noticeId, string kind, CancellationToken ct = default) + { + var (label, fallbackPath) = kind switch + { + DocumentTemplateKinds.SupplierInvoiceNoticeKind => ("开票通知", options.NoticeTemplatePath), + DocumentTemplateKinds.SupplierBillingContractKind => ("开票购销合同", options.ContractTemplatePath), + _ => throw new BillingValidationException(nameof(kind), "单据类型只能是开票通知或开票购销合同。"), + }; + + var notice = await db.SupplierInvoiceNotices.AsNoTracking() + .Include(x => x.Lines) + .Include(x => x.BillingContract) + .SingleOrDefaultAsync(x => x.Id == noticeId, ct) + ?? throw new BillingNotFoundException("开票通知不存在。"); + + var template = await LoadTemplateAsync(kind, fallbackPath, label, ct); + var bytes = BillingDocumentRenderer.Render(template, notice, label); + return (bytes, $"{Sanitize(notice.NoticeNo)}-{Sanitize(notice.SupplierName)}-{label}.xlsx"); + } + + /// Renders a template file against a notice for the template editor preview. + public async Task PreviewAsync(byte[] template, Guid noticeId, string label, CancellationToken ct = default) + { + var notice = await db.SupplierInvoiceNotices.AsNoTracking() + .Include(x => x.Lines) + .Include(x => x.BillingContract) + .SingleOrDefaultAsync(x => x.Id == noticeId, ct) + ?? throw new BillingNotFoundException("开票通知不存在。"); + return BillingDocumentRenderer.Render(template, notice, label); + } + + private async Task LoadTemplateAsync(string kind, string fallbackPath, string label, CancellationToken ct) + { + var imported = (await files.ListAsync( + DocumentTemplateService.TemplateOwnerType, null, kind, null, currentOnly: true, 1, 200, ct)) + .MaxBy(x => x.CreatedAt); + if (imported is not null) + { + await using var content = (await files.OpenDownloadAsync(imported.Id, ct)).Content; + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + return buffer.ToArray(); + } + + try + { + return await File.ReadAllBytesAsync(fallbackPath, ct); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new BillingValidationException("Template", $"{label}模板读取失败:{ex.Message}"); + } + } + + private static string Sanitize(string value) + { + var invalid = Path.GetInvalidFileNameChars(); + var stem = new string(value.Select(ch => invalid.Contains(ch) || ch < 32 ? '_' : ch).ToArray()).Trim(); + return stem.Length == 0 ? "billing" : stem; + } +} diff --git a/src/Leiren.Erp.Application/Billing/BillingDocumentRenderer.cs b/src/Leiren.Erp.Application/Billing/BillingDocumentRenderer.cs new file mode 100644 index 0000000..0996b18 --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/BillingDocumentRenderer.cs @@ -0,0 +1,192 @@ +using System.Globalization; +using System.Text; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Domain.Entities; + +namespace Leiren.Erp.Application.Billing; + +/// +/// Renders the supplier 开票通知书 and 开票用产品购销合同 from a notice +/// snapshot (whose lines were taken from the customs declaration) through +/// . Both document types share one +/// built-in placeholder catalog. +/// +public static class BillingDocumentRenderer +{ + private static readonly string[] HeaderFields = + [ + "NoticeNo", "NoticeDate", "ExportInvoiceNo", "ShipmentNo", "SalesOrderNo", "CustomerPoNo", "ShipmentDate", + "PurchaseContractNo", "ContractNo", "SignedPlace", "SignedDate", + "SupplierName", "SupplierContact", "SupplierPhone", "SupplierFax", "SupplierAddress", + "InvoiceTitle", "InvoiceTitleAddress", "InvoiceTitlePhone", "InvoiceTitleBankName", "InvoiceTitleBankAccount", + "InvoiceTitleTaxNo", "InvoiceTitleCustomsCode", "InvoicingRequirement", "StampRequirement", "ContactName", + "MailingAddress", "Remark", "Currency", + "BuyerName", "BuyerAddress", "BuyerPhone", "BuyerFax", "BuyerBankName", "BuyerBankAccount", "BuyerTaxNo", + "SellerName", "SellerAddress", "SellerContact", "SellerPhone", "SellerFax", + "QualityTechnicalTerms", "DeliveryTerms", "PackagingTerms", "SettlementTerms", "TaxTerms", "IntellectualPropertyTerms", + "LineCount", "TotalQuantity", "TotalAmountIncludingTax", "TotalAmountExcludingTax", "TotalTaxAmount", "TotalAmountInWords", + "TotalAmountText", + ]; + + private static readonly TokenTemplateFields Fields = new( + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "LineNumber", "ProductName", "ProductNameEn", "InternalSku", "CustomerSku", "Specification", "Quantity", "Unit", + "TaxIncludedUnitPrice", "TaxExcludingUnitPrice", "AmountIncludingTax", "AmountExcludingTax", "TaxAmount", "TaxRate", + "LinePurchaseContractNo", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "LineNumber", "Quantity", "TaxIncludedUnitPrice", "TaxExcludingUnitPrice", "AmountIncludingTax", "AmountExcludingTax", + "TaxAmount", "TaxRate", "LineCount", "TotalQuantity", "TotalAmountIncludingTax", "TotalAmountExcludingTax", "TotalTaxAmount", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) { "NoticeDate", "ShipmentDate", "SignedDate" }); + + /// Every placeholder name a 开票通知 / 开票购销合同 template may use. + public static IReadOnlyList FieldNames { get; } = [.. HeaderFields, .. Fields.LineFields]; + + public static byte[] Render(byte[] templateBytes, SupplierInvoiceNotice notice, string documentLabel) + { + ArgumentNullException.ThrowIfNull(notice); + var lines = notice.Lines.OrderBy(x => x.InternalSku, StringComparer.Ordinal).ThenBy(x => x.ContentDescription, StringComparer.Ordinal).ToList(); + return TokenWorkbookRenderer.Render( + templateBytes, BuildHeaderValues(notice), lines.Select((l, i) => (IReadOnlyDictionary)BuildLineValues(l, i)).ToList(), + Fields, documentLabel, message => new BillingValidationException("Template", message)); + } + + private static string N(decimal value) => value.ToString("0.####", CultureInfo.InvariantCulture); + private static string? D(DateOnly? value) => value?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + + private static Dictionary BuildHeaderValues(SupplierInvoiceNotice n) + { + var c = n.BillingContract; + return new(StringComparer.OrdinalIgnoreCase) + { + ["NoticeNo"] = n.NoticeNo, + ["NoticeDate"] = D(n.NoticeDate), + ["ExportInvoiceNo"] = n.ExportInvoiceNo, + ["ShipmentNo"] = n.ShipmentNo, + ["SalesOrderNo"] = n.SalesOrderNo, + ["CustomerPoNo"] = n.CustomerPoNo, + ["ShipmentDate"] = D(n.ShipmentDate), + ["PurchaseContractNo"] = c?.ContractNo ?? n.PurchaseContractNo, + ["ContractNo"] = c?.ContractNo ?? n.PurchaseContractNo ?? n.NoticeNo, + ["SignedPlace"] = c?.SignedPlace, + ["SignedDate"] = D(c?.SignedDate ?? n.NoticeDate), + ["SupplierName"] = n.SupplierName, + ["SupplierContact"] = n.SupplierContact, + ["SupplierPhone"] = n.SupplierPhone, + ["SupplierFax"] = n.SupplierFax, + ["SupplierAddress"] = n.SupplierAddress, + ["InvoiceTitle"] = n.InvoiceTitle, + ["InvoiceTitleAddress"] = n.InvoiceTitleAddress, + ["InvoiceTitlePhone"] = n.InvoiceTitlePhone, + ["InvoiceTitleBankName"] = n.InvoiceTitleBankName, + ["InvoiceTitleBankAccount"] = n.InvoiceTitleBankAccount, + ["InvoiceTitleTaxNo"] = n.InvoiceTitleTaxNo, + ["InvoiceTitleCustomsCode"] = n.InvoiceTitleCustomsCode, + ["InvoicingRequirement"] = n.InvoicingRequirement, + ["StampRequirement"] = n.StampRequirement, + ["ContactName"] = n.ContactName, + ["MailingAddress"] = n.MailingAddress, + ["Remark"] = n.Remark, + ["Currency"] = n.Currency, + ["BuyerName"] = c?.BuyerName ?? n.InvoiceTitle, + ["BuyerAddress"] = c?.BuyerAddress ?? n.InvoiceTitleAddress, + ["BuyerPhone"] = c?.BuyerPhone ?? n.InvoiceTitlePhone, + ["BuyerFax"] = c?.BuyerFax, + ["BuyerBankName"] = c?.BuyerBankName ?? n.InvoiceTitleBankName, + ["BuyerBankAccount"] = c?.BuyerBankAccount ?? n.InvoiceTitleBankAccount, + ["BuyerTaxNo"] = c?.BuyerTaxNo ?? n.InvoiceTitleTaxNo, + ["SellerName"] = c?.SellerName ?? n.SupplierName, + ["SellerAddress"] = c?.SellerAddress ?? n.SupplierAddress, + ["SellerContact"] = c?.SellerContact ?? n.SupplierContact, + ["SellerPhone"] = c?.SellerPhone ?? n.SupplierPhone, + ["SellerFax"] = c?.SellerFax ?? n.SupplierFax, + ["QualityTechnicalTerms"] = c?.QualityTechnicalTerms, + ["DeliveryTerms"] = c?.DeliveryTerms, + ["PackagingTerms"] = c?.PackagingTerms, + ["SettlementTerms"] = c?.SettlementTerms, + ["TaxTerms"] = c?.TaxTerms, + ["IntellectualPropertyTerms"] = c?.IntellectualPropertyTerms, + ["LineCount"] = n.Lines.Count.ToString(CultureInfo.InvariantCulture), + ["TotalQuantity"] = N(n.TotalQuantity), + ["TotalAmountText"] = n.TotalAmountIncludingTax.ToString("#,##0.00", CultureInfo.InvariantCulture), + ["TotalAmountIncludingTax"] = N(n.TotalAmountIncludingTax), + ["TotalAmountExcludingTax"] = N(n.TotalAmountExcludingTax), + ["TotalTaxAmount"] = N(n.TotalTaxAmount), + ["TotalAmountInWords"] = RmbInWords(n.TotalAmountIncludingTax), + }; + } + + private static Dictionary BuildLineValues(SupplierInvoiceNoticeLine l, int index) => new(StringComparer.OrdinalIgnoreCase) + { + ["LineNumber"] = (index + 1).ToString(CultureInfo.InvariantCulture), + ["ProductName"] = string.IsNullOrWhiteSpace(l.ContentDescription) ? l.ProductNameZh : l.ContentDescription, + ["ProductNameEn"] = l.ProductNameEn, + ["InternalSku"] = l.InternalSku, + ["CustomerSku"] = l.CustomerSku, + ["Specification"] = l.Specification, + ["Quantity"] = N(l.Quantity), + ["Unit"] = l.Unit, + ["TaxIncludedUnitPrice"] = N(l.TaxIncludedUnitPrice), + ["TaxExcludingUnitPrice"] = N(l.TaxExcludingUnitPrice), + ["AmountIncludingTax"] = N(l.AmountIncludingTax), + ["AmountExcludingTax"] = N(l.AmountExcludingTax), + ["TaxAmount"] = N(l.TaxAmount), + ["TaxRate"] = N(l.TaxRate), + ["LinePurchaseContractNo"] = l.PurchaseContractNo, + }; + + /// Chinese uppercase RMB amount, e.g. 66211.20 → 陆万陆仟贰佰壹拾壹元贰角. + public static string RmbInWords(decimal amount) + { + const string digits = "零壹贰叁肆伍陆柒捌玖"; + string[] units = ["", "拾", "佰", "仟"]; + string[] sections = ["", "万", "亿", "万亿"]; + + var negative = amount < 0; + var fen = (long)decimal.Round(Math.Abs(amount) * 100, 0, MidpointRounding.AwayFromZero); + var yuan = fen / 100; + var jiao = (int)(fen / 10 % 10); + var cents = (int)(fen % 10); + + var text = new StringBuilder(); + if (yuan == 0) + { + text.Append('零'); + } + else + { + var groups = new List(); + for (var v = yuan; v > 0; v /= 10000) groups.Add((int)(v % 10000)); + var needZero = false; + for (var g = groups.Count - 1; g >= 0; g--) + { + var value = groups[g]; + if (value == 0) { needZero = text.Length > 0; continue; } + if (needZero || (text.Length > 0 && value < 1000)) text.Append('零'); + needZero = false; + var zero = false; + for (var p = 3; p >= 0; p--) + { + var d = value / (int)Math.Pow(10, p) % 10; + if (d == 0) { zero = true; continue; } + if (zero && text.Length > 0 && text[^1] != '零') text.Append('零'); + zero = false; + text.Append(digits[d]).Append(units[p]); + } + text.Append(sections[g]); + } + } + text.Append('元'); + if (jiao == 0 && cents == 0) text.Append('整'); + else + { + if (jiao > 0) text.Append(digits[jiao]).Append('角'); + else if (yuan > 0) text.Append('零'); + if (cents > 0) text.Append(digits[cents]).Append('分'); + } + return (negative ? "负" : "") + text; + } +} diff --git a/src/Leiren.Erp.Application/Billing/BillingExceptions.cs b/src/Leiren.Erp.Application/Billing/BillingExceptions.cs new file mode 100644 index 0000000..2ef34de --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/BillingExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Billing; + +public sealed class BillingNotFoundException(string message) : Exception(message); + +public sealed class BillingConflictException(string message) : Exception(message); + +public sealed class BillingValidationException(IReadOnlyDictionary errors) + : Exception("供应商开票资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public BillingValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Billing/BillingService.cs b/src/Leiren.Erp.Application/Billing/BillingService.cs new file mode 100644 index 0000000..416e90c --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/BillingService.cs @@ -0,0 +1,843 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Billing; + +public sealed class BillingService(IBillingDbContext db) +{ + // ---------- Notices ---------- + + public async Task> ListNoticesAsync( + Guid? shippingBatchId, Guid? purchaseContractId, Guid? supplierId, string? status, string? search, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.SupplierInvoiceNotices.AsNoTracking().Include(x => x.Lines).Include(x => x.Invoices).AsQueryable(); + if (shippingBatchId is not null) query = query.Where(x => x.ShippingBatchId == shippingBatchId.Value); + if (purchaseContractId is not null) query = query.Where(x => x.PurchaseContractId == purchaseContractId.Value); + if (supplierId is not null) query = query.Where(x => x.SupplierId == supplierId.Value); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new BillingValidationException(nameof(status), "开票通知状态无效。"); + query = query.Where(x => x.Status == parsed); + } + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.NoticeNo.Contains(term) || x.SupplierName.Contains(term) || + (x.ExportInvoiceNo != null && x.ExportInvoiceNo.Contains(term)) || + (x.PurchaseContractNo != null && x.PurchaseContractNo.Contains(term)) || + (x.ShipmentNo != null && x.ShipmentNo.Contains(term)) || + (x.SalesOrderNo != null && x.SalesOrderNo.Contains(term))); + } + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new SupplierInvoiceNoticeListItemDto( + x.Id, x.NoticeNo, x.Status.ToString(), x.ShippingBatchId, x.ShipmentNo, x.ExportInvoiceNo, + x.PurchaseContractNo, x.SupplierName, x.Currency, x.TotalAmountIncludingTax, + x.InvoicedAmountIncludingTax, x.RemainingAmountIncludingTax, x.NoticeDate, x.UpdatedAt)).ToList(); + } + + public async Task GetNoticeAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadNoticeAsync(id, ct)); + + public async Task CreateNoticeAsync(CreateSupplierInvoiceNoticeRequest request, CancellationToken ct = default) + { + if (request.Lines is null || request.Lines.Count == 0) + throw new BillingValidationException(nameof(request.Lines), "开票通知至少需要一条明细。"); + var supplierName = TrimOrNull(request.SupplierName); + if (supplierName is null) + throw new BillingValidationException(nameof(request.SupplierName), "供应商不能为空。"); + + var noticeNo = string.IsNullOrWhiteSpace(request.NoticeNo) + ? await GenerateNoticeNoAsync(ct) + : request.NoticeNo.Trim(); + if (await db.SupplierInvoiceNotices.AnyAsync(x => x.NoticeNo == noticeNo, ct)) + throw new BillingConflictException($"开票通知号 {noticeNo} 已存在。"); + + var notice = new SupplierInvoiceNotice + { + NoticeNo = noticeNo, + ShippingBatchId = request.ShippingBatchId, + ShipmentNo = TrimOrNull(request.ShipmentNo), + BillOfLadingNo = TrimOrNull(request.BillOfLadingNo), + VesselName = TrimOrNull(request.VesselName), + VoyageNo = TrimOrNull(request.VoyageNo), + LoadingPort = TrimOrNull(request.LoadingPort), + DestinationPort = TrimOrNull(request.DestinationPort), + ShipmentDate = request.ShipmentDate, + ExportInvoiceNo = TrimOrNull(request.ExportInvoiceNo), + SalesOrderId = request.SalesOrderId, + SalesOrderNo = TrimOrNull(request.SalesOrderNo), + CustomerPoNo = TrimOrNull(request.CustomerPoNo), + PurchaseContractId = request.PurchaseContractId, + PurchaseContractNo = TrimOrNull(request.PurchaseContractNo), + SupplierId = request.SupplierId, + SupplierName = supplierName, + SupplierContact = TrimOrNull(request.SupplierContact), + SupplierPhone = TrimOrNull(request.SupplierPhone), + SupplierFax = TrimOrNull(request.SupplierFax), + SupplierAddress = TrimOrNull(request.SupplierAddress), + InvoiceTitle = TrimOrNull(request.InvoiceTitle), + InvoiceTitleAddress = TrimOrNull(request.InvoiceTitleAddress), + InvoiceTitlePhone = TrimOrNull(request.InvoiceTitlePhone), + InvoiceTitleBankName = TrimOrNull(request.InvoiceTitleBankName), + InvoiceTitleBankAccount = TrimOrNull(request.InvoiceTitleBankAccount), + InvoiceTitleTaxNo = TrimOrNull(request.InvoiceTitleTaxNo), + InvoiceTitleCustomsCode = TrimOrNull(request.InvoiceTitleCustomsCode), + Currency = NormalizeCurrency(request.Currency), + InvoicingRequirement = TrimOrNull(request.InvoicingRequirement), + StampRequirement = TrimOrNull(request.StampRequirement), + ContactName = TrimOrNull(request.ContactName), + MailingAddress = TrimOrNull(request.MailingAddress), + Remark = TrimOrNull(request.Remark), + NoticeDate = request.NoticeDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + }; + notice.Lines = request.Lines.Select(x => BuildLine(notice.Id, x)).ToList(); + notice.BillingContract = BuildBillingContract(notice, request.BillingContractNo, request.SignedPlace, request.SignedDate, + quality: null, delivery: null, packaging: null, settlement: null, tax: null, ip: null); + db.SupplierInvoiceNotices.Add(notice); + await db.SaveChangesAsync(ct); + return ToDto(await LoadNoticeAsync(notice.Id, ct)); + } + + /// + /// One notice (and its billing contract) per supplier of a confirmed + /// shipping batch. Content comes from the batch's confirmed customs + /// declaration: every declaration line keeps the declared customs name and + /// unit; when several suppliers took part in a line (parts, packaging ...) + /// the declared quantity is split between them in proportion to their + /// tax-included purchase amounts for the shipped share, so the suppliers' + /// quantities add up exactly to the declaration. Each supplier invoices its + /// own purchase amount (unit price = amount / allocated quantity). + /// + public async Task GenerateFromShippingBatchAsync( + GenerateBillingNoticesRequest request, CancellationToken ct = default) + { + var batch = await db.ShippingBatches.AsNoTracking().Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == request.ShippingBatchId, ct) + ?? throw new BillingNotFoundException("出货批次不存在。"); + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new BillingConflictException("只有已确认的出货批次可以生成供应商开票通知。"); + if (batch.Lines.Count == 0) + throw new BillingValidationException(nameof(batch.Lines), "出货批次没有出货明细,不能生成开票通知。"); + + var declaration = (await db.CustomsDeclarations.AsNoTracking().Include(x => x.Lines) + .Where(x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Confirmed) + .ToListAsync(ct)) + .MaxBy(x => x.Version) + ?? throw new BillingConflictException("开票内容取自报关资料:请先在出货与报关中确认该批次的报关资料。"); + + var shipmentLines = batch.Lines.ToDictionary(x => x.Id); + var salesLineIds = batch.Lines.Select(x => x.SalesOrderLineId).Distinct().ToList(); + var orderedBySalesLine = await db.SalesOrderLines.AsNoTracking() + .Where(x => salesLineIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.Quantity, ct); + var tasksBySalesLine = (await db.PurchaseTasks.AsNoTracking() + .Where(x => salesLineIds.Contains(x.SalesOrderLineId) && x.Status != PurchaseTaskStatus.Cancelled) + .ToListAsync(ct)) + .GroupBy(x => x.SalesOrderLineId) + .ToDictionary(g => g.Key, g => g.ToList()); + var contractIds = tasksBySalesLine.Values.SelectMany(x => x) + .Select(x => x.PurchaseContractId).Where(x => x is not null).Select(x => x!.Value).Distinct().ToList(); + var contracts = await db.PurchaseContracts.AsNoTracking().Where(x => contractIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + + // Supplier key -> allocated lines. + var groups = new Dictionary Tasks, decimal Quantity, decimal Amount)>>(StringComparer.OrdinalIgnoreCase); + foreach (var declared in declaration.Lines.OrderBy(x => x.LineNumber)) + { + if (!shipmentLines.TryGetValue(declared.ShipmentLineId, out var shipment)) + throw new BillingValidationException(nameof(declaration.Lines), $"报关明细 {declared.LineNumber} 对应的出货明细不存在,请作废后重新生成报关资料。"); + if (!tasksBySalesLine.TryGetValue(shipment.SalesOrderLineId, out var tasks) || tasks.Count == 0) + throw new BillingValidationException(nameof(shipment.SalesOrderLineId), $"{shipment.InternalSku} 没有采购任务,无法确定供应商和采购价格。"); + var missingSupplier = tasks.FirstOrDefault(x => string.IsNullOrWhiteSpace(x.SupplierName)); + if (missingSupplier is not null) + throw new BillingValidationException(nameof(PurchaseTask.SupplierName), $"采购任务「{missingSupplier.ContentDescription}」没有供应商,不能生成开票通知。"); + + // Share of the order line that this shipment carries. + var ordered = orderedBySalesLine.GetValueOrDefault(shipment.SalesOrderLineId); + var share = ordered > 0 ? shipment.Quantity / ordered : 1m; + var bySupplier = tasks.GroupBy(SupplierKey).OrderBy(g => g.First().SupplierName).ToList(); + var amounts = bySupplier + .Select(g => decimal.Round(g.Sum(TaxIncludedAmount) * share, 2, MidpointRounding.AwayFromZero)) + .ToArray(); + var quantities = AllocateQuantity(declared.Quantity, amounts); + for (var i = 0; i < bySupplier.Count; i++) + { + if (!groups.TryGetValue(bySupplier[i].Key, out var list)) groups[bySupplier[i].Key] = list = []; + list.Add((declared, shipment, bySupplier[i].ToList(), quantities[i], amounts[i])); + } + } + + // Duplicate guard before creating anything, so a failed run creates no partial notices. + foreach (var group in groups.Values) + { + var first = group[0].Tasks[0]; + var exists = await db.SupplierInvoiceNotices.AnyAsync(x => + x.ShippingBatchId == batch.Id && x.Status != SupplierInvoiceNoticeStatus.Voided && + ((first.SupplierId != null && x.SupplierId == first.SupplierId) || (first.SupplierId == null && x.SupplierName == first.SupplierName)), ct); + if (exists) + throw new BillingConflictException($"出货批次 {batch.BatchNo} 已为供应商「{first.SupplierName}」生成过开票通知。"); + } + + var supplierIds = groups.Values.Select(x => x[0].Tasks[0].SupplierId).Where(x => x is not null).Select(x => x!.Value).ToList(); + var suppliers = await db.Suppliers.AsNoTracking().Where(x => supplierIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + // Invoice title / mailing details default to the last notice issued, so they are typed once. + var previous = (await db.SupplierInvoiceNotices.AsNoTracking() + .Where(x => x.InvoiceTitle != null) + .ToListAsync(ct)) + .MaxBy(x => x.CreatedAt); + string? Pick(string? value, string? fallback) => TrimOrNull(value) ?? TrimOrNull(fallback); + + var created = new List(); + foreach (var group in groups.Values.OrderBy(x => x[0].Tasks[0].SupplierName)) + { + var first = group[0].Tasks[0]; + var supplier = first.SupplierId is { } sid ? suppliers.GetValueOrDefault(sid) : null; + var contract = group.SelectMany(x => x.Tasks).Select(x => x.PurchaseContractId) + .Where(x => x is not null).Select(x => contracts.GetValueOrDefault(x!.Value)).FirstOrDefault(x => x is not null); + var notice = new SupplierInvoiceNotice + { + NoticeNo = await GenerateNoticeNoAsync(ct), + ShippingBatchId = batch.Id, + ShipmentNo = batch.BatchNo, + BillOfLadingNo = TrimOrNull(batch.BillOfLadingNo), + VesselName = TrimOrNull(batch.VesselName), + VoyageNo = TrimOrNull(batch.VoyageNo), + LoadingPort = TrimOrNull(batch.LoadingPort), + DestinationPort = TrimOrNull(batch.DestinationPort), + ShipmentDate = request.ShipmentDate ?? declaration.ExportDate ?? batch.ShipmentDate, + ExportInvoiceNo = TrimOrNull(request.ExportInvoiceNo) ?? TrimOrNull(declaration.InvoiceNo) ?? batch.BatchNo, + SalesOrderId = batch.SalesOrderId, + SalesOrderNo = TrimOrNull(batch.SalesOrderNo), + CustomerPoNo = TrimOrNull(batch.CustomerPoNo), + PurchaseContractId = contract?.Id, + PurchaseContractNo = contract?.ContractNo, + SupplierId = first.SupplierId, + SupplierName = first.SupplierName, + SupplierContact = contract?.SupplierContact ?? supplier?.ContactName, + SupplierPhone = contract?.SupplierPhone ?? supplier?.ContactPhone, + SupplierAddress = supplier?.Address, + InvoiceTitle = Pick(request.InvoiceTitle, previous?.InvoiceTitle), + InvoiceTitleAddress = Pick(request.InvoiceTitleAddress, previous?.InvoiceTitleAddress), + InvoiceTitlePhone = Pick(request.InvoiceTitlePhone, previous?.InvoiceTitlePhone), + InvoiceTitleBankName = Pick(request.InvoiceTitleBankName, previous?.InvoiceTitleBankName), + InvoiceTitleBankAccount = Pick(request.InvoiceTitleBankAccount, previous?.InvoiceTitleBankAccount), + InvoiceTitleTaxNo = Pick(request.InvoiceTitleTaxNo, previous?.InvoiceTitleTaxNo), + InvoiceTitleCustomsCode = Pick(request.InvoiceTitleCustomsCode, previous?.InvoiceTitleCustomsCode), + Currency = "CNY", + InvoicingRequirement = Pick(request.InvoicingRequirement, previous?.InvoicingRequirement), + StampRequirement = Pick(request.StampRequirement, previous?.StampRequirement), + ContactName = Pick(request.ContactName, previous?.ContactName), + MailingAddress = Pick(request.MailingAddress, previous?.MailingAddress), + NoticeDate = request.NoticeDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + Lines = group.Select(item => + { + var main = item.Tasks.MaxBy(TaxIncludedAmount)!; + return new SupplierInvoiceNoticeLine + { + ShipmentLineId = item.Shipment.Id, + PurchaseTaskId = main.Id, + PurchaseContractId = main.PurchaseContractId, + PurchaseContractNo = main.PurchaseContractId is { } c ? contracts.GetValueOrDefault(c)?.ContractNo : null, + SalesOrderLineId = item.Shipment.SalesOrderLineId, + ProductId = main.ProductId, + InternalSku = item.Declared.InternalSku, + CustomerSku = item.Declared.CustomerSku, + // Name and unit exactly as declared to customs. + ProductNameZh = item.Declared.CustomsNameZh ?? item.Declared.ProductNameZh, + ProductNameEn = item.Declared.CustomsNameEn ?? item.Declared.ProductNameEn, + ContentDescription = item.Declared.CustomsNameZh ?? item.Declared.ProductNameZh, + Specification = TrimOrNull(item.Declared.DeclarationElements), + Quantity = item.Quantity, + Unit = item.Declared.Unit, + UnitPrice = item.Quantity > 0 ? decimal.Round(item.Amount / item.Quantity, 4, MidpointRounding.AwayFromZero) : 0, + TaxIncluded = true, + TaxRate = main.TaxRate, + }; + }).ToList(), + }; + foreach (var line in notice.Lines) ValidateLine(line); + notice.BillingContract = BuildBillingContract(notice, billingContractNo: null, request.SignedPlace, + request.SignedDate ?? request.NoticeDate, request.QualityTechnicalTerms, request.DeliveryTerms, + request.PackagingTerms, request.SettlementTerms, request.TaxTerms, request.IntellectualPropertyTerms); + foreach (var line in notice.Lines) line.SupplierInvoiceNotice = notice; + created.Add(notice); + db.SupplierInvoiceNotices.Add(notice); + } + + await db.SaveChangesAsync(ct); + var result = new List(); + foreach (var notice in created) result.Add(ToDto(await LoadNoticeAsync(notice.Id, ct))); + return new GenerateBillingNoticesResultDto(result); + } + + private static string SupplierKey(PurchaseTask task) => $"{task.SupplierId}|{task.SupplierName}"; + + private static decimal TaxIncludedAmount(PurchaseTask task) + => task.TaxIncluded ? task.Amount : decimal.Round(task.Amount * (1 + task.TaxRate / 100m), 2, MidpointRounding.AwayFromZero); + + /// + /// Splits a declared quantity between suppliers in proportion to their + /// amounts; the parts always add up to . Whole + /// quantities stay whole (largest remainder) and every supplier gets at + /// least one unit when there are enough; otherwise thousandths are used. + /// + internal static decimal[] AllocateQuantity(decimal total, IReadOnlyList weights) + { + var n = weights.Count; + if (n == 1) return [total]; + var sum = weights.Sum(); + var w = sum > 0 ? weights.ToArray() : Enumerable.Repeat(1m, n).ToArray(); + if (sum <= 0) sum = n; + var step = total == decimal.Truncate(total) && total >= n ? 1m : 0.001m; + + var raw = w.Select(x => total * x / sum).ToArray(); + var parts = raw.Select(x => decimal.Floor(x / step) * step).ToArray(); + var remaining = total - parts.Sum(); + foreach (var i in Enumerable.Range(0, n).OrderByDescending(i => raw[i] - parts[i]).ThenBy(i => i)) + { + if (remaining < step) break; + parts[i] += step; + remaining -= step; + } + parts[Array.IndexOf(parts, parts.Max())] += remaining; // sub-step rounding residue + for (var i = 0; i < n; i++) + { + if (parts[i] > 0) continue; + var donor = Array.IndexOf(parts, parts.Max()); + if (parts[donor] <= step) break; + parts[donor] -= step; + parts[i] += step; + } + return parts; + } + + public async Task UpdateNoticeAsync(Guid id, UpdateSupplierInvoiceNoticeRequest request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + try { notice.EnsureDraft(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + + if (TrimOrNull(request.SupplierName) is { } name) notice.SupplierName = name; + notice.SupplierId = request.SupplierId ?? notice.SupplierId; + notice.SupplierContact = TrimOrNull(request.SupplierContact); + notice.SupplierPhone = TrimOrNull(request.SupplierPhone); + notice.SupplierFax = TrimOrNull(request.SupplierFax); + notice.SupplierAddress = TrimOrNull(request.SupplierAddress); + notice.ExportInvoiceNo = TrimOrNull(request.ExportInvoiceNo); + notice.PurchaseContractId = request.PurchaseContractId ?? notice.PurchaseContractId; + notice.PurchaseContractNo = TrimOrNull(request.PurchaseContractNo) ?? notice.PurchaseContractNo; + notice.InvoiceTitle = TrimOrNull(request.InvoiceTitle); + notice.InvoiceTitleAddress = TrimOrNull(request.InvoiceTitleAddress); + notice.InvoiceTitlePhone = TrimOrNull(request.InvoiceTitlePhone); + notice.InvoiceTitleBankName = TrimOrNull(request.InvoiceTitleBankName); + notice.InvoiceTitleBankAccount = TrimOrNull(request.InvoiceTitleBankAccount); + notice.InvoiceTitleTaxNo = TrimOrNull(request.InvoiceTitleTaxNo); + notice.InvoiceTitleCustomsCode = TrimOrNull(request.InvoiceTitleCustomsCode); + if (!string.IsNullOrWhiteSpace(request.Currency)) notice.Currency = NormalizeCurrency(request.Currency); + notice.InvoicingRequirement = TrimOrNull(request.InvoicingRequirement); + notice.StampRequirement = TrimOrNull(request.StampRequirement); + notice.ContactName = TrimOrNull(request.ContactName); + notice.MailingAddress = TrimOrNull(request.MailingAddress); + notice.Remark = TrimOrNull(request.Remark); + if (request.NoticeDate is { } noticeDate) notice.NoticeDate = noticeDate; + + if (request.Lines is not null) + { + if (request.Lines.Count == 0) + throw new BillingValidationException(nameof(request.Lines), "开票通知至少需要一条明细。"); + db.SupplierInvoiceNoticeLines.RemoveRange(notice.Lines); + notice.Lines = request.Lines.Select(x => BuildLine(notice.Id, x)).ToList(); + } + notice.Version++; + notice.Touch(); + SyncBillingContractParties(notice); + await db.SaveChangesAsync(ct); + return ToDto(await LoadNoticeAsync(notice.Id, ct)); + } + + public async Task NotifyAsync(Guid id, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + if (notice.Lines.Count == 0) + throw new BillingValidationException(nameof(notice.Lines), "开票通知没有明细,不能通知供应商。"); + if (string.IsNullOrWhiteSpace(notice.ExportInvoiceNo)) + throw new BillingValidationException(nameof(notice.ExportInvoiceNo), "外销发票号不能为空。"); + if (string.IsNullOrWhiteSpace(notice.InvoiceTitle)) + throw new BillingValidationException(nameof(notice.InvoiceTitle), "开票抬头不能为空。"); + if (notice.TotalAmountIncludingTax <= 0) + throw new BillingValidationException(nameof(notice.TotalAmountIncludingTax), "开票通知含税金额必须大于 0。"); + try { notice.Notify(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(notice); + } + + public async Task AwaitInvoiceAsync(Guid id, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + try { notice.MarkAwaitingInvoice(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(notice); + } + + public async Task VoidNoticeAsync(Guid id, VoidBillingRequest? request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + try { notice.Void(request?.Reason); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + } + + /// + /// Re-splits the batch's declared quantities between its draft supplier + /// notices (single or multiple suppliers per customs item). Every item's + /// quantities must add up to the confirmed declaration; lines set to 0 + /// are removed and a notice left without lines is voided. + /// + public async Task> ReallocateBatchAsync( + Guid shippingBatchId, ReallocateBillingRequest request, CancellationToken ct = default) + { + var notices = await LoadBatchNoticesAsync(shippingBatchId, ct); + if (notices.Any(x => x.Status != SupplierInvoiceNoticeStatus.Draft)) + throw new BillingConflictException("该批次已有开票通知确认,不能再调整各供应商的开票数量。"); + var linesById = notices.SelectMany(x => x.Lines).ToDictionary(x => x.Id); + foreach (var item in request.Lines) + { + if (!linesById.TryGetValue(item.NoticeLineId, out var line)) + throw new BillingValidationException(nameof(request.Lines), "开票明细不属于该出货批次。"); + if (item.Quantity < 0 || item.AmountIncludingTax < 0) + throw new BillingValidationException(nameof(request.Lines), "开票数量和金额不能小于 0。"); + if (item.Quantity == 0 && item.AmountIncludingTax > 0) + throw new BillingValidationException(nameof(request.Lines), $"{line.ContentDescription}:数量为 0 时金额也必须为 0。"); + line.Quantity = item.Quantity; + line.TaxIncluded = true; + line.UnitPrice = item.Quantity > 0 ? decimal.Round(item.AmountIncludingTax / item.Quantity, 4, MidpointRounding.AwayFromZero) : 0; + } + + await EnsureDeclaredTotalsAsync(shippingBatchId, notices, ct); + + foreach (var notice in notices) + { + var removed = notice.Lines.Where(x => x.Quantity == 0).ToList(); + foreach (var line in removed) notice.Lines.Remove(line); + db.SupplierInvoiceNoticeLines.RemoveRange(removed); + if (notice.Lines.Count == 0) + { + notice.Void("开票数量已全部分配给其他供应商"); + continue; + } + notice.Version++; + notice.Touch(); + } + await db.SaveChangesAsync(ct); + return notices.Select(ToDto).ToList(); + } + + /// + /// Final confirmation of a batch's billing: every draft notice is locked + /// and sent to its supplier. Quantities must match the declaration. + /// + public async Task> ConfirmBatchAsync(Guid shippingBatchId, CancellationToken ct = default) + { + var notices = await LoadBatchNoticesAsync(shippingBatchId, ct); + var drafts = notices.Where(x => x.Status == SupplierInvoiceNoticeStatus.Draft).ToList(); + if (drafts.Count == 0) throw new BillingConflictException("该批次没有待确认的开票通知。"); + await EnsureDeclaredTotalsAsync(shippingBatchId, notices, ct); + foreach (var notice in drafts) + { + if (string.IsNullOrWhiteSpace(notice.InvoiceTitle)) + throw new BillingValidationException(nameof(notice.InvoiceTitle), $"{notice.SupplierName} 的开票通知没有发票抬头。"); + if (string.IsNullOrWhiteSpace(notice.ExportInvoiceNo)) + throw new BillingValidationException(nameof(notice.ExportInvoiceNo), $"{notice.SupplierName} 的开票通知没有外销发票号。"); + if (notice.TotalAmountIncludingTax <= 0) + throw new BillingValidationException(nameof(notice.TotalAmountIncludingTax), $"{notice.SupplierName} 的开票含税金额必须大于 0。"); + notice.Notify(); + } + await db.SaveChangesAsync(ct); + return notices.Select(ToDto).ToList(); + } + + private async Task> LoadBatchNoticesAsync(Guid shippingBatchId, CancellationToken ct) + { + var notices = await db.SupplierInvoiceNotices + .Include(x => x.Lines).Include(x => x.Invoices).Include(x => x.BillingContract) + .Where(x => x.ShippingBatchId == shippingBatchId && x.Status != SupplierInvoiceNoticeStatus.Voided) + .ToListAsync(ct); + if (notices.Count == 0) throw new BillingNotFoundException("该出货批次还没有开票通知。"); + return notices; + } + + /// Per customs item, the suppliers' invoiced quantities must equal the declared quantity. + private async Task EnsureDeclaredTotalsAsync(Guid shippingBatchId, IReadOnlyList notices, CancellationToken ct) + { + var declaration = (await db.CustomsDeclarations.AsNoTracking().Include(x => x.Lines) + .Where(x => x.ShippingBatchId == shippingBatchId && x.Status == CustomsDeclarationStatus.Confirmed) + .ToListAsync(ct)) + .MaxBy(x => x.Version); + if (declaration is null) return; + var invoiced = notices.SelectMany(x => x.Lines) + .Where(x => x.ShipmentLineId is not null) + .GroupBy(x => x.ShipmentLineId!.Value) + .ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity)); + foreach (var line in declaration.Lines) + { + var total = invoiced.GetValueOrDefault(line.ShipmentLineId); + if (total != line.Quantity) + throw new BillingValidationException("Quantity", + $"{line.CustomsNameZh ?? line.ProductNameZh}:各供应商开票数量合计 {total:0.###} 与报关数量 {line.Quantity:0.###} 不一致。"); + } + } + + // ---------- Billing purchase/sales contract ---------- + + public async Task GetBillingContractAsync(Guid noticeId, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(noticeId, ct); + if (notice.BillingContract is null) + throw new BillingNotFoundException("开票通知尚未生成购销合同。"); + return ToDto(notice.BillingContract, notice); + } + + public async Task UpdateBillingContractAsync( + Guid noticeId, UpdateSupplierBillingContractRequest request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(noticeId, ct); + try { notice.EnsureDraft(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + var contract = notice.BillingContract ?? throw new BillingNotFoundException("开票通知尚未生成购销合同。"); + if (TrimOrNull(request.ContractNo) is { } no) contract.ContractNo = no; + contract.SignedPlace = TrimOrNull(request.SignedPlace); + if (request.SignedDate is not null) contract.SignedDate = request.SignedDate; + if (TrimOrNull(request.BuyerName) is { } buyer) contract.BuyerName = buyer; + contract.BuyerAddress = TrimOrNull(request.BuyerAddress); + contract.BuyerPhone = TrimOrNull(request.BuyerPhone); + contract.BuyerFax = TrimOrNull(request.BuyerFax); + contract.BuyerBankName = TrimOrNull(request.BuyerBankName); + contract.BuyerBankAccount = TrimOrNull(request.BuyerBankAccount); + contract.BuyerTaxNo = TrimOrNull(request.BuyerTaxNo); + if (TrimOrNull(request.SellerName) is { } seller) contract.SellerName = seller; + contract.SellerAddress = TrimOrNull(request.SellerAddress); + contract.SellerContact = TrimOrNull(request.SellerContact); + contract.SellerPhone = TrimOrNull(request.SellerPhone); + contract.SellerFax = TrimOrNull(request.SellerFax); + contract.QualityTechnicalTerms = TrimOrNull(request.QualityTechnicalTerms); + contract.DeliveryTerms = TrimOrNull(request.DeliveryTerms); + contract.PackagingTerms = TrimOrNull(request.PackagingTerms); + contract.SettlementTerms = TrimOrNull(request.SettlementTerms); + contract.TaxTerms = TrimOrNull(request.TaxTerms); + contract.IntellectualPropertyTerms = TrimOrNull(request.IntellectualPropertyTerms); + contract.BreachTerms = TrimOrNull(request.BreachTerms); + contract.DisputeResolutionTerms = TrimOrNull(request.DisputeResolutionTerms); + contract.TradeSecurityTerms = TrimOrNull(request.TradeSecurityTerms); + contract.OtherTerms = TrimOrNull(request.OtherTerms); + contract.Version++; + contract.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(contract, notice); + } + + // ---------- Supplier invoices ---------- + + public async Task> ListInvoicesAsync( + Guid? noticeId, string? status, string? search, int page, int pageSize, CancellationToken ct = default) + { + var query = db.SupplierInvoices.AsNoTracking().Include(x => x.SupplierInvoiceNotice).AsQueryable(); + if (noticeId is not null) query = query.Where(x => x.SupplierInvoiceNoticeId == noticeId.Value); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new BillingValidationException(nameof(status), "供应商发票状态无效。"); + query = query.Where(x => x.Status == parsed); + } + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.InvoiceNo.Contains(term) || x.SupplierName.Contains(term) || + (x.InvoiceCode != null && x.InvoiceCode.Contains(term))); + } + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetInvoiceAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadInvoiceAsync(id, ct)); + + public async Task RegisterInvoiceAsync(Guid noticeId, RegisterSupplierInvoiceRequest request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(noticeId, ct); + var invoiceNo = TrimOrNull(request.InvoiceNo) + ?? throw new BillingValidationException(nameof(request.InvoiceNo), "发票号码不能为空。"); + if (request.AmountIncludingTax <= 0) + throw new BillingValidationException(nameof(request.AmountIncludingTax), "发票含税金额必须大于 0。"); + if (request.AmountExcludingTax < 0 || request.TaxAmount < 0) + throw new BillingValidationException(nameof(request.AmountExcludingTax), "发票不含税金额和税额不能小于 0。"); + if (Math.Abs(request.AmountExcludingTax + request.TaxAmount - request.AmountIncludingTax) > 0.01m) + throw new BillingValidationException(nameof(request.AmountIncludingTax), "发票不含税金额与税额之和必须等于含税金额。"); + if (request.TaxRate is < 0 or > 100) + throw new BillingValidationException(nameof(request.TaxRate), "税率必须在 0 到 100 之间(百分数)。"); + var currency = string.IsNullOrWhiteSpace(request.Currency) ? notice.Currency : NormalizeCurrency(request.Currency); + if (!string.Equals(currency, notice.Currency, StringComparison.OrdinalIgnoreCase)) + throw new BillingValidationException(nameof(request.Currency), "发票币种必须与开票通知币种一致。"); + if (notice.InvoicedAmountIncludingTax + request.AmountIncludingTax > notice.TotalAmountIncludingTax + 0.01m) + throw new BillingValidationException(nameof(request.AmountIncludingTax), + $"累计登记发票含税金额不能超过开票通知含税金额 {notice.TotalAmountIncludingTax}。"); + if (await db.SupplierInvoices.AnyAsync(x => x.InvoiceNo == invoiceNo && x.SupplierName == notice.SupplierName + && x.Status != SupplierInvoiceStatus.Voided, ct)) + throw new BillingConflictException($"供应商发票号 {invoiceNo} 已登记。"); + + try { notice.MarkInvoiceReceived(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + + var invoice = new SupplierInvoice + { + SupplierInvoiceNoticeId = notice.Id, + InvoiceNo = invoiceNo, + InvoiceCode = TrimOrNull(request.InvoiceCode), + InvoiceType = ParseInvoiceType(request.InvoiceType), + SupplierId = notice.SupplierId, + SupplierName = notice.SupplierName, + InvoiceDate = request.InvoiceDate ?? request.ReceivedDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + ReceivedDate = request.ReceivedDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + Currency = currency, + TaxRate = request.TaxRate, + AmountExcludingTax = decimal.Round(request.AmountExcludingTax, 2, MidpointRounding.AwayFromZero), + TaxAmount = decimal.Round(request.TaxAmount, 2, MidpointRounding.AwayFromZero), + AmountIncludingTax = decimal.Round(request.AmountIncludingTax, 2, MidpointRounding.AwayFromZero), + AttachmentReference = TrimOrNull(request.AttachmentReference), + Remark = TrimOrNull(request.Remark), + }; + db.SupplierInvoices.Add(invoice); + await db.SaveChangesAsync(ct); + return ToDto(await LoadInvoiceAsync(invoice.Id, ct)); + } + + public async Task HandInvoiceToFinanceAsync(Guid id, HandSupplierInvoiceToFinanceRequest? request, CancellationToken ct = default) + { + var invoice = await LoadInvoiceAsync(id, ct); + var notice = invoice.SupplierInvoiceNotice ?? await LoadNoticeAsync(invoice.SupplierInvoiceNoticeId, ct); + try { invoice.HandToFinance(request?.HandedBy); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + if (notice.Status == SupplierInvoiceNoticeStatus.InvoiceReceived) + { + try { notice.MarkHandedToFinance(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + } + await db.SaveChangesAsync(ct); + return ToDto(await LoadInvoiceAsync(id, ct)); + } + + public async Task CompleteInvoiceAsync(Guid id, CancellationToken ct = default) + { + var invoice = await LoadInvoiceAsync(id, ct); + var notice = invoice.SupplierInvoiceNotice ?? await LoadNoticeAsync(invoice.SupplierInvoiceNoticeId, ct); + try { invoice.Complete(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + var fullyInvoiced = notice.RemainingAmountIncludingTax <= 0.01m; + var allCompleted = notice.Invoices + .Where(x => x.Status != SupplierInvoiceStatus.Voided) + .All(x => x.Status == SupplierInvoiceStatus.Completed); + if (fullyInvoiced && allCompleted && notice.Status == SupplierInvoiceNoticeStatus.HandedToFinance) + { + try { notice.MarkCompleted(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + } + await db.SaveChangesAsync(ct); + return ToDto(await LoadInvoiceAsync(id, ct)); + } + + public async Task VoidInvoiceAsync(Guid id, VoidBillingRequest? request, CancellationToken ct = default) + { + var invoice = await LoadInvoiceAsync(id, ct); + var notice = invoice.SupplierInvoiceNotice ?? await LoadNoticeAsync(invoice.SupplierInvoiceNoticeId, ct); + try { invoice.Void(request?.Reason); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + notice.Invoices = notice.Invoices.Count > 0 ? notice.Invoices : [.. await db.SupplierInvoices.Where(x => x.SupplierInvoiceNoticeId == notice.Id).ToListAsync(ct)]; + notice.RevertAfterInvoiceVoid(); + await db.SaveChangesAsync(ct); + } + + // ---------- Helpers ---------- + + private SupplierInvoiceNoticeLine BuildLine(Guid noticeId, BillingNoticeLineRequest request) + { + var line = new SupplierInvoiceNoticeLine + { + SupplierInvoiceNoticeId = noticeId, + ShipmentLineId = request.ShipmentLineId, + PurchaseTaskId = request.PurchaseTaskId, + PurchaseContractId = request.PurchaseContractId, + PurchaseContractNo = TrimOrNull(request.PurchaseContractNo), + SalesOrderLineId = request.SalesOrderLineId, + ProductId = request.ProductId, + InternalSku = TrimOrNull(request.InternalSku), + CustomerSku = TrimOrNull(request.CustomerSku), + ProductNameZh = TrimOrNull(request.ProductNameZh) ?? TrimOrNull(request.ContentDescription) ?? string.Empty, + ProductNameEn = TrimOrNull(request.ProductNameEn), + ContentDescription = TrimOrNull(request.ContentDescription) ?? TrimOrNull(request.ProductNameZh) ?? string.Empty, + Specification = TrimOrNull(request.Specification), + Quantity = request.Quantity, + Unit = TrimOrNull(request.Unit) ?? string.Empty, + UnitPrice = request.UnitPrice, + TaxIncluded = request.TaxIncluded, + TaxRate = request.TaxRate, + }; + ValidateLine(line); + return line; + } + + private static void ValidateLine(SupplierInvoiceNoticeLine line) + { + if (line.Quantity <= 0) + throw new BillingValidationException(nameof(line.Quantity), "开票数量必须大于 0。"); + if (line.UnitPrice < 0) + throw new BillingValidationException(nameof(line.UnitPrice), "开票单价不能小于 0。"); + if (line.TaxRate is < 0 or > 100) + throw new BillingValidationException(nameof(line.TaxRate), "税率必须在 0 到 100 之间(百分数)。"); + if (string.IsNullOrWhiteSpace(line.Unit)) + throw new BillingValidationException(nameof(line.Unit), "开票单位不能为空,必须使用规范中文单位。"); + if (string.IsNullOrWhiteSpace(line.ContentDescription)) + throw new BillingValidationException(nameof(line.ContentDescription), "开票品名不能为空。"); + if (string.IsNullOrWhiteSpace(line.ProductNameZh)) + line.ProductNameZh = line.ContentDescription; + } + + private static SupplierBillingContract BuildBillingContract( + SupplierInvoiceNotice notice, string? billingContractNo, string? signedPlace, DateOnly? signedDate, + string? quality, string? delivery, string? packaging, string? settlement, string? tax, string? ip) + => new() + { + SupplierInvoiceNotice = notice, + ContractNo = TrimOrNull(billingContractNo) ?? notice.PurchaseContractNo ?? notice.NoticeNo, + PurchaseContractNo = notice.PurchaseContractNo, + ExportInvoiceNo = notice.ExportInvoiceNo, + BuyerName = notice.InvoiceTitle ?? string.Empty, + BuyerAddress = notice.InvoiceTitleAddress, + BuyerPhone = notice.InvoiceTitlePhone, + BuyerBankName = notice.InvoiceTitleBankName, + BuyerBankAccount = notice.InvoiceTitleBankAccount, + BuyerTaxNo = notice.InvoiceTitleTaxNo, + SellerSupplierId = notice.SupplierId, + SellerName = notice.SupplierName, + SellerAddress = notice.SupplierAddress, + SellerContact = notice.SupplierContact, + SellerPhone = notice.SupplierPhone, + SellerFax = notice.SupplierFax, + SignedPlace = TrimOrNull(signedPlace), + SignedDate = signedDate ?? notice.NoticeDate, + Currency = notice.Currency, + QualityTechnicalTerms = TrimOrNull(quality), + DeliveryTerms = TrimOrNull(delivery), + PackagingTerms = TrimOrNull(packaging), + SettlementTerms = TrimOrNull(settlement), + TaxTerms = TrimOrNull(tax), + IntellectualPropertyTerms = TrimOrNull(ip), + }; + + private static void SyncBillingContractParties(SupplierInvoiceNotice notice) + { + if (notice.BillingContract is null) return; + var c = notice.BillingContract; + c.PurchaseContractNo = notice.PurchaseContractNo; + c.ExportInvoiceNo = notice.ExportInvoiceNo; + c.BuyerName = notice.InvoiceTitle ?? c.BuyerName; + c.BuyerAddress = notice.InvoiceTitleAddress; + c.BuyerPhone = notice.InvoiceTitlePhone; + c.BuyerBankName = notice.InvoiceTitleBankName; + c.BuyerBankAccount = notice.InvoiceTitleBankAccount; + c.BuyerTaxNo = notice.InvoiceTitleTaxNo; + c.SellerSupplierId = notice.SupplierId; + c.SellerName = notice.SupplierName; + c.SellerAddress = notice.SupplierAddress; + c.SellerContact = notice.SupplierContact; + c.SellerPhone = notice.SupplierPhone; + c.SellerFax = notice.SupplierFax; + c.Currency = notice.Currency; + c.Touch(); + } + + private async Task GenerateNoticeNoAsync(CancellationToken ct) + { + for (var attempt = 0; attempt < 5; attempt++) + { + var candidate = $"BIN-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString("N")[..4].ToUpperInvariant()}"; + if (!await db.SupplierInvoiceNotices.AnyAsync(x => x.NoticeNo == candidate, ct)) + return candidate; + } + return $"BIN-{Guid.NewGuid():N}"; + } + + private async Task LoadNoticeAsync(Guid id, CancellationToken ct) + => await db.SupplierInvoiceNotices + .Include(x => x.Lines) + .Include(x => x.Invoices) + .Include(x => x.BillingContract) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new BillingNotFoundException("开票通知不存在。"); + + private async Task LoadInvoiceAsync(Guid id, CancellationToken ct) + => await db.SupplierInvoices + .Include(x => x.SupplierInvoiceNotice!) + .ThenInclude(x => x.Lines) + .Include(x => x.SupplierInvoiceNotice!) + .ThenInclude(x => x.Invoices) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new BillingNotFoundException("供应商发票不存在。"); + + private static SupplierInvoiceType ParseInvoiceType(string? value) + => string.IsNullOrWhiteSpace(value) + ? SupplierInvoiceType.VatSpecial + : Enum.TryParse(value, ignoreCase: true, out var parsed) + ? parsed + : throw new BillingValidationException(nameof(value), "发票类型无效。"); + + private static string NormalizeCurrency(string? currency) + { + var normalized = string.IsNullOrWhiteSpace(currency) ? "CNY" : currency.Trim().ToUpperInvariant(); + if (normalized.Length != 3) + throw new BillingValidationException(nameof(currency), "币种必须是 3 位代码,如 CNY、USD。"); + return normalized; + } + + private static string? TrimOrNull(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static SupplierInvoiceNoticeLineDto ToDto(SupplierInvoiceNoticeLine l) => new( + l.Id, l.SupplierInvoiceNoticeId, l.ShipmentLineId, l.PurchaseTaskId, l.PurchaseContractId, + l.PurchaseContractNo, l.SalesOrderLineId, l.ProductId, l.InternalSku, l.CustomerSku, + l.ProductNameZh, l.ProductNameEn, l.ContentDescription, l.Specification, l.Quantity, l.Unit, + l.UnitPrice, l.TaxIncluded, l.TaxRate, l.TaxIncludedUnitPrice, l.TaxExcludingUnitPrice, + l.AmountExcludingTax, l.TaxAmount, l.AmountIncludingTax); + + private static SupplierInvoiceNoticeDto ToDto(SupplierInvoiceNotice n) => new( + n.Id, n.NoticeNo, n.Status.ToString(), n.Version, n.ShippingBatchId, n.ShipmentNo, n.BillOfLadingNo, + n.VesselName, n.VoyageNo, n.LoadingPort, n.DestinationPort, n.ShipmentDate, n.ExportInvoiceNo, + n.SalesOrderId, n.SalesOrderNo, n.CustomerPoNo, n.PurchaseContractId, n.PurchaseContractNo, + n.SupplierId, n.SupplierName, n.SupplierContact, n.SupplierPhone, n.SupplierFax, n.SupplierAddress, + n.InvoiceTitle, n.InvoiceTitleAddress, n.InvoiceTitlePhone, n.InvoiceTitleBankName, + n.InvoiceTitleBankAccount, n.InvoiceTitleTaxNo, n.InvoiceTitleCustomsCode, n.Currency, + n.InvoicingRequirement, n.StampRequirement, n.ContactName, n.MailingAddress, n.Remark, n.NoticeDate, + n.TotalQuantity, n.TotalAmountExcludingTax, n.TotalTaxAmount, n.TotalAmountIncludingTax, + n.InvoicedAmountIncludingTax, n.RemainingAmountIncludingTax, + n.CreatedAt, n.UpdatedAt, n.NotifiedAt, n.AwaitingInvoiceAt, n.InvoiceReceivedAt, + n.HandedToFinanceAt, n.CompletedAt, n.VoidedAt, n.VoidReason, + n.Lines.OrderBy(x => x.ProductNameZh).Select(ToDto).ToList(), + n.Invoices.OrderBy(x => x.InvoiceDate).Select(ToDto).ToList(), + n.BillingContract is null ? null : ToDto(n.BillingContract, n)); + + private static SupplierBillingContractDto ToDto(SupplierBillingContract c, SupplierInvoiceNotice notice) => new( + c.Id, c.SupplierInvoiceNoticeId, c.ContractNo, c.PurchaseContractNo, c.ExportInvoiceNo, c.Version, + c.BuyerName, c.BuyerAddress, c.BuyerPhone, c.BuyerFax, c.BuyerBankName, c.BuyerBankAccount, c.BuyerTaxNo, + c.SellerSupplierId, c.SellerName, c.SellerAddress, c.SellerContact, c.SellerPhone, c.SellerFax, + c.SignedPlace, c.SignedDate, c.Currency, c.QualityTechnicalTerms, c.DeliveryTerms, c.PackagingTerms, + c.SettlementTerms, c.TaxTerms, c.IntellectualPropertyTerms, c.BreachTerms, c.DisputeResolutionTerms, + c.TradeSecurityTerms, c.OtherTerms, + notice.TotalAmountExcludingTax, notice.TotalTaxAmount, notice.TotalAmountIncludingTax, + c.CreatedAt, c.UpdatedAt, + notice.Lines.OrderBy(x => x.ProductNameZh).Select(ToDto).ToList()); + + private static SupplierInvoiceDto ToDto(SupplierInvoice i) => new( + i.Id, i.SupplierInvoiceNoticeId, i.SupplierInvoiceNotice?.NoticeNo ?? string.Empty, i.InvoiceNo, + i.InvoiceCode, i.InvoiceType.ToString(), i.SupplierId, i.SupplierName, i.InvoiceDate, i.ReceivedDate, + i.Currency, i.TaxRate, i.AmountExcludingTax, i.TaxAmount, i.AmountIncludingTax, i.Status.ToString(), + i.AttachmentReference, i.Remark, i.CreatedAt, i.UpdatedAt, i.HandedToFinanceAt, i.HandedToFinanceBy, + i.CompletedAt, i.VoidedAt, i.VoidReason); +} diff --git a/src/Leiren.Erp.Application/Billing/IBillingDbContext.cs b/src/Leiren.Erp.Application/Billing/IBillingDbContext.cs new file mode 100644 index 0000000..aa8e050 --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/IBillingDbContext.cs @@ -0,0 +1,26 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Billing; + +/// +/// EF Core boundary for the Billing module; implemented by Infrastructure. +/// Shipping/Purchasing sets are read only to snapshot confirmed-shipment and +/// purchase-task data into a notice at generation time. +/// +public interface IBillingDbContext +{ + DbSet SupplierInvoiceNotices { get; } + DbSet SupplierInvoiceNoticeLines { get; } + DbSet SupplierInvoices { get; } + DbSet SupplierBillingContracts { get; } + DbSet ShippingBatches { get; } + DbSet ShipmentLines { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet SalesOrderLines { get; } + DbSet Suppliers { get; } + DbSet CustomsDeclarations { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Catalog/CatalogExceptions.cs b/src/Leiren.Erp.Application/Catalog/CatalogExceptions.cs new file mode 100644 index 0000000..278d79c --- /dev/null +++ b/src/Leiren.Erp.Application/Catalog/CatalogExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Catalog; + +public sealed class CatalogNotFoundException(string message) : Exception(message); + +public sealed class CatalogConflictException(string message) : Exception(message); + +public sealed class CatalogValidationException(IReadOnlyDictionary errors) + : Exception("产品资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public CatalogValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Catalog/ICatalogDbContext.cs b/src/Leiren.Erp.Application/Catalog/ICatalogDbContext.cs new file mode 100644 index 0000000..d5fe6d4 --- /dev/null +++ b/src/Leiren.Erp.Application/Catalog/ICatalogDbContext.cs @@ -0,0 +1,16 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Catalog; + +/// EF Core boundary for the Catalog module; implemented by Infrastructure. +public interface ICatalogDbContext +{ + DbSet Products { get; } + DbSet Suppliers { get; } + DbSet ProductParts { get; } + DbSet ProductSupplierQuotes { get; } + DbSet ProductChangeLogs { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Catalog/ProductService.cs b/src/Leiren.Erp.Application/Catalog/ProductService.cs new file mode 100644 index 0000000..c67d0d9 --- /dev/null +++ b/src/Leiren.Erp.Application/Catalog/ProductService.cs @@ -0,0 +1,727 @@ +using System.Globalization; +using System.Text.Json; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Catalog; + +public sealed class ProductService(ICatalogDbContext db) +{ + public async Task> ListAsync( + string? search, string? status, int page, int pageSize, CancellationToken ct = default) + { + var query = db.Products.AsNoTracking().AsQueryable(); + + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + { + throw new CatalogValidationException(nameof(status), "产品状态无效。"); + } + + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.InternalSku.Contains(term) || + x.NameZh.Contains(term) || + x.NameEn.Contains(term) || + (x.HsCode != null && x.HsCode.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + + var items = await query + .OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize) + .Take(pageSize) + .ToListAsync(ct); + + return items.Select(ToListItem).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task GetCompletenessAsync(Guid id, CancellationToken ct = default) + => BuildCompleteness(await LoadAsync(id, ct)); + + public async Task> ListHistoryAsync(Guid id, CancellationToken ct = default) + { + if (!await db.Products.AnyAsync(x => x.Id == id, ct)) + throw new CatalogNotFoundException("产品不存在。"); + var entries = await db.ProductChangeLogs.AsNoTracking() + .Where(x => x.ProductId == id) + .OrderByDescending(x => x.Id) + .ToListAsync(ct); + return entries.Select(ToDto).ToList(); + } + + /// + /// Completeness per docs/02 §3: only the basic publish fields are + /// required/blocking; purchase, shipping and customs fields are advisory + /// per-use groups and never block publish. + /// + public static ProductCompletenessDto BuildCompleteness(Product product) + { + var required = product.GetMissingPublishFields(); + + var purchase = new List(); + if (product.SupplierQuotes.Count == 0) purchase.Add("SupplierQuote"); + if (string.IsNullOrWhiteSpace(product.PurchaseRequirement)) purchase.Add(nameof(Product.PurchaseRequirement)); + + var shipping = new List(); + if (product.PackingRate is null) shipping.Add(nameof(Product.PackingRate)); + if (product.CartonLength is null) shipping.Add(nameof(Product.CartonLength)); + if (product.CartonWidth is null) shipping.Add(nameof(Product.CartonWidth)); + if (product.CartonHeight is null) shipping.Add(nameof(Product.CartonHeight)); + if (product.CartonGrossWeight is null) shipping.Add(nameof(Product.CartonGrossWeight)); + if (product.CartonNetWeight is null) shipping.Add(nameof(Product.CartonNetWeight)); + + var customs = new List(); + if (string.IsNullOrWhiteSpace(product.HsCode)) customs.Add(nameof(Product.HsCode)); + if (string.IsNullOrWhiteSpace(product.CustomsNameZh)) customs.Add(nameof(Product.CustomsNameZh)); + if (string.IsNullOrWhiteSpace(product.CustomsNameEn)) customs.Add(nameof(Product.CustomsNameEn)); + if (string.IsNullOrWhiteSpace(product.CustomsUnit)) customs.Add(nameof(Product.CustomsUnit)); + if (string.IsNullOrWhiteSpace(product.DeclarationElements)) customs.Add(nameof(Product.DeclarationElements)); + + var optional = purchase.Concat(shipping).Concat(customs).ToList(); + var blocking = required.Select(field => $"发布前必须填写{field}。").ToList(); + return new ProductCompletenessDto( + product.Id, product.Status.ToString(), product.Version, + product.Status == ProductStatus.Draft && required.Count == 0, + required, purchase, shipping, customs, optional, blocking); + } + + public async Task CreateDraftAsync(SaveProductDraftRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = new Product { Status = ProductStatus.Draft, Version = 1 }; + ApplyDraft(product, request); + await EnsureSkuAvailableAsync(product.InternalSku, excludeId: null, ct); + db.Products.Add(product); + AddChangeLog(product, ProductChangeAction.DraftCreated, NonEmptyFields(Snapshot(product)), + $"创建产品草稿 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task UpdateDraftAsync(Guid id, SaveProductDraftRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadAsync(id, ct); + + if (product.Status == ProductStatus.Published) + { + // Editing a published product creates the next draft version; the + // published version (and anything referencing it) stays untouched. + var draft = CopyAsNewDraft(product); + var before = Snapshot(draft); + ApplyDraft(draft, request); + await EnsureSkuAvailableAsync(draft.InternalSku, draft.Id, ct); + db.Products.Add(draft); + AddChangeLog(draft, ProductChangeAction.DraftVersionCreated, ChangedFields(before, Snapshot(draft)), + $"基于已发布版本 V{product.Version} 创建新草稿 V{draft.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(await LoadAsync(draft.Id, ct)); + } + + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("已停用或历史版本的产品不能编辑,请基于已发布版本建立新草稿。"); + } + + var beforeSave = Snapshot(product); + ApplyDraft(product, request); + await EnsureSkuAvailableAsync(product.InternalSku, product.Id, ct); + product.Touch(); + AddChangeLog(product, ProductChangeAction.DraftSaved, ChangedFields(beforeSave, Snapshot(product)), + $"保存产品草稿 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task PublishAsync(Guid id, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadAsync(id, ct); + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("只有草稿状态的产品可以发布。"); + } + + // Only the required basic fields block publish (docs/02 §3); + // purchase/shipping/customs gaps are advisory completeness warnings. + var completeness = BuildCompleteness(product); + if (completeness.RequiredMissingFields.Count > 0) + { + throw new CatalogValidationException(completeness.RequiredMissingFields.ToDictionary( + field => field, + field => new[] { $"发布前必须填写{field}。" })); + } + + var currentPublished = await db.Products + .Where(x => x.InternalSku == product.InternalSku + && x.Status == ProductStatus.Published + && x.Id != product.Id) + .ToListAsync(ct); + foreach (var old in currentPublished) + { + old.Status = ProductStatus.Superseded; + old.Touch(); + AddChangeLog(old, ProductChangeAction.Superseded, ["Status"], + $"版本 V{old.Version} 已被 V{product.Version} 取代。", actorUserId, actorUserName); + } + + product.Publish(); + AddChangeLog(product, ProductChangeAction.Published, ["Status"], + $"发布产品 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task DisableAsync(Guid id, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadAsync(id, ct); + try + { + product.Disable(); + } + catch (InvalidOperationException ex) + { + throw new CatalogConflictException(ex.Message); + } + + AddChangeLog(product, ProductChangeAction.Disabled, ["Status"], + $"停用产品 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task DeleteDraftAsync(Guid id, CancellationToken ct = default) + { + var product = await LoadAsync(id, ct); + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("只有未发布的草稿产品可以删除;已发布产品只能停用。"); + } + + db.Products.Remove(product); + await db.SaveChangesAsync(ct); + } + + public async Task AddPartAsync(Guid productId, SaveProductPartRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var part = new ProductPart { ProductId = product.Id }; + ApplyPart(part, request); + await ValidateComponentAsync(part, product.Id, ct); + db.ProductParts.Add(part); + product.Touch(); + AddChangeLog(product, ProductChangeAction.PartAdded, NonEmptyFields(Snapshot(part)), + $"添加零件 {part.Name}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(part); + } + + public async Task UpdatePartAsync( + Guid productId, Guid partId, SaveProductPartRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var part = product.Parts.SingleOrDefault(x => x.Id == partId) + ?? throw new CatalogNotFoundException("产品零件不存在。"); + var before = Snapshot(part); + ApplyPart(part, request); + await ValidateComponentAsync(part, product.Id, ct); + part.UpdatedAt = DateTimeOffset.UtcNow; + product.Touch(); + AddChangeLog(product, ProductChangeAction.PartUpdated, ChangedFields(before, Snapshot(part)), + $"修改零件 {part.Name}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(part); + } + + public async Task DeletePartAsync(Guid productId, Guid partId, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var part = product.Parts.SingleOrDefault(x => x.Id == partId) + ?? throw new CatalogNotFoundException("产品零件不存在。"); + var summary = $"删除零件 {part.Name}。"; + db.ProductParts.Remove(part); + product.Touch(); + AddChangeLog(product, ProductChangeAction.PartDeleted, ["Name"], summary, actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + } + + public async Task AddQuoteAsync( + Guid productId, CreateSupplierQuoteRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var values = await ResolveQuoteValuesAsync(product, request, ct); + var quote = new ProductSupplierQuote { ProductId = product.Id }; + ApplyQuote(quote, request, values); + ClearOtherDefaults(product, quote); + + db.ProductSupplierQuotes.Add(quote); + product.Touch(); + AddChangeLog(product, ProductChangeAction.QuoteAdded, + ["SupplierName", "UnitPrice", "Currency"], + $"添加供应商报价 {quote.SupplierName} {quote.UnitPrice.ToString(CultureInfo.InvariantCulture)} {quote.Currency}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(quote); + } + + public async Task UpdateQuoteAsync( + Guid productId, Guid quoteId, CreateSupplierQuoteRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var quote = product.SupplierQuotes.SingleOrDefault(x => x.Id == quoteId) + ?? throw new CatalogNotFoundException("供应商报价不存在。"); + var before = Snapshot(quote); + var values = await ResolveQuoteValuesAsync(product, request, ct); + ApplyQuote(quote, request, values); + ClearOtherDefaults(product, quote); + product.Touch(); + AddChangeLog(product, ProductChangeAction.QuoteUpdated, ChangedFields(before, Snapshot(quote)), + $"修改供应商报价 {quote.SupplierName} {quote.UnitPrice.ToString(CultureInfo.InvariantCulture)} {quote.Currency}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(quote); + } + + public async Task DeleteQuoteAsync(Guid productId, Guid quoteId, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var quote = product.SupplierQuotes.SingleOrDefault(x => x.Id == quoteId) + ?? throw new CatalogNotFoundException("供应商报价不存在。"); + var summary = $"删除供应商报价 {quote.SupplierName} {quote.UnitPrice.ToString(CultureInfo.InvariantCulture)} {quote.Currency}。"; + db.ProductSupplierQuotes.Remove(quote); + product.Touch(); + AddChangeLog(product, ProductChangeAction.QuoteDeleted, + ["SupplierName", "UnitPrice", "Currency"], summary, actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + } + + private readonly record struct QuoteValues( + Guid? ProductPartId, string SupplierName, PurchaseContentType ContentType, string Currency, string PricingUnit); + + private async Task ResolveQuoteValuesAsync( + Product product, CreateSupplierQuoteRequest request, CancellationToken ct) + { + // When a master supplier is selected, its current name becomes the quote + // snapshot; free-text names remain allowed for quotes without a master id. + var supplierName = request.SupplierName?.Trim(); + if (request.SupplierId is { } supplierId) + { + var supplier = await db.Suppliers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == supplierId, ct) + ?? throw new CatalogValidationException(nameof(request.SupplierId), "供应商不存在。"); + if (!supplier.IsActive) + throw new CatalogValidationException(nameof(request.SupplierId), "供应商已停用,不能新增报价。"); + supplierName = supplier.Name; + } + + if (string.IsNullOrWhiteSpace(supplierName)) + { + throw new CatalogValidationException(nameof(request.SupplierName), "供应商名称不能为空。"); + } + + if (request.UnitPrice < 0) + { + throw new CatalogValidationException(nameof(request.UnitPrice), "单价不能小于 0。"); + } + + if (request.TaxRate is < 0 or > 100) + { + throw new CatalogValidationException(nameof(request.TaxRate), "税率必须在 0 到 100 之间(百分数)。"); + } + + if (request.EffectiveFrom is not null && request.EffectiveTo is not null + && request.EffectiveTo < request.EffectiveFrom) + { + throw new CatalogValidationException(nameof(request.EffectiveTo), "失效日期不能早于生效日期。"); + } + + Guid? productPartId = null; + if (request.ProductPartId is not null) + { + var part = product.Parts.SingleOrDefault(x => x.Id == request.ProductPartId.Value) + ?? throw new CatalogValidationException(nameof(request.ProductPartId), "零件不属于当前产品。"); + productPartId = part.Id; + } + + var currency = string.IsNullOrWhiteSpace(request.Currency) ? "CNY" : request.Currency.Trim().ToUpperInvariant(); + if (currency.Length != 3) + { + throw new CatalogValidationException(nameof(request.Currency), "币种必须是 3 位代码,如 CNY、USD。"); + } + + return new QuoteValues( + productPartId, + supplierName, + ParseEnum(request.ContentType, PurchaseContentType.Finished, nameof(request.ContentType)), + currency, + string.IsNullOrWhiteSpace(request.PricingUnit) ? product.Unit : request.PricingUnit.Trim()); + } + + private static void ApplyQuote(ProductSupplierQuote quote, CreateSupplierQuoteRequest request, QuoteValues values) + { + quote.ProductPartId = values.ProductPartId; + quote.SupplierId = request.SupplierId; + quote.SupplierName = values.SupplierName; + quote.SupplierProductName = TrimOrNull(request.SupplierProductName); + quote.SupplierProductSku = TrimOrNull(request.SupplierProductSku); + quote.ContentType = values.ContentType; + quote.UnitPrice = request.UnitPrice; + quote.Currency = values.Currency; + quote.PricingUnit = values.PricingUnit; + quote.TaxIncluded = request.TaxIncluded; + quote.TaxRate = request.TaxRate; + quote.MinimumOrderQuantity = request.MinimumOrderQuantity; + quote.LeadTimeDays = request.LeadTimeDays; + quote.EffectiveFrom = request.EffectiveFrom; + quote.EffectiveTo = request.EffectiveTo; + quote.IsDefault = request.IsDefault; + quote.Requirement = TrimOrNull(request.Requirement); + quote.Remark = TrimOrNull(request.Remark); + } + + private static void ClearOtherDefaults(Product product, ProductSupplierQuote quote) + { + if (!quote.IsDefault) return; + foreach (var other in product.SupplierQuotes.Where(x => x.Id != quote.Id && x.ProductPartId == quote.ProductPartId)) + { + other.IsDefault = false; + } + } + + private static Dictionary Snapshot(ProductSupplierQuote q) => new() + { + [nameof(q.ProductPartId)] = F(q.ProductPartId), [nameof(q.SupplierId)] = F(q.SupplierId), + [nameof(q.SupplierName)] = q.SupplierName, [nameof(q.SupplierProductName)] = q.SupplierProductName, + [nameof(q.SupplierProductSku)] = q.SupplierProductSku, [nameof(q.ContentType)] = F(q.ContentType), + [nameof(q.UnitPrice)] = F(q.UnitPrice), [nameof(q.Currency)] = q.Currency, [nameof(q.PricingUnit)] = q.PricingUnit, + [nameof(q.TaxIncluded)] = F(q.TaxIncluded), [nameof(q.TaxRate)] = F(q.TaxRate), + [nameof(q.MinimumOrderQuantity)] = F(q.MinimumOrderQuantity), [nameof(q.LeadTimeDays)] = F(q.LeadTimeDays), + [nameof(q.EffectiveFrom)] = F(q.EffectiveFrom), [nameof(q.EffectiveTo)] = F(q.EffectiveTo), + [nameof(q.IsDefault)] = F(q.IsDefault), [nameof(q.Requirement)] = q.Requirement, [nameof(q.Remark)] = q.Remark + }; + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.Products + .Include(x => x.Parts) + .Include(x => x.SupplierQuotes) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new CatalogNotFoundException("产品不存在。"); + + private async Task LoadDraftAsync(Guid id, CancellationToken ct) + { + var product = await LoadAsync(id, ct); + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("只有草稿状态的产品可以维护零件和供应商报价;已发布产品请先编辑新版本。"); + } + + return product; + } + + private async Task EnsureSkuAvailableAsync(string sku, Guid? excludeId, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(sku)) return; + + var exists = await db.Products.AnyAsync(x => + x.InternalSku == sku + && x.Status != ProductStatus.Superseded + && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) + { + throw new CatalogConflictException($"内部货号 {sku} 已被其他产品版本使用。"); + } + } + + private async Task ValidateComponentAsync(ProductPart part, Guid productId, CancellationToken ct) + { + if (part.ComponentProductId is null) return; + if (part.ComponentProductId == productId) + { + throw new CatalogValidationException(nameof(part.ComponentProductId), "零件不能引用产品自身。"); + } + + if (!await db.Products.AnyAsync(x => x.Id == part.ComponentProductId.Value, ct)) + { + throw new CatalogValidationException(nameof(part.ComponentProductId), "引用的零件产品不存在。"); + } + } + + private static Product CopyAsNewDraft(Product source) + { + var draft = new Product + { + InternalSku = source.InternalSku, + NameZh = source.NameZh, + NameEn = source.NameEn, + Category = source.Category, + ProductType = source.ProductType, + Unit = source.Unit, + ProductLength = source.ProductLength, + ProductWidth = source.ProductWidth, + ProductHeight = source.ProductHeight, + DimensionUnit = source.DimensionUnit, + Description = source.Description, + PurchaseRequirement = source.PurchaseRequirement, + QualityRequirement = source.QualityRequirement, + DefaultOrigin = source.DefaultOrigin, + Remark = source.Remark, + PackingRate = source.PackingRate, + CartonLength = source.CartonLength, + CartonWidth = source.CartonWidth, + CartonHeight = source.CartonHeight, + CartonGrossWeight = source.CartonGrossWeight, + CartonNetWeight = source.CartonNetWeight, + CartonMaterial = source.CartonMaterial, + PackagingNote = source.PackagingNote, + HsCode = source.HsCode, + CustomsNameZh = source.CustomsNameZh, + CustomsNameEn = source.CustomsNameEn, + CustomsUnit = source.CustomsUnit, + DeclarationElements = source.DeclarationElements, + OriginCountry = source.OriginCountry, + CustomsRemark = source.CustomsRemark, + Status = ProductStatus.Draft, + Version = source.Version + 1 + }; + + var partIdMap = new Dictionary(); + foreach (var part in source.Parts.OrderBy(x => x.SortOrder)) + { + var copy = new ProductPart + { + Product = draft, + ComponentProductId = part.ComponentProductId, + Name = part.Name, + PartType = part.PartType, + ComponentSku = part.ComponentSku, + QuantityPerProduct = part.QuantityPerProduct, + Unit = part.Unit, + Requirement = part.Requirement, + IsRequired = part.IsRequired, + SortOrder = part.SortOrder, + IsActive = part.IsActive + }; + partIdMap[part.Id] = copy.Id; + draft.Parts.Add(copy); + } + + foreach (var quote in source.SupplierQuotes) + { + draft.SupplierQuotes.Add(new ProductSupplierQuote + { + Product = draft, + ProductPartId = quote.ProductPartId is { } oldPartId && partIdMap.TryGetValue(oldPartId, out var newPartId) ? newPartId : null, + SupplierId = quote.SupplierId, + SupplierName = quote.SupplierName, + SupplierProductName = quote.SupplierProductName, + SupplierProductSku = quote.SupplierProductSku, + ContentType = quote.ContentType, + UnitPrice = quote.UnitPrice, + Currency = quote.Currency, + PricingUnit = quote.PricingUnit, + TaxIncluded = quote.TaxIncluded, + TaxRate = quote.TaxRate, + MinimumOrderQuantity = quote.MinimumOrderQuantity, + LeadTimeDays = quote.LeadTimeDays, + EffectiveFrom = quote.EffectiveFrom, + EffectiveTo = quote.EffectiveTo, + IsDefault = quote.IsDefault, + Requirement = quote.Requirement, + Remark = quote.Remark + }); + } + + return draft; + } + + private static void ApplyDraft(Product product, SaveProductDraftRequest request) + { + product.InternalSku = (request.InternalSku ?? string.Empty).Trim(); + product.NameZh = (request.NameZh ?? string.Empty).Trim(); + product.NameEn = (request.NameEn ?? string.Empty).Trim(); + product.Category = (request.Category ?? string.Empty).Trim(); + product.ProductType = string.IsNullOrWhiteSpace(request.ProductType) + ? null + : ParseEnum(request.ProductType, (ProductType?)null, nameof(request.ProductType)); + product.Unit = (request.Unit ?? string.Empty).Trim(); + product.ProductLength = request.ProductLength; + product.ProductWidth = request.ProductWidth; + product.ProductHeight = request.ProductHeight; + product.DimensionUnit = TrimOrNull(request.DimensionUnit); + product.Description = TrimOrNull(request.Description); + product.PurchaseRequirement = TrimOrNull(request.PurchaseRequirement); + product.QualityRequirement = TrimOrNull(request.QualityRequirement); + product.DefaultOrigin = TrimOrNull(request.DefaultOrigin); + product.Remark = TrimOrNull(request.Remark); + product.PackingRate = request.PackingRate; + product.CartonLength = request.CartonLength; + product.CartonWidth = request.CartonWidth; + product.CartonHeight = request.CartonHeight; + product.CartonGrossWeight = request.CartonGrossWeight; + product.CartonNetWeight = request.CartonNetWeight; + product.CartonMaterial = TrimOrNull(request.CartonMaterial); + product.PackagingNote = TrimOrNull(request.PackagingNote); + product.HsCode = TrimOrNull(request.HsCode); + product.CustomsNameZh = TrimOrNull(request.CustomsNameZh); + product.CustomsNameEn = TrimOrNull(request.CustomsNameEn); + product.CustomsUnit = TrimOrNull(request.CustomsUnit); + product.DeclarationElements = TrimOrNull(request.DeclarationElements); + product.OriginCountry = TrimOrNull(request.OriginCountry); + product.CustomsRemark = TrimOrNull(request.CustomsRemark); + + if (product.PackingRate is <= 0) + { + throw new CatalogValidationException(nameof(request.PackingRate), "装箱率必须大于 0。"); + } + } + + private static void ApplyPart(ProductPart part, SaveProductPartRequest request) + { + if (string.IsNullOrWhiteSpace(request.Name)) + { + throw new CatalogValidationException(nameof(request.Name), "零件名称不能为空。"); + } + + if (string.IsNullOrWhiteSpace(request.Unit)) + { + throw new CatalogValidationException(nameof(request.Unit), "零件计量单位不能为空。"); + } + + if (request.QuantityPerProduct <= 0) + { + throw new CatalogValidationException(nameof(request.QuantityPerProduct), "每套用量必须大于 0。"); + } + + part.Name = request.Name.Trim(); + part.PartType = ParseEnum(request.PartType, ProductPartType.Accessory, nameof(request.PartType)); + part.ComponentProductId = request.ComponentProductId; + part.ComponentSku = TrimOrNull(request.ComponentSku); + part.QuantityPerProduct = request.QuantityPerProduct; + part.Unit = request.Unit.Trim(); + part.Requirement = TrimOrNull(request.Requirement); + part.IsRequired = request.IsRequired; + part.SortOrder = request.SortOrder; + } + + private static T ParseEnum(string? value, T? fallback, string field) where T : struct, Enum + { + if (string.IsNullOrWhiteSpace(value)) + { + return fallback ?? throw new CatalogValidationException(field, $"{field} 不能为空。"); + } + + return Enum.TryParse(value, ignoreCase: true, out var parsed) + ? parsed + : throw new CatalogValidationException(field, $"{field} 的值无效。"); + } + + // Overload used where a non-nullable fallback is supplied. + private static T ParseEnum(string? value, T fallback, string field) where T : struct, Enum + => string.IsNullOrWhiteSpace(value) ? fallback : ParseEnum(value, (T?)null, field); + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private void AddChangeLog(Product product, ProductChangeAction action, IReadOnlyList changedFields, + string summary, Guid? actorUserId, string? actorUserName) + { + var entry = new ProductChangeLog + { + ProductId = product.Id, + Product = product, + ActorUserId = actorUserId, + ActorUserName = string.IsNullOrWhiteSpace(actorUserName) ? null : actorUserName.Trim()[..Math.Min(200, actorUserName.Trim().Length)], + Action = action, + ProductVersion = product.Version, + ChangedFieldsJson = JsonSerializer.Serialize(changedFields), + Summary = summary.Length <= 500 ? summary : summary[..500] + }; + product.ChangeLogs.Add(entry); + db.ProductChangeLogs.Add(entry); + } + + private static ProductChangeLogDto ToDto(ProductChangeLog entry) + { + IReadOnlyList fields; + try { fields = JsonSerializer.Deserialize>(entry.ChangedFieldsJson) ?? []; } + catch (JsonException) { fields = []; } + return new ProductChangeLogDto(entry.Id, entry.ProductId, entry.ActorUserId, entry.ActorUserName, + entry.Action.ToString(), entry.ProductVersion, fields, entry.Summary, entry.CreatedAt); + } + + private static IReadOnlyList ChangedFields( + IReadOnlyDictionary before, IReadOnlyDictionary after) + => after.Keys.Where(k => !string.Equals(before.GetValueOrDefault(k), after[k], StringComparison.Ordinal)).ToList(); + + private static IReadOnlyList NonEmptyFields(IReadOnlyDictionary snapshot) + => snapshot.Where(x => !string.IsNullOrWhiteSpace(x.Value)).Select(x => x.Key).ToList(); + + private static string? F(object? value) => value switch + { + null => null, + IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString() + }; + + private static Dictionary Snapshot(Product p) => new() + { + [nameof(p.InternalSku)] = p.InternalSku, [nameof(p.NameZh)] = p.NameZh, [nameof(p.NameEn)] = p.NameEn, + [nameof(p.Category)] = p.Category, [nameof(p.ProductType)] = F(p.ProductType), [nameof(p.Unit)] = p.Unit, + [nameof(p.ProductLength)] = F(p.ProductLength), [nameof(p.ProductWidth)] = F(p.ProductWidth), [nameof(p.ProductHeight)] = F(p.ProductHeight), + [nameof(p.DimensionUnit)] = p.DimensionUnit, [nameof(p.Description)] = p.Description, + [nameof(p.PurchaseRequirement)] = p.PurchaseRequirement, [nameof(p.QualityRequirement)] = p.QualityRequirement, + [nameof(p.DefaultOrigin)] = p.DefaultOrigin, [nameof(p.Remark)] = p.Remark, + [nameof(p.PackingRate)] = F(p.PackingRate), [nameof(p.CartonLength)] = F(p.CartonLength), + [nameof(p.CartonWidth)] = F(p.CartonWidth), [nameof(p.CartonHeight)] = F(p.CartonHeight), + [nameof(p.CartonGrossWeight)] = F(p.CartonGrossWeight), [nameof(p.CartonNetWeight)] = F(p.CartonNetWeight), + [nameof(p.CartonMaterial)] = p.CartonMaterial, [nameof(p.PackagingNote)] = p.PackagingNote, + [nameof(p.HsCode)] = p.HsCode, [nameof(p.CustomsNameZh)] = p.CustomsNameZh, [nameof(p.CustomsNameEn)] = p.CustomsNameEn, + [nameof(p.CustomsUnit)] = p.CustomsUnit, [nameof(p.DeclarationElements)] = p.DeclarationElements, + [nameof(p.OriginCountry)] = p.OriginCountry, [nameof(p.CustomsRemark)] = p.CustomsRemark + }; + + private static Dictionary Snapshot(ProductPart p) => new() + { + [nameof(p.Name)] = p.Name, [nameof(p.PartType)] = F(p.PartType), [nameof(p.ComponentProductId)] = F(p.ComponentProductId), + [nameof(p.ComponentSku)] = p.ComponentSku, [nameof(p.QuantityPerProduct)] = F(p.QuantityPerProduct), + [nameof(p.Unit)] = p.Unit, [nameof(p.Requirement)] = p.Requirement, [nameof(p.IsRequired)] = F(p.IsRequired), + [nameof(p.SortOrder)] = F(p.SortOrder), [nameof(p.IsActive)] = F(p.IsActive) + }; + + private static ProductListItemDto ToListItem(Product p) => new( + p.Id, p.InternalSku, p.NameZh, p.NameEn, p.Category, + p.ProductType?.ToString(), p.Unit, p.Status.ToString(), p.Version, + p.HsCode, p.UpdatedAt, p.PublishedAt); + + private static ProductPartDto ToDto(ProductPart part) => new( + part.Id, part.ProductId, part.ComponentProductId, part.Name, part.PartType.ToString(), + part.ComponentSku, part.QuantityPerProduct, part.Unit, part.Requirement, + part.IsRequired, part.SortOrder, part.IsActive); + + private static SupplierQuoteDto ToDto(ProductSupplierQuote q) => new( + q.Id, q.ProductId, q.ProductPartId, q.SupplierId, q.SupplierName, + q.SupplierProductName, q.SupplierProductSku, q.ContentType.ToString(), + q.UnitPrice, q.Currency, q.PricingUnit, q.TaxIncluded, q.TaxRate, + q.MinimumOrderQuantity, q.LeadTimeDays, q.EffectiveFrom, q.EffectiveTo, + q.IsDefault, q.Requirement, q.Remark, q.CreatedAt); + + private static ProductDto ToDto(Product p) => new( + p.Id, p.InternalSku, p.NameZh, p.NameEn, p.Category, p.ProductType?.ToString(), p.Unit, + p.ProductLength, p.ProductWidth, p.ProductHeight, p.DimensionUnit, p.Description, + p.PurchaseRequirement, p.QualityRequirement, p.DefaultOrigin, p.Remark, + p.PackingRate, p.CartonLength, p.CartonWidth, p.CartonHeight, + p.CartonGrossWeight, p.CartonNetWeight, p.CartonMaterial, p.PackagingNote, + p.HsCode, p.CustomsNameZh, p.CustomsNameEn, p.CustomsUnit, p.DeclarationElements, + p.OriginCountry, p.CustomsRemark, + p.Status.ToString(), p.Version, p.CreatedAt, p.UpdatedAt, p.PublishedAt, + p.Parts.OrderBy(x => x.SortOrder).ThenBy(x => x.Name).Select(ToDto).ToList(), + p.SupplierQuotes.OrderByDescending(x => x.CreatedAt).Select(ToDto).ToList()); +} diff --git a/src/Leiren.Erp.Application/Class1.cs b/src/Leiren.Erp.Application/Class1.cs new file mode 100644 index 0000000..a377b2c --- /dev/null +++ b/src/Leiren.Erp.Application/Class1.cs @@ -0,0 +1,6 @@ +namespace Leiren.Erp.Application; + +public class Class1 +{ + +} diff --git a/src/Leiren.Erp.Application/Customs/CiPlDocumentGenerationService.cs b/src/Leiren.Erp.Application/Customs/CiPlDocumentGenerationService.cs new file mode 100644 index 0000000..806c624 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CiPlDocumentGenerationService.cs @@ -0,0 +1,204 @@ +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Generates customs and customer document workbooks (every shipping-batch +/// ) for a confirmed shipping batch from a mapped +/// XLSX template version. The template file and the generated file both live +/// in the Files module; each regeneration stores a new attachment version of +/// the document package's file and a new document-package version, then locks +/// the template mappings. Unconfirmed batches and templates with unmapped +/// placeholders are refused before any file is produced. +/// +public sealed class CiPlDocumentGenerationService( + ICustomsDbContext db, FileService files, DocumentTemplateMappingService mappings) +{ + public const string OwnerType = "document-package"; + public const string ContentType = + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public async Task GenerateAsync( + Guid shippingBatchId, GenerateCiPlDocumentRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + + if (request.TemplateVersionId is not { } templateVersionId || templateVersionId == Guid.Empty) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "必须选择已完成字段映射的模板版本。"); + + var batch = await db.ShippingBatches.AsNoTracking() + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == shippingBatchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new CustomsConflictException("只有已确认的出货批次可以生成单证。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(shippingBatchId), "出货批次没有出货明细,不能生成单证。"); + + var lines = batch.Lines.OrderBy(x => x.CreatedAt).ThenBy(x => x.Id).ToList(); + + // Template bytes come from the Files module; the template version id + // is the immutable template file version id. + byte[] templateBytes; + FileAttachmentDto templateFile; + try + { + templateFile = await files.GetAsync(templateVersionId, ct); + await using var download = (await files.OpenDownloadAsync(templateVersionId, ct)).Content; + using var buffer = new MemoryStream(); + await download.CopyToAsync(buffer, ct); + templateBytes = buffer.ToArray(); + } + catch (FilesNotFoundException) + { + throw new CustomsNotFoundException("模板版本文件不存在。"); + } + if (!string.Equals(templateFile.Extension, ".xlsx", StringComparison.OrdinalIgnoreCase)) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "模板文件必须是 .xlsx 文件。"); + if (templateBytes.Length == 0) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "模板文件内容为空。"); + // The template's own type decides the document kind unless the caller names one. + var kind = ParseKind(request.DocumentKind ?? templateFile.Category); + + TemplateScanResult scan; + try + { + scan = TemplatePlaceholderScanner.Scan(templateBytes); + } + catch (DocumentTemplateValidationException ex) + { + throw new CustomsValidationException(ex.Errors); + } + var scannedNames = scan.Placeholders.Select(x => x.Name).ToList(); + if (scannedNames.Count == 0) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "模板中没有 {{...}} 占位符,不能生成。"); + + // Refuses generation, listing every unmapped placeholder, when the + // mapping profile for this template version is incomplete. + var profile = await mappings.ValidateForGenerationAsync(templateVersionId, scannedNames, ct); + if (!string.IsNullOrWhiteSpace(profile.TemplateReference) + && Guid.TryParse(profile.TemplateReference, out var referencedFileId) + && referencedFileId != templateVersionId) + { + throw new CustomsValidationException(nameof(request.TemplateVersionId), + "映射记录的模板引用与所选模板版本文件不一致,禁止生成。"); + } + + var mappingsByKey = profile.Mappings.ToDictionary( + m => DocumentTemplateFieldMapping.NormalizePlaceholderKey(m.Placeholder), + m => new CiPlMappedField( + m.Placeholder, m.BusinessField, + DocumentTemplateFields.TryGet(m.BusinessField, out var def) ? def.Scope : TemplateFieldScope.Header, + m.NumberFormat), + StringComparer.Ordinal); + + var source = await DocumentRenderSource.LoadAsync(db, batch, ct); + if (DocumentRenderSource.IsCustomsKind(kind) && source.Declaration is null) + throw new CustomsConflictException("报关单证从报关资料取数:请先在出货与报关中填写并确认该批次的报关资料。"); + + var generatedAt = DateTimeOffset.UtcNow; + var rendered = CiPlTemplateRenderer.Render( + templateBytes, batch, lines, kind, source, mappingsByKey, generatedAt); + + var version = (await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id && x.DocumentKind == kind) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + + var package = new DocumentPackage + { + ShippingBatchId = batch.Id, + CustomsDeclarationId = DocumentRenderSource.IsCustomsKind(kind) ? source.Declaration?.Id : null, + DocumentKind = kind, + Status = DocumentPackageStatus.Generated, + Version = version, + PackageNo = $"DOC-{batch.BatchNo}-{kind.ToString().ToUpperInvariant()}-{version}", + TemplateReference = profile.TemplateReference ?? templateVersionId.ToString("D"), + TemplateVersionId = templateVersionId, + TemplateVersion = templateFile.Version.ToString(), + OutputFormat = "xlsx", + Currency = batch.Currency, + LineCount = lines.Count, + TotalQuantity = DocumentRenderSource.IsCustomsKind(kind) ? source.Declaration!.TotalQuantity : lines.Sum(x => x.Quantity), + TotalAmount = DocumentRenderSource.IsCustomsKind(kind) ? source.Declaration!.TotalAmount : lines.Sum(x => x.Amount), + TotalCartonCount = lines.Sum(x => x.CartonCount ?? 0), + TotalGrossWeight = lines.Sum(x => x.TotalGrossWeight ?? 0), + TotalNetWeight = lines.Sum(x => x.TotalNetWeight ?? 0), + TotalCbm = lines.Sum(x => x.TotalCbm ?? 0), + GeneratedAt = generatedAt, + GeneratedBy = TrimOrNull(request.GeneratedBy), + Remark = TrimOrNull(request.Remark) + }; + + var fileName = $"{SanitizeFileStem(batch.BatchNo)}-{kind}-{version}.xlsx"; + var category = kind.ToString(); + var description = + $"客户单证 {package.PackageNo};出货批次 {batch.BatchNo};模板版本 {templateVersionId:D};生成时间 {generatedAt:yyyy-MM-dd HH:mm:ss} UTC。"; + + await using var outputStream = new MemoryStream(rendered, writable: false); + + // Regenerating the same batch + kind stores a new version of the + // previous generated file, keeping every earlier file downloadable. + var previousFileId = await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id && x.DocumentKind == kind && x.GeneratedFileReference != null) + .OrderByDescending(x => x.Version) + .Select(x => x.GeneratedFileReference) + .FirstOrDefaultAsync(ct); + + FileAttachmentDto file; + if (previousFileId is not null && Guid.TryParse(previousFileId, out var anchorId)) + { + file = await files.UploadNewVersionAsync( + anchorId, outputStream, fileName, ContentType, category, description, ct: ct); + } + else + { + file = await files.UploadAsync(new UploadFileCommand( + OwnerType, package.Id, category, description, fileName, ContentType, outputStream), ct); + } + + package.GeneratedFileReference = file.Id.ToString("D"); + package.GeneratedFileName = file.OriginalFileName; + + db.DocumentPackages.Add(package); + await db.SaveChangesAsync(ct); + + await mappings.LockAfterGenerationAsync(templateVersionId, package.Id, ct); + + return new CiPlDocumentGenerationResultDto( + ToDto(package), file, $"/api/files/{file.Id}/download", scannedNames); + } + + private static DocumentKind ParseKind(string? value) + { + if (string.IsNullOrWhiteSpace(value) + || !Enum.TryParse(value.Trim(), ignoreCase: true, out var kind)) + { + throw new CustomsValidationException(nameof(GenerateCiPlDocumentRequest.DocumentKind), + "单证类型无效,只能使用报关或客户单证模板生成。"); + } + return kind; + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + private static string SanitizeFileStem(string batchNo) + { + var invalid = Path.GetInvalidFileNameChars(); + var stem = new string(batchNo.Trim().Select(c => invalid.Contains(c) ? '-' : c).ToArray()); + return string.IsNullOrWhiteSpace(stem) ? "shipment" : stem; + } + + private static DocumentPackageDto ToDto(DocumentPackage p) => new( + p.Id, p.ShippingBatchId, p.CustomsDeclarationId, p.PackageNo, p.DocumentKind.ToString(), + p.Status.ToString(), p.Version, p.TemplateReference, p.TemplateVersion, p.OutputFormat, + p.GeneratedFileReference, p.GeneratedFileName, p.Currency, p.LineCount, p.TotalQuantity, + p.TotalAmount, p.TotalCartonCount, p.TotalGrossWeight, p.TotalNetWeight, p.TotalCbm, + p.GeneratedAt, p.GeneratedBy, p.ConfirmedAt, p.ConfirmedBy, p.ExportedAt, p.ExportedBy, + p.VoidedAt, p.Remark, p.CreatedAt, p.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Customs/CiPlTemplateRenderer.cs b/src/Leiren.Erp.Application/Customs/CiPlTemplateRenderer.cs new file mode 100644 index 0000000..e899717 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CiPlTemplateRenderer.cs @@ -0,0 +1,412 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using ClosedXML.Excel; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; + +namespace Leiren.Erp.Application.Customs; + +/// One resolved placeholder mapping used by the renderer (placeholder key is the normalized name). +public sealed record CiPlMappedField(string Placeholder, string BusinessField, TemplateFieldScope Scope, string? NumberFormat); + +/// +/// Renders a customer CI/PL workbook from a real XLSX template and the +/// confirmed shipping-batch snapshot. Placeholders are discovered by scanning +/// every worksheet's used range (never fixed cell coordinates); the row +/// carrying line-scope placeholders is copied once per shipment line, and all +/// totals are computed in code from the shipment-line snapshots — template +/// formulas are never evaluated or relied upon. +/// +public static partial class CiPlTemplateRenderer +{ + [GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)] + private static partial Regex TokenRegex(); + + public static byte[] Render( + byte[] templateBytes, + ShippingBatch batch, + IReadOnlyList lines, + DocumentKind kind, + DocumentRenderSource source, + IReadOnlyDictionary mappingsByPlaceholderKey, + DateTimeOffset generatedAt, + bool allowUnmapped = false) + { + ArgumentNullException.ThrowIfNull(templateBytes); + ArgumentNullException.ThrowIfNull(batch); + ArgumentNullException.ThrowIfNull(lines); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(mappingsByPlaceholderKey); + + // Customs documents print the declared quantity / price / HS code; + // every customs-only field (报关品名, 申报要素 ...) is read from the + // declaration line of the same shipment line whenever one exists. + var declaredByShipmentLine = source.Declaration?.Lines.ToDictionary(x => x.ShipmentLineId) + ?? new Dictionary(); + var useDeclared = DocumentRenderSource.IsCustomsKind(kind) && source.Declaration is not null; + var docLines = lines + .Select(l => new DocLine(l, declaredByShipmentLine.GetValueOrDefault(l.Id), useDeclared)) + .ToList(); + var totals = ComputeTotals(docLines); + var context = new RenderContext(batch, docLines, kind, source, totals, generatedAt); + + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(new MemoryStream(templateBytes, writable: false)); + } + catch (Exception ex) + { + throw new CustomsValidationException("TemplateVersionId", $"模板 Excel 文件无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + if (workbook.Worksheets.Count == 0) + throw new CustomsValidationException("TemplateVersionId", "模板工作簿中没有任何工作表。"); + + // Pre-pass: every placeholder in the workbook must be mapped to a + // known business field, otherwise generation is refused with the + // full list of missing placeholders. Previews (allowUnmapped) keep + // unmapped tokens as written so an incomplete mapping can be tested. + var unmapped = new SortedSet(StringComparer.OrdinalIgnoreCase); + foreach (var sheet in workbook.Worksheets) + foreach (var name in ScanPlaceholderNames(sheet)) + if (!mappingsByPlaceholderKey.TryGetValue(NormalizeKey(name), out var field) + || !DocumentTemplateFields.TryGet(field.BusinessField, out _)) + unmapped.Add(name); + if (unmapped.Count > 0 && !allowUnmapped) + { + throw new CustomsValidationException(new Dictionary + { + ["UnmappedPlaceholders"] = unmapped.Select(p => $"{{{{{p}}}}}").ToArray() + }); + } + + var usable = mappingsByPlaceholderKey + .Where(x => DocumentTemplateFields.TryGet(x.Value.BusinessField, out _)) + .ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal); + foreach (var sheet in workbook.Worksheets) + RenderSheet(sheet, context, usable); + + using var output = new MemoryStream(); + workbook.SaveAs(output); + return output.ToArray(); + } + } + + // ---------- Sheet rendering ---------- + + private static void RenderSheet( + IXLWorksheet sheet, RenderContext context, IReadOnlyDictionary mappings) + { + var range = sheet.RangeUsed(); + if (range is null) return; + var firstColumn = range.FirstColumn().ColumnNumber(); + var lastColumn = range.LastColumn().ColumnNumber(); + + // Detail rows carry at least one line-scope placeholder; the template + // block spans from the first to the last such row. + var detailRows = new SortedSet(); + foreach (var cell in range.Cells()) + { + var text = CellTokenText(cell); + if (text is null) continue; + foreach (Match match in TokenRegex().Matches(text)) + { + if (mappings.TryGetValue(NormalizeKey(match.Groups[1].Value.Trim()), out var field) + && field.Scope == TemplateFieldScope.Line) + detailRows.Add(cell.Address.RowNumber); + } + } + + var lineIndexByRow = new Dictionary(); + if (detailRows.Count > 0) + { + var blockStart = detailRows.Min; + var blockEnd = detailRows.Max; + var height = blockEnd - blockStart + 1; + var lineCount = context.Lines.Count; + + var mergedInsideBlock = sheet.MergedRanges + .Select(r => (FirstRow: r.FirstRow().RowNumber(), FirstCol: r.FirstColumn().ColumnNumber(), + LastRow: r.LastRow().RowNumber(), LastCol: r.LastColumn().ColumnNumber())) + .Where(m => m.FirstRow >= blockStart && m.LastRow <= blockEnd) + .ToList(); + var templateHeights = Enumerable.Range(blockStart, height).Select(r => sheet.Row(r).Height).ToList(); + + if (lineCount > 1) + { + var extraRows = (lineCount - 1) * height; + sheet.Row(blockEnd + 1).InsertRowsAbove(extraRows); + + var templateRange = sheet.Range(blockStart, firstColumn, blockEnd, lastColumn); + for (var copy = 1; copy < lineCount; copy++) + { + var targetStart = blockStart + copy * height; + templateRange.CopyTo(sheet.Cell(targetStart, firstColumn)); + for (var r = 0; r < height; r++) + sheet.Row(targetStart + r).Height = templateHeights[r]; + foreach (var m in mergedInsideBlock) + { + var offset = copy * height; + try { sheet.Range(m.FirstRow + offset, m.FirstCol, m.LastRow + offset, m.LastCol).Merge(); } + catch (InvalidOperationException) { /* already merged by the copy */ } + } + } + } + + for (var i = 0; i < lineCount; i++) + for (var r = 0; r < height; r++) + lineIndexByRow[blockStart + i * height + r] = i; + } + + // Replacement pass over the (now expanded) used range. + var expanded = sheet.RangeUsed(); + if (expanded is null) return; + foreach (var cell in expanded.Cells()) + { + var text = CellTokenText(cell); + if (text is null) continue; + + int? lineIndex = lineIndexByRow.TryGetValue(cell.Address.RowNumber, out var idx) ? idx : null; + ReplaceCell(cell, text, context, mappings, lineIndex); + } + } + + private static void ReplaceCell( + IXLCell cell, string text, RenderContext context, + IReadOnlyDictionary mappings, int? lineIndex) + { + var matches = TokenRegex().Matches(text); + if (matches.Count == 0) return; + + // A cell holding exactly one placeholder takes the typed value so + // numbers and dates stay real Excel values. + if (matches.Count == 1 && string.Equals(text.Trim(), matches[0].Value, StringComparison.Ordinal)) + { + // Unmapped tokens (preview only) stay as written. + if (!mappings.TryGetValue(NormalizeKey(matches[0].Groups[1].Value.Trim()), out var field)) return; + var value = ResolveValue(field, context, lineIndex); + SetTypedValue(cell, value, field.NumberFormat); + return; + } + + var replaced = TokenRegex().Replace(text, match => + { + if (!mappings.TryGetValue(NormalizeKey(match.Groups[1].Value.Trim()), out var field)) return match.Value; + var value = ResolveValue(field, context, lineIndex); + return FormatAsText(value); + }); + cell.Value = replaced; + } + + private static object? ResolveValue(CiPlMappedField field, RenderContext context, int? lineIndex) + { + if (!DocumentTemplateFields.TryGet(field.BusinessField, out var definition)) + throw new CustomsValidationException("BusinessField", $"业务字段 \"{field.BusinessField}\" 不在允许字段目录中。"); + + return definition.Scope switch + { + TemplateFieldScope.Line => lineIndex is { } i + ? LineValue(definition.Key, context.Lines[i], i + 1, context) + : throw new CustomsValidationException("TemplateVersionId", + $"明细字段 {definition.Key} 的占位符没有放在明细行中,无法生成。"), + TemplateFieldScope.Total => TotalValue(definition.Key, context.Totals), + _ => HeaderValue(definition.Key, context) + }; + } + + // ---------- Field values (shipment snapshot only) ---------- + + private static object? HeaderValue(string key, RenderContext c) => key switch + { + "BatchNo" => c.Batch.BatchNo, + "SalesOrderNo" => c.Batch.SalesOrderNo, + "CustomerName" => c.Batch.CustomerName, + "CustomerPoNo" => c.Batch.CustomerPoNo, + "Currency" => c.Batch.Currency, + "ShipmentDate" => c.Batch.ShipmentDate, + "CutoffDate" => c.Batch.CutoffDate, + "Etd" => c.Batch.Etd, + "Eta" => c.Batch.Eta, + "VesselName" => c.Batch.VesselName, + "VoyageNo" => c.Batch.VoyageNo, + "BillOfLadingNo" => c.Batch.BillOfLadingNo, + "LoadingPort" => c.Batch.LoadingPort, + "DestinationPort" => c.Batch.DestinationPort, + "DestinationCountry" => c.Batch.DestinationCountry, + "TransportMode" => c.Batch.TransportMode, + "TradeTerm" => c.Batch.TradeTerm, + "FreightForwarder" => c.Batch.FreightForwarder, + "ContainerNumbers" => c.Batch.Containers.Count == 0 + ? null + : string.Join(", ", c.Batch.Containers.Select(x => x.ContainerNo)), + "DeclarationNo" => c.Source.Declaration?.DeclarationNo, + "DocumentKind" => c.Kind.ToString(), + "GeneratedDate" => DateOnly.FromDateTime(c.GeneratedAt.UtcDateTime), + "InvoiceNo" => c.Source.Declaration?.InvoiceNo ?? c.Batch.BatchNo, + "CustomerAddress" => c.Source.Customer?.Address, + "OrderDate" => c.Source.OrderDate, + "ExportDate" => c.Source.Declaration?.ExportDate ?? c.Batch.Etd ?? c.Batch.ShipmentDate, + "DeclarationDate" => c.Source.Declaration?.DeclarationDate, + "TradeMode" => c.Source.Declaration?.TradeMode, + "ExemptionNature" => c.Source.Declaration?.ExemptionNature, + "CurrencyNameZh" => CurrencyNameZh(c.Batch.Currency), + _ => throw UnknownField(key) + }; + + private static object? LineValue(string key, DocLine d, int lineNumber, RenderContext c) + { + var l = d.Shipment; + var declared = d.Declared; + return key switch + { + "LineNumber" => lineNumber, + "InternalSku" => l.InternalSku, + "ProductNameZh" => l.ProductNameZh, + "ProductNameEn" => l.ProductNameEn, + "CustomerSku" => l.CustomerSku, + "CustomerProductName" => l.CustomerProductName, + "HsCode" => d.UseDeclared ? declared!.HsCode : declared?.HsCode ?? l.HsCode, + "Quantity" => d.Quantity, + "Unit" => d.UseDeclared ? declared!.Unit : l.Unit, + "UnitPrice" => d.UseDeclared ? declared!.UnitPrice : l.UnitPrice, + "Amount" => d.Amount, + "PackingRate" => l.PackingRate, + "CartonCount" => l.CartonCount, + "CartonLength" => l.CartonLength, + "CartonWidth" => l.CartonWidth, + "CartonHeight" => l.CartonHeight, + "CartonGrossWeight" => l.CartonGrossWeight, + "CartonNetWeight" => l.CartonNetWeight, + "LineTotalGrossWeight" => l.TotalGrossWeight, + "LineTotalNetWeight" => l.TotalNetWeight, + "LineTotalCbm" => l.TotalCbm, + "Remark" => l.Remark, + "CustomsNameZh" => declared?.CustomsNameZh ?? l.ProductNameZh, + "CustomsNameEn" => declared?.CustomsNameEn ?? l.ProductNameEn, + "DeclarationElements" => declared?.DeclarationElements, + "OriginCountry" => declared?.OriginCountry, + "DomesticSourcePlace" => declared?.DomesticSourcePlace, + "ExemptionInfo" => declared?.ExemptionInfo, + "LineCurrencyZh" => CurrencyNameZh(c.Batch.Currency), + _ => throw UnknownField(key) + }; + } + + private static object? TotalValue(string key, Totals t) => key switch + { + "LineCount" => t.LineCount, + "TotalQuantity" => t.TotalQuantity, + "TotalAmount" => t.TotalAmount, + "TotalCartonCount" => t.TotalCartonCount, + "TotalGrossWeight" => t.TotalGrossWeight, + "TotalNetWeight" => t.TotalNetWeight, + "TotalCbm" => t.TotalCbm, + _ => throw UnknownField(key) + }; + + private static Totals ComputeTotals(IReadOnlyList lines) => new( + lines.Count, + lines.Sum(x => x.Quantity), + lines.Sum(x => x.Amount), + lines.Sum(x => x.Shipment.CartonCount ?? 0), + lines.Sum(x => x.Shipment.TotalGrossWeight ?? 0), + lines.Sum(x => x.Shipment.TotalNetWeight ?? 0), + lines.Sum(x => x.Shipment.TotalCbm ?? 0)); + + /// Chinese currency name used by the customs declaration (币制). + private static string CurrencyNameZh(string currency) => currency.ToUpperInvariant() switch + { + "USD" => "美元", + "CNY" or "RMB" => "人民币", + "EUR" => "欧元", + "GBP" => "英镑", + "JPY" => "日元", + "HKD" => "港币", + "AUD" => "澳大利亚元", + "CAD" => "加拿大元", + _ => currency, + }; + + // ---------- Cell helpers ---------- + + /// Token-bearing text of a cell, or null. Formula cells are skipped: their values are never a data source. + private static string? CellTokenText(IXLCell cell) + { + if (cell.HasFormula) return null; + string text; + try { text = cell.GetString(); } + catch (InvalidOperationException) { return null; } + return text.Contains("{{", StringComparison.Ordinal) ? text : null; + } + + private static IEnumerable ScanPlaceholderNames(IXLWorksheet sheet) + { + var range = sheet.RangeUsed(); + if (range is null) yield break; + foreach (var cell in range.Cells()) + { + var text = CellTokenText(cell); + if (text is null) continue; + foreach (Match match in TokenRegex().Matches(text)) + yield return match.Groups[1].Value.Trim(); + } + } + + private static void SetTypedValue(IXLCell cell, object? value, string? numberFormat) + { + switch (value) + { + case null: cell.Value = string.Empty; break; + case string s: cell.Value = s; break; + case decimal d: cell.Value = d; break; + case int i: cell.Value = i; break; + case DateOnly d: + cell.Value = d.ToDateTime(TimeOnly.MinValue); + if (string.IsNullOrWhiteSpace(numberFormat)) cell.Style.DateFormat.Format = "yyyy-mm-dd"; + break; + case DateTime dt: cell.Value = dt; break; + default: cell.Value = value.ToString(); break; + } + + if (!string.IsNullOrWhiteSpace(numberFormat) && value is not string) + { + try { cell.Style.NumberFormat.Format = numberFormat.Trim(); } + catch (ArgumentException) { /* keep the template cell's own format */ } + } + } + + private static string FormatAsText(object? value) => value switch + { + null => string.Empty, + decimal d => d.ToString(CultureInfo.InvariantCulture), + int i => i.ToString(CultureInfo.InvariantCulture), + DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + DateTime dt => dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + _ => value.ToString() ?? string.Empty + }; + + private static string NormalizeKey(string placeholder) + => DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); + + private static CustomsValidationException UnknownField(string key) + => new("BusinessField", $"业务字段 \"{key}\" 不在允许字段目录中。"); + + private sealed record Totals( + int LineCount, decimal TotalQuantity, decimal TotalAmount, int TotalCartonCount, + decimal TotalGrossWeight, decimal TotalNetWeight, decimal TotalCbm); + + /// One document line: the shipment line plus its customs-declaration line, if any. + private sealed record DocLine(ShipmentLine Shipment, CustomsDeclarationLine? Declared, bool UseDeclaredValues) + { + public bool UseDeclared => UseDeclaredValues && Declared is not null; + public decimal Quantity => UseDeclared ? Declared!.Quantity : Shipment.Quantity; + public decimal Amount => UseDeclared ? Declared!.Amount : Shipment.Amount; + } + + private sealed record RenderContext( + ShippingBatch Batch, IReadOnlyList Lines, DocumentKind Kind, + DocumentRenderSource Source, Totals Totals, DateTimeOffset GeneratedAt); +} diff --git a/src/Leiren.Erp.Application/Customs/CustomsExceptions.cs b/src/Leiren.Erp.Application/Customs/CustomsExceptions.cs new file mode 100644 index 0000000..17a8082 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CustomsExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Customs; + +public sealed class CustomsNotFoundException(string message) : Exception(message); + +public sealed class CustomsConflictException(string message) : Exception(message); + +public sealed class CustomsValidationException(IReadOnlyDictionary errors) + : Exception("报关与单证资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public CustomsValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Customs/CustomsService.cs b/src/Leiren.Erp.Application/Customs/CustomsService.cs new file mode 100644 index 0000000..fc6cb1a --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CustomsService.cs @@ -0,0 +1,527 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +public sealed class CustomsService(ICustomsDbContext db, DocumentTemplateMappingService templateMappings) +{ + private static readonly DocumentKind[] CustomsKinds = + [ + DocumentKind.CustomsInvoice, + DocumentKind.CustomsPackingList, + DocumentKind.CustomsSalesContract, + DocumentKind.CustomsDeclarationData + ]; + + // ---------- Customs declarations ---------- + + public async Task> ListAsync( + string? search, string? status, Guid? shippingBatchId, int page, int pageSize, CancellationToken ct = default) + { + var query = db.CustomsDeclarations.AsNoTracking().Include(x => x.Lines).AsQueryable(); + + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new CustomsValidationException(nameof(status), "报关资料状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (shippingBatchId is { } batchId) query = query.Where(x => x.ShippingBatchId == batchId); + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.ShippingBatchNo.Contains(term) + || x.SalesOrderNo.Contains(term) + || x.CustomerName.Contains(term) + || (x.DeclarationNo != null && x.DeclarationNo.Contains(term)) + || (x.CustomerPoNo != null && x.CustomerPoNo.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new CustomsDeclarationListItemDto( + x.Id, x.ShippingBatchId, x.ShippingBatchNo, x.Version, x.DeclarationNo, + x.SalesOrderNo, x.CustomerName, x.Currency, x.Status.ToString(), + x.TotalQuantity, x.TotalAmount, x.Lines.Count, x.UpdatedAt)).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task CreateFromShippingBatchAsync( + CreateCustomsDeclarationRequest request, CancellationToken ct = default) + { + if (request.ShippingBatchId == Guid.Empty) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "必须选择出货批次。"); + + var batch = await db.ShippingBatches.AsNoTracking() + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == request.ShippingBatchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new CustomsConflictException("只有已确认的出货批次可以生成报关资料。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "出货批次没有出货明细,不能生成报关资料。"); + + var hasDraft = await db.CustomsDeclarations.AnyAsync( + x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Draft, ct); + if (hasDraft) + throw new CustomsConflictException("该出货批次已有草稿报关资料,请编辑现有草稿或先将其作废。"); + + var overrides = new Dictionary(); + if (request.Lines is not null) + { + var shipmentLineIds = batch.Lines.Select(x => x.Id).ToHashSet(); + foreach (var line in request.Lines) + { + if (!shipmentLineIds.Contains(line.ShipmentLineId)) + throw new CustomsValidationException(nameof(request.Lines), "报关明细覆盖项引用了不属于该出货批次的出货明细。"); + overrides[line.ShipmentLineId] = line; + } + } + + // Product customs defaults are resolved through the sales order lines + // (shipment lines carry no ProductId); they are snapshotted now. + var salesOrderLineIds = batch.Lines.Select(x => x.SalesOrderLineId).Distinct().ToList(); + var productIdBySalesLine = await db.SalesOrderLines.AsNoTracking() + .Where(x => salesOrderLineIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.ProductId, ct); + var productIds = productIdBySalesLine.Values.Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Where(x => productIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, ct); + + var version = (await db.CustomsDeclarations.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + + // Customs details of the latest confirmed declaration carry forward: + // per product (by internal SKU) and, for the header, per customer. + var skus = batch.Lines.Select(x => x.InternalSku).Distinct().ToList(); + var history = (await db.CustomsDeclarationLines.AsNoTracking() + .Where(l => skus.Contains(l.InternalSku) && l.CustomsDeclaration!.Status == CustomsDeclarationStatus.Confirmed) + .Select(l => new { l.CustomsDeclaration!.ConfirmedAt, Line = l }) + .ToListAsync(ct)) + .GroupBy(x => x.Line.InternalSku) + .ToDictionary(g => g.Key, g => g.OrderByDescending(x => x.ConfirmedAt).First().Line); + var lastForCustomer = (await db.CustomsDeclarations.AsNoTracking() + .Where(x => x.CustomerId == batch.CustomerId && x.Status == CustomsDeclarationStatus.Confirmed) + .Select(x => new { x.ConfirmedAt, x.TradeMode, x.ExemptionNature }) + .ToListAsync(ct)) + .OrderByDescending(x => x.ConfirmedAt) + .FirstOrDefault(); + + var declaration = new CustomsDeclaration + { + ShippingBatchId = batch.Id, + Version = version, + DeclarationNo = TrimOrNull(request.DeclarationNo), + InvoiceNo = TrimOrNull(request.InvoiceNo), + ShippingBatchNo = batch.BatchNo, + SalesOrderId = batch.SalesOrderId, + SalesOrderNo = batch.SalesOrderNo, + CustomerId = batch.CustomerId, + CustomerName = batch.CustomerName, + CustomerPoNo = batch.CustomerPoNo, + Currency = batch.Currency, + VesselName = batch.VesselName, + VoyageNo = batch.VoyageNo, + BillOfLadingNo = batch.BillOfLadingNo, + LoadingPort = batch.LoadingPort, + DestinationPort = batch.DestinationPort, + DestinationCountry = batch.DestinationCountry, + TransportMode = batch.TransportMode, + TradeTerm = batch.TradeTerm, + ContainerNumbers = batch.Containers.Count == 0 + ? null + : string.Join(", ", batch.Containers.Select(x => x.ContainerNo)), + TradeMode = TrimOrNull(request.TradeMode) ?? lastForCustomer?.TradeMode, + ExemptionNature = TrimOrNull(request.ExemptionNature) ?? lastForCustomer?.ExemptionNature, + ExportDate = request.ExportDate, + DeclarationDate = request.DeclarationDate, + Remark = TrimOrNull(request.Remark), + Status = CustomsDeclarationStatus.Draft + }; + + var orderedLines = batch.Lines.OrderBy(x => x.CreatedAt).ToList(); + for (var i = 0; i < orderedLines.Count; i++) + { + var source = orderedLines[i]; + overrides.TryGetValue(source.Id, out var ov); + Product? product = null; + if (productIdBySalesLine.TryGetValue(source.SalesOrderLineId, out var productId)) + products.TryGetValue(productId, out product); + history.TryGetValue(source.InternalSku, out var last); + + var quantity = ov?.Quantity ?? source.Quantity; + var unitPrice = ov?.UnitPrice ?? source.UnitPrice; + if (quantity <= 0) + throw new CustomsValidationException($"Lines[{i}].Quantity", "报关数量必须大于 0。"); + if (unitPrice < 0) + throw new CustomsValidationException($"Lines[{i}].UnitPrice", "报关单价不能小于 0。"); + + var line = new CustomsDeclarationLine + { + ShipmentLineId = source.Id, + SalesOrderLineId = source.SalesOrderLineId, + LineNumber = i + 1, + InternalSku = source.InternalSku, + ProductNameZh = source.ProductNameZh, + ProductNameEn = source.ProductNameEn, + CustomerSku = source.CustomerSku, + CustomerProductName = source.CustomerProductName, + HsCode = TrimOrNull(ov?.HsCode) ?? TrimOrNull(last?.HsCode) ?? TrimOrNull(source.HsCode) ?? TrimOrNull(product?.HsCode), + CustomsNameZh = TrimOrNull(ov?.CustomsNameZh) ?? TrimOrNull(last?.CustomsNameZh) ?? TrimOrNull(product?.CustomsNameZh), + CustomsNameEn = TrimOrNull(ov?.CustomsNameEn) ?? TrimOrNull(last?.CustomsNameEn) ?? TrimOrNull(product?.CustomsNameEn), + DeclarationElements = TrimOrNull(ov?.DeclarationElements) ?? TrimOrNull(last?.DeclarationElements) ?? TrimOrNull(product?.DeclarationElements), + OriginCountry = TrimOrNull(ov?.OriginCountry) ?? TrimOrNull(last?.OriginCountry) ?? TrimOrNull(product?.OriginCountry) ?? TrimOrNull(product?.DefaultOrigin), + DomesticSourcePlace = TrimOrNull(ov?.DomesticSourcePlace) ?? TrimOrNull(last?.DomesticSourcePlace), + ExemptionInfo = TrimOrNull(ov?.ExemptionInfo) ?? TrimOrNull(last?.ExemptionInfo), + Quantity = quantity, + Unit = TrimOrNull(ov?.CustomsUnit) ?? TrimOrNull(last?.Unit) ?? TrimOrNull(product?.CustomsUnit) ?? source.Unit, + UnitPrice = unitPrice, + CartonCount = source.CartonCount ?? 0, + TotalGrossWeight = source.TotalGrossWeight ?? 0, + TotalNetWeight = source.TotalNetWeight ?? 0, + TotalCbm = source.TotalCbm ?? 0 + }; + line.RecalculateAmount(); + declaration.Lines.Add(line); + } + + declaration.RecalculateTotals(); + db.CustomsDeclarations.Add(declaration); + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + public async Task UpdateAsync( + Guid id, UpdateCustomsDeclarationRequest request, CancellationToken ct = default) + { + var declaration = await LoadAsync(id, ct); + try { declaration.EnsureDraft(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + + declaration.DeclarationNo = TrimOrNull(request.DeclarationNo); + declaration.InvoiceNo = TrimOrNull(request.InvoiceNo); + declaration.ExportDate = request.ExportDate; + declaration.DeclarationDate = request.DeclarationDate; + declaration.TradeMode = TrimOrNull(request.TradeMode); + declaration.ExemptionNature = TrimOrNull(request.ExemptionNature); + declaration.Remark = TrimOrNull(request.Remark); + + if (request.Lines is not null) + { + var linesById = declaration.Lines.ToDictionary(x => x.Id); + var seen = new HashSet(); + foreach (var r in request.Lines) + { + if (!seen.Add(r.Id) || !linesById.TryGetValue(r.Id, out var line)) + throw new CustomsValidationException(nameof(request.Lines), "报关明细不存在或重复。"); + if (r.Quantity <= 0) + throw new CustomsValidationException(nameof(r.Quantity), "报关数量必须大于 0。"); + if (r.UnitPrice < 0) + throw new CustomsValidationException(nameof(r.UnitPrice), "报关单价不能小于 0。"); + + line.HsCode = TrimOrNull(r.HsCode); + line.CustomsNameZh = TrimOrNull(r.CustomsNameZh); + line.CustomsNameEn = TrimOrNull(r.CustomsNameEn); + line.Unit = TrimOrNull(r.CustomsUnit) ?? line.Unit; + line.DeclarationElements = TrimOrNull(r.DeclarationElements); + line.OriginCountry = TrimOrNull(r.OriginCountry); + line.DomesticSourcePlace = TrimOrNull(r.DomesticSourcePlace); + line.ExemptionInfo = TrimOrNull(r.ExemptionInfo); + line.Quantity = r.Quantity; + line.UnitPrice = r.UnitPrice; + line.Remark = TrimOrNull(r.Remark); + line.RecalculateAmount(); + } + } + + declaration.RecalculateTotals(); + declaration.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + public async Task ConfirmAsync( + Guid id, ConfirmCustomsDeclarationRequest? request, CancellationToken ct = default) + { + var declaration = await LoadAsync(id, ct); + + var errors = new Dictionary(); + if (declaration.Lines.Count == 0) errors["Lines"] = ["报关资料至少需要一条明细。"]; + for (var i = 0; i < declaration.Lines.Count; i++) + { + var line = declaration.Lines[i]; + if (string.IsNullOrWhiteSpace(line.HsCode)) errors[$"Lines[{i}].HsCode"] = ["确认前必须填写 HS 编码。"]; + if (string.IsNullOrWhiteSpace(line.CustomsNameZh)) errors[$"Lines[{i}].CustomsNameZh"] = ["确认前必须填写中文报关品名。"]; + if (string.IsNullOrWhiteSpace(line.Unit)) errors[$"Lines[{i}].Unit"] = ["确认前必须填写报关单位。"]; + if (line.Quantity <= 0) errors[$"Lines[{i}].Quantity"] = ["报关数量必须大于 0。"]; + if (line.UnitPrice < 0) errors[$"Lines[{i}].UnitPrice"] = ["报关单价不能小于 0。"]; + } + if (errors.Count > 0) throw new CustomsValidationException(errors); + + declaration.RecalculateTotals(); + try { declaration.Confirm(request?.ConfirmedBy); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + public async Task VoidAsync(Guid id, CancellationToken ct = default) + { + var declaration = await LoadAsync(id, ct); + try { declaration.Void(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + // ---------- Document packages ---------- + + public async Task> ListDocumentsAsync( + Guid shippingBatchId, CancellationToken ct = default) + { + await EnsureBatchExistsAsync(shippingBatchId, ct); + var items = await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == shippingBatchId) + .OrderByDescending(x => x.Id) + .ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task> ListDocumentsForCustomsAsync( + Guid customsDeclarationId, CancellationToken ct = default) + { + _ = await LoadAsync(customsDeclarationId, ct); + var items = await db.DocumentPackages.AsNoTracking() + .Where(x => x.CustomsDeclarationId == customsDeclarationId) + .OrderByDescending(x => x.Id) + .ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetDocumentAsync( + Guid shippingBatchId, Guid documentId, CancellationToken ct = default) + => ToDto(await LoadDocumentAsync(shippingBatchId, documentId, ct)); + + public async Task GenerateDocumentAsync( + Guid shippingBatchId, GenerateDocumentPackageRequest request, CancellationToken ct = default) + { + var batch = await LoadConfirmedBatchAsync(shippingBatchId, ct); + var kind = ParseKind(request.DocumentKind); + + // A mapped template version must be fully mapped before generation; + // this throws listing every unmapped placeholder. An explicit + // TemplateVersionId with no mapping profile is refused as well. + Guid? templateVersionId = request.TemplateVersionId; + DocumentTemplateMappingProfileDto? templateProfile = null; + if (templateVersionId is { } explicitVersionId) + { + templateProfile = await templateMappings.ValidateForGenerationAsync(explicitVersionId, scannedPlaceholders: null, ct); + } + else if (Guid.TryParse(TrimOrNull(request.TemplateReference), out var referenceVersionId) + && await templateMappings.ProfileExistsAsync(referenceVersionId, ct)) + { + templateVersionId = referenceVersionId; + templateProfile = await templateMappings.ValidateForGenerationAsync(referenceVersionId, scannedPlaceholders: null, ct); + } + + CustomsDeclaration? customs = null; + if (request.CustomsDeclarationId is { } customsId) + { + customs = await LoadAsync(customsId, ct); + if (customs.ShippingBatchId != batch.Id) + throw new CustomsValidationException(nameof(request.CustomsDeclarationId), "报关资料不属于该出货批次。"); + } + else if (CustomsKinds.Contains(kind)) + { + customs = await db.CustomsDeclarations.AsNoTracking() + .Include(x => x.Lines) + .Where(x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Confirmed) + .OrderByDescending(x => x.Version) + .FirstOrDefaultAsync(ct); + } + + if (CustomsKinds.Contains(kind)) + { + if (customs is null) + throw new CustomsValidationException(nameof(request.CustomsDeclarationId), "生成报关单证前必须先确认该出货批次的报关资料。"); + if (customs.Status != CustomsDeclarationStatus.Confirmed) + throw new CustomsConflictException("只有已确认的报关资料可以生成报关单证包。"); + } + + var version = (await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id && x.DocumentKind == kind) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + + var package = new DocumentPackage + { + ShippingBatchId = batch.Id, + CustomsDeclarationId = customs?.Id, + DocumentKind = kind, + Status = DocumentPackageStatus.Generated, + Version = version, + PackageNo = $"DOC-{batch.BatchNo}-{kind.ToString().ToUpperInvariant()}-{version}", + TemplateReference = templateProfile?.TemplateReference ?? TrimOrNull(request.TemplateReference), + TemplateVersion = TrimOrNull(request.TemplateVersion), + TemplateVersionId = templateVersionId, + OutputFormat = TrimOrNull(request.OutputFormat), + GeneratedFileReference = null, + GeneratedFileName = null, + GeneratedAt = DateTimeOffset.UtcNow, + GeneratedBy = TrimOrNull(request.GeneratedBy), + Remark = TrimOrNull(request.Remark) + }; + + if (customs is not null) + { + package.Currency = customs.Currency; + package.LineCount = customs.Lines.Count; + package.TotalQuantity = customs.TotalQuantity; + package.TotalAmount = customs.TotalAmount; + package.TotalCartonCount = customs.TotalCartonCount; + package.TotalGrossWeight = customs.TotalGrossWeight; + package.TotalNetWeight = customs.TotalNetWeight; + package.TotalCbm = customs.TotalCbm; + } + else + { + package.Currency = batch.Currency; + package.LineCount = batch.Lines.Count; + package.TotalQuantity = batch.TotalQuantity; + package.TotalAmount = batch.TotalAmount; + package.TotalCartonCount = batch.TotalCartonCount; + package.TotalGrossWeight = batch.TotalGrossWeight; + package.TotalNetWeight = batch.TotalNetWeight; + package.TotalCbm = batch.TotalCbm; + } + + db.DocumentPackages.Add(package); + await db.SaveChangesAsync(ct); + if (templateProfile is not null && templateVersionId is { } usedVersionId) + await templateMappings.LockAfterGenerationAsync(usedVersionId, package.Id, ct); + return ToDto(package); + } + + public async Task GenerateForCustomsAsync( + Guid customsDeclarationId, GenerateCustomsDocumentPackageRequest request, CancellationToken ct = default) + { + var declaration = await LoadAsync(customsDeclarationId, ct); + if (declaration.Status != CustomsDeclarationStatus.Confirmed) + throw new CustomsConflictException("只有已确认的报关资料可以生成单证包。"); + + return await GenerateDocumentAsync(declaration.ShippingBatchId, new GenerateDocumentPackageRequest( + request.DocumentKind, declaration.Id, request.TemplateReference, request.TemplateVersion, + request.OutputFormat, request.GeneratedBy, request.Remark, request.TemplateVersionId), ct); + } + + public async Task ConfirmDocumentAsync( + Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CancellationToken ct = default) + { + var package = await LoadDocumentAsync(shippingBatchId, documentId, ct); + try { package.Confirm(request?.Actor); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(package); + } + + public async Task ExportDocumentAsync( + Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CancellationToken ct = default) + { + var package = await LoadDocumentAsync(shippingBatchId, documentId, ct); + try { package.MarkExported(request?.Actor); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(package); + } + + public async Task VoidDocumentAsync( + Guid shippingBatchId, Guid documentId, CancellationToken ct = default) + { + var package = await LoadDocumentAsync(shippingBatchId, documentId, ct); + try { package.Void(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(package); + } + + // ---------- Helpers ---------- + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.CustomsDeclarations + .Include(x => x.Lines.OrderBy(l => l.LineNumber)) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new CustomsNotFoundException("报关资料不存在。"); + + private async Task LoadDocumentAsync(Guid shippingBatchId, Guid documentId, CancellationToken ct) + { + await EnsureBatchExistsAsync(shippingBatchId, ct); + return await db.DocumentPackages.SingleOrDefaultAsync( + x => x.Id == documentId && x.ShippingBatchId == shippingBatchId, ct) + ?? throw new CustomsNotFoundException("单证包不存在。"); + } + + private async Task EnsureBatchExistsAsync(Guid shippingBatchId, CancellationToken ct) + { + if (!await db.ShippingBatches.AsNoTracking().AnyAsync(x => x.Id == shippingBatchId, ct)) + throw new CustomsNotFoundException("出货批次不存在。"); + } + + private async Task LoadConfirmedBatchAsync(Guid shippingBatchId, CancellationToken ct) + { + var batch = await db.ShippingBatches.AsNoTracking() + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == shippingBatchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new CustomsConflictException("只有已确认的出货批次可以生成单证包。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(shippingBatchId), "出货批次没有出货明细,不能生成单证包。"); + return batch; + } + + private static DocumentKind ParseKind(string? value) + { + if (string.IsNullOrWhiteSpace(value) || !Enum.TryParse(value.Trim(), ignoreCase: true, out var kind)) + throw new CustomsValidationException(nameof(GenerateDocumentPackageRequest.DocumentKind), + "单证类型无效,可选值:CustomsInvoice、CustomsPackingList、CustomsSalesContract、CustomsDeclarationData、CommercialInvoice、PackingList。"); + return kind; + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + private static CustomsDeclarationLineDto ToDto(CustomsDeclarationLine l) => new( + l.Id, l.CustomsDeclarationId, l.ShipmentLineId, l.SalesOrderLineId, l.LineNumber, + l.InternalSku, l.ProductNameZh, l.ProductNameEn, l.CustomerSku, l.CustomerProductName, + l.HsCode, l.CustomsNameZh, l.CustomsNameEn, l.DeclarationElements, l.OriginCountry, + l.DomesticSourcePlace, l.ExemptionInfo, l.Quantity, l.Unit, l.UnitPrice, l.Amount, + l.CartonCount, l.TotalGrossWeight, l.TotalNetWeight, l.TotalCbm, l.Remark); + + private static CustomsDeclarationDto ToDto(CustomsDeclaration d) => new( + d.Id, d.ShippingBatchId, d.Version, d.DeclarationNo, d.ShippingBatchNo, d.SalesOrderId, + d.SalesOrderNo, d.CustomerId, d.CustomerName, d.CustomerPoNo, d.Currency, d.VesselName, + d.VoyageNo, d.BillOfLadingNo, d.LoadingPort, d.DestinationPort, d.DestinationCountry, + d.TransportMode, d.TradeTerm, d.ContainerNumbers, d.TradeMode, d.ExemptionNature, + d.ExportDate, d.DeclarationDate, d.Status.ToString(), d.TotalQuantity, d.TotalAmount, + d.TotalCartonCount, d.TotalGrossWeight, d.TotalNetWeight, d.TotalCbm, d.Remark, + d.ConfirmedAt, d.ConfirmedBy, d.VoidedAt, d.CreatedAt, d.UpdatedAt, + d.Lines.OrderBy(x => x.LineNumber).Select(ToDto).ToList(), d.InvoiceNo); + + private static DocumentPackageDto ToDto(DocumentPackage p) => new( + p.Id, p.ShippingBatchId, p.CustomsDeclarationId, p.PackageNo, p.DocumentKind.ToString(), + p.Status.ToString(), p.Version, p.TemplateReference, p.TemplateVersion, p.OutputFormat, + p.GeneratedFileReference, p.GeneratedFileName, p.Currency, p.LineCount, p.TotalQuantity, + p.TotalAmount, p.TotalCartonCount, p.TotalGrossWeight, p.TotalNetWeight, p.TotalCbm, + p.GeneratedAt, p.GeneratedBy, p.ConfirmedAt, p.ConfirmedBy, p.ExportedAt, p.ExportedBy, + p.VoidedAt, p.Remark, p.CreatedAt, p.UpdatedAt, p.TemplateVersionId); +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentRenderSource.cs b/src/Leiren.Erp.Application/Customs/DocumentRenderSource.cs new file mode 100644 index 0000000..c73f9e4 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentRenderSource.cs @@ -0,0 +1,34 @@ +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Data a shipping-batch document is rendered from besides the batch itself: +/// the latest confirmed customs declaration (报关资料), the customer master +/// (address for the "TO" block) and the primary order date. +/// +public sealed record DocumentRenderSource(CustomsDeclaration? Declaration, Customer? Customer, DateOnly? OrderDate) +{ + public static readonly DocumentRenderSource Empty = new(null, null, null); + + /// Customs documents (报关发票/装箱单/外销合同/报关单) are read from the declaration. + public static bool IsCustomsKind(DocumentKind kind) => kind is DocumentKind.CustomsInvoice + or DocumentKind.CustomsPackingList or DocumentKind.CustomsSalesContract or DocumentKind.CustomsDeclarationData; + + public static async Task LoadAsync(ICustomsDbContext db, ShippingBatch batch, CancellationToken ct) + { + var declaration = await db.CustomsDeclarations.AsNoTracking() + .Include(x => x.Lines) + .Where(x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Confirmed) + .OrderByDescending(x => x.Version) + .FirstOrDefaultAsync(ct); + var customer = await db.Customers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == batch.CustomerId, ct); + var orderDate = await db.SalesOrders.AsNoTracking() + .Where(x => x.Id == batch.SalesOrderId) + .Select(x => (DateOnly?)x.OrderDate) + .FirstOrDefaultAsync(ct); + return new DocumentRenderSource(declaration, customer, orderDate); + } +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentTemplateCatalogService.cs b/src/Leiren.Erp.Application/Customs/DocumentTemplateCatalogService.cs new file mode 100644 index 0000000..9176e96 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentTemplateCatalogService.cs @@ -0,0 +1,168 @@ +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Purchasing; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Template editor backend: lists every imported template (current version +/// per template) with its mapping state, and renders previews against chosen +/// test data without storing anything. Shipping-batch kinds render through +/// their field mappings (unmapped placeholders stay visible); purchase-contract +/// templates render with the contract renderer's built-in placeholders. +/// +public sealed class DocumentTemplateCatalogService( + ICustomsDbContext customs, + IPurchasingDbContext purchasing, + FileService files, + DocumentTemplateMappingService mappings, + BillingDocumentExportService billingDocuments) +{ + public IReadOnlyList ListKinds() => DocumentTemplateKinds.All; + + public async Task> ListAsync(CancellationToken ct = default) + { + var current = await files.ListAsync( + DocumentTemplateService.TemplateOwnerType, null, null, null, currentOnly: true, 1, 200, ct); + var result = new List(current.Count); + // A template imported for one customer stores that customer as the file owner. + var ownerIds = current.Select(x => x.OwnerId).Distinct().ToList(); + var customers = await customs.Customers.AsNoTracking() + .Where(x => ownerIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.Name, ct); + foreach (var item in current) + { + var kind = DocumentTemplateKinds.Find(item.Category); + if (kind is null) continue; + var file = await files.GetAsync(item.Id, ct); + + IReadOnlyList placeholders; + IReadOnlyList unfilled; + var hasProfile = kind.UsesFieldMapping && await mappings.ProfileExistsAsync(item.Id, ct); + var locked = false; + if (hasProfile) + { + var profile = await mappings.GetProfileAsync(item.Id, ct); + placeholders = profile.Placeholders; + unfilled = profile.UnmappedPlaceholders; + locked = profile.IsLocked; + } + else + { + placeholders = TemplatePlaceholderScanner.Scan(await ReadAsync(item.Id, ct)) + .Placeholders.Select(x => x.Name).ToList(); + unfilled = kind.UsesFieldMapping + ? placeholders + : placeholders.Where(x => !kind.BuiltInFields.Contains(x, StringComparer.OrdinalIgnoreCase)).ToList(); + } + + result.Add(new DocumentTemplateListItemDto( + item.FileGroupId, item.Id, + string.IsNullOrWhiteSpace(file.Description) ? Path.GetFileNameWithoutExtension(file.OriginalFileName) : file.Description, + kind.Key, item.Version, item.OriginalFileName, item.UploadedBy, item.CreatedAt, + placeholders, unfilled, hasProfile, locked, + customers.ContainsKey(item.OwnerId) ? item.OwnerId : null, + customers.GetValueOrDefault(item.OwnerId))); + } + return result + .OrderBy(x => DocumentTemplateKinds.All.ToList().FindIndex(k => k.Key == x.DocumentKind)) + .ThenByDescending(x => x.UploadedAt) + .ToList(); + } + + public async Task<(byte[] Bytes, string FileName)> PreviewAsync( + Guid templateVersionId, PreviewDocumentTemplateRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + FileAttachmentDto template; + try + { + template = await files.GetAsync(templateVersionId, ct); + } + catch (FilesNotFoundException) + { + throw new CustomsNotFoundException("模板版本文件不存在。"); + } + var kind = DocumentTemplateKinds.Find(template.Category) + ?? throw new CustomsValidationException("TemplateVersionId", "该文件不是已导入的单证模板。"); + var bytes = await ReadAsync(templateVersionId, ct); + var stem = Path.GetFileNameWithoutExtension(template.OriginalFileName); + + if (kind.DataSource == DocumentTemplateKinds.PurchaseContract) + { + if (request.PurchaseContractId is not { } contractId) + throw new CustomsValidationException(nameof(request.PurchaseContractId), "请选择一份采购合同作为测试数据。"); + var contract = await purchasing.PurchaseContracts.AsNoTracking() + .Include(x => x.Tasks) + .SingleOrDefaultAsync(x => x.Id == contractId, ct) + ?? throw new CustomsNotFoundException("采购合同不存在。"); + var lines = contract.Tasks.Where(x => x.Status != PurchaseTaskStatus.Cancelled).OrderBy(x => x.CreatedAt).ToList(); + try + { + return (PurchaseContractTemplateRenderer.Render(bytes, contract, lines, DateTimeOffset.UtcNow), $"{stem}-预览.xlsx"); + } + catch (PurchasingValidationException ex) + { + throw new CustomsValidationException(ex.Errors); + } + } + + if (kind.DataSource == DocumentTemplateKinds.SupplierInvoiceNotice) + { + if (request.SupplierInvoiceNoticeId is not { } noticeId) + throw new CustomsValidationException(nameof(request.SupplierInvoiceNoticeId), "请选择一份开票通知作为测试数据。"); + try + { + return (await billingDocuments.PreviewAsync(bytes, noticeId, kind.DisplayName, ct), $"{stem}-预览.xlsx"); + } + catch (BillingValidationException ex) + { + throw new CustomsValidationException(ex.Errors); + } + catch (BillingNotFoundException ex) + { + throw new CustomsNotFoundException(ex.Message); + } + } + if (request.ShippingBatchId is not { } batchId) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "请选择一个出货批次作为测试数据。"); + var batch = await customs.ShippingBatches.AsNoTracking() + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == batchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "该出货批次没有出货明细,无法预览。"); + + var mapped = new Dictionary(StringComparer.Ordinal); + if (await mappings.ProfileExistsAsync(templateVersionId, ct)) + { + foreach (var m in (await mappings.GetProfileAsync(templateVersionId, ct)).Mappings) + { + mapped[DocumentTemplateFieldMapping.NormalizePlaceholderKey(m.Placeholder)] = new CiPlMappedField( + m.Placeholder, m.BusinessField, + DocumentTemplateFields.TryGet(m.BusinessField, out var def) ? def.Scope : TemplateFieldScope.Header, + m.NumberFormat); + } + } + + var source = await DocumentRenderSource.LoadAsync(customs, batch, ct); + var rendered = CiPlTemplateRenderer.Render( + bytes, batch, batch.Lines.OrderBy(x => x.CreatedAt).ThenBy(x => x.Id).ToList(), + Enum.Parse(kind.Key), source, mapped, DateTimeOffset.UtcNow, allowUnmapped: true); + return (rendered, $"{stem}-预览.xlsx"); + } + + private async Task ReadAsync(Guid fileId, CancellationToken ct) + { + await using var content = (await files.OpenDownloadAsync(fileId, ct)).Content; + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + return buffer.ToArray(); + } +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentTemplateFields.cs b/src/Leiren.Erp.Application/Customs/DocumentTemplateFields.cs new file mode 100644 index 0000000..95a2c8b --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentTemplateFields.cs @@ -0,0 +1,104 @@ +using Leiren.Erp.Domain.Enums; + +namespace Leiren.Erp.Application.Customs; + +/// One allowed business field a template placeholder may map to. +public sealed record TemplateFieldDefinition(string Key, string DisplayName, TemplateFieldScope Scope, string ValueType); + +/// +/// The closed catalog of business fields available to CI/PL and customs +/// document templates. Values come from the confirmed shipping-batch snapshot +/// and, for the customs fields, the confirmed customs declaration (报关资料) +/// of the batch — never from current product master data. Customs document +/// kinds take quantity, unit, price and HS code from the declaration. Keys are +/// unique; the line-level weight/CBM keys carry a Line prefix so they +/// cannot collide with the document totals. +/// +public static class DocumentTemplateFields +{ + public static readonly IReadOnlyList All = + [ + // Header — shipping batch / sales order / logistics snapshot + new("BatchNo", "出货批次号", TemplateFieldScope.Header, "String"), + new("SalesOrderNo", "销售订单号", TemplateFieldScope.Header, "String"), + new("CustomerName", "客户名称", TemplateFieldScope.Header, "String"), + new("CustomerPoNo", "客户PO号", TemplateFieldScope.Header, "String"), + new("Currency", "币种", TemplateFieldScope.Header, "String"), + new("ShipmentDate", "出货日期", TemplateFieldScope.Header, "Date"), + new("CutoffDate", "截关日期", TemplateFieldScope.Header, "Date"), + new("Etd", "ETD", TemplateFieldScope.Header, "Date"), + new("Eta", "ETA", TemplateFieldScope.Header, "Date"), + new("VesselName", "船名", TemplateFieldScope.Header, "String"), + new("VoyageNo", "航次", TemplateFieldScope.Header, "String"), + new("BillOfLadingNo", "提单号", TemplateFieldScope.Header, "String"), + new("LoadingPort", "装货港", TemplateFieldScope.Header, "String"), + new("DestinationPort", "目的港", TemplateFieldScope.Header, "String"), + new("DestinationCountry", "目的国", TemplateFieldScope.Header, "String"), + new("TransportMode", "运输方式", TemplateFieldScope.Header, "String"), + new("TradeTerm", "贸易术语", TemplateFieldScope.Header, "String"), + new("FreightForwarder", "货代", TemplateFieldScope.Header, "String"), + new("ContainerNumbers", "集装箱号", TemplateFieldScope.Header, "String"), + new("DeclarationNo", "报关单号", TemplateFieldScope.Header, "String"), + new("DocumentKind", "单证类型", TemplateFieldScope.Header, "String"), + new("GeneratedDate", "生成日期", TemplateFieldScope.Header, "Date"), + new("InvoiceNo", "发票编号", TemplateFieldScope.Header, "String"), + new("CustomerAddress", "客户地址", TemplateFieldScope.Header, "String"), + new("OrderDate", "订单日期", TemplateFieldScope.Header, "Date"), + new("ExportDate", "出口日期", TemplateFieldScope.Header, "Date"), + new("DeclarationDate", "申报日期", TemplateFieldScope.Header, "Date"), + new("TradeMode", "监管方式", TemplateFieldScope.Header, "String"), + new("ExemptionNature", "征免性质", TemplateFieldScope.Header, "String"), + new("CurrencyNameZh", "币制(中文)", TemplateFieldScope.Header, "String"), + + // Line — one value per shipment line (actual packing snapshot) + new("LineNumber", "行号", TemplateFieldScope.Line, "Integer"), + new("InternalSku", "内部货号", TemplateFieldScope.Line, "String"), + new("ProductNameZh", "中文品名", TemplateFieldScope.Line, "String"), + new("ProductNameEn", "英文品名", TemplateFieldScope.Line, "String"), + new("CustomerSku", "客户SKU", TemplateFieldScope.Line, "String"), + new("CustomerProductName", "客户品名", TemplateFieldScope.Line, "String"), + new("HsCode", "HS编码", TemplateFieldScope.Line, "String"), + new("Quantity", "数量", TemplateFieldScope.Line, "Decimal"), + new("Unit", "单位", TemplateFieldScope.Line, "String"), + new("UnitPrice", "单价", TemplateFieldScope.Line, "Decimal"), + new("Amount", "金额", TemplateFieldScope.Line, "Decimal"), + new("PackingRate", "装箱率", TemplateFieldScope.Line, "Integer"), + new("CartonCount", "箱数", TemplateFieldScope.Line, "Integer"), + new("CartonLength", "外箱长(cm)", TemplateFieldScope.Line, "Decimal"), + new("CartonWidth", "外箱宽(cm)", TemplateFieldScope.Line, "Decimal"), + new("CartonHeight", "外箱高(cm)", TemplateFieldScope.Line, "Decimal"), + new("CartonGrossWeight", "单箱毛重", TemplateFieldScope.Line, "Decimal"), + new("CartonNetWeight", "单箱净重", TemplateFieldScope.Line, "Decimal"), + new("LineTotalGrossWeight", "本行总毛重", TemplateFieldScope.Line, "Decimal"), + new("LineTotalNetWeight", "本行总净重", TemplateFieldScope.Line, "Decimal"), + new("LineTotalCbm", "本行总体积(CBM)", TemplateFieldScope.Line, "Decimal"), + new("Remark", "备注", TemplateFieldScope.Line, "String"), + new("CustomsNameZh", "报关中文品名", TemplateFieldScope.Line, "String"), + new("CustomsNameEn", "报关英文品名", TemplateFieldScope.Line, "String"), + new("DeclarationElements", "申报要素", TemplateFieldScope.Line, "String"), + new("OriginCountry", "原产国", TemplateFieldScope.Line, "String"), + new("DomesticSourcePlace", "境内货源地", TemplateFieldScope.Line, "String"), + new("ExemptionInfo", "征免", TemplateFieldScope.Line, "String"), + new("LineCurrencyZh", "币制(明细行)", TemplateFieldScope.Line, "String"), + + // Total — aggregated over the batch snapshot at generation time + new("LineCount", "明细行数", TemplateFieldScope.Total, "Integer"), + new("TotalQuantity", "总数量", TemplateFieldScope.Total, "Decimal"), + new("TotalAmount", "总金额", TemplateFieldScope.Total, "Decimal"), + new("TotalCartonCount", "总箱数", TemplateFieldScope.Total, "Integer"), + new("TotalGrossWeight", "总毛重", TemplateFieldScope.Total, "Decimal"), + new("TotalNetWeight", "总净重", TemplateFieldScope.Total, "Decimal"), + new("TotalCbm", "总体积(CBM)", TemplateFieldScope.Total, "Decimal"), + ]; + + private static readonly Dictionary ByKey = + All.ToDictionary(x => x.Key, StringComparer.OrdinalIgnoreCase); + + public static bool TryGet(string? key, out TemplateFieldDefinition definition) + { + definition = null!; + return !string.IsNullOrWhiteSpace(key) && ByKey.TryGetValue(key.Trim(), out definition!); + } + + public static IReadOnlyList Keys => All.Select(x => x.Key).ToList(); +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentTemplateMappingService.cs b/src/Leiren.Erp.Application/Customs/DocumentTemplateMappingService.cs new file mode 100644 index 0000000..c155098 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentTemplateMappingService.cs @@ -0,0 +1,432 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Persistence and validation for versioned CI/PL template field mappings. +/// A profile belongs to exactly one immutable template version +/// (, the +/// scanned template file version id). Every placeholder found in the template +/// must map to a field from before a +/// document may be generated; generation locks the profile forever. +/// +public sealed class DocumentTemplateMappingService(IDocumentTemplateMappingDbContext db) +{ + public IReadOnlyList ListFields() + => DocumentTemplateFields.All + .Select(x => new DocumentTemplateFieldDto(x.Key, x.DisplayName, x.Scope.ToString(), x.ValueType)) + .ToList(); + + // ---------- Profiles ---------- + + public async Task CreateProfileAsync( + Guid templateVersionId, CreateDocumentTemplateMappingProfileRequest request, CancellationToken ct = default) + { + if (!await db.FileAttachments.AsNoTracking().AnyAsync(x => x.Id == templateVersionId && !x.IsDeleted, ct)) + throw new CustomsNotFoundException("模板版本(扫描的模板文件)不存在。"); + if (await db.DocumentTemplateMappingProfiles.AsNoTracking().AnyAsync(x => x.TemplateVersionId == templateVersionId, ct)) + throw new CustomsConflictException("该模板版本已存在字段映射,请直接编辑现有映射或上传新模板版本。"); + + var errors = new ErrorBag(); + var placeholders = NormalizePlaceholders(request.Placeholders, errors); + var mappings = ValidateMappingInputs(request.Mappings, placeholders, errors); + errors.ThrowIfAny(); + + var profile = new DocumentTemplateMappingProfile + { + TemplateVersionId = templateVersionId, + TemplateId = request.TemplateId, + TemplateReference = TrimOrNull(request.TemplateReference) ?? templateVersionId.ToString("D"), + DocumentKind = TrimOrNull(request.DocumentKind), + Placeholders = placeholders + }; + foreach (var (placeholder, businessField, numberFormat) in mappings) + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + + db.DocumentTemplateMappingProfiles.Add(profile); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task GetProfileAsync(Guid templateVersionId, CancellationToken ct = default) + => ToDto(await LoadProfileAsync(templateVersionId, ct)); + + public Task ProfileExistsAsync(Guid templateVersionId, CancellationToken ct = default) + => db.DocumentTemplateMappingProfiles.AsNoTracking().AnyAsync(x => x.TemplateVersionId == templateVersionId, ct); + + public async Task> ListProfilesAsync(Guid? templateId, CancellationToken ct = default) + { + IQueryable query = db.DocumentTemplateMappingProfiles.AsNoTracking().Include(x => x.Mappings); + if (templateId is { } id) query = query.Where(x => x.TemplateId == id); + var items = await query.OrderByDescending(x => x.Id).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task UpdateProfileAsync( + Guid templateVersionId, UpdateDocumentTemplateMappingProfileRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + + var errors = new ErrorBag(); + var placeholders = request.Placeholders is null ? profile.Placeholders : NormalizePlaceholders(request.Placeholders, errors); + if (request.Placeholders is not null) + { + var keys = placeholders.Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey).ToHashSet(StringComparer.Ordinal); + var orphaned = profile.Mappings.Where(m => !keys.Contains(m.PlaceholderKey)).Select(m => m.Placeholder).ToList(); + if (orphaned.Count > 0) + errors.Add("Placeholders", $"以下映射的占位符不在新占位符列表中,请先删除这些映射:{string.Join("、", orphaned)}。"); + } + errors.ThrowIfAny(); + + profile.TemplateId = request.TemplateId; + profile.TemplateReference = TrimOrNull(request.TemplateReference) ?? profile.TemplateReference; + profile.DocumentKind = TrimOrNull(request.DocumentKind); + profile.Placeholders = placeholders; + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task DeleteProfileAsync(Guid templateVersionId, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + db.DocumentTemplateFieldMappings.RemoveRange(profile.Mappings); + db.DocumentTemplateMappingProfiles.Remove(profile); + await db.SaveChangesAsync(ct); + } + + // ---------- Mapping CRUD ---------- + + public async Task AddMappingAsync( + Guid templateVersionId, SaveDocumentTemplateFieldMappingRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + + var errors = new ErrorBag(); + var input = ValidateMappingInputs([request], profile.Placeholders, errors); + if (input.Count == 1 && profile.Mappings.Any(m => m.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(input[0].Placeholder))) + errors.Add(nameof(request.Placeholder), $"占位符 {input[0].Placeholder} 已有映射,不能重复映射。"); + errors.ThrowIfAny(); + + var (placeholder, businessField, numberFormat) = input[0]; + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task UpdateMappingAsync( + Guid templateVersionId, Guid mappingId, SaveDocumentTemplateFieldMappingRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + var mapping = profile.Mappings.SingleOrDefault(x => x.Id == mappingId) + ?? throw new CustomsNotFoundException("字段映射不存在。"); + + var errors = new ErrorBag(); + var input = ValidateMappingInputs([request], profile.Placeholders, errors); + if (input.Count == 1) + { + var key = DocumentTemplateFieldMapping.NormalizePlaceholderKey(input[0].Placeholder); + if (profile.Mappings.Any(m => m.Id != mappingId && m.PlaceholderKey == key)) + errors.Add(nameof(request.Placeholder), $"占位符 {input[0].Placeholder} 已有映射,不能重复映射。"); + } + errors.ThrowIfAny(); + + var (placeholder, businessField, numberFormat) = input[0]; + mapping.Placeholder = placeholder; + mapping.PlaceholderKey = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); + mapping.BusinessField = businessField; + mapping.NumberFormat = numberFormat; + mapping.Touch(); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task DeleteMappingAsync( + Guid templateVersionId, Guid mappingId, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + var mapping = profile.Mappings.SingleOrDefault(x => x.Id == mappingId) + ?? throw new CustomsNotFoundException("字段映射不存在。"); + db.DocumentTemplateFieldMappings.Remove(mapping); + profile.Mappings.Remove(mapping); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task ReplaceMappingsAsync( + Guid templateVersionId, ReplaceDocumentTemplateFieldMappingsRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + + var errors = new ErrorBag(); + var mappings = ValidateMappingInputs(request.Mappings, profile.Placeholders, errors); + errors.ThrowIfAny(); + + db.DocumentTemplateFieldMappings.RemoveRange(profile.Mappings); + profile.Mappings.Clear(); + foreach (var (placeholder, businessField, numberFormat) in mappings) + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task CopyMappingsAsync( + Guid templateVersionId, CopyDocumentTemplateMappingsRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + var source = await LoadProfileAsync(request.SourceTemplateVersionId, ct); + + var inputs = source.Mappings + .Select(m => new SaveDocumentTemplateFieldMappingRequest(m.Placeholder, m.BusinessField, m.NumberFormat)) + .ToList(); + var errors = new ErrorBag(); + var mappings = ValidateMappingInputs(inputs, profile.Placeholders, errors); + foreach (var duplicate in mappings.Where(m => profile.Mappings.Any(x => + x.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(m.Placeholder)))) + errors.Add(nameof(SaveDocumentTemplateFieldMappingRequest.Placeholder), $"占位符 {duplicate.Placeholder} 已有映射,不能重复映射。"); + errors.ThrowIfAny(); + + foreach (var (placeholder, businessField, numberFormat) in mappings) + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + // ---------- Generation validation / locking ---------- + + public async Task ValidateAsync( + Guid templateVersionId, IReadOnlyCollection? scannedPlaceholders = null, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + return BuildValidation(profile, scannedPlaceholders); + } + + /// + /// Throws listing every unmapped + /// placeholder (and any unknown placeholder/business field) when this + /// template version is not fully mapped; otherwise returns the profile. + /// Callers generating XLSX must call this before rendering. + /// + public async Task ValidateForGenerationAsync( + Guid templateVersionId, IReadOnlyCollection? scannedPlaceholders = null, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + var result = BuildValidation(profile, scannedPlaceholders); + ThrowIfInvalid(result); + return ToDto(profile); + } + + /// Parameterless-placeholder overload of using the stored scan snapshot. + public Task EnsureGenerationAllowedAsync(Guid templateVersionId, CancellationToken ct = default) + => ValidateForGenerationAsync(templateVersionId, scannedPlaceholders: null, ct); + + /// Locks the profile after a document package was generated from it; locked mappings are immutable. + public async Task LockAfterGenerationAsync( + Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + profile.LockAfterGeneration(documentPackageId); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + /// Alias for . + public Task MarkUsedAsync(Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default) + => LockAfterGenerationAsync(templateVersionId, documentPackageId, ct); + + // ---------- Helpers ---------- + + private async Task LoadProfileAsync(Guid templateVersionId, CancellationToken ct) + => await db.DocumentTemplateMappingProfiles + .Include(x => x.Mappings) + .SingleOrDefaultAsync(x => x.TemplateVersionId == templateVersionId, ct) + ?? throw new CustomsNotFoundException("该模板版本尚无字段映射,请先创建映射。"); + + private async Task EnsureMutableAsync(DocumentTemplateMappingProfile profile, CancellationToken ct) + { + if (!profile.IsLocked && + await db.DocumentPackages.AsNoTracking().AnyAsync(x => x.TemplateVersionId == profile.TemplateVersionId, ct)) + profile.IsLocked = true; + try { profile.EnsureMutable(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + } + + private static DocumentTemplateFieldMapping NewMapping( + DocumentTemplateMappingProfile profile, string placeholder, string businessField, string? numberFormat) => new() + { + MappingProfileId = profile.Id, + MappingProfile = profile, + TemplateVersionId = profile.TemplateVersionId, + Placeholder = placeholder, + PlaceholderKey = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder), + BusinessField = businessField, + NumberFormat = numberFormat + }; + + private static List NormalizePlaceholders(IReadOnlyList? raw, ErrorBag errors) + { + var result = new List(); + if (raw is null) return result; + var seen = new HashSet(StringComparer.Ordinal); + foreach (var item in raw) + { + var name = NormalizePlaceholder(item); + if (name is null) + { + errors.Add("Placeholders", $"占位符名称无效:\"{item}\"。"); + continue; + } + if (!seen.Add(DocumentTemplateFieldMapping.NormalizePlaceholderKey(name))) + errors.Add("Placeholders", $"占位符 {name} 在扫描结果中重复。"); + else + result.Add(name); + } + return result; + } + + private static List<(string Placeholder, string BusinessField, string? NumberFormat)> ValidateMappingInputs( + IReadOnlyList? inputs, + IReadOnlyList knownPlaceholders, + ErrorBag errors) + { + var result = new List<(string, string, string?)>(); + if (inputs is null) return result; + + var knownKeys = knownPlaceholders + .Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey) + .ToHashSet(StringComparer.Ordinal); + var seen = new HashSet(StringComparer.Ordinal); + + foreach (var input in inputs) + { + var placeholder = NormalizePlaceholder(input.Placeholder); + if (placeholder is null) + { + errors.Add(nameof(input.Placeholder), $"占位符名称无效:\"{input.Placeholder}\"(应为不含花括号的名称,如 CustomerName)。"); + continue; + } + var key = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); + if (!seen.Add(key)) + errors.Add(nameof(input.Placeholder), $"占位符 {placeholder} 重复映射。"); + if (knownKeys.Count > 0 && !knownKeys.Contains(key)) + errors.Add(nameof(input.Placeholder), $"占位符 {placeholder} 不在该模板版本的扫描结果中,不能映射。"); + + if (!DocumentTemplateFields.TryGet(input.BusinessField, out var field)) + { + errors.Add(nameof(input.BusinessField), + $"业务字段 \"{input.BusinessField}\" 不在允许字段目录中。允许字段:{string.Join("、", DocumentTemplateFields.Keys)}。"); + continue; + } + + var numberFormat = TrimOrNull(input.NumberFormat); + if (numberFormat is { Length: > 100 }) + { + errors.Add(nameof(input.NumberFormat), "数字/日期格式长度不能超过 100。"); + continue; + } + result.Add((placeholder, field.Key, numberFormat)); + } + return result; + } + + private static DocumentTemplateValidationResultDto BuildValidation( + DocumentTemplateMappingProfile profile, IReadOnlyCollection? scannedPlaceholders) + { + var errors = new ErrorBag(); + var placeholders = scannedPlaceholders is null + ? profile.Placeholders + : NormalizePlaceholders(scannedPlaceholders.ToList(), errors); + var placeholderKeys = placeholders + .Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey) + .ToHashSet(StringComparer.Ordinal); + + var unmapped = placeholders + .Where(p => !profile.Mappings.Any(m => m.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(p))) + .ToList(); + var unknownPlaceholders = profile.Mappings + .Where(m => placeholderKeys.Count > 0 && !placeholderKeys.Contains(m.PlaceholderKey)) + .Select(m => m.Placeholder).ToList(); + var unknownFields = profile.Mappings + .Where(m => !DocumentTemplateFields.TryGet(m.BusinessField, out _)) + .Select(m => m.BusinessField).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + + return new DocumentTemplateValidationResultDto( + profile.TemplateVersionId, + placeholders.Count > 0 && unmapped.Count == 0 && unknownPlaceholders.Count == 0 && unknownFields.Count == 0, + placeholders, unmapped, unknownPlaceholders, unknownFields, + profile.Mappings.Count(m => placeholderKeys.Contains(m.PlaceholderKey))); + } + + private static void ThrowIfInvalid(DocumentTemplateValidationResultDto result) + { + if (result.IsValid) return; + var errors = new Dictionary(); + if (result.Placeholders.Count == 0) + errors["Placeholders"] = ["该模板版本没有登记任何扫描占位符,无法确认全部占位符已映射,禁止生成。"]; + if (result.UnmappedPlaceholders.Count > 0) + errors["UnmappedPlaceholders"] = result.UnmappedPlaceholders.Select(p => $"{{{{{p}}}}}").ToArray(); + if (result.UnknownPlaceholders.Count > 0) + errors["UnknownPlaceholders"] = result.UnknownPlaceholders.Select(p => $"{{{{{p}}}}}").ToArray(); + if (result.UnknownBusinessFields.Count > 0) + errors["BusinessField"] = result.UnknownBusinessFields + .Select(f => $"业务字段 \"{f}\" 不在允许字段目录中。允许字段:{string.Join("、", DocumentTemplateFields.Keys)}。").ToArray(); + throw new CustomsValidationException(errors); + } + + private static string? NormalizePlaceholder(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) return null; + var name = raw.Trim(); + if (name.StartsWith("{{", StringComparison.Ordinal) && name.EndsWith("}}", StringComparison.Ordinal) && name.Length > 4) + name = name[2..^2].Trim(); + if (name.Length is 0 or > 200 || name.Contains('{') || name.Contains('}') || name.Contains('\n') || name.Contains('\r')) + return null; + return name; + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + private static DocumentTemplateFieldMappingDto ToDto(DocumentTemplateFieldMapping m) => new( + m.Id, m.MappingProfileId, m.TemplateVersionId, m.Placeholder, m.BusinessField, + DocumentTemplateFields.TryGet(m.BusinessField, out var field) ? field.Scope.ToString() : "Unknown", + m.NumberFormat, m.CreatedAt, m.UpdatedAt); + + private static DocumentTemplateMappingProfileDto ToDto(DocumentTemplateMappingProfile p) + { + var mappedKeys = p.Mappings.Select(x => x.PlaceholderKey).ToHashSet(StringComparer.Ordinal); + return new DocumentTemplateMappingProfileDto( + p.Id, p.TemplateVersionId, p.TemplateId, p.TemplateReference, p.DocumentKind, + p.Placeholders, p.IsLocked, p.LockedAt, p.LockedByDocumentPackageId, p.CreatedAt, p.UpdatedAt, + p.Mappings.OrderBy(x => x.Placeholder, StringComparer.OrdinalIgnoreCase).Select(ToDto).ToList(), + p.Placeholders.Where(x => !mappedKeys.Contains(DocumentTemplateFieldMapping.NormalizePlaceholderKey(x))).ToList()); + } + + private sealed class ErrorBag + { + private readonly Dictionary> _errors = new(StringComparer.Ordinal); + public void Add(string field, string message) + { + if (!_errors.TryGetValue(field, out var list)) _errors[field] = list = []; + list.Add(message); + } + public void ThrowIfAny() + { + if (_errors.Count > 0) + throw new CustomsValidationException(_errors.ToDictionary(x => x.Key, x => x.Value.ToArray())); + } + } +} diff --git a/src/Leiren.Erp.Application/Customs/ICustomsDbContext.cs b/src/Leiren.Erp.Application/Customs/ICustomsDbContext.cs new file mode 100644 index 0000000..334b6ed --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/ICustomsDbContext.cs @@ -0,0 +1,23 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// EF Core boundary for the Customs/Documents module; implemented by Infrastructure. +/// Shipping, Sales, and Catalog sets are read here only to snapshot a confirmed +/// shipping batch and its product customs defaults at creation time. +/// +public interface ICustomsDbContext +{ + DbSet ShippingBatches { get; } + DbSet SalesOrderLines { get; } + DbSet SalesOrders { get; } + DbSet Customers { get; } + DbSet Products { get; } + DbSet CustomsDeclarations { get; } + DbSet CustomsDeclarationLines { get; } + DbSet DocumentPackages { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Customs/IDocumentTemplateMappingDbContext.cs b/src/Leiren.Erp.Application/Customs/IDocumentTemplateMappingDbContext.cs new file mode 100644 index 0000000..1c2feb3 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/IDocumentTemplateMappingDbContext.cs @@ -0,0 +1,19 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// EF Core boundary for document-template field mappings; implemented by +/// Infrastructure. FileAttachments/DocumentPackages are read to verify the +/// template version exists and to lock mappings once a package is generated. +/// +public interface IDocumentTemplateMappingDbContext +{ + DbSet DocumentTemplateMappingProfiles { get; } + DbSet DocumentTemplateFieldMappings { get; } + DbSet DocumentPackages { get; } + DbSet FileAttachments { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Dashboard/DashboardService.cs b/src/Leiren.Erp.Application/Dashboard/DashboardService.cs new file mode 100644 index 0000000..b64b3c4 --- /dev/null +++ b/src/Leiren.Erp.Application/Dashboard/DashboardService.cs @@ -0,0 +1,46 @@ +using Leiren.Erp.Contracts; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Dashboard; + +public sealed class DashboardService(IDashboardDbContext db) +{ + public async Task GetSummaryAsync(CancellationToken ct = default) + { + var salesOrders = await SummarizeAsync(db.SalesOrders.AsNoTracking().Select(x => x.Status), ct); + var purchaseTasks = await SummarizeAsync(db.PurchaseTasks.AsNoTracking().Select(x => x.Status), ct); + var purchaseContracts = await SummarizeAsync(db.PurchaseContracts.AsNoTracking().Select(x => x.Status), ct); + var shippingBatches = await SummarizeAsync(db.ShippingBatches.AsNoTracking().Select(x => x.Status), ct); + var customsDeclarations = await SummarizeAsync(db.CustomsDeclarations.AsNoTracking().Select(x => x.Status), ct); + var billingNotices = await SummarizeAsync(db.SupplierInvoiceNotices.AsNoTracking().Select(x => x.Status), ct); + var products = await SummarizeAsync(db.Products.AsNoTracking().Select(x => x.Status), ct); + + return new DashboardSummaryDto( + DateTimeOffset.UtcNow, + salesOrders, + purchaseTasks, + purchaseContracts, + shippingBatches, + customsDeclarations, + billingNotices, + products); + } + + // Every enum value is reported (zero when absent) so clients render a stable summary. + private static async Task SummarizeAsync( + IQueryable statuses, CancellationToken ct) + where TStatus : struct, Enum + { + var rows = await statuses + .GroupBy(status => status) + .Select(group => new { Status = group.Key, Count = group.Count() }) + .ToListAsync(ct); + + var counts = rows.ToDictionary(row => row.Status, row => row.Count); + var byStatus = Enum.GetValues() + .Select(status => new DashboardStatusCountDto(status.ToString(), counts.GetValueOrDefault(status))) + .ToList(); + + return new DashboardSectionDto(byStatus.Sum(item => item.Count), byStatus); + } +} diff --git a/src/Leiren.Erp.Application/Dashboard/IDashboardDbContext.cs b/src/Leiren.Erp.Application/Dashboard/IDashboardDbContext.cs new file mode 100644 index 0000000..63ea06c --- /dev/null +++ b/src/Leiren.Erp.Application/Dashboard/IDashboardDbContext.cs @@ -0,0 +1,16 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Dashboard; + +/// EF Core boundary for read-only dashboard aggregates; implemented by Infrastructure. +public interface IDashboardDbContext +{ + DbSet SalesOrders { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet ShippingBatches { get; } + DbSet CustomsDeclarations { get; } + DbSet SupplierInvoiceNotices { get; } + DbSet Products { get; } +} diff --git a/src/Leiren.Erp.Application/Documents/DocumentTemplateKinds.cs b/src/Leiren.Erp.Application/Documents/DocumentTemplateKinds.cs new file mode 100644 index 0000000..626b400 --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/DocumentTemplateKinds.cs @@ -0,0 +1,40 @@ +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Application.Purchasing; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Application.Documents; + +/// +/// The closed set of template types the template editor imports. The key is +/// stored as the template file's category. Shipping-batch kinds are the +/// DocumentKind values and are filled through field mappings; the +/// purchase contract uses the renderer's built-in placeholder names. +/// +public static class DocumentTemplateKinds +{ + public const string ShippingBatch = "ShippingBatch"; + /// Kind key and data source of purchase-contract templates. + public const string PurchaseContract = "PurchaseContract"; + /// Data source of the supplier billing documents (开票通知 / 开票购销合同). + public const string SupplierInvoiceNotice = "SupplierInvoiceNotice"; + public const string SupplierInvoiceNoticeKind = "SupplierInvoiceNotice"; + public const string SupplierBillingContractKind = "SupplierBillingContract"; + + public static readonly IReadOnlyList All = + [ + new("CustomsInvoice", "报关发票", ShippingBatch, true, []), + new("CustomsPackingList", "报关装箱单", ShippingBatch, true, []), + new("CustomsSalesContract", "报关外销合同", ShippingBatch, true, []), + new("CustomsDeclarationData", "报关单数据", ShippingBatch, true, []), + new("CommercialInvoice", "客户 CI", ShippingBatch, true, []), + new("PackingList", "客户 PL", ShippingBatch, true, []), + new(PurchaseContract, "采购合同", PurchaseContract, false, PurchaseContractTemplateRenderer.FieldNames), + new(SupplierInvoiceNoticeKind, "开票通知", SupplierInvoiceNotice, false, BillingDocumentRenderer.FieldNames), + new(SupplierBillingContractKind, "开票购销合同", SupplierInvoiceNotice, false, BillingDocumentRenderer.FieldNames), + ]; + + public static DocumentTemplateKindDto? Find(string? key) + => string.IsNullOrWhiteSpace(key) + ? null + : All.FirstOrDefault(x => string.Equals(x.Key, key.Trim(), StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/Leiren.Erp.Application/Documents/DocumentTemplateService.cs b/src/Leiren.Erp.Application/Documents/DocumentTemplateService.cs new file mode 100644 index 0000000..328a95e --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/DocumentTemplateService.cs @@ -0,0 +1,172 @@ +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Application.Documents; + +/// Optional metadata supplied alongside an uploaded CI/PL template. +public sealed record DocumentTemplateUploadOptions( + string? Name, + string? DocumentKind, + Guid? CustomerId, + string? UploadedBy, + Guid? UploadedByUserId = null); + +/// +/// Stores customer CI/PL .xlsx templates through +/// (content on the server filesystem, metadata in the database) and scans +/// them for placeholders. Scanning happens before storage, so an unreadable +/// workbook or a template without any placeholder never leaves an orphan +/// file behind. No template entity is kept here: the stored file group is +/// the logical template and each file version is one immutable template +/// version, referenced by its file id. +/// +public sealed class DocumentTemplateService(FileService files, FileStorageOptions storageOptions) +{ + public const string TemplateOwnerType = "DocumentTemplate"; + + public async Task UploadAsync( + Stream content, string? originalFileName, string? contentType, + DocumentTemplateUploadOptions options, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(options); + + var bytes = await ReadTemplateBytesAsync(content, originalFileName, ct); + var scan = ScanBytes(bytes); + + await using var stored = new MemoryStream(bytes, writable: false); + var file = await files.UploadAsync(new UploadFileCommand( + OwnerType: TemplateOwnerType, + OwnerId: options.CustomerId ?? Guid.NewGuid(), + Category: RequireKind(options.DocumentKind), + Description: NormalizeOptional(options.Name, 1000, nameof(options.Name)), + OriginalFileName: originalFileName, + ContentType: contentType, + Content: stored, + UploadedByUserId: options.UploadedByUserId, + UploadedBy: options.UploadedBy), ct); + + return ToResult(file, options.Name, options.DocumentKind, options.CustomerId, scan); + } + + /// Stores a new immutable version of the template the given file version belongs to. + public async Task UploadNewVersionAsync( + Guid fileId, Stream content, string? originalFileName, string? contentType, + DocumentTemplateUploadOptions options, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(options); + + var existing = await files.GetAsync(fileId, ct); + EnsureTemplateFile(existing); + + var bytes = await ReadTemplateBytesAsync(content, originalFileName, ct); + var scan = ScanBytes(bytes); + + await using var stored = new MemoryStream(bytes, writable: false); + var file = await files.UploadNewVersionAsync( + fileId, stored, originalFileName, contentType, + options.DocumentKind is null ? existing.Category : RequireKind(options.DocumentKind), + NormalizeOptional(options.Name, 1000, nameof(options.Name)) ?? existing.Description, + options.UploadedByUserId, options.UploadedBy, ct); + + return ToResult(file, options.Name ?? existing.Description, + options.DocumentKind ?? existing.Category, + options.CustomerId, scan); + } + + /// Re-scans an already stored template file version. + public async Task ScanStoredAsync(Guid fileId, CancellationToken ct = default) + { + var file = await files.GetAsync(fileId, ct); + EnsureTemplateFile(file); + + var download = await files.OpenDownloadAsync(fileId, ct); + await using var content = download.Content; + var bytes = await ReadTemplateBytesAsync(content, file.OriginalFileName, ct); + var scan = ScanBytes(bytes); + + return ToResult(file, file.Description, file.Category, null, scan); + } + + private static TemplateScanResult ScanBytes(byte[] bytes) + { + var scan = TemplatePlaceholderScanner.Scan(bytes); + if (scan.Placeholders.Count == 0) + { + var detail = scan.Warnings.Count > 0 ? string.Join(" ", scan.Warnings) : null; + throw new DocumentTemplateValidationException( + "file", "模板中未找到任何 {{...}} 占位符,无法导入。" + (detail is null ? string.Empty : $" {detail}")); + } + return scan; + } + + private async Task ReadTemplateBytesAsync(Stream content, string? originalFileName, CancellationToken ct) + { + var extension = Path.GetExtension(FileService.SanitizeFileName(originalFileName)).ToLowerInvariant(); + if (extension != ".xlsx") + { + throw new DocumentTemplateValidationException( + "file", "模板必须是 .xlsx 文件。"); + } + + var maxBytes = storageOptions.MaxFileSizeBytes > 0 ? storageOptions.MaxFileSizeBytes : 50L * 1024 * 1024; + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await content.ReadAsync(chunk.AsMemory(), ct)) > 0) + { + if (buffer.Length + read > maxBytes) + { + throw new DocumentTemplateValidationException( + "file", $"模板文件大小超过上限 {maxBytes} 字节。"); + } + buffer.Write(chunk, 0, read); + } + if (buffer.Length == 0) + { + throw new DocumentTemplateValidationException("file", "模板文件内容为空。"); + } + return buffer.ToArray(); + } + + private static void EnsureTemplateFile(FileAttachmentDto file) + { + if (!string.Equals(file.Extension, ".xlsx", StringComparison.OrdinalIgnoreCase)) + { + throw new DocumentTemplateValidationException( + "file", "只能扫描 .xlsx 模板文件。"); + } + } + + private static DocumentTemplateUploadResultDto ToResult( + FileAttachmentDto file, string? name, string? documentKind, Guid? customerId, TemplateScanResult scan) => new( + TemplateId: file.FileGroupId, + TemplateVersionId: file.Id, + TemplateReference: file.Id.ToString("D"), + SourceFileId: file.Id, + Name: string.IsNullOrWhiteSpace(name) ? Path.GetFileNameWithoutExtension(file.OriginalFileName) : name.Trim(), + DocumentKind: string.IsNullOrWhiteSpace(documentKind) ? file.Category : documentKind.Trim(), + CustomerId: customerId, + File: file, + Worksheets: scan.Worksheets, + Placeholders: scan.Placeholders, + LineRows: scan.LineRows, + Warnings: scan.Warnings); + + private static string RequireKind(string? documentKind) + => DocumentTemplateKinds.Find(documentKind)?.Key + ?? throw new DocumentTemplateValidationException(nameof(documentKind), + $"模板类型无效,可选:{string.Join("、", DocumentTemplateKinds.All.Select(x => $"{x.DisplayName}({x.Key})"))}。"); + + private static string? NormalizeOptional(string? value, int maxLength, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + var trimmed = value.Trim(); + if (trimmed.Length > maxLength) + throw new DocumentTemplateValidationException(field, $"长度不能超过 {maxLength} 个字符。"); + if (trimmed.Any(char.IsControl)) + throw new DocumentTemplateValidationException(field, "不能包含控制字符。"); + return trimmed; + } +} diff --git a/src/Leiren.Erp.Application/Documents/TemplatePlaceholderScanner.cs b/src/Leiren.Erp.Application/Documents/TemplatePlaceholderScanner.cs new file mode 100644 index 0000000..0287948 --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/TemplatePlaceholderScanner.cs @@ -0,0 +1,249 @@ +using System.Text.RegularExpressions; +using ClosedXML.Excel; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Application.Documents; + +public sealed class DocumentTemplateValidationException(IReadOnlyDictionary errors) + : Exception("模板文件校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public DocumentTemplateValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} + +public sealed record TemplateScanResult( + IReadOnlyList Worksheets, + IReadOnlyList Placeholders, + IReadOnlyList LineRows, + IReadOnlyList Warnings); + +/// +/// Scans every worksheet of a real .xlsx template for {{...}} tokens. +/// Cells are discovered from each worksheet's used range, never from fixed +/// coordinates. A token is a line-row token when its name carries a line +/// prefix (Line., Lines., Item., Detail., +/// Row., also with :/_ separators); a worksheet row is a +/// detail row when it holds a line-row token or at least two distinct +/// placeholders, which is how a copied detail row appears in CI/PL templates. +/// +public static partial class TemplatePlaceholderScanner +{ + private const string LineScope = "LineRow"; + private const string DocumentScope = "Document"; + private const string MixedScope = "Mixed"; + + private static readonly string[] LinePrefixes = + ["Line", "Lines", "Item", "Items", "Detail", "Details", "Row"]; + + [GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)] + private static partial Regex TokenRegex(); + + private sealed record Occurrence( + string Name, + string Worksheet, + int WorksheetIndex, + string CellAddress, + int Row, + int Column, + string CellText, + bool IsLineRowToken); + + public static TemplateScanResult Scan(byte[] bytes) + { + ArgumentNullException.ThrowIfNull(bytes); + return Scan(new MemoryStream(bytes, writable: false)); + } + + public static TemplateScanResult Scan(Stream content) + { + ArgumentNullException.ThrowIfNull(content); + + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(content); + } + catch (Exception ex) + { + throw new DocumentTemplateValidationException( + "file", $"Excel 文件无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + var worksheets = workbook.Worksheets.Select(x => x.Name).ToList(); + if (worksheets.Count == 0) + { + throw new DocumentTemplateValidationException( + "file", "工作簿中没有任何工作表。"); + } + + var occurrences = new List(); + var warnings = new List(); + + var worksheetIndex = 0; + foreach (var sheet in workbook.Worksheets) + { + worksheetIndex++; + var range = sheet.RangeUsed(); + if (range is null) continue; + + foreach (var cell in range.CellsUsed()) + { + foreach (var text in CandidateTexts(cell)) + { + ScanCellText(text, sheet.Name, worksheetIndex, cell, occurrences, warnings); + } + } + } + + // A row is a detail row when it carries a line-row token or holds + // at least two distinct placeholders (a copied detail row). + var lineRowKeys = occurrences + .GroupBy(x => (x.Worksheet, x.Row)) + .Where(g => g.Any(x => x.IsLineRowToken) + || g.Select(x => x.Name).Distinct(StringComparer.OrdinalIgnoreCase).Count() >= 2) + .Select(g => g.Key) + .ToHashSet(); + + var locationsByName = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var firstNameByKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var occurrence in occurrences) + { + var isOnLineRow = lineRowKeys.Contains((occurrence.Worksheet, occurrence.Row)); + var location = new TemplatePlaceholderLocationDto( + occurrence.Worksheet, + occurrence.CellAddress, + occurrence.Row, + occurrence.Column, + occurrence.CellText, + isOnLineRow ? LineScope : DocumentScope, + occurrence.IsLineRowToken, + isOnLineRow); + if (!locationsByName.TryGetValue(occurrence.Name, out var list)) + { + list = []; + locationsByName[occurrence.Name] = list; + firstNameByKey[occurrence.Name] = occurrence.Name; + } + list.Add(location); + } + + var placeholders = locationsByName + .Select(pair => + { + var name = firstNameByKey[pair.Key]; + var locations = pair.Value; + var scope = locations.All(x => x.IsOnLineRow) ? LineScope + : locations.All(x => !x.IsOnLineRow) ? DocumentScope + : MixedScope; + return new TemplatePlaceholderDto( + name, + "{{" + name + "}}", + scope, + locations.Count, + locations.Any(x => x.IsLineRowToken), + locations.Any(x => x.IsOnLineRow), + locations); + }) + .OrderBy(x => x.Locations[0].Worksheet, StringComparer.Ordinal) + .ThenBy(x => x.Locations[0].Row) + .ThenBy(x => x.Locations[0].Column) + .ToList(); + + var lineRows = occurrences + .Where(x => lineRowKeys.Contains((x.Worksheet, x.Row))) + .GroupBy(x => (x.Worksheet, x.WorksheetIndex, x.Row)) + .OrderBy(g => g.Key.WorksheetIndex) + .ThenBy(g => g.Key.Row) + .Select(g => new TemplateLineRowDto( + g.Key.Worksheet, + g.Key.Row, + g.Select(x => x.Name).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), + g.Select(x => x.CellAddress).Distinct(StringComparer.Ordinal).ToList())) + .ToList(); + + return new TemplateScanResult(worksheets, placeholders, lineRows, warnings); + } + } + + /// Display text of a cell, plus its formula text when it has one. + private static IEnumerable CandidateTexts(IXLCell cell) + { + var seen = new HashSet(StringComparer.Ordinal); + var formatted = cell.GetFormattedString(); + if (!string.IsNullOrEmpty(formatted) && seen.Add(formatted)) + yield return formatted; + + if (cell.HasFormula) + { + var formula = cell.FormulaA1; + if (!string.IsNullOrEmpty(formula) && seen.Add(formula)) + yield return formula; + } + } + + private static void ScanCellText( + string text, string worksheet, int worksheetIndex, IXLCell cell, + List occurrences, List warnings) + { + var address = cell.Address.ToString() ?? string.Empty; + var foundInText = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (Match match in TokenRegex().Matches(text)) + { + var name = match.Groups[1].Value.Trim(); + if (name.Length == 0) + { + warnings.Add($"工作表「{worksheet}」单元格 {address} 包含空占位符 {{{{}}}},已忽略。"); + continue; + } + // The same token appearing in both the display text and the + // formula of one cell is a single occurrence. + if (!foundInText.Add(name)) continue; + if (occurrences.Any(x => x.Worksheet == worksheet && x.CellAddress == address + && string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase))) + continue; + occurrences.Add(new Occurrence( + name, worksheet, worksheetIndex, address, + cell.Address.RowNumber, cell.Address.ColumnNumber, + text, IsLineRowToken(name))); + } + + var unclosed = CountOccurrences(text, "{{") - TokenRegex().Matches(text).Count; + if (unclosed > 0) + { + warnings.Add($"工作表「{worksheet}」单元格 {address} 包含 {unclosed} 个未闭合的 {{{{,未计入占位符。"); + } + } + + internal static bool IsLineRowToken(string name) + { + foreach (var prefix in LinePrefixes) + { + if (name.Length > prefix.Length + && name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + && name[prefix.Length] is '.' or ':' or '_') + { + return true; + } + } + return false; + } + + private static int CountOccurrences(string text, string token) + { + var count = 0; + var index = 0; + while ((index = text.IndexOf(token, index, StringComparison.Ordinal)) >= 0) + { + count++; + index += token.Length; + } + return count; + } +} diff --git a/src/Leiren.Erp.Application/Documents/TokenWorkbookRenderer.cs b/src/Leiren.Erp.Application/Documents/TokenWorkbookRenderer.cs new file mode 100644 index 0000000..b199bcf --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/TokenWorkbookRenderer.cs @@ -0,0 +1,214 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using ClosedXML.Excel; + +namespace Leiren.Erp.Application.Documents; + +/// +/// Placeholder names a built-in (mapping-free) template may use. Line fields +/// mark the row block copied once per line; numeric and date fields become +/// typed Excel values when a cell holds only that placeholder. +/// +public sealed record TokenTemplateFields( + IReadOnlySet LineFields, IReadOnlySet NumericFields, IReadOnlySet DateFields); + +/// +/// Renders the first worksheet of an XLSX template whose cells contain +/// {{Field}} placeholders with fixed (built-in) names. Header and total +/// placeholders are replaced in place; the row block carrying line +/// placeholders is copied once per line, including merged cells and row +/// heights, so a template authored with one sample line grows to any number +/// of lines. Formula cells are left untouched. Errors are reported through +/// so each module keeps its own exception type. +/// +public static partial class TokenWorkbookRenderer +{ + [GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)] + private static partial Regex TokenRegex(); + + public static byte[] Render( + byte[] templateBytes, + IReadOnlyDictionary headerValues, + IReadOnlyList> lineValues, + TokenTemplateFields fields, + string templateLabel, + Func error) + { + ArgumentNullException.ThrowIfNull(templateBytes); + if (lineValues.Count == 0) throw error($"{templateLabel}没有可导出的明细。"); + + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(new MemoryStream(templateBytes, writable: false)); + } + catch (Exception ex) + { + throw error($"{templateLabel}模板无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + var sheet = workbook.Worksheets.FirstOrDefault() ?? throw error($"{templateLabel}模板没有工作表。"); + if (sheet.RangeUsed() is null) throw error($"{templateLabel}模板没有内容。"); + + var known = new HashSet(headerValues.Keys, StringComparer.OrdinalIgnoreCase); + known.UnionWith(lineValues[0].Keys); + var unknown = ScanTokenNames(sheet).Where(name => !known.Contains(name)).Distinct().ToList(); + if (unknown.Count > 0) + throw error($"模板包含未知占位符:{string.Join("、", unknown.Select(x => "{{" + x + "}}"))}"); + + var lineRows = FindLineRows(sheet, fields.LineFields); + if (lineRows.Count == 0) throw error($"{templateLabel}模板缺少明细行占位符。"); + + var blockStart = lineRows.Min; + var blockHeight = lineRows.Max - blockStart + 1; + CopyLineBlock(sheet, blockStart, lineRows.Max, blockHeight, lineValues.Count); + + var rowLineIndex = new Dictionary(); + for (var i = 0; i < lineValues.Count; i++) + for (var r = 0; r < blockHeight; r++) + rowLineIndex[blockStart + i * blockHeight + r] = i; + + // Line rows see their line's values plus every header/total value + // (e.g. a document number repeated on each line). + var mergedLines = lineValues.Select(line => + { + var merged = new Dictionary(headerValues, StringComparer.OrdinalIgnoreCase); + foreach (var (key, value) in line) merged[key] = value; + return merged; + }).ToList(); + foreach (var cell in sheet.RangeUsed()!.Cells()) + { + if (cell.HasFormula) continue; + IReadOnlyDictionary values = rowLineIndex.TryGetValue(cell.Address.RowNumber, out var index) + ? mergedLines[index] + : headerValues; + ApplyCell(cell, values, fields); + } + + using var output = new MemoryStream(); + workbook.SaveAs(output); + return output.ToArray(); + } + } + + private static void CopyLineBlock(IXLWorksheet sheet, int blockStart, int blockEnd, int blockHeight, int lineCount) + { + if (lineCount <= 1) return; + + var used = sheet.RangeUsed()!; + var firstColumn = used.FirstColumn().ColumnNumber(); + var lastColumn = used.LastColumn().ColumnNumber(); + + var templateHeights = Enumerable.Range(blockStart, blockHeight).Select(row => sheet.Row(row).Height).ToList(); + var mergedInsideBlock = sheet.MergedRanges + .Select(range => ( + FirstRow: range.FirstRow().RowNumber(), + FirstColumn: range.FirstColumn().ColumnNumber(), + LastRow: range.LastRow().RowNumber(), + LastColumn: range.LastColumn().ColumnNumber())) + .Where(range => range.FirstRow >= blockStart && range.LastRow <= blockEnd) + .ToList(); + + sheet.Row(blockEnd + 1).InsertRowsAbove((lineCount - 1) * blockHeight); + + var source = sheet.Range(blockStart, firstColumn, blockEnd, lastColumn); + for (var copy = 1; copy < lineCount; copy++) + { + var targetStart = blockStart + copy * blockHeight; + source.CopyTo(sheet.Cell(targetStart, firstColumn)); + for (var r = 0; r < blockHeight; r++) + { + var height = templateHeights[r]; + if (height > 0) sheet.Row(targetStart + r).Height = height; + } + + var offset = copy * blockHeight; + foreach (var merged in mergedInsideBlock) + { + try + { + sheet.Range(merged.FirstRow + offset, merged.FirstColumn, + merged.LastRow + offset, merged.LastColumn).Merge(); + } + catch (InvalidOperationException) + { + // The copy already produced the merged range. + } + } + } + } + + private static void ApplyCell(IXLCell cell, IReadOnlyDictionary values, TokenTemplateFields fields) + { + var text = cell.Value.ToString(); + if (string.IsNullOrWhiteSpace(text)) return; + + var matches = TokenRegex().Matches(text); + if (matches.Count == 0) return; + + if (matches.Count == 1 && text.Trim().Equals(matches[0].Value, StringComparison.Ordinal)) + { + var name = matches[0].Groups[1].Value.Trim(); + var raw = values.TryGetValue(name, out var value) ? value : null; + + if (raw is null) + { + cell.Value = string.Empty; + return; + } + + if (fields.NumericFields.Contains(name) && + decimal.TryParse(raw, NumberStyles.Number, CultureInfo.InvariantCulture, out var number)) + { + cell.Value = number; + return; + } + + if (fields.DateFields.Contains(name) && + DateTime.TryParseExact(raw, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + { + cell.Value = date; + cell.Style.NumberFormat.Format = "yyyy-mm-dd"; + return; + } + + cell.Value = raw; + return; + } + + cell.Value = TokenRegex().Replace(text, match => + { + var name = match.Groups[1].Value.Trim(); + return values.TryGetValue(name, out var value) ? value ?? string.Empty : match.Value; + }); + } + + private static SortedSet FindLineRows(IXLWorksheet sheet, IReadOnlySet lineFields) + { + var rows = new SortedSet(); + foreach (var cell in sheet.RangeUsed()!.Cells()) + { + if (cell.HasFormula) continue; + var text = cell.Value.ToString(); + if (!text.Contains("{{", StringComparison.Ordinal)) continue; + foreach (Match match in TokenRegex().Matches(text)) + if (lineFields.Contains(match.Groups[1].Value.Trim())) + rows.Add(cell.Address.RowNumber); + } + return rows; + } + + private static IEnumerable ScanTokenNames(IXLWorksheet sheet) + { + foreach (var cell in sheet.RangeUsed()!.Cells()) + { + if (cell.HasFormula) continue; + var text = cell.Value.ToString(); + if (!text.Contains("{{", StringComparison.Ordinal)) continue; + foreach (Match match in TokenRegex().Matches(text)) + yield return match.Groups[1].Value.Trim(); + } + } +} diff --git a/src/Leiren.Erp.Application/Files/FileService.cs b/src/Leiren.Erp.Application/Files/FileService.cs new file mode 100644 index 0000000..192a194 --- /dev/null +++ b/src/Leiren.Erp.Application/Files/FileService.cs @@ -0,0 +1,356 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Files; + +public sealed class FileService(IFilesDbContext db, IFileStorage storage, FileStorageOptions options) +{ + public async Task UploadAsync(UploadFileCommand command, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(command); + if (command.Content is null) + throw new FilesValidationException("file", "文件内容为空。"); + + var ownerType = NormalizeOwnerType(command.OwnerType); + if (command.OwnerId == Guid.Empty) + throw new FilesValidationException(nameof(command.OwnerId), "附件所属业务对象不能为空。"); + + var originalFileName = SanitizeFileName(command.OriginalFileName); + var extension = ValidateExtension(originalFileName); + var now = DateTimeOffset.UtcNow; + + var file = new FileAttachment + { + FileGroupId = Guid.NewGuid(), + OwnerType = ownerType, + OwnerId = command.OwnerId, + Category = NormalizeOptional(command.Category, 100, nameof(command.Category)), + Description = NormalizeOptional(command.Description, 1000, nameof(command.Description)), + OriginalFileName = originalFileName, + ContentType = SanitizeContentType(command.ContentType, extension), + Extension = extension, + Version = 1, + IsCurrentVersion = true, + UploadedByUserId = command.UploadedByUserId, + UploadedBy = NormalizeOptional(command.UploadedBy, 200, nameof(command.UploadedBy)), + CreatedAt = now, + UpdatedAt = now + }; + file.StorageKey = BuildStorageKey(file, now); + + var written = await storage.SaveAsync(file.StorageKey, command.Content, ct); + if (written.SizeBytes <= 0) + { + await storage.DeleteAsync(file.StorageKey, ct); + throw new FilesValidationException("file", "文件内容为空。"); + } + + file.SizeBytes = written.SizeBytes; + file.Sha256 = written.Sha256; + + try + { + db.FileAttachments.Add(file); + await db.SaveChangesAsync(ct); + } + catch + { + await storage.DeleteAsync(file.StorageKey, CancellationToken.None); + throw; + } + + return ToDto(file); + } + + /// Stores a new immutable version of the file group the given version belongs to. + public async Task UploadNewVersionAsync( + Guid fileId, Stream content, string? originalFileName, string? contentType, + string? category, string? description, Guid? uploadedByUserId = null, string? uploadedBy = null, + CancellationToken ct = default) + { + if (content is null) + throw new FilesValidationException("file", "文件内容为空。"); + + var anchor = await LoadAsync(fileId, ct); + var nextVersion = (await db.FileAttachments + .Where(x => x.FileGroupId == anchor.FileGroupId) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + var group = await db.FileAttachments + .Where(x => x.FileGroupId == anchor.FileGroupId && !x.IsDeleted) + .ToListAsync(ct); + if (group.Count == 0) + throw new FilesNotFoundException("文件不存在。"); + + var current = group.SingleOrDefault(x => x.IsCurrentVersion) + ?? throw new FilesConflictException("文件组没有当前版本。"); + var safeName = SanitizeFileName(originalFileName); + var extension = ValidateExtension(safeName); + var now = DateTimeOffset.UtcNow; + + var file = new FileAttachment + { + FileGroupId = current.FileGroupId, + PreviousVersionId = current.Id, + OwnerType = current.OwnerType, + OwnerId = current.OwnerId, + Category = NormalizeOptional(category, 100, nameof(category)) ?? current.Category, + Description = NormalizeOptional(description, 1000, nameof(description)) ?? current.Description, + OriginalFileName = safeName, + ContentType = SanitizeContentType(contentType, extension), + Extension = extension, + Version = nextVersion, + IsCurrentVersion = true, + UploadedByUserId = uploadedByUserId, + UploadedBy = NormalizeOptional(uploadedBy, 200, nameof(uploadedBy)), + CreatedAt = now, + UpdatedAt = now + }; + file.StorageKey = BuildStorageKey(file, now); + + var written = await storage.SaveAsync(file.StorageKey, content, ct); + if (written.SizeBytes <= 0) + { + await storage.DeleteAsync(file.StorageKey, ct); + throw new FilesValidationException("file", "文件内容为空。"); + } + + file.SizeBytes = written.SizeBytes; + file.Sha256 = written.Sha256; + current.IsCurrentVersion = false; + current.Touch(); + + try + { + db.FileAttachments.Add(file); + await db.SaveChangesAsync(ct); + } + catch + { + await storage.DeleteAsync(file.StorageKey, CancellationToken.None); + throw; + } + + return ToDto(file); + } + + public async Task> ListAsync( + string? ownerType, Guid? ownerId, string? category, string? search, bool currentOnly, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.FileAttachments.AsNoTracking().Where(x => !x.IsDeleted); + if (!string.IsNullOrWhiteSpace(ownerType)) + { + var normalized = NormalizeOwnerType(ownerType); + query = query.Where(x => x.OwnerType == normalized); + } + if (ownerId is not null) query = query.Where(x => x.OwnerId == ownerId.Value); + if (!string.IsNullOrWhiteSpace(category)) + { + var normalizedCategory = category.Trim(); + query = query.Where(x => x.Category == normalizedCategory); + } + if (currentOnly) query = query.Where(x => x.IsCurrentVersion); + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.OriginalFileName.Contains(term) || + x.Sha256.Contains(term) || + x.OwnerType.Contains(term) || + (x.Category != null && x.Category.Contains(term)) || + (x.Description != null && x.Description.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToListItem).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task> ListVersionsAsync(Guid id, CancellationToken ct = default) + { + var file = await LoadAsync(id, ct); + var versions = await db.FileAttachments.AsNoTracking() + .Where(x => x.FileGroupId == file.FileGroupId && !x.IsDeleted) + .OrderByDescending(x => x.Version) + .ToListAsync(ct); + return versions.Select(ToDto).ToList(); + } + + public async Task OpenDownloadAsync(Guid id, CancellationToken ct = default) + { + var file = await LoadAsync(id, ct); + Stream content; + try + { + content = await storage.OpenReadAsync(file.StorageKey, ct); + } + catch (FileNotFoundException) + { + throw new FilesNotFoundException("文件内容不存在或已被移除。"); + } + catch (DirectoryNotFoundException) + { + throw new FilesNotFoundException("文件内容不存在或已被移除。"); + } + + if (content.CanSeek && content.Length != file.SizeBytes) + { + await content.DisposeAsync(); + throw new FilesConflictException("文件内容大小与元数据不一致。"); + } + + return new FileDownloadResult( + new FileDownloadInfo(file.Id, file.OriginalFileName, file.ContentType, file.SizeBytes, file.Sha256), + content); + } + + public async Task DeleteAsync(Guid id, CancellationToken ct = default) + { + var file = await LoadAsync(id, ct); + var wasCurrent = file.IsCurrentVersion; + var groupId = file.FileGroupId; + var storageKey = file.StorageKey; + + file.IsDeleted = true; + file.IsCurrentVersion = false; + file.DeletedAt = DateTimeOffset.UtcNow; + file.Touch(); + + if (wasCurrent) + { + var previous = await db.FileAttachments + .Where(x => x.FileGroupId == groupId && x.Id != id && !x.IsDeleted) + .OrderByDescending(x => x.Version) + .FirstOrDefaultAsync(ct); + if (previous is not null) + { + previous.IsCurrentVersion = true; + previous.Touch(); + } + } + + await db.SaveChangesAsync(ct); + await storage.DeleteAsync(storageKey, ct); + } + + // ---------- Helpers ---------- + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.FileAttachments.SingleOrDefaultAsync(x => x.Id == id && !x.IsDeleted, ct) + ?? throw new FilesNotFoundException("文件不存在。"); + + private string BuildStorageKey(FileAttachment file, DateTimeOffset now) + { + var stem = Path.GetFileNameWithoutExtension(file.OriginalFileName); + var safeStem = new string(stem.Select(ch => char.IsLetterOrDigit(ch) || ch is '-' or '_' ? ch : '_').ToArray()).Trim('_'); + if (safeStem.Length == 0) safeStem = "file"; + if (safeStem.Length > 60) safeStem = safeStem[..60]; + // Relative key only; LocalFileStorage resolves it under the configured root. + return $"files/{now.UtcDateTime:yyyy}/{now.UtcDateTime:MM}/{file.OwnerType}/{file.OwnerId:D}/{file.FileGroupId:D}/v{file.Version}-{file.Id:D}-{safeStem}{file.Extension}"; + } + + private string ValidateExtension(string fileName) + { + var extension = Path.GetExtension(fileName).ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(extension) || extension.Length > 20) + throw new FilesValidationException("file", "文件必须包含扩展名。"); + var allowed = options.AllowedExtensions + .Select(x => x.Trim().ToLowerInvariant()) + .Select(x => x.StartsWith('.') ? x : "." + x) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + if (allowed.Count > 0 && !allowed.Contains(extension)) + throw new FilesValidationException("file", $"不允许上传 {extension} 类型的文件。"); + return extension; + } + + internal static string SanitizeFileName(string? originalFileName) + { + if (string.IsNullOrWhiteSpace(originalFileName)) + throw new FilesValidationException("file", "文件名不能为空。"); + + // Take the basename only, treating both separators as path separators on every OS, + // so a Windows-style "..\..\x.pdf" cannot traverse on any host. + var name = originalFileName.Replace('\\', '/'); + var slash = name.LastIndexOf('/'); + if (slash >= 0) name = name[(slash + 1)..]; + name = name.Trim().TrimEnd('.', ' '); + + if (name.Length == 0 || name is "." or "..") + throw new FilesValidationException("file", "文件名无效。"); + + var invalid = Path.GetInvalidFileNameChars(); + var chars = name.Select(ch => ch < 32 || invalid.Contains(ch) ? '_' : ch).ToArray(); + name = new string(chars).Trim().TrimEnd('.', ' '); + if (name.Length == 0 || name is "." or "..") + throw new FilesValidationException("file", "文件名无效。"); + + if (name.Length > 200) + { + var extension = Path.GetExtension(name); + var stem = Path.GetFileNameWithoutExtension(name); + name = stem[..Math.Max(1, 200 - extension.Length)] + extension; + } + return name; + } + + internal static string NormalizeOwnerType(string? ownerType) + { + if (string.IsNullOrWhiteSpace(ownerType)) + throw new FilesValidationException(nameof(ownerType), "附件所属业务对象类型不能为空。"); + var normalized = ownerType.Trim().ToLowerInvariant(); + if (normalized.Length > 100 || normalized is "." or ".." || + !char.IsLetterOrDigit(normalized[0]) || + normalized.Any(ch => !(char.IsLetterOrDigit(ch) || ch is '-' or '_' or '.'))) + throw new FilesValidationException(nameof(ownerType), "附件所属业务对象类型无效。"); + return normalized; + } + + private static string? NormalizeOptional(string? value, int maxLength, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + var trimmed = value.Trim(); + if (trimmed.Length > maxLength) + throw new FilesValidationException(field, $"长度不能超过 {maxLength} 个字符。"); + if (trimmed.Any(char.IsControl)) + throw new FilesValidationException(field, "不能包含控制字符。"); + return trimmed; + } + + private static string SanitizeContentType(string? contentType, string extension) + { + var value = contentType?.Split(';', 2)[0].Trim().ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(value) || value.Length > 200 || value.Any(char.IsControl) || !value.Contains('/')) + { + value = extension switch + { + ".pdf" => "application/pdf", + ".png" => "image/png", + ".jpg" or ".jpeg" => "image/jpeg", + ".gif" => "image/gif", + ".webp" => "image/webp", + ".txt" => "text/plain", + ".csv" => "text/csv", + ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".zip" => "application/zip", + _ => "application/octet-stream" + }; + } + return value; + } + + private static FileAttachmentDto ToDto(FileAttachment x) => new( + x.Id, x.FileGroupId, x.PreviousVersionId, x.OwnerType, x.OwnerId, x.Category, x.Description, + x.OriginalFileName, x.StorageKey, x.ContentType, x.Extension, x.SizeBytes, x.Sha256, + x.Version, x.IsCurrentVersion, x.UploadedByUserId, x.UploadedBy, x.CreatedAt, x.UpdatedAt); + + private static FileAttachmentListItemDto ToListItem(FileAttachment x) => new( + x.Id, x.FileGroupId, x.OwnerType, x.OwnerId, x.Category, x.OriginalFileName, x.ContentType, + x.Extension, x.SizeBytes, x.Sha256, x.Version, x.IsCurrentVersion, x.UploadedBy, x.CreatedAt, x.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Files/FilesExceptions.cs b/src/Leiren.Erp.Application/Files/FilesExceptions.cs new file mode 100644 index 0000000..d3adf61 --- /dev/null +++ b/src/Leiren.Erp.Application/Files/FilesExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Files; + +public sealed class FilesNotFoundException(string message) : Exception(message); + +public sealed class FilesConflictException(string message) : Exception(message); + +public sealed class FilesValidationException(IReadOnlyDictionary errors) + : Exception("文件资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public FilesValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Files/IFileStorage.cs b/src/Leiren.Erp.Application/Files/IFileStorage.cs new file mode 100644 index 0000000..90db8bc --- /dev/null +++ b/src/Leiren.Erp.Application/Files/IFileStorage.cs @@ -0,0 +1,53 @@ +namespace Leiren.Erp.Application.Files; + +/// Configuration for server-side file storage. Content never goes to the database. +public sealed class FileStorageOptions +{ + /// Storage root. Relative values are resolved against the API content root at startup. + public string RootPath { get; set; } = "data/storage"; + + public long MaxFileSizeBytes { get; set; } = 50 * 1024 * 1024; + + public List AllowedExtensions { get; set; } = + [ + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".txt", ".csv", ".zip", ".rar", ".7z" + ]; +} + +public sealed record StoredFileWriteResult(long SizeBytes, string Sha256); + +/// +/// Stores file content under relative keys beneath a configured root. +/// Implementations must reject absolute keys and any key escaping the root. +/// +public interface IFileStorage +{ + Task SaveAsync(string storageKey, Stream content, CancellationToken cancellationToken = default); + Task OpenReadAsync(string storageKey, CancellationToken cancellationToken = default); + Task DeleteAsync(string storageKey, CancellationToken cancellationToken = default); + Task ExistsAsync(string storageKey, CancellationToken cancellationToken = default); +} + +/// Upload input carrying the content stream; kept in Application because streams are not wire contracts. +public sealed record UploadFileCommand( + string? OwnerType, + Guid OwnerId, + string? Category, + string? Description, + string? OriginalFileName, + string? ContentType, + Stream Content, + Guid? UploadedByUserId = null, + string? UploadedBy = null); + +public sealed record FileDownloadResult(FileDownloadInfo File, Stream Content); + +/// Download metadata handed to the API layer without exposing a server filesystem path. +public sealed record FileDownloadInfo( + Guid Id, + string OriginalFileName, + string ContentType, + long SizeBytes, + string Sha256); diff --git a/src/Leiren.Erp.Application/Files/IFilesDbContext.cs b/src/Leiren.Erp.Application/Files/IFilesDbContext.cs new file mode 100644 index 0000000..bf4675f --- /dev/null +++ b/src/Leiren.Erp.Application/Files/IFilesDbContext.cs @@ -0,0 +1,12 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Files; + +/// EF Core boundary for the Files module; implemented by Infrastructure. +public interface IFilesDbContext +{ + DbSet FileAttachments { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Finance/PayableService.cs b/src/Leiren.Erp.Application/Finance/PayableService.cs new file mode 100644 index 0000000..ff86f57 --- /dev/null +++ b/src/Leiren.Erp.Application/Finance/PayableService.cs @@ -0,0 +1,83 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Finance; + +/// EF Core boundary for the Finance module; implemented by Infrastructure. +public interface IFinanceDbContext +{ + DbSet SupplierPayables { get; } + DbSet PurchaseContracts { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} + +public sealed class FinanceValidationException(string field, string message) : Exception(message) +{ + public IReadOnlyDictionary Errors { get; } = new Dictionary { [field] = [message] }; +} + +public sealed class FinanceNotFoundException(string message) : Exception(message); + +public sealed class FinanceConflictException(string message) : Exception(message); + +/// +/// Supplier payables: one per confirmed purchase contract (created by the +/// purchasing module on confirmation). Lists are returned whole so the +/// client can filter, sort and total them; paying is a single final step. +/// +public sealed class PayableService(IFinanceDbContext db) +{ + public async Task> ListAsync(CancellationToken ct = default) + { + var items = await db.SupplierPayables.AsNoTracking().ToListAsync(ct); + return items.OrderByDescending(x => x.CreatedAt).Select(ToDto).ToList(); + } + + public async Task PayAsync(Guid id, PaySupplierPayableRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + var payable = await db.SupplierPayables.SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new FinanceNotFoundException("待付款项不存在。"); + var paidDate = request.PaidDate ?? DateOnly.FromDateTime(DateTime.Today); + if (paidDate > DateOnly.FromDateTime(DateTime.Today)) + throw new FinanceValidationException(nameof(request.PaidDate), "付款日期不能晚于今天。"); + + try + { + payable.MarkPaid(paidDate, Trim(request.PaymentReference), Trim(request.PaidBy), Trim(request.Remark)); + } + catch (InvalidOperationException ex) + { + throw new FinanceConflictException(ex.Message); + } + await db.SaveChangesAsync(ct); + return ToDto(payable); + } + + /// + /// Creates the payable for every confirmed contract that has none — covers + /// contracts confirmed before payables existed. Idempotent. + /// + public async Task BackfillAsync(CancellationToken ct = default) + { + var existing = (await db.SupplierPayables.AsNoTracking().Select(x => x.PurchaseContractId).ToListAsync(ct)).ToHashSet(); + var contracts = await db.PurchaseContracts.Include(x => x.Tasks) + .Where(x => x.Status != PurchaseContractStatus.Draft && x.Status != PurchaseContractStatus.Voided) + .ToListAsync(ct); + var missing = contracts.Where(x => !existing.Contains(x.Id)).ToList(); + foreach (var contract in missing) + db.SupplierPayables.Add(SupplierPayable.ForContract(contract)); + if (missing.Count > 0) await db.SaveChangesAsync(ct); + return missing.Count; + } + + private static string? Trim(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static SupplierPayableDto ToDto(SupplierPayable x) => new( + x.Id, x.PayableNo, x.PurchaseContractId, x.ContractNo, x.SupplierId, x.SupplierName, x.CustomerOrderNo, + x.Currency, x.Amount, x.PaymentTerms, x.Status.ToString(), x.PaidDate, x.PaymentReference, x.PaidBy, + x.PaidAt, x.Remark, x.CreatedAt, x.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Identity/IIdentityDbContext.cs b/src/Leiren.Erp.Application/Identity/IIdentityDbContext.cs new file mode 100644 index 0000000..0bc9830 --- /dev/null +++ b/src/Leiren.Erp.Application/Identity/IIdentityDbContext.cs @@ -0,0 +1,17 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Identity; + +/// EF Core boundary for the Identity module; implemented by Infrastructure. +public interface IIdentityDbContext +{ + DbSet Users { get; } + DbSet Roles { get; } + DbSet Permissions { get; } + DbSet UserRoles { get; } + DbSet RolePermissions { get; } + DbSet UserPermissions { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Identity/IdentityExceptions.cs b/src/Leiren.Erp.Application/Identity/IdentityExceptions.cs new file mode 100644 index 0000000..04027cc --- /dev/null +++ b/src/Leiren.Erp.Application/Identity/IdentityExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Identity; + +public sealed class IdentityNotFoundException(string message) : Exception(message); + +public sealed class IdentityConflictException(string message) : Exception(message); + +public sealed class IdentityValidationException(IReadOnlyDictionary errors) + : Exception("授权数据校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public IdentityValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Identity/IdentityService.cs b/src/Leiren.Erp.Application/Identity/IdentityService.cs new file mode 100644 index 0000000..c46914c --- /dev/null +++ b/src/Leiren.Erp.Application/Identity/IdentityService.cs @@ -0,0 +1,364 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Authorization; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Identity; + +/// +/// Server-side authorization source of truth. Effective permissions are the union of a +/// user's direct permissions and every assigned role's permissions; anything not granted +/// is denied. Password hashing stays with the API host (ASP.NET Core Identity hasher), +/// this service only persists the hash it is given. +/// +public sealed class IdentityService(IIdentityDbContext db) +{ + private static readonly IReadOnlyDictionary SystemRoles = + new Dictionary(StringComparer.Ordinal) + { + ["admin"] = ("系统管理员", AuthorizationCatalog.Permissions.Select(x => x.Code).ToArray()), + ["sales"] = ("销售", ["dashboard:view", "sales:view", "sales:edit", "sales:confirm", "sales:export", "customers:view", "customers:edit", "customers:export", "catalog:view", "files:view", "files:edit", "files:download"]), + ["purchase"] = ("采购", ["dashboard:view", "purchase:view", "purchase:edit", "purchase:confirm", "purchase:generate", "purchase:export", "sales:view", "suppliers:view", "suppliers:edit", "suppliers:export", "catalog:view", "files:view", "files:edit", "files:download"]), + ["shipping"] = ("出货", ["dashboard:view", "shipping:view", "shipping:edit", "shipping:confirm", "shipping:generate", "shipping:export", "sales:view", "catalog:view", "files:view", "files:edit", "files:download"]), + ["customs"] = ("报关", ["dashboard:view", "customs:view", "customs:edit", "customs:confirm", "customs:generate", "customs:export", "shipping:view", "sales:view", "catalog:view", "files:view", "files:edit", "files:download"]), + ["billing"] = ("开票", ["dashboard:view", "billing:view", "billing:edit", "billing:confirm", "billing:generate", "billing:export", "purchase:view", "suppliers:view", "files:view", "files:edit", "files:download"]), + ["catalog"] = ("产品维护", ["dashboard:view", "catalog:view", "catalog:edit", "catalog:publish", "catalog:disable", "catalog:export", "files:view", "files:edit", "files:download"]), + }; + + public IReadOnlyList ListModules() => + AuthorizationCatalog.Modules.Select(x => new ModuleDto(x.Code, x.Name)).ToList(); + + public IReadOnlyList ListPermissions() => + AuthorizationCatalog.Permissions.Select(x => new PermissionDto(x.Code, x.Module, x.Action)).ToList(); + + /// Idempotently creates the permission catalog and system roles. + public async Task EnsureAuthorizationCatalogAsync(CancellationToken ct = default) + { + var existingPermissions = await db.Permissions.ToListAsync(ct); + var byCode = existingPermissions.ToDictionary(x => x.Code, StringComparer.Ordinal); + var changed = false; + foreach (var definition in AuthorizationCatalog.Permissions) + { + if (byCode.ContainsKey(definition.Code)) continue; + var permission = new AppPermission { Code = definition.Code, Module = definition.Module, Action = definition.Action }; + db.Permissions.Add(permission); + byCode[definition.Code] = permission; + changed = true; + } + if (changed) await db.SaveChangesAsync(ct); + + foreach (var (code, (name, permissions)) in SystemRoles) + { + var role = await db.Roles + .Include(x => x.Permissions) + .SingleOrDefaultAsync(x => x.Code == code, ct); + if (role is null) + { + role = new AppRole { Code = code, Name = name, IsSystem = true }; + db.Roles.Add(role); + await db.SaveChangesAsync(ct); + } + + var desired = permissions.ToHashSet(StringComparer.Ordinal); + var currentCodes = await db.RolePermissions + .Where(x => x.RoleId == role.Id) + .Join(db.Permissions, x => x.PermissionId, p => p.Id, (_, p) => p.Code) + .ToListAsync(ct); + var current = currentCodes.ToHashSet(StringComparer.Ordinal); + if (current.SetEquals(desired)) continue; + + var existingLinks = await db.RolePermissions.Where(x => x.RoleId == role.Id).ToListAsync(ct); + db.RolePermissions.RemoveRange(existingLinks); + foreach (var permissionCode in desired) + { + db.RolePermissions.Add(new RolePermission { RoleId = role.Id, PermissionId = byCode[permissionCode].Id }); + } + await db.SaveChangesAsync(ct); + } + } + + public async Task> GetEffectivePermissionsAsync(Guid userId, CancellationToken ct = default) + { + var direct = db.UserPermissions + .Where(x => x.UserId == userId) + .Join(db.Permissions, x => x.PermissionId, p => p.Id, (_, p) => p.Code); + var viaRoles = db.UserRoles + .Where(x => x.UserId == userId) + .Join(db.RolePermissions, ur => ur.RoleId, rp => rp.RoleId, (_, rp) => rp.PermissionId) + .Join(db.Permissions, id => id, p => p.Id, (_, p) => p.Code); + var codes = await direct.Union(viaRoles).ToListAsync(ct); + return codes.OrderBy(x => x, StringComparer.Ordinal).ToList(); + } + + public async Task HasPermissionAsync(Guid userId, string permission, CancellationToken ct = default) + { + if (!AuthorizationCatalog.TryNormalizePermission(permission, out var code)) return false; + var permissions = await GetEffectivePermissionsAsync(userId, ct); + return permissions.Contains(code, StringComparer.Ordinal); + } + + public async Task HasModuleAsync(Guid userId, string module, CancellationToken ct = default) + { + var normalized = AuthorizationCatalog.NormalizeModule(module); + if (normalized is null) return false; + var permissions = await GetEffectivePermissionsAsync(userId, ct); + return permissions.Any(x => AuthorizationCatalog.ModuleOf(x) == normalized); + } + + public async Task CreateUserAsync(CreateUserRequest request, string passwordHash, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(request?.UserName) || string.IsNullOrWhiteSpace(request.DisplayName)) + throw new IdentityValidationException("user", "用户名和显示名称不能为空。"); + if (string.IsNullOrWhiteSpace(passwordHash)) + throw new IdentityValidationException("password", "密码不能为空。"); + + var userName = request.UserName.Trim(); + if (await db.Users.AnyAsync(x => x.UserName == userName, ct)) + throw new IdentityConflictException($"用户名 {userName} 已存在。"); + + var roles = await ResolveRolesAsync(request.RoleCodes, ct); + var permissions = ResolvePermissionCodes(request.Permissions, request.Modules); + + var user = new AppUser + { + UserName = userName, + DisplayName = request.DisplayName.Trim(), + PasswordHash = passwordHash, + IsActive = true, + }; + db.Users.Add(user); + await db.SaveChangesAsync(ct); + + foreach (var role in roles) + db.UserRoles.Add(new UserRole { UserId = user.Id, RoleId = role.Id }); + await AddDirectPermissionsAsync(user.Id, permissions, ct); + await db.SaveChangesAsync(ct); + return await GetUserAsync(user.Id, ct); + } + + public async Task> ListUsersAsync(int page, int pageSize, CancellationToken ct = default) + { + var safePage = Math.Max(1, page); + var safePageSize = Math.Clamp(pageSize, 1, 200); + var users = await db.Users + .OrderBy(x => x.UserName) + .Skip((safePage - 1) * safePageSize) + .Take(safePageSize) + .ToListAsync(ct); + var result = new List(users.Count); + foreach (var user in users) result.Add(await ToDtoAsync(user, ct)); + return result; + } + + public async Task GetUserAsync(Guid userId, CancellationToken ct = default) + { + var user = await db.Users.SingleOrDefaultAsync(x => x.Id == userId, ct) + ?? throw new IdentityNotFoundException("用户不存在。"); + return await ToDtoAsync(user, ct); + } + + public async Task AssignRolesAsync(Guid userId, AssignRolesRequest request, CancellationToken ct = default) + { + _ = await GetUserEntityAsync(userId, ct); + var roles = await ResolveRolesAsync(request?.RoleCodes, ct); + var existing = await db.UserRoles.Where(x => x.UserId == userId).ToListAsync(ct); + db.UserRoles.RemoveRange(existing); + foreach (var role in roles) + db.UserRoles.Add(new UserRole { UserId = userId, RoleId = role.Id }); + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + /// + /// Replaces the user's directly granted module access (module:view). Modules that + /// come from roles remain effective and are still reported in the user's module list. + /// + public async Task AssignModulesAsync(Guid userId, AssignModulesRequest request, CancellationToken ct = default) + { + _ = await GetUserEntityAsync(userId, ct); + var modules = NormalizeModules(request?.Modules); + var directView = await db.UserPermissions + .Where(x => x.UserId == userId) + .Join(db.Permissions, up => up.PermissionId, p => p.Id, (up, p) => new { Link = up, p.Code, p.Module, p.Action }) + .Where(x => x.Action == "view") + .ToListAsync(ct); + foreach (var item in directView.Where(x => !modules.Contains(x.Module))) + db.UserPermissions.Remove(item.Link); + var kept = directView.Where(x => modules.Contains(x.Module)).Select(x => x.Module).ToHashSet(StringComparer.Ordinal); + foreach (var module in modules.Where(x => !kept.Contains(x))) + { + var permission = await GetPermissionEntityAsync(AuthorizationCatalog.ViewPermission(module), ct); + db.UserPermissions.Add(new UserPermission { UserId = userId, PermissionId = permission.Id }); + } + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + public async Task AssignPermissionsAsync(Guid userId, AssignPermissionsRequest request, CancellationToken ct = default) + { + _ = await GetUserEntityAsync(userId, ct); + var codes = ResolvePermissionCodes(request?.Permissions, null); + var existing = await db.UserPermissions.Where(x => x.UserId == userId).ToListAsync(ct); + db.UserPermissions.RemoveRange(existing); + await AddDirectPermissionsAsync(userId, codes, ct); + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + public async Task SetUserActiveAsync(Guid userId, bool isActive, CancellationToken ct = default) + { + var user = await GetUserEntityAsync(userId, ct); + user.IsActive = isActive; + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + public async Task AssignRoleToUserAsync(Guid userId, string roleCode, CancellationToken ct = default) + { + var role = await db.Roles.SingleOrDefaultAsync(x => x.Code == roleCode, ct) + ?? throw new IdentityNotFoundException($"角色 {roleCode} 不存在。"); + if (!await db.UserRoles.AnyAsync(x => x.UserId == userId && x.RoleId == role.Id, ct)) + { + db.UserRoles.Add(new UserRole { UserId = userId, RoleId = role.Id }); + await db.SaveChangesAsync(ct); + } + } + + public async Task> ListRolesAsync(CancellationToken ct = default) + { + var roles = await db.Roles.OrderBy(x => x.Code).ToListAsync(ct); + var result = new List(roles.Count); + foreach (var role in roles) result.Add(await ToDtoAsync(role, ct)); + return result; + } + + public async Task CreateRoleAsync(CreateRoleRequest request, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(request?.Code) || string.IsNullOrWhiteSpace(request.Name)) + throw new IdentityValidationException("role", "角色编码和名称不能为空。"); + var code = request.Code.Trim().ToLowerInvariant(); + if (code.Any(c => !(char.IsLower(c) || char.IsDigit(c) || c is '-' or '_'))) + throw new IdentityValidationException("code", "角色编码只能包含小写字母、数字、连字符和下划线。"); + if (await db.Roles.AnyAsync(x => x.Code == code, ct)) + throw new IdentityConflictException($"角色编码 {code} 已存在。"); + + var permissions = ResolvePermissionCodes(request.Permissions, request.Modules); + var role = new AppRole { Code = code, Name = request.Name.Trim(), Description = request.Description?.Trim(), IsSystem = false }; + db.Roles.Add(role); + await db.SaveChangesAsync(ct); + foreach (var permissionCode in permissions) + { + var permission = await GetPermissionEntityAsync(permissionCode, ct); + db.RolePermissions.Add(new RolePermission { RoleId = role.Id, PermissionId = permission.Id }); + } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(role, ct); + } + + public async Task UpdateRolePermissionsAsync(Guid roleId, UpdateRolePermissionsRequest request, CancellationToken ct = default) + { + var role = await db.Roles.SingleOrDefaultAsync(x => x.Id == roleId, ct) + ?? throw new IdentityNotFoundException("角色不存在。"); + var permissions = ResolvePermissionCodes(request?.Permissions, request?.Modules); + var existing = await db.RolePermissions.Where(x => x.RoleId == roleId).ToListAsync(ct); + db.RolePermissions.RemoveRange(existing); + foreach (var permissionCode in permissions) + { + var permission = await GetPermissionEntityAsync(permissionCode, ct); + db.RolePermissions.Add(new RolePermission { RoleId = role.Id, PermissionId = permission.Id }); + } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(role, ct); + } + + private async Task GetUserEntityAsync(Guid userId, CancellationToken ct) => + await db.Users.SingleOrDefaultAsync(x => x.Id == userId, ct) + ?? throw new IdentityNotFoundException("用户不存在。"); + + private async Task GetPermissionEntityAsync(string code, CancellationToken ct) => + await db.Permissions.SingleOrDefaultAsync(x => x.Code == code, ct) + ?? throw new IdentityNotFoundException($"权限 {code} 不存在,请先初始化权限目录。"); + + private async Task AddDirectPermissionsAsync(Guid userId, IReadOnlyCollection codes, CancellationToken ct) + { + foreach (var code in codes) + { + var permission = await GetPermissionEntityAsync(code, ct); + db.UserPermissions.Add(new UserPermission { UserId = userId, PermissionId = permission.Id }); + } + } + + private async Task> ResolveRolesAsync(IReadOnlyList? roleCodes, CancellationToken ct) + { + if (roleCodes is null || roleCodes.Count == 0) return []; + var codes = roleCodes.Select(x => x?.Trim().ToLowerInvariant()) + .Where(x => !string.IsNullOrEmpty(x)).Select(x => x!).Distinct(StringComparer.Ordinal).ToList(); + var roles = await db.Roles.Where(x => codes.Contains(x.Code)).ToListAsync(ct); + var missing = codes.Except(roles.Select(x => x.Code), StringComparer.Ordinal).ToList(); + if (missing.Count > 0) + throw new IdentityValidationException("roleCodes", $"角色不存在:{string.Join(", ", missing)}"); + return roles; + } + + private static IReadOnlyList ResolvePermissionCodes(IReadOnlyList? permissions, IReadOnlyList? modules) + { + var codes = new HashSet(StringComparer.Ordinal); + if (permissions is not null) + { + foreach (var raw in permissions) + { + if (!AuthorizationCatalog.TryNormalizePermission(raw, out var code)) + throw new IdentityValidationException("permissions", $"未知权限:{raw}"); + codes.Add(code); + } + } + foreach (var module in NormalizeModules(modules)) + codes.Add(AuthorizationCatalog.ViewPermission(module)); + return codes.OrderBy(x => x, StringComparer.Ordinal).ToList(); + } + + private static IReadOnlyList NormalizeModules(IReadOnlyList? modules) + { + if (modules is null || modules.Count == 0) return []; + var result = new HashSet(StringComparer.Ordinal); + foreach (var raw in modules) + { + var module = AuthorizationCatalog.NormalizeModule(raw) + ?? throw new IdentityValidationException("modules", $"未知模块:{raw}"); + result.Add(module); + } + return result.OrderBy(x => x, StringComparer.Ordinal).ToList(); + } + + private async Task ToDtoAsync(AppUser user, CancellationToken ct) + { + var roles = await db.UserRoles + .Where(x => x.UserId == user.Id) + .Join(db.Roles, ur => ur.RoleId, r => r.Id, (_, r) => r.Code) + .ToListAsync(ct); + var directPermissions = await db.UserPermissions + .Where(x => x.UserId == user.Id) + .Join(db.Permissions, up => up.PermissionId, p => p.Id, (_, p) => p.Code) + .ToListAsync(ct); + var directModules = directPermissions.Select(AuthorizationCatalog.ModuleOf) + .Distinct(StringComparer.Ordinal).OrderBy(x => x, StringComparer.Ordinal).ToList(); + var permissions = await GetEffectivePermissionsAsync(user.Id, ct); + var modules = permissions.Select(AuthorizationCatalog.ModuleOf) + .Distinct(StringComparer.Ordinal).OrderBy(x => x, StringComparer.Ordinal).ToList(); + return new UserDto(user.Id, user.UserName, user.DisplayName, user.IsActive, user.CreatedAt, + roles.OrderBy(x => x, StringComparer.Ordinal).ToList(), modules, permissions, + directModules, directPermissions.OrderBy(x => x, StringComparer.Ordinal).ToList()); + } + + private async Task ToDtoAsync(AppRole role, CancellationToken ct) + { + var permissions = await db.RolePermissions + .Where(x => x.RoleId == role.Id) + .Join(db.Permissions, rp => rp.PermissionId, p => p.Id, (_, p) => p.Code) + .ToListAsync(ct); + var modules = permissions.Select(AuthorizationCatalog.ModuleOf) + .Distinct(StringComparer.Ordinal).OrderBy(x => x, StringComparer.Ordinal).ToList(); + return new RoleDto(role.Id, role.Code, role.Name, role.Description, role.IsSystem, + permissions.OrderBy(x => x, StringComparer.Ordinal).ToList(), modules); + } +} diff --git a/src/Leiren.Erp.Application/Leiren.Erp.Application.csproj b/src/Leiren.Erp.Application/Leiren.Erp.Application.csproj new file mode 100644 index 0000000..3e7187c --- /dev/null +++ b/src/Leiren.Erp.Application/Leiren.Erp.Application.csproj @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + net11.0 + enable + enable + + + diff --git a/src/Leiren.Erp.Application/MasterData/IMasterDataDbContext.cs b/src/Leiren.Erp.Application/MasterData/IMasterDataDbContext.cs new file mode 100644 index 0000000..757d104 --- /dev/null +++ b/src/Leiren.Erp.Application/MasterData/IMasterDataDbContext.cs @@ -0,0 +1,22 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.MasterData; + +/// +/// EF Core boundary for the MasterData module; implemented by Infrastructure. +/// Referencing sets are read only to block deleting a supplier that is already +/// used by quotes, purchasing or billing records. +/// +public interface IMasterDataDbContext +{ + DbSet Suppliers { get; } + DbSet ProductSupplierQuotes { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet SupplierInvoiceNotices { get; } + DbSet SupplierInvoices { get; } + DbSet SupplierBillingContracts { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/MasterData/MasterDataExceptions.cs b/src/Leiren.Erp.Application/MasterData/MasterDataExceptions.cs new file mode 100644 index 0000000..a4c878b --- /dev/null +++ b/src/Leiren.Erp.Application/MasterData/MasterDataExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.MasterData; + +public sealed class MasterDataNotFoundException(string message) : Exception(message); + +public sealed class MasterDataConflictException(string message) : Exception(message); + +public sealed class MasterDataValidationException(IReadOnlyDictionary errors) + : Exception("主数据校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public MasterDataValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/MasterData/SupplierService.cs b/src/Leiren.Erp.Application/MasterData/SupplierService.cs new file mode 100644 index 0000000..4209b72 --- /dev/null +++ b/src/Leiren.Erp.Application/MasterData/SupplierService.cs @@ -0,0 +1,131 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.MasterData; + +public sealed class SupplierService(IMasterDataDbContext db) +{ + public async Task> ListAsync( + string? search, bool? isActive, int page, int pageSize, CancellationToken ct = default) + { + var query = db.Suppliers.AsNoTracking().AsQueryable(); + if (isActive is { } active) query = query.Where(x => x.IsActive == active); + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.Name.Contains(term) + || (x.Code != null && x.Code.Contains(term)) + || (x.NameEn != null && x.NameEn.Contains(term)) + || (x.ContactName != null && x.ContactName.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderBy(x => x.Name) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task CreateAsync(SaveSupplierRequest request, CancellationToken ct = default) + { + var supplier = new Supplier(); + Apply(supplier, request); + await EnsureCodeAvailableAsync(supplier.Code, null, ct); + db.Suppliers.Add(supplier); + await db.SaveChangesAsync(ct); + return ToDto(supplier); + } + + public async Task UpdateAsync(Guid id, SaveSupplierRequest request, CancellationToken ct = default) + { + var supplier = await LoadAsync(id, ct); + Apply(supplier, request); + await EnsureCodeAvailableAsync(supplier.Code, supplier.Id, ct); + supplier.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(supplier); + } + + public async Task DeactivateAsync(Guid id, CancellationToken ct = default) + { + var supplier = await LoadAsync(id, ct); + supplier.IsActive = false; + supplier.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(supplier); + } + + public async Task DeleteAsync(Guid id, CancellationToken ct = default) + { + var supplier = await LoadAsync(id, ct); + if (await IsReferencedAsync(id, ct)) + throw new MasterDataConflictException("供应商已被报价、采购或开票记录引用,不能删除;请改为停用。"); + db.Suppliers.Remove(supplier); + await db.SaveChangesAsync(ct); + } + + private async Task IsReferencedAsync(Guid id, CancellationToken ct) + => await db.ProductSupplierQuotes.AnyAsync(x => x.SupplierId == id, ct) + || await db.PurchaseTasks.AnyAsync(x => x.SupplierId == id, ct) + || await db.PurchaseContracts.AnyAsync(x => x.SupplierId == id, ct) + || await db.SupplierInvoiceNotices.AnyAsync(x => x.SupplierId == id, ct) + || await db.SupplierInvoices.AnyAsync(x => x.SupplierId == id, ct) + || await db.SupplierBillingContracts.AnyAsync(x => x.SellerSupplierId == id, ct); + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.Suppliers.SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new MasterDataNotFoundException("供应商不存在。"); + + private async Task EnsureCodeAvailableAsync(string? code, Guid? excludeId, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(code)) return; + var exists = await db.Suppliers.AnyAsync( + x => x.Code == code.Trim() && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) + throw new MasterDataValidationException(nameof(SaveSupplierRequest.Code), $"供应商编码 {code.Trim()} 已存在。"); + } + + private static void Apply(Supplier s, SaveSupplierRequest r) + { + if (string.IsNullOrWhiteSpace(r.Name)) + throw new MasterDataValidationException(nameof(r.Name), "供应商名称不能为空。"); + if (r.DefaultTaxRate is < 0 or > 100) + throw new MasterDataValidationException(nameof(r.DefaultTaxRate), "默认税率必须在 0 到 100 之间(百分数)。"); + if (!string.IsNullOrWhiteSpace(r.ContactEmail) && !r.ContactEmail.Trim().Contains('@')) + throw new MasterDataValidationException(nameof(r.ContactEmail), "邮箱格式无效。"); + + s.Code = TrimOrNull(r.Code); + s.Name = r.Name.Trim(); + s.NameEn = TrimOrNull(r.NameEn); + s.ContactName = TrimOrNull(r.ContactName); + s.Address = TrimOrNull(r.Address); + s.ContactPhone = TrimOrNull(r.ContactPhone); + s.ContactEmail = TrimOrNull(r.ContactEmail); + s.PaymentTerms = TrimOrNull(r.PaymentTerms); + s.DefaultCurrency = NormalizeCurrency(r.DefaultCurrency); + s.TaxNumber = TrimOrNull(r.TaxNumber); + s.DefaultTaxRate = r.DefaultTaxRate; + s.Remark = TrimOrNull(r.Remark); + s.IsActive = r.IsActive; + } + + private static string? NormalizeCurrency(string? value) + { + var currency = TrimOrNull(value)?.ToUpperInvariant(); + if (currency is not null && currency.Length != 3) + throw new MasterDataValidationException(nameof(SaveSupplierRequest.DefaultCurrency), "默认币种必须是 3 位代码,如 CNY、USD。"); + return currency; + } + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static SupplierDto ToDto(Supplier s) => new( + s.Id, s.Code, s.Name, s.NameEn, s.ContactName, s.Address, s.ContactPhone, s.ContactEmail, + s.PaymentTerms, s.DefaultCurrency, s.TaxNumber, s.DefaultTaxRate, s.Remark, s.IsActive, + s.CreatedAt, s.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Purchasing/IPurchasingDbContext.cs b/src/Leiren.Erp.Application/Purchasing/IPurchasingDbContext.cs new file mode 100644 index 0000000..ee8eb86 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/IPurchasingDbContext.cs @@ -0,0 +1,25 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Purchasing; + +/// +/// EF Core boundary for the Purchasing module; implemented by Infrastructure. +/// Sales sets are read here only to validate the explicit +/// generate-from-sales-order command against a confirmed order. +/// +public interface IPurchasingDbContext +{ + DbSet SalesOrders { get; } + DbSet SalesOrderLines { get; } + DbSet Products { get; } + DbSet ProductParts { get; } + DbSet ProductSupplierQuotes { get; } + DbSet Suppliers { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet PurchaseArrivals { get; } + DbSet SupplierPayables { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Purchasing/PurchaseContractExportService.cs b/src/Leiren.Erp.Application/Purchasing/PurchaseContractExportService.cs new file mode 100644 index 0000000..3082905 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchaseContractExportService.cs @@ -0,0 +1,114 @@ +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Purchasing; + +/// +/// Generates a purchase-contract workbook from the contract's stored snapshot +/// (contract fields plus its purchase-task lines) and stores the result through +/// the Files module. The workbook is rendered from the configured XLSX template; +/// master data (products, suppliers, quotes) is never read here, so later +/// master-data changes cannot alter an exported contract. Re-exporting the same +/// contract stores a new version of the same file group. +/// +public sealed class PurchaseContractExportService( + IPurchasingDbContext db, FileService files, PurchaseContractTemplateOptions template) +{ + public const string OwnerType = "purchase-contract"; + public const string Category = "generated-contract"; + public const string ContentType = + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public async Task ExportAsync(Guid contractId, CancellationToken ct = default) + { + var (contract, lines, rendered) = await RenderAsync(contractId, ct); + using var stream = new MemoryStream(rendered); + + var fileName = $"{SanitizeFileStem(contract.ContractNo)}-采购合同.xlsx"; + var description = + $"采购合同 {contract.ContractNo} 导出;合同版本 {contract.Version};状态 {contract.Status};生成时间 {DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss} UTC。"; + + // One logical file per contract: a re-export becomes a new version of + // the existing generated-contract file instead of a second attachment. + var existing = await files.ListAsync(OwnerType, contract.Id, Category, null, true, 1, 1, ct); + var file = existing.Count > 0 + ? await files.UploadNewVersionAsync( + existing[0].Id, stream, fileName, ContentType, Category, description, ct: ct) + : await files.UploadAsync(new UploadFileCommand( + OwnerType, contract.Id, Category, description, fileName, ContentType, stream), ct); + + return new PurchaseContractExportDto( + contract.Id, contract.ContractNo, contract.Version, contract.Status.ToString(), + file, $"/api/files/{file.Id}/download"); + } + + /// Renders the contract workbook without storing a file; used by the confirm preview. + public async Task<(byte[] Bytes, string FileName)> PreviewAsync(Guid contractId, CancellationToken ct = default) + { + var (contract, _, rendered) = await RenderAsync(contractId, ct); + return (rendered, $"{SanitizeFileStem(contract.ContractNo)}-采购合同-预览.xlsx"); + } + + private async Task<(Domain.Entities.PurchaseContract Contract, List Lines, byte[] Bytes)> RenderAsync( + Guid contractId, CancellationToken ct) + { + var contract = await db.PurchaseContracts.AsNoTracking() + .Include(x => x.Tasks) + .SingleOrDefaultAsync(x => x.Id == contractId, ct) + ?? throw new PurchasingNotFoundException("采购合同不存在。"); + + if (contract.Status == PurchaseContractStatus.Voided) + throw new PurchasingConflictException("已作废的采购合同不能导出。"); + + var lines = contract.Tasks + .Where(x => x.Status != PurchaseTaskStatus.Cancelled) + .OrderBy(x => x.CreatedAt) + .ToList(); + if (lines.Count == 0) + throw new PurchasingValidationException(nameof(contract.Tasks), "采购合同没有可导出的采购任务。"); + + var templateBytes = await LoadTemplateAsync(ct); + + var rendered = PurchaseContractTemplateRenderer.Render( + templateBytes, contract, lines, DateTimeOffset.UtcNow); + return (contract, lines, rendered); + } + + /// + /// The most recently imported purchase-contract template (template editor) + /// wins; without one, the configured template file is used. + /// + private async Task LoadTemplateAsync(CancellationToken ct) + { + var imported = (await files.ListAsync( + DocumentTemplateService.TemplateOwnerType, null, DocumentTemplateKinds.PurchaseContract, null, + currentOnly: true, 1, 200, ct)) + .MaxBy(x => x.CreatedAt); + if (imported is not null) + { + await using var content = (await files.OpenDownloadAsync(imported.Id, ct)).Content; + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + return buffer.ToArray(); + } + + try + { + return await File.ReadAllBytesAsync(template.TemplatePath, ct); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new PurchasingValidationException("Template", $"采购合同模板读取失败:{ex.Message}"); + } + } + + private static string SanitizeFileStem(string contractNo) + { + var invalid = Path.GetInvalidFileNameChars(); + var stem = new string(contractNo.Select(ch => invalid.Contains(ch) || ch < 32 ? '_' : ch).ToArray()).Trim(); + return stem.Length == 0 ? "purchase-contract" : stem; + } +} diff --git a/src/Leiren.Erp.Application/Purchasing/PurchaseContractTemplateRenderer.cs b/src/Leiren.Erp.Application/Purchasing/PurchaseContractTemplateRenderer.cs new file mode 100644 index 0000000..ab6cf82 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchaseContractTemplateRenderer.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Domain.Entities; + +namespace Leiren.Erp.Application.Purchasing; + +/// +/// Renders a purchase-contract workbook from a real XLSX template through +/// : header and total placeholders are +/// replaced in place and the line block is copied once per contract task. +/// Values come from the contract snapshot only. +/// +public static class PurchaseContractTemplateRenderer +{ + private static readonly TokenTemplateFields Fields = new( + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "CustomerPoNo", "LineNumber", "CustomerSku", "InternalSku", "Unit", "ContentDescription", + "ContentType", "PackagingRequirement", "PurchaseRequirement", "Quantity", "UnitPrice", + "Amount", "TaxRate", "TaxIncluded", "DueDate", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "LineNumber", "Quantity", "UnitPrice", "Amount", "TaxRate", "TotalAmount", "LineCount", "Version", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "SignedDate", "RequiredCompletionDate", "DueDate", "GeneratedDate", + }); + + public static byte[] Render( + byte[] templateBytes, PurchaseContract contract, IReadOnlyList lines, DateTimeOffset generatedAt) + { + ArgumentNullException.ThrowIfNull(contract); + ArgumentNullException.ThrowIfNull(lines); + return TokenWorkbookRenderer.Render( + templateBytes, BuildHeaderValues(contract, lines, generatedAt), BuildLineValues(contract, lines), + Fields, "采购合同", message => new PurchasingValidationException("Template", message)); + } + + private static Dictionary BuildHeaderValues( + PurchaseContract contract, IReadOnlyList lines, DateTimeOffset generatedAt) + => new(StringComparer.OrdinalIgnoreCase) + { + ["ContractNo"] = contract.ContractNo, + ["SupplierName"] = contract.SupplierName, + ["SupplierContact"] = contract.SupplierContact, + ["SupplierPhone"] = contract.SupplierPhone, + ["CustomerOrderNo"] = contract.CustomerOrderNo, + ["SignedDate"] = contract.SignedDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["RequiredCompletionDate"] = contract.RequiredCompletionDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["PaymentTerms"] = contract.PaymentTerms, + ["Currency"] = contract.Currency, + ["Status"] = contract.Status.ToString(), + ["Version"] = contract.Version.ToString(CultureInfo.InvariantCulture), + ["LineCount"] = lines.Count.ToString(CultureInfo.InvariantCulture), + ["TotalAmount"] = lines.Sum(x => x.Amount).ToString("0.####", CultureInfo.InvariantCulture), + ["GeneratedDate"] = generatedAt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["Terms"] = contract.Terms, + }; + + private static List> BuildLineValues( + PurchaseContract contract, IReadOnlyList lines) + { + var result = new List>(lines.Count); + for (var i = 0; i < lines.Count; i++) + { + var task = lines[i]; + result.Add(new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["LineNumber"] = (i + 1).ToString(CultureInfo.InvariantCulture), + ["CustomerPoNo"] = task.CustomerPoNo ?? contract.CustomerOrderNo, + ["CustomerSku"] = task.CustomerSku ?? task.InternalSku, + ["InternalSku"] = task.InternalSku, + ["Unit"] = task.Unit, + ["ContentDescription"] = task.ContentDescription, + ["ContentType"] = task.ContentType.ToString(), + ["PackagingRequirement"] = task.PackagingRequirement ?? task.PurchaseRequirement, + ["PurchaseRequirement"] = task.PurchaseRequirement, + ["Quantity"] = task.Quantity.ToString("0.####", CultureInfo.InvariantCulture), + ["UnitPrice"] = task.UnitPrice.ToString("0.####", CultureInfo.InvariantCulture), + ["Amount"] = task.Amount.ToString("0.####", CultureInfo.InvariantCulture), + ["TaxRate"] = task.TaxRate.ToString("0.####", CultureInfo.InvariantCulture), + ["TaxIncluded"] = task.TaxIncluded ? "是" : "否", + ["DueDate"] = task.DueDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + }); + } + return result; + } + + /// Header placeholder names; must match the keys of . + private static readonly string[] HeaderFields = + [ + "ContractNo", "SupplierName", "SupplierContact", "SupplierPhone", "CustomerOrderNo", "SignedDate", + "RequiredCompletionDate", "PaymentTerms", "Currency", "Status", "Version", "LineCount", "TotalAmount", + "GeneratedDate", "Terms", + ]; + + /// Every placeholder name a purchase-contract template may use (header + line). + public static IReadOnlyList FieldNames { get; } = [.. HeaderFields, .. Fields.LineFields.Where(x => !HeaderFields.Contains(x, StringComparer.OrdinalIgnoreCase))]; +} + +/// Absolute path of the XLSX template used for purchase-contract exports. +public sealed record PurchaseContractTemplateOptions(string TemplatePath); diff --git a/src/Leiren.Erp.Application/Purchasing/PurchaseService.cs b/src/Leiren.Erp.Application/Purchasing/PurchaseService.cs new file mode 100644 index 0000000..0ac0575 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchaseService.cs @@ -0,0 +1,723 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Purchasing; + +public sealed class PurchaseService(IPurchasingDbContext db) +{ + // ---------- Purchase tasks ---------- + + public async Task> ListTasksAsync( + Guid? salesOrderId, Guid? purchaseContractId, string? status, string? search, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.PurchaseTasks.AsNoTracking().AsQueryable(); + if (salesOrderId is not null) query = query.Where(x => x.SalesOrderId == salesOrderId.Value); + if (purchaseContractId is not null) query = query.Where(x => x.PurchaseContractId == purchaseContractId.Value); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new PurchasingValidationException(nameof(status), "采购任务状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.ContentDescription.Contains(term) || + x.SupplierName.Contains(term) || + x.SalesOrderNo.Contains(term) || + (x.CustomerPoNo != null && x.CustomerPoNo.Contains(term)) || + (x.InternalSku != null && x.InternalSku.Contains(term)) || + (x.CustomerSku != null && x.CustomerSku.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToListItem).ToList(); + } + + /// + /// Purchasing page view: every non-cancelled customer order grouped with its + /// products and parts, plus the supplier and quantity currently assigned to + /// each row (TBD until a purchase plan exists). + /// + public async Task> GetOverviewAsync(CancellationToken ct = default) + { + var orders = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines) + .Where(x => x.Status != SalesOrderStatus.Cancelled) + .OrderByDescending(x => x.OrderDate) + .ThenBy(x => x.OrderNumber) + .ToListAsync(ct); + + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => x.Status != PurchaseTaskStatus.Cancelled) + .ToListAsync(ct); + + var productIds = orders.SelectMany(x => x.Lines).Select(x => x.ProductId).Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Include(x => x.Parts) + .Where(x => productIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, ct); + + var contractIds = tasks + .Where(x => x.PurchaseContractId is not null) + .Select(x => x.PurchaseContractId!.Value) + .Distinct() + .ToList(); + var contractStatuses = contractIds.Count == 0 + ? new Dictionary() + : await db.PurchaseContracts.AsNoTracking() + .Where(x => contractIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.Status, ct); + + var result = new List(orders.Count); + foreach (var order in orders) + { + var orderTasks = tasks.Where(x => x.SalesOrderId == order.Id).ToList(); + // A draft contract has not been exported/confirmed yet, so the next + // action is still the export step; only a confirmed contract can + // accept arrivals. + var planStatus = orderTasks.Count == 0 + ? "待生成采购方案" + : orderTasks.All(x => x.Status == PurchaseTaskStatus.Completed) + ? "已完成" + : orderTasks.Any(x => x.PurchaseContractId is null + || !contractStatuses.TryGetValue(x.PurchaseContractId.Value, out var status) + || status == PurchaseContractStatus.Draft) + ? "待导出采购合同" + : "待到货确认"; + + var productsDto = new List(); + foreach (var line in order.Lines.OrderBy(x => x.LineNumber)) + { + if (!products.TryGetValue(line.ProductId, out var product)) continue; + var lineTasks = orderTasks.Where(x => x.SalesOrderLineId == line.Id).ToList(); + var parts = product.Parts.Where(x => x.IsActive).OrderBy(x => x.SortOrder).ToList(); + var rows = new List(); + + if (parts.Count == 0) + { + var task = lineTasks.FirstOrDefault(x => x.ProductPartId is null); + rows.Add(new PurchaseOverviewRowDto(null, line.ProductNameZh, + SupplierNameOf(task), task?.Quantity ?? line.Quantity, task?.Unit ?? line.Unit)); + } + else + { + foreach (var part in parts) + { + var task = lineTasks.FirstOrDefault(x => x.ProductPartId == part.Id); + rows.Add(new PurchaseOverviewRowDto(part.Id, part.Name, SupplierNameOf(task), + task?.Quantity ?? line.Quantity * part.QuantityPerProduct, task?.Unit ?? part.Unit)); + } + + // A task can outlive the part it referenced; keep it visible instead of dropping it. + foreach (var task in lineTasks.Where(x => x.ProductPartId is not null && parts.All(p => p.Id != x.ProductPartId))) + rows.Add(new PurchaseOverviewRowDto(task.ProductPartId, task.ContentDescription, SupplierNameOf(task), task.Quantity, task.Unit)); + } + + productsDto.Add(new PurchaseOverviewProductDto(product.Id, line.ProductInternalSku, line.ProductNameZh, rows)); + } + + result.Add(new PurchaseOverviewDto(order.Id, order.OrderNumber, order.CustomerPoNumber, order.CustomerName, + order.Status.ToString(), order.OrderDate, order.RequiredDeliveryDate, planStatus, productsDto, + orderTasks.Count, orderTasks.Count(x => x.PurchaseContractId is null))); + } + + return result; + } + + private static string SupplierNameOf(PurchaseTask? task) + => string.IsNullOrWhiteSpace(task?.SupplierName) ? "TBD" : task!.SupplierName; + + public async Task GetTaskAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadTaskAsync(id, ct)); + + public async Task CreateTaskAsync(CreatePurchaseTaskRequest request, CancellationToken ct = default) + { + var (order, line) = await LoadConfirmedLineAsync(request.SalesOrderId, request.SalesOrderLineId, ct); + var productId = await ResolveProductPartAsync(request.ProductId ?? line.ProductId, request.ProductPartId, ct); + var supplier = await ResolveSupplierAsync(request.SupplierId, request.SupplierName, ct); + + var task = new PurchaseTask + { + SalesOrderId = order.Id, + SalesOrderLineId = line.Id, + ProductId = productId.ProductId, + ProductPartId = productId.PartId, + SalesOrderNo = order.OrderNumber, + CustomerPoNo = order.CustomerPoNumber, + InternalSku = line.ProductInternalSku, + ProductNameZh = line.ProductNameZh, + ProductNameEn = line.ProductNameEn, + CustomerSku = line.CustomerSku + }; + ApplyTaskFields(task, request.ContentDescription, request.ContentType, supplier.Id, + supplier.Name, request.Quantity, request.Unit ?? line.Unit, request.UnitPrice, + request.Currency, request.TaxIncluded, request.TaxRate, request.DueDate, + request.PurchaseRequirement, request.PackagingRequirement, line); + db.PurchaseTasks.Add(task); + await db.SaveChangesAsync(ct); + return ToDto(task); + } + + public async Task GenerateFromSalesOrderAsync( + GeneratePurchaseTasksRequest request, CancellationToken ct = default) + { + var order = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == request.SalesOrderId, ct) + ?? throw new PurchasingNotFoundException("销售订单不存在。"); + EnsureConfirmed(order); + + var lines = order.Lines.OrderBy(x => x.LineNumber).ToList(); + if (request.SalesOrderLineIds is { Count: > 0 }) + { + var wanted = request.SalesOrderLineIds.Distinct().ToList(); + var missing = wanted.Where(id => lines.All(x => x.Id != id)).ToList(); + if (missing.Count > 0) + throw new PurchasingValidationException(nameof(request.SalesOrderLineIds), "部分订单明细不属于该销售订单。"); + lines = lines.Where(x => wanted.Contains(x.Id)).ToList(); + } + + var taskedLineIds = (await db.PurchaseTasks.AsNoTracking() + .Where(x => x.SalesOrderId == order.Id && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => x.SalesOrderLineId).ToListAsync(ct)) + .ToHashSet(); + + var created = new List(); + var skipped = new List(); + var assignments = request.Assignments ?? []; + var supplierIds = assignments.Select(x => x.SupplierId).Distinct().ToList(); + var supplierMap = supplierIds.Count == 0 + ? new Dictionary() + : await db.Suppliers.AsNoTracking() + .Where(x => supplierIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, ct); + if (supplierIds.Any(id => !supplierMap.ContainsKey(id))) + throw new PurchasingValidationException(nameof(request.Assignments), "部分供应商不存在。"); + + foreach (var line in lines) + { + if (taskedLineIds.Contains(line.Id)) + { + skipped.Add(line.Id); + continue; + } + + var product = await db.Products.AsNoTracking() + .Include(x => x.Parts) + .Include(x => x.SupplierQuotes) + .SingleOrDefaultAsync(x => x.Id == line.ProductId, ct) + ?? throw new PurchasingValidationException(nameof(line.ProductId), $"订单明细 {line.LineNumber} 引用的产品不存在。"); + + var parts = product.Parts.Where(x => x.IsActive).OrderBy(x => x.SortOrder).ToList(); + if (parts.Count == 0) + { + created.Add(BuildGeneratedTask(order, line, product, part: null, product.SupplierQuotes, assignments, supplierMap)); + } + else + { + created.AddRange(parts.Select(part => + BuildGeneratedTask(order, line, product, part, product.SupplierQuotes, assignments, supplierMap))); + } + } + + db.PurchaseTasks.AddRange(created); + await db.SaveChangesAsync(ct); + return new GeneratePurchaseTasksResultDto(created.Select(x => ToDto(x)).ToList(), skipped); + } + + public async Task UpdateTaskAsync(Guid id, UpdatePurchaseTaskRequest request, CancellationToken ct = default) + { + var task = await LoadTaskAsync(id, ct); + if (task.PurchaseContractId is not null) + throw new PurchasingConflictException("采购任务已加入采购合同,不能直接编辑;请先作废该合同。"); + try { task.EnsureEditable(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + + var resolved = await ResolveProductPartAsync(request.ProductId ?? task.ProductId, request.ProductPartId, ct); + task.ProductId = resolved.ProductId; + task.ProductPartId = resolved.PartId; + var line = await db.SalesOrderLines.AsNoTracking().SingleOrDefaultAsync(x => x.Id == task.SalesOrderLineId, ct); + var supplier = await ResolveSupplierAsync(request.SupplierId, request.SupplierName, ct); + ApplyTaskFields(task, request.ContentDescription, request.ContentType, supplier.Id, + supplier.Name, request.Quantity, request.Unit, request.UnitPrice, + request.Currency, request.TaxIncluded, request.TaxRate, request.DueDate, + request.PurchaseRequirement, request.PackagingRequirement, line); + task.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(task); + } + + public async Task CancelTaskAsync(Guid id, CancellationToken ct = default) + { + var task = await LoadTaskAsync(id, ct); + if (task.PurchaseContractId is { } contractId) + { + var contract = await db.PurchaseContracts.SingleOrDefaultAsync(x => x.Id == contractId, ct); + if (contract is not null && contract.Status != PurchaseContractStatus.Draft) + throw new PurchasingConflictException("采购任务已随采购合同确认,不能单独取消;请先作废合同。"); + task.PurchaseContractId = null; + task.PurchaseContract = null; + } + + try { task.Cancel(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + } + + // ---------- Purchase contracts ---------- + + public async Task> ListContractsAsync( + string? status, string? search, int page, int pageSize, CancellationToken ct = default) + { + var query = db.PurchaseContracts.AsNoTracking().Include(x => x.Tasks).AsQueryable(); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new PurchasingValidationException(nameof(status), "采购合同状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.ContractNo.Contains(term) || x.SupplierName.Contains(term) || + (x.CustomerOrderNo != null && x.CustomerOrderNo.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new PurchaseContractListItemDto( + x.Id, x.ContractNo, x.SupplierName, x.CustomerOrderNo, x.RequiredCompletionDate, + x.Currency, x.Status.ToString(), x.TotalAmount, + x.Tasks.Count(t => t.Status != PurchaseTaskStatus.Cancelled), x.UpdatedAt)).ToList(); + } + + public async Task GetContractAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadContractAsync(id, ct)); + + public async Task CreateContractAsync(CreatePurchaseContractRequest request, CancellationToken ct = default) + { + if (request.TaskIds is null || request.TaskIds.Count == 0) + throw new PurchasingValidationException(nameof(request.TaskIds), "采购合同至少需要一个采购任务。"); + + var taskIds = request.TaskIds.Distinct().ToList(); + var tasks = await db.PurchaseTasks.Where(x => taskIds.Contains(x.Id)).ToListAsync(ct); + if (tasks.Count != taskIds.Count) + throw new PurchasingNotFoundException("部分采购任务不存在。"); + + foreach (var task in tasks) + { + if (task.Status != PurchaseTaskStatus.Pending) + throw new PurchasingConflictException($"采购任务「{task.ContentDescription}」不是待下单状态,不能加入新合同。"); + if (task.PurchaseContractId is not null) + throw new PurchasingConflictException($"采购任务「{task.ContentDescription}」已加入其他采购合同。"); + } + // A master supplier id resolves to the supplier's current name/contact + // snapshot for the contract; otherwise the task snapshot name is used. + Supplier? masterSupplier = null; + if (request.SupplierId is { } contractSupplierId) + { + masterSupplier = await db.Suppliers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == contractSupplierId, ct) + ?? throw new PurchasingValidationException(nameof(request.SupplierId), "供应商不存在。"); + if (!masterSupplier.IsActive) + throw new PurchasingValidationException(nameof(request.SupplierId), "供应商已停用,不能新建采购合同。"); + } + + var supplierName = masterSupplier?.Name ?? (string.IsNullOrWhiteSpace(request.SupplierName) + ? tasks.Select(x => x.SupplierName).FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)) ?? string.Empty + : request.SupplierName.Trim()); + if (string.IsNullOrWhiteSpace(supplierName)) + throw new PurchasingValidationException(nameof(request.SupplierName), "供应商不能为空。"); + if (tasks.Any(x => !string.IsNullOrWhiteSpace(x.SupplierName) && + !string.Equals(x.SupplierName, supplierName, StringComparison.OrdinalIgnoreCase))) + throw new PurchasingConflictException("一份采购合同只能包含同一供应商的采购任务。"); + if (request.SupplierId is not null && tasks.Any(x => x.SupplierId is not null && x.SupplierId != request.SupplierId)) + throw new PurchasingConflictException("采购任务的供应商与合同供应商不一致。"); + if (tasks.Select(x => x.Currency).Distinct(StringComparer.OrdinalIgnoreCase).Count() > 1) + throw new PurchasingConflictException("一份采购合同只能包含同一币种的采购任务。"); + + var contractNo = string.IsNullOrWhiteSpace(request.ContractNo) + ? $"PC-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString("N")[..4].ToUpperInvariant()}" + : request.ContractNo.Trim(); + if (await db.PurchaseContracts.AnyAsync(x => x.ContractNo == contractNo, ct)) + throw new PurchasingConflictException($"采购合同号 {contractNo} 已存在。"); + + var contract = new PurchaseContract + { + ContractNo = contractNo, + SupplierId = request.SupplierId ?? tasks.Select(x => x.SupplierId).FirstOrDefault(x => x is not null), + SupplierName = supplierName, + SupplierContact = TrimOrNull(request.SupplierContact) ?? masterSupplier?.ContactName, + SupplierPhone = TrimOrNull(request.SupplierPhone) ?? masterSupplier?.ContactPhone, + CustomerOrderNo = TrimOrNull(request.CustomerOrderNo) + ?? string.Join(", ", tasks.Select(x => x.SalesOrderNo).Distinct()), + SignedDate = request.SignedDate, + RequiredCompletionDate = request.RequiredCompletionDate, + PaymentTerms = TrimOrNull(request.PaymentTerms) ?? masterSupplier?.PaymentTerms, + Terms = TrimOrNull(request.Terms), + Currency = tasks[0].Currency + }; + if (contract.RequiredCompletionDate is not null && contract.SignedDate is not null && + contract.RequiredCompletionDate < contract.SignedDate) + throw new PurchasingValidationException(nameof(request.RequiredCompletionDate), "完货时间不能早于签约时间。"); + + db.PurchaseContracts.Add(contract); + foreach (var task in tasks) + { + task.PurchaseContractId = contract.Id; + task.Touch(); + } + + await db.SaveChangesAsync(ct); + return ToDto(await LoadContractAsync(contract.Id, ct)); + } + + public async Task UpdateContractAsync( + Guid id, UpdatePurchaseContractRequest request, CancellationToken ct = default) + { + var contract = await LoadContractAsync(id, ct); + if (contract.Status != PurchaseContractStatus.Draft) + throw new PurchasingConflictException("只有草稿状态的采购合同可以修改。"); + if (request.RequiredCompletionDate is not null && request.SignedDate is not null && + request.RequiredCompletionDate < request.SignedDate) + throw new PurchasingValidationException(nameof(request.RequiredCompletionDate), "完货时间不能早于签约时间。"); + + contract.CustomerOrderNo = TrimOrNull(request.CustomerOrderNo); + contract.SignedDate = request.SignedDate; + contract.RequiredCompletionDate = request.RequiredCompletionDate; + contract.PaymentTerms = TrimOrNull(request.PaymentTerms); + contract.Terms = TrimOrNull(request.Terms); + // The version changes only when a draft contract is edited; confirm locks it. + contract.Version++; + contract.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(contract); + } + + public async Task ConfirmContractAsync(Guid id, CancellationToken ct = default) + { + var contract = await LoadContractAsync(id, ct); + if (contract.Tasks.Count(x => x.Status != PurchaseTaskStatus.Cancelled) == 0) + throw new PurchasingValidationException(nameof(contract.Tasks), "采购合同没有可确认的采购任务。"); + if (contract.Tasks.Any(x => x.Status != PurchaseTaskStatus.Pending && x.Status != PurchaseTaskStatus.Cancelled)) + throw new PurchasingConflictException("合同中存在不是待下单状态的采购任务,不能确认。"); + + try { contract.Confirm(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + + foreach (var task in contract.Tasks.Where(x => x.Status == PurchaseTaskStatus.Pending)) + { + task.Status = PurchaseTaskStatus.Ordered; + task.Touch(); + } + + // A confirmed contract is an amount owed to the supplier. + db.SupplierPayables.Add(SupplierPayable.ForContract(contract)); + await db.SaveChangesAsync(ct); + return ToDto(contract); + } + + public async Task VoidContractAsync(Guid id, CancellationToken ct = default) + { + var contract = await LoadContractAsync(id, ct); + try { contract.Void(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + + foreach (var task in contract.Tasks) + { + task.PurchaseContractId = null; + if (task.Status == PurchaseTaskStatus.Ordered) + task.Status = PurchaseTaskStatus.Pending; + task.Touch(); + } + + contract.Tasks.Clear(); + var payable = await db.SupplierPayables.SingleOrDefaultAsync(x => x.PurchaseContractId == contract.Id, ct); + if (payable?.Status == SupplierPayableStatus.Paid) + throw new PurchasingConflictException("该采购合同的款项已付款,不能作废。"); + payable?.Void(); + await db.SaveChangesAsync(ct); + } + + // ---------- Arrival / completion ---------- + + public async Task RecordArrivalAsync( + Guid taskId, RecordPurchaseArrivalRequest request, CancellationToken ct = default) + { + var task = await LoadTaskAsync(taskId, ct); + if (task.Status is not (PurchaseTaskStatus.Ordered or PurchaseTaskStatus.PartiallyCompleted)) + throw new PurchasingConflictException(task.Status switch + { + PurchaseTaskStatus.Pending => "采购任务尚未通过已确认的采购合同下单,不能登记到货。", + PurchaseTaskStatus.Completed => "采购任务已全部到货,不能继续登记。", + PurchaseTaskStatus.Cancelled => "采购任务已取消,不能登记到货。", + _ => "当前采购任务状态不能登记到货。" + }); + if (request.Quantity <= 0) + throw new PurchasingValidationException(nameof(request.Quantity), "本次到货数量必须大于 0。"); + if (request.Quantity > task.RemainingQuantity) + throw new PurchasingValidationException(nameof(request.Quantity), + $"本次到货数量不能超过剩余数量 {task.RemainingQuantity}。"); + if (request.PackingRate is <= 0) + throw new PurchasingValidationException(nameof(request.PackingRate), "实际装箱率必须大于 0。"); + if (request.CartonCount is <= 0) + throw new PurchasingValidationException(nameof(request.CartonCount), "实际箱数必须大于 0。"); + foreach (var (value, field) in new[] + { + (request.CartonLength, nameof(request.CartonLength)), + (request.CartonWidth, nameof(request.CartonWidth)), + (request.CartonHeight, nameof(request.CartonHeight)), + (request.CartonGrossWeight, nameof(request.CartonGrossWeight)), + (request.CartonNetWeight, nameof(request.CartonNetWeight)) + }) + { + if (value is < 0) + throw new PurchasingValidationException(field, "实际包装尺寸和重量不能小于 0。"); + } + + var cartonCount = request.CartonCount + ?? (request.PackingRate is { } rate + ? (int)decimal.Ceiling(request.Quantity / rate) + : null); + var arrival = new PurchaseArrival + { + PurchaseTaskId = task.Id, + Quantity = request.Quantity, + ArrivedDate = request.ArrivedDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + PackingRate = request.PackingRate, + CartonCount = cartonCount, + CartonLength = request.CartonLength, + CartonWidth = request.CartonWidth, + CartonHeight = request.CartonHeight, + CartonGrossWeight = request.CartonGrossWeight, + CartonNetWeight = request.CartonNetWeight, + // Carton dimensions are centimetres (product-master convention); + // totals are computed here, never taken from client input. + TotalGrossWeight = cartonCount is { } c && request.CartonGrossWeight is { } gw ? c * gw : null, + TotalNetWeight = cartonCount is { } c2 && request.CartonNetWeight is { } nw ? c2 * nw : null, + TotalCbm = cartonCount is { } c3 && request.CartonLength is { } l && request.CartonWidth is { } w && request.CartonHeight is { } h + ? decimal.Round(l * w * h / 1_000_000m * c3, 4, MidpointRounding.AwayFromZero) + : null, + ExceptionNote = TrimOrNull(request.ExceptionNote), + Remark = TrimOrNull(request.Remark) + }; + + db.PurchaseArrivals.Add(arrival); + task.ApplyArrival(request.Quantity); + + if (task.PurchaseContractId is { } contractId) + { + var contract = await LoadContractAsync(contractId, ct); + contract.RefreshProgress(); + } + + await db.SaveChangesAsync(ct); + return ToDto(arrival); + } + + // ---------- Helpers ---------- + + private async Task<(SalesOrder Order, SalesOrderLine Line)> LoadConfirmedLineAsync( + Guid salesOrderId, Guid salesOrderLineId, CancellationToken ct) + { + var order = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == salesOrderId, ct) + ?? throw new PurchasingNotFoundException("销售订单不存在。"); + EnsureConfirmed(order); + var line = order.Lines.SingleOrDefault(x => x.Id == salesOrderLineId) + ?? throw new PurchasingValidationException(nameof(salesOrderLineId), "订单明细不属于该销售订单。"); + return (order, line); + } + + private static void EnsureConfirmed(SalesOrder order) + { + if (order.Status != SalesOrderStatus.Confirmed) + throw new PurchasingConflictException("只有已确认的销售订单可以生成采购任务。"); + } + + private PurchaseTask BuildGeneratedTask( + SalesOrder order, SalesOrderLine line, Product product, ProductPart? part, + IReadOnlyCollection quotes, + IReadOnlyList assignments, + IReadOnlyDictionary suppliers) + { + var quote = quotes + .Where(x => x.ProductPartId == part?.Id) + .OrderByDescending(x => x.IsDefault) + .ThenByDescending(x => x.CreatedAt) + .FirstOrDefault(); + var assignment = assignments + .FirstOrDefault(x => x.SalesOrderLineId == line.Id && x.ProductPartId == part?.Id); + var supplier = assignment is null ? null : suppliers[assignment.SupplierId]; + + var contentType = part is null + ? PurchaseContentType.Finished + : ParseContentType(part.PartType.ToString()); + if (!string.IsNullOrWhiteSpace(assignment?.ContentType)) + contentType = ParseContentType(assignment!.ContentType); + + return new PurchaseTask + { + SalesOrderId = order.Id, + SalesOrderLineId = line.Id, + ProductId = product.Id, + ProductPartId = part?.Id, + SalesOrderNo = order.OrderNumber, + CustomerPoNo = order.CustomerPoNumber, + InternalSku = line.ProductInternalSku, + ProductNameZh = line.ProductNameZh, + ProductNameEn = line.ProductNameEn, + CustomerSku = line.CustomerSku, + ContentDescription = assignment is { ContentDescription: { Length: > 0 } description } + ? description.Trim() + : part?.Name ?? line.ProductNameZh, + ContentType = contentType, + SupplierId = assignment?.SupplierId ?? quote?.SupplierId, + SupplierName = supplier?.Name ?? quote?.SupplierName ?? string.Empty, + Quantity = part is null ? line.Quantity : line.Quantity * part.QuantityPerProduct, + Unit = assignment?.Unit is { Length: > 0 } unit ? unit.Trim() : part?.Unit ?? line.Unit, + UnitPrice = assignment?.UnitPrice ?? quote?.UnitPrice ?? 0, + Currency = assignment?.Currency is { Length: > 0 } currency ? currency.Trim() : quote?.Currency ?? "CNY", + TaxIncluded = assignment?.TaxIncluded ?? quote?.TaxIncluded ?? false, + TaxRate = assignment?.TaxRate ?? quote?.TaxRate ?? 0, + DueDate = line.RequiredDeliveryDate ?? order.RequiredDeliveryDate, + PurchaseRequirement = product.PurchaseRequirement, + PackagingRequirement = product.PackagingNote + }; + } + + private async Task<(Guid? ProductId, Guid? PartId)> ResolveProductPartAsync( + Guid? productId, Guid? partId, CancellationToken ct) + { + if (partId is not null) + { + var part = await db.ProductParts.AsNoTracking().SingleOrDefaultAsync(x => x.Id == partId.Value, ct) + ?? throw new PurchasingValidationException(nameof(partId), "产品部件不存在。"); + if (productId is not null && part.ProductId != productId.Value) + throw new PurchasingValidationException(nameof(partId), "产品部件不属于指定产品。"); + return (part.ProductId, part.Id); + } + + if (productId is not null && !await db.Products.AnyAsync(x => x.Id == productId.Value, ct)) + throw new PurchasingValidationException(nameof(productId), "产品不存在。"); + return (productId, null); + } + + /// + /// Resolves an optional master supplier id to the snapshot name stored on the + /// task. Without an id the caller-provided (snapshot) name is kept as-is. + /// + private async Task<(Guid? Id, string? Name)> ResolveSupplierAsync( + Guid? supplierId, string? supplierName, CancellationToken ct) + { + if (supplierId is not { } id) return (null, supplierName); + var supplier = await db.Suppliers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new PurchasingValidationException(nameof(supplierId), "供应商不存在。"); + if (!supplier.IsActive) + throw new PurchasingValidationException(nameof(supplierId), "供应商已停用,不能用于采购任务。"); + return (supplier.Id, supplier.Name); + } + + private static void ApplyTaskFields( + PurchaseTask task, string? contentDescription, string? contentType, Guid? supplierId, + string? supplierName, decimal quantity, string? unit, decimal unitPrice, string? currency, + bool taxIncluded, decimal taxRate, DateOnly? dueDate, string? purchaseRequirement, + string? packagingRequirement, SalesOrderLine? line) + { + if (quantity <= 0) + throw new PurchasingValidationException(nameof(quantity), "采购数量必须大于 0。"); + if (unitPrice < 0) + throw new PurchasingValidationException(nameof(unitPrice), "采购单价不能小于 0。"); + if (taxRate is < 0 or > 100) + throw new PurchasingValidationException(nameof(taxRate), "税率必须在 0 到 100 之间(百分数)。"); + if (quantity < task.ArrivedQuantity) + throw new PurchasingValidationException(nameof(quantity), "采购数量不能小于已到货数量。"); + + var normalizedCurrency = string.IsNullOrWhiteSpace(currency) ? "CNY" : currency.Trim().ToUpperInvariant(); + if (normalizedCurrency.Length != 3) + throw new PurchasingValidationException(nameof(currency), "币种必须是 3 位代码,如 CNY、USD。"); + + task.ContentDescription = string.IsNullOrWhiteSpace(contentDescription) + ? (line?.ProductNameZh ?? task.ContentDescription) + : contentDescription.Trim(); + if (string.IsNullOrWhiteSpace(task.ContentDescription)) + throw new PurchasingValidationException(nameof(contentDescription), "采购内容不能为空。"); + task.ContentType = ParseContentType(contentType); + task.SupplierId = supplierId; + task.SupplierName = (supplierName ?? string.Empty).Trim(); + task.Quantity = quantity; + task.Unit = string.IsNullOrWhiteSpace(unit) ? (line?.Unit ?? task.Unit) : unit.Trim(); + if (string.IsNullOrWhiteSpace(task.Unit)) + throw new PurchasingValidationException(nameof(unit), "采购单位不能为空。"); + task.UnitPrice = unitPrice; + task.Currency = normalizedCurrency; + task.TaxIncluded = taxIncluded; + task.TaxRate = taxRate; + task.DueDate = dueDate; + task.PurchaseRequirement = TrimOrNull(purchaseRequirement); + task.PackagingRequirement = TrimOrNull(packagingRequirement); + } + + private async Task LoadTaskAsync(Guid id, CancellationToken ct) + => await db.PurchaseTasks + .Include(x => x.Arrivals) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new PurchasingNotFoundException("采购任务不存在。"); + + private async Task LoadContractAsync(Guid id, CancellationToken ct) + => await db.PurchaseContracts + .Include(x => x.Tasks) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new PurchasingNotFoundException("采购合同不存在。"); + + private static PurchaseContentType ParseContentType(string? value) + => string.IsNullOrWhiteSpace(value) + ? PurchaseContentType.Finished + : Enum.TryParse(value, ignoreCase: true, out var parsed) + ? parsed + : throw new PurchasingValidationException(nameof(value), "采购内容类型无效。"); + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static PurchaseTaskListItemDto ToListItem(PurchaseTask t) => new( + t.Id, t.SalesOrderId, t.SalesOrderLineId, t.PurchaseContractId, + t.ProductId, t.ProductPartId, t.SupplierId, t.SalesOrderNo, + t.CustomerPoNo, t.InternalSku, t.CustomerSku, t.ContentDescription, t.ContentType.ToString(), + t.SupplierName, t.Quantity, t.Unit, t.UnitPrice, t.Currency, t.TaxIncluded, t.TaxRate, t.Amount, t.DueDate, + t.Status.ToString(), t.ArrivedQuantity, t.RemainingQuantity, t.UpdatedAt); + + private static PurchaseTaskDto ToDto(PurchaseTask t) => new( + t.Id, t.SalesOrderId, t.SalesOrderLineId, t.PurchaseContractId, t.ProductId, t.ProductPartId, + t.SalesOrderNo, t.CustomerPoNo, t.InternalSku, t.ProductNameZh, t.ProductNameEn, t.CustomerSku, + t.ContentDescription, t.ContentType.ToString(), t.SupplierId, t.SupplierName, t.Quantity, t.Unit, + t.UnitPrice, t.Currency, t.TaxIncluded, t.TaxRate, t.Amount, t.DueDate, t.PurchaseRequirement, + t.PackagingRequirement, t.Status.ToString(), t.ArrivedQuantity, t.RemainingQuantity, + t.CreatedAt, t.UpdatedAt, t.CompletedAt, + t.Arrivals.OrderBy(x => x.ArrivedDate).ThenBy(x => x.CreatedAt).Select(ToDto).ToList()); + + private static PurchaseArrivalDto ToDto(PurchaseArrival a) => new( + a.Id, a.PurchaseTaskId, a.Quantity, a.ArrivedDate, a.PackingRate, a.CartonCount, + a.CartonLength, a.CartonWidth, a.CartonHeight, a.CartonGrossWeight, a.CartonNetWeight, + a.TotalGrossWeight, a.TotalNetWeight, a.TotalCbm, a.ExceptionNote, a.Remark, a.CreatedAt); + + private static PurchaseContractDto ToDto(PurchaseContract c) => new( + c.Id, c.ContractNo, c.SupplierId, c.SupplierName, c.SupplierContact, c.SupplierPhone, + c.CustomerOrderNo, c.SignedDate, c.RequiredCompletionDate, c.PaymentTerms, c.Terms, + c.Currency, c.Status.ToString(), c.Version, c.TotalAmount, c.CreatedAt, c.UpdatedAt, + c.ConfirmedAt, c.CompletedAt, + c.Tasks.OrderBy(x => x.CreatedAt).Select(ToListItem).ToList()); +} diff --git a/src/Leiren.Erp.Application/Purchasing/PurchasingExceptions.cs b/src/Leiren.Erp.Application/Purchasing/PurchasingExceptions.cs new file mode 100644 index 0000000..5c8cb0c --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchasingExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Purchasing; + +public sealed class PurchasingNotFoundException(string message) : Exception(message); + +public sealed class PurchasingConflictException(string message) : Exception(message); + +public sealed class PurchasingValidationException(IReadOnlyDictionary errors) + : Exception("采购资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public PurchasingValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Sales/ISalesDbContext.cs b/src/Leiren.Erp.Application/Sales/ISalesDbContext.cs new file mode 100644 index 0000000..4eaeefe --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/ISalesDbContext.cs @@ -0,0 +1,25 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Sales; + +/// +/// EF Core boundary for the Sales module; implemented by Infrastructure. +/// Purchase/shipment/billing sets are read-only here and used solely to +/// compute the workbench summary from source records; Sales never writes them. +/// +public interface ISalesDbContext +{ + DbSet Customers { get; } + DbSet SalesOrders { get; } + DbSet SalesOrderLines { get; } + DbSet Products { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseArrivals { get; } + DbSet ShipmentLines { get; } + DbSet SupplierInvoiceNotices { get; } + DbSet SupplierInvoiceNoticeLines { get; } + DbSet SupplierInvoices { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Sales/PoExcelImportService.cs b/src/Leiren.Erp.Application/Sales/PoExcelImportService.cs new file mode 100644 index 0000000..b42ced7 --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/PoExcelImportService.cs @@ -0,0 +1,727 @@ +using System.Globalization; +using ClosedXML.Excel; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Sales; + +/// Order-header values supplied alongside the uploaded PO workbook (multipart form fields). +public sealed record PoExcelImportOptions( + Guid? CustomerId, + string? CustomerPoNumber, + string? OrderNumber, + DateOnly? OrderDate, + DateOnly? RequiredDeliveryDate, + string? Currency, + string? TransportMode, + string? LoadingPort, + string? DestinationPort, + string? DestinationCountry, + string? TradeTerm, + string? PaymentTerms, + string? ShippingNote, + string? Remark, + string? SheetName, + bool CreateDraft, + bool AttachOriginal, + string? UploadedBy); + +/// +/// Header-driven customer-PO (.xlsx) importer. Columns are located by header +/// name (Chinese/English aliases), never by fixed cell coordinates, and the +/// header row / worksheet are discovered from those names. Every non-blank +/// data row is returned with its real worksheet row number and explicit +/// errors; a draft order is created only when every row is valid, so no row +/// can be silently skipped. +/// +public sealed class PoExcelImportService( + ISalesDbContext db, + SalesOrderService salesOrders, + FileService files, + FileStorageOptions storageOptions) +{ + private const string FieldInternalSku = "InternalSku"; + private const string FieldCustomerSku = "CustomerSku"; + private const string FieldCustomerProductName = "CustomerProductName"; + private const string FieldQuantity = "Quantity"; + private const string FieldUnit = "Unit"; + private const string FieldPackingRate = "PackingRate"; + private const string FieldUnitPrice = "UnitPrice"; + private const string FieldAmount = "Amount"; + private const string FieldRequiredDeliveryDate = "RequiredDeliveryDate"; + private const string FieldCustomerRemark = "CustomerRemark"; + private const string FieldRemark = "Remark"; + + private static readonly string[] RequiredFields = [FieldInternalSku, FieldQuantity]; + + public async Task ImportAsync( + Stream content, + string? fileName, + string? contentType, + PoExcelImportOptions options, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(options); + + var safeFileName = fileName?.Trim() ?? string.Empty; + if (safeFileName.Length == 0 || + !string.Equals(Path.GetExtension(safeFileName), ".xlsx", StringComparison.OrdinalIgnoreCase)) + throw new SalesValidationException("file", "PO 导入只接受真实 .xlsx 文件。"); + + if (options.AttachOriginal && !options.CreateDraft) + throw new SalesValidationException( + "attachOriginal", + "保存原始 PO 附件需要同时创建草稿订单(createDraft=true),因为附件必须关联到订单。"); + + var bytes = await ReadAllBytesAsync(content, ct); + + var preview = await ParsePreviewAsync(bytes, safeFileName, options.SheetName, ct); + if (!options.CreateDraft || !preview.CanCreateDraft) + return new PoImportResultDto(preview, null, null); + + if (options.CustomerId is not { } customerId || customerId == Guid.Empty) + throw new SalesValidationException("customerId", "创建草稿订单时必须选择客户。"); + + var request = new SaveSalesOrderRequest( + options.OrderNumber, + customerId, + options.CustomerPoNumber, + options.OrderDate, + options.RequiredDeliveryDate, + options.Currency, + options.TransportMode, + options.LoadingPort, + options.DestinationPort, + options.DestinationCountry, + options.TradeTerm, + options.PaymentTerms, + options.ShippingNote, + PoAttachmentReference: null, + PoAttachmentFileName: null, + options.Remark, + preview.Rows.Select(x => new SalesOrderLineRequest( + x.ProductId!.Value, + x.CustomerSku, + x.CustomerProductName, + x.Quantity!.Value, + x.Unit, + x.PackingRate, + x.UnitPrice ?? 0m, + x.RequiredDeliveryDate, + x.CustomerRemark, + x.Remark)).ToList()); + + var created = await salesOrders.CreateAsync(request, ct); + + FileAttachmentDto? attachment = null; + if (options.AttachOriginal) + { + await using var original = new MemoryStream(bytes, writable: false); + attachment = await files.UploadAsync(new UploadFileCommand( + OwnerType: "SalesOrder", + OwnerId: created.Id, + Category: "CustomerPO", + Description: "原始客户 PO Excel(PO 导入)", + OriginalFileName: safeFileName, + ContentType: contentType, + Content: original, + UploadedByUserId: null, + UploadedBy: options.UploadedBy), ct); + + // Point the order at the stored original PO through the existing + // attachment reference fields; the file itself stays in FileService. + var order = await db.SalesOrders.SingleAsync(x => x.Id == created.Id, ct); + order.PoAttachmentReference = attachment.Id.ToString("D"); + order.PoAttachmentFileName = attachment.OriginalFileName; + order.Touch(); + await db.SaveChangesAsync(ct); + created = await salesOrders.GetAsync(created.Id, ct); + } + + return new PoImportResultDto(preview, created, attachment); + } + + // ---------- Workbook parsing ---------- + + private async Task ParsePreviewAsync( + byte[] bytes, string fileName, string? requestedSheetName, CancellationToken ct) + { + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(new MemoryStream(bytes, writable: false)); + } + catch (Exception ex) + { + throw new SalesValidationException("file", $"Excel 文件无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + var sheets = workbook.Worksheets.ToList(); + var availableSheets = sheets.Select(x => x.Name).ToList(); + if (sheets.Count == 0) + { + return EmptyPreview(fileName, null, availableSheets, + [new PoImportIssueDto(null, "file", "工作簿中没有任何工作表。")]); + } + + SheetCandidate? candidate = null; + var selectionIssues = new List(); + + if (!string.IsNullOrWhiteSpace(requestedSheetName)) + { + var sheet = sheets.FirstOrDefault(x => + string.Equals(x.Name, requestedSheetName.Trim(), StringComparison.OrdinalIgnoreCase)); + if (sheet is null) + { + return EmptyPreview(fileName, requestedSheetName.Trim(), availableSheets, + [new PoImportIssueDto(null, "sheetName", + $"工作表「{requestedSheetName.Trim()}」不存在。可用工作表:{string.Join("、", availableSheets)}。")]); + } + + var (found, ambiguity) = ScanSheet(sheet); + if (ambiguity is not null) + return EmptyPreview(fileName, sheet.Name, availableSheets, [ambiguity]); + if (found is null) + return EmptyPreview(fileName, sheet.Name, availableSheets, MissingHeaderIssues(sheet)); + candidate = found; + } + else + { + var candidates = new List(); + var ambiguities = new List(); + foreach (var sheet in sheets) + { + var (found, ambiguity) = ScanSheet(sheet); + if (found is not null) candidates.Add(found); + if (ambiguity is not null) ambiguities.Add(ambiguity); + } + + if (ambiguities.Count > 0) + return EmptyPreview(fileName, null, availableSheets, ambiguities); + if (candidates.Count > 1) + { + return EmptyPreview(fileName, null, availableSheets, + [new PoImportIssueDto(null, "sheetName", + $"多个工作表都包含可识别的 PO 表头({string.Join("、", candidates.Select(x => x.Sheet.Name))}),无法确定导入哪一个,请指定 sheetName。")]); + } + if (candidates.Count == 0) + { + return EmptyPreview(fileName, null, availableSheets, + [new PoImportIssueDto(null, "headers", + $"未在任何工作表中找到同时包含必填表头「{FieldLabel(FieldInternalSku)}」和「{FieldLabel(FieldQuantity)}」的表头行。" + + $"必填表头:{string.Join("、", RequiredFields.Select(FieldLabel))}。请检查表头名称,或指定 sheetName 后重试。")]); + } + candidate = candidates[0]; + } + + selectionIssues.AddRange(candidate.Map.Issues); + + var parsedRows = ParseDataRows(candidate); + await ResolveProductsAsync(parsedRows, ct); + + var rows = parsedRows.Select(x => x.ToDto()).ToList(); + if (rows.Count == 0) + selectionIssues.Add(new PoImportIssueDto(null, "rows", "表头之后没有数据行。")); + + var canCreate = selectionIssues.Count == 0 && rows.Count > 0 && rows.All(x => x.IsValid); + return new PoImportPreviewDto( + fileName, + candidate.Sheet.Name, + availableSheets, + candidate.HeaderRow, + candidate.Map.Headers, + candidate.Map.UnrecognizedHeaders, + selectionIssues, + rows, + candidate.BlankRowNumbers, + rows.Count, + rows.Count(x => x.IsValid), + rows.Count(x => !x.IsValid), + canCreate); + } + } + + private static PoImportPreviewDto EmptyPreview( + string fileName, string? sheetName, IReadOnlyList availableSheets, + IReadOnlyList issues) => new( + fileName, sheetName, availableSheets, null, [], [], issues, [], [], 0, 0, 0, false); + + /// Finds the header row of one sheet by recognized header names (first 50 used rows). + private static (SheetCandidate? Candidate, PoImportIssueDto? Ambiguity) ScanSheet(IXLWorksheet sheet) + { + var range = sheet.RangeUsed(); + if (range is null) return (null, null); + + var firstRow = range.FirstRow().RowNumber(); + var lastRow = range.LastRow().RowNumber(); + var firstColumn = range.FirstColumn().ColumnNumber(); + var lastColumn = range.LastColumn().ColumnNumber(); + var scanEnd = Math.Min(lastRow, firstRow + 49); + + var qualified = new List(); + for (var row = firstRow; row <= scanEnd; row++) + { + var map = MapHeaders(sheet, row, firstColumn, lastColumn); + if (map.Columns.ContainsKey(FieldInternalSku) && map.Columns.ContainsKey(FieldQuantity)) + qualified.Add(new SheetCandidate(sheet, row, firstColumn, lastColumn, lastRow, map)); + } + + if (qualified.Count == 0) return (null, null); + + var bestScore = qualified.Max(x => x.Map.Columns.Count); + var best = qualified.Where(x => x.Map.Columns.Count == bestScore).ToList(); + if (best.Count > 1) + { + return (null, new PoImportIssueDto(null, "headers", + $"工作表「{sheet.Name}」中第 {string.Join("、", best.Select(x => x.HeaderRow))} 行都包含同等完整的 PO 表头,表头行不明确,请删除多余表头行或整理文件后重试。")); + } + return (best[0], null); + } + + private static IReadOnlyList MissingHeaderIssues(IXLWorksheet sheet) + { + var range = sheet.RangeUsed(); + if (range is null) + return [new PoImportIssueDto(null, "headers", $"工作表「{sheet.Name}」是空的,没有可识别的表头行。")]; + + var firstRow = range.FirstRow().RowNumber(); + var lastRow = range.LastRow().RowNumber(); + var firstColumn = range.FirstColumn().ColumnNumber(); + var lastColumn = range.LastColumn().ColumnNumber(); + var scanEnd = Math.Min(lastRow, firstRow + 49); + + HeaderMap? best = null; + var bestRow = firstRow; + for (var row = firstRow; row <= scanEnd; row++) + { + var map = MapHeaders(sheet, row, firstColumn, lastColumn); + if (best is null || map.Columns.Count > best.Columns.Count) + { + best = map; + bestRow = row; + } + } + + var issues = new List(); + if (best is not null) issues.AddRange(best.Issues); + foreach (var field in RequiredFields.Where(f => best is null || !best.Columns.ContainsKey(f))) + { + issues.Add(new PoImportIssueDto(bestRow, field, + $"缺少必填表头「{FieldLabel(field)}」。已识别表头:{(best is null || best.Headers.Count == 0 ? "(无)" : string.Join("、", best.Headers))}。")); + } + if (issues.Count == 0) + issues.Add(new PoImportIssueDto(null, "headers", $"工作表「{sheet.Name}」中未找到可识别的表头行。")); + return issues; + } + + private static HeaderMap MapHeaders(IXLWorksheet sheet, int row, int firstColumn, int lastColumn) + { + var map = new HeaderMap(); + for (var column = firstColumn; column <= lastColumn; column++) + { + var header = CellText(sheet.Cell(row, column)); + if (string.IsNullOrWhiteSpace(header)) continue; + map.Headers.Add(header); + map.HeadersInColumnOrder[column] = header; + + if (!HeaderAliases.TryGetValue(NormalizeHeader(header), out var field)) + { + map.UnrecognizedHeaders.Add(header); + continue; + } + if (map.Columns.TryGetValue(field, out var existingColumn)) + { + map.Issues.Add(new PoImportIssueDto(row, field, + $"表头字段「{FieldLabel(field)}」不明确:第 {XLHelper.GetColumnLetterFromNumber(existingColumn)} 列与第 {XLHelper.GetColumnLetterFromNumber(column)} 列都映射到该字段,请只保留一列。")); + continue; + } + map.Columns[field] = column; + } + return map; + } + + private static List ParseDataRows(SheetCandidate candidate) + { + var sheet = candidate.Sheet; + var rows = new List(); + + for (var rowNumber = candidate.HeaderRow + 1; rowNumber <= candidate.LastRow; rowNumber++) + { + var raw = new Dictionary(StringComparer.Ordinal); + var anyValue = false; + for (var column = candidate.FirstColumn; column <= candidate.LastColumn; column++) + { + var text = CellText(sheet.Cell(rowNumber, column)); + if (!string.IsNullOrWhiteSpace(text)) anyValue = true; + if (candidate.Map.HeadersInColumnOrder.TryGetValue(column, out var header)) + { + if (header is not null) + { + var key = header; + if (raw.ContainsKey(key)) key = $"{header}(列 {XLHelper.GetColumnLetterFromNumber(column)})"; + raw[key] = text; + } + } + } + + if (!anyValue) + { + candidate.BlankRowNumbers.Add(rowNumber); + continue; + } + + var parsed = new ParsedRow { RowNumber = rowNumber, RawValues = raw }; + string? Text(string field) => + candidate.Map.Columns.TryGetValue(field, out var col) ? CellText(sheet.Cell(rowNumber, col)) : null; + IXLCell? Cell(string field) => + candidate.Map.Columns.TryGetValue(field, out var col) ? sheet.Cell(rowNumber, col) : null; + + parsed.InternalSku = Text(FieldInternalSku); + if (string.IsNullOrWhiteSpace(parsed.InternalSku)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldInternalSku, "内部货号为空。")); + parsed.CustomerSku = Text(FieldCustomerSku); + parsed.CustomerProductName = Text(FieldCustomerProductName); + parsed.Unit = Text(FieldUnit); + parsed.CustomerRemark = Text(FieldCustomerRemark); + parsed.Remark = Text(FieldRemark); + + var quantityCell = Cell(FieldQuantity); + var quantityText = Text(FieldQuantity); + if (quantityCell is null || string.IsNullOrWhiteSpace(quantityText)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldQuantity, "数量为空。")); + else if (!TryParseDecimal(quantityCell, out var quantity)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldQuantity, $"数量「{quantityText}」不是有效数字。")); + else if (quantity <= 0) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldQuantity, "数量必须大于 0。")); + else + parsed.Quantity = quantity; + + var packingText = Text(FieldPackingRate); + if (!string.IsNullOrWhiteSpace(packingText)) + { + if (!TryParseDecimal(Cell(FieldPackingRate)!, out var packing)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldPackingRate, $"装箱率「{packingText}」不是有效数字。")); + else if (packing <= 0 || packing != Math.Truncate(packing) || packing > int.MaxValue) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldPackingRate, $"装箱率「{packingText}」必须是大于 0 的整数。")); + else + parsed.PackingRate = (int)packing; + } + + var priceText = Text(FieldUnitPrice); + if (!string.IsNullOrWhiteSpace(priceText)) + { + if (!TryParseDecimal(Cell(FieldUnitPrice)!, out var price)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldUnitPrice, $"单价「{priceText}」不是有效数字。")); + else if (price < 0) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldUnitPrice, "单价不能小于 0。")); + else + parsed.UnitPrice = price; + } + + var amountText = Text(FieldAmount); + if (!string.IsNullOrWhiteSpace(amountText)) + { + if (!TryParseDecimal(Cell(FieldAmount)!, out var amount)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldAmount, $"金额「{amountText}」不是有效数字。")); + else + { + parsed.Amount = amount; + if (parsed.Quantity is { } q && parsed.UnitPrice is { } p && + Math.Abs(amount - q * p) > 0.05m) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldAmount, + $"金额 {amount} 与数量×单价({q}×{p}={q * p})不一致。")); + } + } + + var dateCell = Cell(FieldRequiredDeliveryDate); + var dateText = Text(FieldRequiredDeliveryDate); + if (dateCell is not null && !string.IsNullOrWhiteSpace(dateText)) + { + if (TryParseDate(dateCell, out var date)) + parsed.RequiredDeliveryDate = date; + else + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldRequiredDeliveryDate, $"交期「{dateText}」不是有效日期。")); + } + + rows.Add(parsed); + } + return rows; + } + + private async Task ResolveProductsAsync(List rows, CancellationToken ct) + { + var skus = rows.Select(x => x.InternalSku) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x!.Trim()) + .Distinct(StringComparer.Ordinal) + .ToList(); + if (skus.Count == 0) return; + + var products = (await db.Products.AsNoTracking() + .Where(x => skus.Contains(x.InternalSku)) + .Select(x => new { x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status }) + .ToListAsync(ct)) + .Select(x => new ProductLookup(x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status)) + .ToList(); + + // Case-variant SKUs are not matched by the exact query above; fall back + // to a key-only scan so they resolve instead of being reported missing. + var missing = skus.Where(s => products.All(p => + !string.Equals(p.InternalSku, s, StringComparison.OrdinalIgnoreCase))).ToList(); + if (missing.Count > 0) + { + var allKeys = (await db.Products.AsNoTracking() + .Select(x => new { x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status }) + .ToListAsync(ct)) + .Select(x => new ProductLookup(x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status)); + products.AddRange(allKeys.Where(p => missing.Contains(p.InternalSku, StringComparer.OrdinalIgnoreCase))); + } + + var bySku = products + .GroupBy(x => x.InternalSku, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + + foreach (var row in rows) + { + if (string.IsNullOrWhiteSpace(row.InternalSku)) continue; + var sku = row.InternalSku.Trim(); + if (!bySku.TryGetValue(sku, out var matches)) + { + row.Errors.Add(new PoImportIssueDto(row.RowNumber, FieldInternalSku, $"产品货号「{sku}」不存在。")); + continue; + } + if (matches.Count > 1) + { + row.Errors.Add(new PoImportIssueDto(row.RowNumber, FieldInternalSku, $"产品货号「{sku}」对应多个产品,无法确定。")); + continue; + } + var product = matches[0]; + row.ProductId = product.Id; + row.ProductInternalSku = product.InternalSku; + row.ProductNameZh = product.NameZh; + row.ProductNameEn = product.NameEn; + if (product.Status != ProductStatus.Published) + row.Errors.Add(new PoImportIssueDto(row.RowNumber, FieldInternalSku, + $"产品 {product.InternalSku} 未发布(当前状态 {product.Status}),不能加入订单。")); + } + } + + // ---------- Cell helpers ---------- + + private static string? CellText(IXLCell cell) + { + if (cell.IsEmpty()) return null; + try + { + if (cell.DataType == XLDataType.DateTime) + return cell.GetDateTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + var text = cell.GetString(); + return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + } + catch (Exception) + { + var text = cell.Value.ToString(); + return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + } + } + + private static bool TryParseDecimal(IXLCell cell, out decimal value) + { + value = 0; + if (cell.IsEmpty()) return false; + if (cell.DataType == XLDataType.Number) + { + try { value = cell.GetValue(); return true; } + catch (Exception) { return false; } + } + if (cell.DataType is XLDataType.DateTime or XLDataType.Boolean) return false; + + var text = CellText(cell); + if (string.IsNullOrWhiteSpace(text)) return false; + var cleaned = text.Replace(",", string.Empty).Replace(" ", string.Empty) + .Trim('¥', '¥', '$', '€', '£'); + return decimal.TryParse(cleaned, NumberStyles.Number | NumberStyles.AllowCurrencySymbol, + CultureInfo.InvariantCulture, out value) + || decimal.TryParse(cleaned, NumberStyles.Number, CultureInfo.CurrentCulture, out value); + } + + private static bool TryParseDate(IXLCell cell, out DateOnly value) + { + value = default; + if (cell.IsEmpty()) return false; + if (cell.DataType == XLDataType.DateTime) + { + value = DateOnly.FromDateTime(cell.GetDateTime()); + return true; + } + if (cell.DataType == XLDataType.Number) + { + try + { + var serial = cell.GetValue(); + if (serial is <= 0 or > 100000) return false; + value = DateOnly.FromDateTime(DateTime.FromOADate(serial)); + return true; + } + catch (Exception) { return false; } + } + + var text = CellText(cell); + if (string.IsNullOrWhiteSpace(text)) return false; + // ISO-style formats first so slash dates are not silently reinterpreted. + string[] formats = + [ + "yyyy-MM-dd", "yyyy/MM/dd", "yyyy/M/d", "yyyy.MM.dd", "yyyy年M月d日", + "M/d/yyyy", "MM/dd/yyyy", "d/M/yyyy", "dd/MM/yyyy" + ]; + if (DateOnly.TryParseExact(text, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) + return true; + return DateOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out value); + } + + private async Task ReadAllBytesAsync(Stream content, CancellationToken ct) + { + var maxBytes = storageOptions.MaxFileSizeBytes > 0 ? storageOptions.MaxFileSizeBytes : 50L * 1024 * 1024; + await using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await content.ReadAsync(chunk, ct)) > 0) + { + if (buffer.Length + read > maxBytes) + throw new SalesValidationException("file", $"PO 文件超过大小上限({maxBytes} 字节)。"); + buffer.Write(chunk, 0, read); + } + if (buffer.Length == 0) + throw new SalesValidationException("file", "PO 文件内容为空。"); + return buffer.ToArray(); + } + + // ---------- Header aliases ---------- + + private static string NormalizeHeader(string header) + => new(header.Trim().ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray()); + + private static string FieldLabel(string field) => field switch + { + FieldInternalSku => "内部货号", + FieldCustomerSku => "客户货号", + FieldCustomerProductName => "客户英文描述", + FieldQuantity => "数量", + FieldUnit => "单位", + FieldPackingRate => "装箱率", + FieldUnitPrice => "单价", + FieldAmount => "金额", + FieldRequiredDeliveryDate => "交期", + FieldCustomerRemark => "客户备注", + FieldRemark => "备注", + _ => field + }; + + private static readonly IReadOnlyDictionary HeaderAliases = BuildHeaderAliases(); + + private static IReadOnlyDictionary BuildHeaderAliases() + { + var map = new Dictionary(StringComparer.Ordinal); + void Add(string field, params string[] aliases) + { + foreach (var alias in aliases) map[NormalizeHeader(alias)] = field; + } + + Add(FieldInternalSku, + "Internal SKU", "InternalSku", "Product SKU", "Product Code", "Product No", "Product Number", + "Item Code", "Item No", "Item Number", "Article", "Article No", "Article Number", "SKU", + "内部货号", "内部编号", "产品货号", "产品编号", "产品料号", "货号", "商品编号", "料号"); + Add(FieldCustomerSku, + "Customer SKU", "Customer Item", "Customer Item No", "Customer Item Code", + "Customer Product Code", "Customer Part No", "Customer Part Number", "Customer No", + "客户货号", "客户SKU", "客户料号", "客户编号", "客户产品编号"); + Add(FieldCustomerProductName, + "Customer Product Name", "Customer Description", "Customer Product Description", + "English Description", "Product Description", "Item Description", "Description", + "Description EN", "Product Name EN", "English Name", "Product Description EN", + "英文品名", "英文名称", "英文描述", "客户品名", "客户描述", "客户产品名称", "产品英文名", "商品英文描述"); + Add(FieldQuantity, + "Quantity", "Qty", "Order Quantity", "Order Qty", "Ordered Quantity", "Ordered Qty", + "Purchase Quantity", "Quantity Ordered", "Qty Pcs", "Quantity Pcs", + "数量", "订购数量", "订单数量", "采购数量", "下单数量"); + Add(FieldUnit, + "Unit", "UOM", "Unit of Measure", "单位", "计量单位"); + Add(FieldPackingRate, + "Packing Rate", "Pack Rate", "Quantity Per Carton", "Qty Per Carton", "Pcs Per Carton", + "Pieces Per Carton", "Per Carton", "Qty Per Ctn", "Pcs Per Ctn", "Quantity Per Ctn", "Packing Quantity", + "装箱率", "每箱数量", "每箱件数", "入数", "单箱数量", "装箱数", "每箱装箱数"); + Add(FieldUnitPrice, + "Unit Price", "Price", "Unit Cost", "Sale Price", "Selling Price", "Unit Amount", + "单价", "价格", "未税单价"); + Add(FieldAmount, + "Amount", "Line Amount", "Total Amount", "Total Price", "Total", + "金额", "小计", "总金额", "行金额"); + Add(FieldRequiredDeliveryDate, + "Required Delivery Date", "Delivery Date", "Requested Delivery Date", "Requested Date", + "Required Date", "Delivery", "ETA", "ETD", "Ship Date", + "交期", "交货日期", "交货期", "要求交期", "要求交货日期", "到货日期", "出货日期"); + Add(FieldCustomerRemark, + "Customer Remark", "Customer Remarks", "Customer Note", "Customer Notes", "客户备注"); + Add(FieldRemark, + "Remark", "Remarks", "Note", "Notes", "备注", "说明"); + return map; + } + + // ---------- Internal parse state ---------- + + private sealed class HeaderMap + { + public Dictionary Columns { get; } = new(StringComparer.Ordinal); + public List Headers { get; } = []; + public List UnrecognizedHeaders { get; } = []; + public List Issues { get; } = []; + /// Column number -> original header text, for raw-row preservation. + public Dictionary HeadersInColumnOrder { get; } = new(); + } + + private sealed class SheetCandidate( + IXLWorksheet sheet, int headerRow, int firstColumn, int lastColumn, int lastRow, HeaderMap map) + { + public IXLWorksheet Sheet { get; } = sheet; + public int HeaderRow { get; } = headerRow; + public int FirstColumn { get; } = firstColumn; + public int LastColumn { get; } = lastColumn; + public int LastRow { get; } = lastRow; + public HeaderMap Map { get; } = map; + public List BlankRowNumbers { get; } = []; + } + + private sealed class ParsedRow + { + public int RowNumber { get; set; } + public string? InternalSku { get; set; } + public Guid? ProductId { get; set; } + public string? ProductInternalSku { get; set; } + public string? ProductNameZh { get; set; } + public string? ProductNameEn { get; set; } + public string? CustomerSku { get; set; } + public string? CustomerProductName { get; set; } + public decimal? Quantity { get; set; } + public string? Unit { get; set; } + public int? PackingRate { get; set; } + public decimal? UnitPrice { get; set; } + public decimal? Amount { get; set; } + public DateOnly? RequiredDeliveryDate { get; set; } + public string? CustomerRemark { get; set; } + public string? Remark { get; set; } + public IReadOnlyDictionary RawValues { get; set; } = new Dictionary(); + public List Errors { get; } = []; + + public PoImportRowDto ToDto() => new( + RowNumber, InternalSku, ProductId, ProductInternalSku, ProductNameZh, ProductNameEn, + CustomerSku, CustomerProductName, Quantity, Unit, PackingRate, UnitPrice, Amount, + RequiredDeliveryDate, CustomerRemark, Remark, RawValues, Errors.ToList()); + } + + private sealed record ProductLookup(Guid Id, string InternalSku, string NameZh, string NameEn, ProductStatus Status); +} diff --git a/src/Leiren.Erp.Application/Sales/SalesExceptions.cs b/src/Leiren.Erp.Application/Sales/SalesExceptions.cs new file mode 100644 index 0000000..4b674d4 --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/SalesExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Sales; + +public sealed class SalesNotFoundException(string message) : Exception(message); + +public sealed class SalesConflictException(string message) : Exception(message); + +public sealed class SalesValidationException(IReadOnlyDictionary errors) + : Exception("客户订单校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public SalesValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Sales/SalesOrderService.cs b/src/Leiren.Erp.Application/Sales/SalesOrderService.cs new file mode 100644 index 0000000..3390fa4 --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/SalesOrderService.cs @@ -0,0 +1,587 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Sales; + +public sealed class SalesOrderService(ISalesDbContext db) +{ + // ---------- Customers ---------- + + public async Task> ListCustomersAsync( + string? search, bool? isActive, int page, int pageSize, CancellationToken ct = default) + { + var query = db.Customers.AsNoTracking().AsQueryable(); + if (isActive is { } active) query = query.Where(x => x.IsActive == active); + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.Name.Contains(term) + || (x.Code != null && x.Code.Contains(term)) + || (x.NameEn != null && x.NameEn.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderBy(x => x.Name) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetCustomerAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadCustomerAsync(id, ct)); + + public async Task CreateCustomerAsync(SaveCustomerRequest request, CancellationToken ct = default) + { + var customer = new Customer(); + ApplyCustomer(customer, request); + await EnsureCustomerCodeAvailableAsync(customer.Code, null, ct); + db.Customers.Add(customer); + await db.SaveChangesAsync(ct); + return ToDto(customer); + } + + public async Task UpdateCustomerAsync(Guid id, SaveCustomerRequest request, CancellationToken ct = default) + { + var customer = await LoadCustomerAsync(id, ct); + ApplyCustomer(customer, request); + await EnsureCustomerCodeAvailableAsync(customer.Code, customer.Id, ct); + customer.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(customer); + } + + // ---------- Sales orders ---------- + + public async Task> ListAsync( + string? search, string? status, Guid? customerId, int page, int pageSize, CancellationToken ct = default) + { + var query = db.SalesOrders.AsNoTracking().Include(x => x.Lines).AsQueryable(); + + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new SalesValidationException(nameof(status), "客户订单状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (customerId is { } cid) query = query.Where(x => x.CustomerId == cid); + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.OrderNumber.Contains(term) + || x.CustomerPoNumber.Contains(term) + || x.CustomerName.Contains(term)); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + var summaries = await ComputeSummariesAsync(items, ct); + return items.Select(x => new SalesOrderListItemDto( + x.Id, x.OrderNumber, x.CustomerId, x.CustomerName, x.CustomerPoNumber, + x.OrderDate, x.RequiredDeliveryDate, x.Currency, x.Status.ToString(), + x.TotalAmount, x.Lines.Count, x.UpdatedAt, summaries[x.Id])).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => await ToDtoAsync(await LoadOrderAsync(id, ct), ct); + + public async Task CreateAsync(SaveSalesOrderRequest request, CancellationToken ct = default) + { + var customer = await ResolveCustomerAsync(request.CustomerId, ct); + var lines = await BuildLinesAsync(request, ct); + + var order = new SalesOrder { Status = SalesOrderStatus.Draft }; + ApplyOrder(order, request, customer); + order.OrderNumber = await ResolveOrderNumberAsync(request.OrderNumber, null, ct); + foreach (var line in lines) order.Lines.Add(line); + order.RecalculateTotal(); + + db.SalesOrders.Add(order); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(order, ct); + } + + public async Task UpdateAsync(Guid id, SaveSalesOrderRequest request, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + EnsureDraft(order); + + var customer = await ResolveCustomerAsync(request.CustomerId, ct); + var lines = await BuildLinesAsync(request, ct); + + ApplyOrder(order, request, customer); + order.OrderNumber = await ResolveOrderNumberAsync(request.OrderNumber, order.Id, ct); + + // Full-line replacement: lines are owned by the order (cascade delete). + db.SalesOrderLines.RemoveRange(order.Lines); + order.Lines.Clear(); + foreach (var line in lines) order.Lines.Add(line); + order.RecalculateTotal(); + order.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadOrderAsync(order.Id, ct), ct); + } + + public async Task ConfirmAsync(Guid id, ConfirmSalesOrderRequest? request, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + EnsureDraft(order); + + var errors = new Dictionary(); + var customer = await db.Customers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == order.CustomerId, ct); + if (customer is null) errors["CustomerId"] = ["客户不存在。"]; + else if (!customer.IsActive) errors["CustomerId"] = ["客户已停用,不能确认订单。"]; + if (string.IsNullOrWhiteSpace(order.CustomerPoNumber)) errors["CustomerPoNumber"] = ["确认前必须填写客户 PO 号。"]; + if (order.Lines.Count == 0) errors["Lines"] = ["确认前订单至少需要一条明细。"]; + + // Products must still be Published at confirmation time. + var productIds = order.Lines.Select(x => x.ProductId).Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Where(x => productIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + for (var i = 0; i < order.Lines.Count; i++) + { + var line = order.Lines[i]; + if (!products.TryGetValue(line.ProductId, out var product)) + errors[$"Lines[{i}].ProductId"] = ["产品不存在。"]; + else if (product.Status != ProductStatus.Published) + errors[$"Lines[{i}].ProductId"] = [$"产品 {product.InternalSku} 未发布(当前状态 {product.Status}),不能确认订单。"]; + if (line.Quantity <= 0) errors[$"Lines[{i}].Quantity"] = ["数量必须大于 0。"]; + } + + if (errors.Count > 0) throw new SalesValidationException(errors); + + order.RecalculateTotal(); + try { order.Confirm(request?.ConfirmedBy); } + catch (InvalidOperationException ex) { throw new SalesConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(order, ct); + } + + public async Task CancelAsync(Guid id, CancelSalesOrderRequest? request, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + try { order.Cancel(request?.Reason); } + catch (InvalidOperationException ex) { throw new SalesConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(order, ct); + } + + /// Deletes a draft order with its lines; confirmed orders can only be cancelled. + public async Task DeleteAsync(Guid id, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + EnsureDraft(order); + db.SalesOrderLines.RemoveRange(order.Lines); + db.SalesOrders.Remove(order); + await db.SaveChangesAsync(ct); + } + + // ---------- Helpers ---------- + + private static void EnsureDraft(SalesOrder order) + { + try { order.EnsureDraft(); } + catch (InvalidOperationException ex) { throw new SalesConflictException(ex.Message); } + } + + private async Task LoadCustomerAsync(Guid id, CancellationToken ct) + => await db.Customers.SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new SalesNotFoundException("客户不存在。"); + + private async Task LoadOrderAsync(Guid id, CancellationToken ct) + => await db.SalesOrders.Include(x => x.Lines.OrderBy(l => l.LineNumber)).Include(x => x.Customer) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new SalesNotFoundException("客户订单不存在。"); + + private async Task ResolveCustomerAsync(Guid customerId, CancellationToken ct) + { + if (customerId == Guid.Empty) + throw new SalesValidationException(nameof(SaveSalesOrderRequest.CustomerId), "必须选择客户。"); + var customer = await db.Customers.SingleOrDefaultAsync(x => x.Id == customerId, ct); + if (customer is null) + throw new SalesValidationException(nameof(SaveSalesOrderRequest.CustomerId), "客户不存在。"); + if (!customer.IsActive) + throw new SalesValidationException(nameof(SaveSalesOrderRequest.CustomerId), "客户已停用,不能用于新订单。"); + return customer; + } + + private async Task> BuildLinesAsync(SaveSalesOrderRequest request, CancellationToken ct) + { + if (request.Lines is null || request.Lines.Count == 0) + throw new SalesValidationException(nameof(request.Lines), "订单至少需要一条明细。"); + + var productIds = request.Lines.Select(x => x.ProductId).Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Where(x => productIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + + var errors = new Dictionary(); + var lines = new List(request.Lines.Count); + for (var i = 0; i < request.Lines.Count; i++) + { + var r = request.Lines[i]; + if (r.ProductId == Guid.Empty || !products.TryGetValue(r.ProductId, out var product)) + { + errors[$"Lines[{i}].ProductId"] = ["产品不存在。"]; + continue; + } + var lineValid = true; + // Only Published products may be sold; Draft/Disabled/Superseded are rejected. + if (product.Status != ProductStatus.Published) + { + errors[$"Lines[{i}].ProductId"] = [$"产品 {product.InternalSku} 未发布(当前状态 {product.Status}),不能加入订单。"]; + lineValid = false; + } + if (r.Quantity <= 0) { errors[$"Lines[{i}].Quantity"] = ["数量必须大于 0。"]; lineValid = false; } + if (r.UnitPrice < 0) { errors[$"Lines[{i}].UnitPrice"] = ["单价不能小于 0。"]; lineValid = false; } + if (r.PackingRate is <= 0) { errors[$"Lines[{i}].PackingRate"] = ["装箱率必须大于 0。"]; lineValid = false; } + if (!lineValid) continue; + + var line = new SalesOrderLine + { + LineNumber = i + 1, + ProductId = product.Id, + ProductInternalSku = product.InternalSku, + ProductNameZh = product.NameZh, + ProductNameEn = product.NameEn, + ProductHsCode = product.HsCode, + CustomerSku = TrimOrNull(r.CustomerSku), + CustomerProductNameOverride = TrimOrNull(r.CustomerProductNameOverride), + Quantity = r.Quantity, + Unit = string.IsNullOrWhiteSpace(r.Unit) ? product.Unit : r.Unit.Trim(), + PackingRate = r.PackingRate ?? product.PackingRate, + UnitPrice = r.UnitPrice, + RequiredDeliveryDate = r.RequiredDeliveryDate ?? request.RequiredDeliveryDate, + CustomerRemark = TrimOrNull(r.CustomerRemark), + Remark = TrimOrNull(r.Remark), + }; + line.RecalculateAmount(); + lines.Add(line); + } + + if (errors.Count > 0) throw new SalesValidationException(errors); + return lines; + } + + private async Task ResolveOrderNumberAsync(string? requested, Guid? excludeId, CancellationToken ct) + { + var number = TrimOrNull(requested); + number ??= $"SO-{DateTime.UtcNow:yyyyMMdd}-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}"; + var exists = await db.SalesOrders.AnyAsync( + x => x.OrderNumber == number && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) throw new SalesValidationException(nameof(SaveSalesOrderRequest.OrderNumber), $"订单号 {number} 已存在。"); + return number; + } + + private async Task EnsureCustomerCodeAvailableAsync(string? code, Guid? excludeId, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(code)) return; + var exists = await db.Customers.AnyAsync( + x => x.Code == code.Trim() && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) throw new SalesValidationException(nameof(SaveCustomerRequest.Code), $"客户编码 {code.Trim()} 已存在。"); + } + + private static void ApplyCustomer(Customer c, SaveCustomerRequest r) + { + if (string.IsNullOrWhiteSpace(r.Name)) + throw new SalesValidationException(nameof(r.Name), "客户名称不能为空。"); + c.Code = TrimOrNull(r.Code); + c.Name = r.Name.Trim(); + c.NameEn = TrimOrNull(r.NameEn); + c.Country = TrimOrNull(r.Country); + c.Address = TrimOrNull(r.Address); + c.ContactName = TrimOrNull(r.ContactName); + c.ContactEmail = TrimOrNull(r.ContactEmail); + c.ContactPhone = TrimOrNull(r.ContactPhone); + c.PaymentTerms = TrimOrNull(r.PaymentTerms); + c.DefaultCurrency = NormalizeCurrency(r.DefaultCurrency); + c.TradeTerm = TrimOrNull(r.TradeTerm); + c.Remark = TrimOrNull(r.Remark); + c.IsActive = r.IsActive; + } + + private static void ApplyOrder(SalesOrder o, SaveSalesOrderRequest r, Customer customer) + { + if (string.IsNullOrWhiteSpace(r.CustomerPoNumber)) + throw new SalesValidationException(nameof(r.CustomerPoNumber), "客户 PO 号不能为空。"); + o.CustomerId = customer.Id; + o.CustomerName = customer.Name; + o.CustomerPoNumber = r.CustomerPoNumber.Trim(); + o.OrderDate = r.OrderDate ?? DateOnly.FromDateTime(DateTime.UtcNow); + o.RequiredDeliveryDate = r.RequiredDeliveryDate; + o.Currency = NormalizeCurrency(r.Currency) ?? customer.DefaultCurrency ?? "USD"; + o.TransportMode = TrimOrNull(r.TransportMode); + o.LoadingPort = TrimOrNull(r.LoadingPort); + o.DestinationPort = TrimOrNull(r.DestinationPort); + o.DestinationCountry = TrimOrNull(r.DestinationCountry) ?? customer.Country; + o.TradeTerm = TrimOrNull(r.TradeTerm) ?? customer.TradeTerm; + o.PaymentTerms = TrimOrNull(r.PaymentTerms) ?? customer.PaymentTerms; + o.ShippingNote = TrimOrNull(r.ShippingNote); + o.PoAttachmentReference = TrimOrNull(r.PoAttachmentReference); + o.PoAttachmentFileName = TrimOrNull(r.PoAttachmentFileName); + o.Remark = TrimOrNull(r.Remark); + } + + private static string? NormalizeCurrency(string? value) + { + var v = TrimOrNull(value); + if (v is null) return null; + if (v.Length != 3) throw new SalesValidationException("Currency", "币种必须为 3 位代码(如 USD、CNY)。"); + return v.ToUpperInvariant(); + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + // ---------- Workbench summary (computed, never persisted) ---------- + + private sealed record TaskProgress(Guid Id, Guid SalesOrderId, Guid SalesOrderLineId, decimal Quantity); + + private sealed record NoticeProgress( + Guid Id, Guid SalesOrderId, Guid? SupplierId, string SupplierName, string Currency, + SupplierInvoiceNoticeStatus Status, decimal TotalAmountIncludingTax); + + private sealed record InvoiceProgress( + Guid NoticeId, SupplierInvoiceStatus Status, decimal AmountIncludingTax); + + private async Task ToDtoAsync(SalesOrder order, CancellationToken ct) + { + var summaries = await ComputeSummariesAsync([order], ct); + return ToDto(order, summaries[order.Id]); + } + + private async Task> ComputeSummariesAsync( + IReadOnlyList orders, CancellationToken ct) + { + if (orders.Count == 0) + return new Dictionary(); + + var orderIds = orders.Select(x => x.Id).ToList(); + + // Cancelled purchase tasks no longer represent purchasing work. + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => orderIds.Contains(x.SalesOrderId) && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => new TaskProgress(x.Id, x.SalesOrderId, x.SalesOrderLineId, x.Quantity)) + .ToListAsync(ct); + + var taskIds = tasks.Select(x => x.Id).ToList(); + var arrivedByTask = taskIds.Count == 0 + ? new Dictionary() + : (await db.PurchaseArrivals.AsNoTracking() + .Where(x => taskIds.Contains(x.PurchaseTaskId)) + .Select(x => new { x.PurchaseTaskId, x.Quantity }) + .ToListAsync(ct)) + .GroupBy(x => x.PurchaseTaskId) + .ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity)); + + // Same convention as ShippingService's over-shipment guard: lines of + // cancelled batches do not count as shipped, all others do. + var shippedByLine = (await db.ShipmentLines.AsNoTracking() + .Where(x => orderIds.Contains(x.SalesOrderId) + && x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .Select(x => new { x.SalesOrderId, x.SalesOrderLineId, x.Quantity }) + .ToListAsync(ct)) + .GroupBy(x => (x.SalesOrderId, x.SalesOrderLineId)) + .ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity)); + + // Billing is derived, never stored on the order: non-voided notices + // linked to the order, grouped by supplier below, plus their + // non-voided (active) invoices. + var noticeRows = await db.SupplierInvoiceNotices.AsNoTracking() + .Where(x => x.SalesOrderId != null && orderIds.Contains(x.SalesOrderId.Value) + && x.Status != SupplierInvoiceNoticeStatus.Voided) + .Select(x => new { x.Id, SalesOrderId = x.SalesOrderId!.Value, x.SupplierId, x.SupplierName, x.Currency, x.Status }) + .ToListAsync(ct); + var noticeIds = noticeRows.Select(x => x.Id).ToList(); + var noticeTotals = noticeIds.Count == 0 + ? new Dictionary() + : (await db.SupplierInvoiceNoticeLines.AsNoTracking() + .Where(x => noticeIds.Contains(x.SupplierInvoiceNoticeId)) + .Select(x => new { x.SupplierInvoiceNoticeId, x.Quantity, x.UnitPrice, x.TaxIncluded, x.TaxRate }) + .ToListAsync(ct)) + .GroupBy(x => x.SupplierInvoiceNoticeId) + .ToDictionary(g => g.Key, g => g.Sum(x => NoticeLineAmountIncludingTax(x.Quantity, x.UnitPrice, x.TaxIncluded, x.TaxRate))); + var notices = noticeRows.Select(x => new NoticeProgress( + x.Id, x.SalesOrderId, x.SupplierId, x.SupplierName, x.Currency, x.Status, + noticeTotals.TryGetValue(x.Id, out var total) ? total : 0m)).ToList(); + var invoices = noticeIds.Count == 0 + ? new List() + : await db.SupplierInvoices.AsNoTracking() + .Where(x => noticeIds.Contains(x.SupplierInvoiceNoticeId) && x.Status != SupplierInvoiceStatus.Voided) + .Select(x => new InvoiceProgress(x.SupplierInvoiceNoticeId, x.Status, x.AmountIncludingTax)) + .ToListAsync(ct); + + return orders.ToDictionary( + x => x.Id, + x => ComputeSummary(x, tasks.Where(t => t.SalesOrderId == x.Id).ToList(), arrivedByTask, shippedByLine, + notices.Where(n => n.SalesOrderId == x.Id).ToList(), invoices)); + } + + private static SalesOrderWorkbenchSummaryDto ComputeSummary( + SalesOrder order, + IReadOnlyList tasks, + IReadOnlyDictionary arrivedByTask, + IReadOnlyDictionary<(Guid SalesOrderId, Guid SalesOrderLineId), decimal> shippedByLine, + IReadOnlyList notices, + IReadOnlyList allInvoices) + { + var lines = order.Lines.OrderBy(x => x.LineNumber).ToList(); + var orderedQuantity = lines.Sum(x => x.Quantity); + + decimal Arrived(TaskProgress t) => arrivedByTask.TryGetValue(t.Id, out var q) ? q : 0m; + bool TaskComplete(TaskProgress t) => t.Quantity > 0 && Arrived(t) >= t.Quantity; + + var tasksByLine = tasks.GroupBy(x => x.SalesOrderLineId) + .ToDictionary(g => g.Key, g => g.ToList()); + var purchaseCompletedLines = lines.Count(line => + tasksByLine.TryGetValue(line.Id, out var lineTasks) + && lineTasks.Count > 0 + && lineTasks.All(TaskComplete)); + var isPurchaseComplete = lines.Count > 0 && purchaseCompletedLines == lines.Count; + + var purchaseTaskQuantity = tasks.Sum(x => x.Quantity); + var arrivedQuantity = tasks.Sum(Arrived); + var purchasePercent = purchaseTaskQuantity > 0 + ? Math.Round(tasks.Sum(t => Math.Min(Arrived(t), t.Quantity)) / purchaseTaskQuantity * 100m, 2) + : 0m; + + decimal shippedRaw = 0m, shippedCapped = 0m, remaining = 0m; + foreach (var line in lines) + { + var shipped = shippedByLine.TryGetValue((order.Id, line.Id), out var q) ? q : 0m; + shippedRaw += shipped; + shippedCapped += Math.Min(shipped, line.Quantity); + remaining += Math.Max(line.Quantity - shipped, 0m); + } + + var isFullyShipped = lines.Count > 0 && orderedQuantity > 0 && remaining == 0m; + var shipmentPercent = orderedQuantity > 0 + ? Math.Round(shippedCapped / orderedQuantity * 100m, 2) + : 0m; + var isReadyToShip = order.Status == SalesOrderStatus.Confirmed && isPurchaseComplete && !isFullyShipped; + + var workbenchStatus = + order.Status == SalesOrderStatus.Cancelled ? "Cancelled" : + order.Status == SalesOrderStatus.Draft ? "Draft" : + isFullyShipped ? "Completed" : + shippedRaw > 0 ? "PartiallyShipped" : + isPurchaseComplete ? "ReadyToShip" : + tasks.Count == 0 ? "PendingPurchase" : + "PurchaseInProgress"; + + var supplierBillings = ComputeSupplierBillings(notices, allInvoices); + var noticeIds = notices.Select(x => x.Id).ToHashSet(); + var orderInvoices = allInvoices.Where(x => noticeIds.Contains(x.NoticeId)).ToList(); + var completedNotices = notices.Count(x => IsNoticeBillingComplete(x, allInvoices)); + var billingNoticeAmount = notices.Sum(x => x.TotalAmountIncludingTax); + var billingInvoicedAmount = orderInvoices.Sum(x => x.AmountIncludingTax); + var billingCompletedAmount = orderInvoices + .Where(x => x.Status == SupplierInvoiceStatus.Completed).Sum(x => x.AmountIncludingTax); + var isBillingComplete = notices.Count > 0 && completedNotices == notices.Count; + var billingStatus = isBillingComplete ? "Completed" + : orderInvoices.Count > 0 || completedNotices > 0 ? "PartiallyCompleted" + : "Pending"; + var billingPercent = billingNoticeAmount > 0 + ? Math.Round(billingCompletedAmount / billingNoticeAmount * 100m, 2) + : 0m; + + return new SalesOrderWorkbenchSummaryDto( + workbenchStatus, + lines.Count, + lines.Count(line => tasksByLine.ContainsKey(line.Id)), + purchaseCompletedLines, + tasks.Count, + tasks.Count(TaskComplete), + orderedQuantity, + purchaseTaskQuantity, + arrivedQuantity, + shippedRaw, + remaining, + purchasePercent, + shipmentPercent, + isPurchaseComplete, + isReadyToShip, + isFullyShipped, + billingStatus, + supplierBillings.Count, + notices.Count, + completedNotices, + orderInvoices.Count, + orderInvoices.Count(x => x.Status == SupplierInvoiceStatus.Completed), + billingNoticeAmount, + billingInvoicedAmount, + billingCompletedAmount, + Math.Max(billingNoticeAmount - billingInvoicedAmount, 0m), + billingPercent, + isBillingComplete, + supplierBillings); + } + + // Same tax-inclusive amount as SupplierInvoiceNoticeLine.AmountIncludingTax. + private static decimal NoticeLineAmountIncludingTax(decimal quantity, decimal unitPrice, bool taxIncluded, decimal taxRate) + => taxIncluded + ? decimal.Round(quantity * unitPrice, 2, MidpointRounding.AwayFromZero) + : decimal.Round(quantity * decimal.Round(unitPrice * (1 + taxRate / 100m), 4, MidpointRounding.AwayFromZero), + 2, MidpointRounding.AwayFromZero); + + private static bool IsNoticeBillingComplete(NoticeProgress notice, IReadOnlyList allInvoices) + { + if (notice.Status != SupplierInvoiceNoticeStatus.Completed || notice.TotalAmountIncludingTax <= 0) + return false; + var invoices = allInvoices.Where(x => x.NoticeId == notice.Id).ToList(); + return invoices.Count > 0 + && invoices.All(x => x.Status == SupplierInvoiceStatus.Completed) + && invoices.Sum(x => x.AmountIncludingTax) >= notice.TotalAmountIncludingTax - 0.01m; + } + + private static IReadOnlyList ComputeSupplierBillings( + IReadOnlyList notices, IReadOnlyList allInvoices) + => notices + .GroupBy(x => (x.SupplierId, x.SupplierName, x.Currency)) + .OrderBy(g => g.Key.SupplierName, StringComparer.OrdinalIgnoreCase) + .ThenBy(g => g.Key.Currency, StringComparer.OrdinalIgnoreCase) + .Select(g => + { + var groupInvoices = allInvoices.Where(x => g.Any(n => n.Id == x.NoticeId)).ToList(); + var noticeAmount = g.Sum(x => x.TotalAmountIncludingTax); + var invoiced = groupInvoices.Sum(x => x.AmountIncludingTax); + var completedAmount = groupInvoices + .Where(x => x.Status == SupplierInvoiceStatus.Completed).Sum(x => x.AmountIncludingTax); + var completedNotices = g.Count(x => IsNoticeBillingComplete(x, allInvoices)); + var isComplete = completedNotices == g.Count(); + return new SalesOrderSupplierBillingSummaryDto( + g.Key.SupplierId, g.Key.SupplierName, g.Key.Currency, + isComplete ? "Completed" : groupInvoices.Count > 0 || completedNotices > 0 ? "PartiallyCompleted" : "Pending", + g.Count(), completedNotices, + groupInvoices.Count, + groupInvoices.Count(x => x.Status == SupplierInvoiceStatus.Completed), + noticeAmount, invoiced, completedAmount, + Math.Max(noticeAmount - invoiced, 0m), + noticeAmount > 0 ? Math.Round(completedAmount / noticeAmount * 100m, 2) : 0m, + isComplete); + }).ToList(); + + private static CustomerDto ToDto(Customer c) => new( + c.Id, c.Code, c.Name, c.NameEn, c.Country, c.Address, c.ContactName, c.ContactEmail, + c.ContactPhone, c.PaymentTerms, c.DefaultCurrency, c.TradeTerm, c.Remark, c.IsActive, + c.CreatedAt, c.UpdatedAt); + + private static SalesOrderLineDto ToDto(SalesOrderLine l) => new( + l.Id, l.SalesOrderId, l.LineNumber, l.ProductId, l.ProductInternalSku, l.ProductNameZh, + l.ProductNameEn, l.ProductHsCode, l.CustomerSku, l.CustomerProductNameOverride, + l.EffectiveCustomerProductName, l.Quantity, l.Unit, l.PackingRate, + l.PackingRate is > 0 ? Math.Ceiling(l.Quantity / l.PackingRate.Value) : null, + l.UnitPrice, l.Amount, l.RequiredDeliveryDate, l.CustomerRemark, l.Remark); + + private static SalesOrderDto ToDto(SalesOrder o, SalesOrderWorkbenchSummaryDto summary) => new( + o.Id, o.OrderNumber, o.CustomerId, o.CustomerName, o.CustomerPoNumber, o.OrderDate, + o.RequiredDeliveryDate, o.Currency, o.Status.ToString(), o.TransportMode, o.LoadingPort, + o.DestinationPort, o.DestinationCountry, o.TradeTerm, o.PaymentTerms, o.ShippingNote, + o.PoAttachmentReference, o.PoAttachmentFileName, o.TotalAmount, + o.Lines.Sum(x => x.Quantity), o.Remark, o.ConfirmedAt, o.ConfirmedBy, o.CancelledAt, + o.CancellationReason, o.CreatedAt, o.UpdatedAt, + o.Lines.OrderBy(x => x.LineNumber).Select(ToDto).ToList(), summary); +} diff --git a/src/Leiren.Erp.Application/Shipping/IShippingDbContext.cs b/src/Leiren.Erp.Application/Shipping/IShippingDbContext.cs new file mode 100644 index 0000000..0aa8ef5 --- /dev/null +++ b/src/Leiren.Erp.Application/Shipping/IShippingDbContext.cs @@ -0,0 +1,23 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Shipping; + +/// +/// EF Core boundary for the Shipping module; implemented by Infrastructure. +/// Sales/Purchasing sets are read here only to validate shipment lines against +/// a confirmed sales order and its purchase completion (arrivals). +/// +public interface IShippingDbContext +{ + DbSet SalesOrders { get; } + DbSet SalesOrderLines { get; } + DbSet Products { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseArrivals { get; } + DbSet ShippingBatches { get; } + DbSet ShippingContainers { get; } + DbSet ShipmentLines { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Shipping/ShippingExceptions.cs b/src/Leiren.Erp.Application/Shipping/ShippingExceptions.cs new file mode 100644 index 0000000..f12a242 --- /dev/null +++ b/src/Leiren.Erp.Application/Shipping/ShippingExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Shipping; + +public sealed class ShippingNotFoundException(string message) : Exception(message); + +public sealed class ShippingConflictException(string message) : Exception(message); + +public sealed class ShippingValidationException(IReadOnlyDictionary errors) + : Exception("出货资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public ShippingValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Shipping/ShippingService.cs b/src/Leiren.Erp.Application/Shipping/ShippingService.cs new file mode 100644 index 0000000..8349575 --- /dev/null +++ b/src/Leiren.Erp.Application/Shipping/ShippingService.cs @@ -0,0 +1,630 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Shipping; + +public sealed class ShippingService(IShippingDbContext db) +{ + // ---------- Batches ---------- + + public async Task> ListBatchesAsync( + Guid? salesOrderId, string? status, string? search, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.ShippingBatches.AsNoTracking() + .Include(x => x.Lines).Include(x => x.Containers).AsQueryable(); + if (salesOrderId is not null) + query = query.Where(x => x.SalesOrderId == salesOrderId.Value || x.Lines.Any(l => l.SalesOrderId == salesOrderId.Value)); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new ShippingValidationException(nameof(status), "出货批次状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.BatchNo.Contains(term) || x.SalesOrderNo.Contains(term) || + x.CustomerName.Contains(term) || + (x.CustomerPoNo != null && x.CustomerPoNo.Contains(term)) || + (x.BillOfLadingNo != null && x.BillOfLadingNo.Contains(term)) || + (x.VesselName != null && x.VesselName.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new ShippingBatchListItemDto( + x.Id, x.BatchNo, x.SalesOrderId, x.SalesOrderNo, x.CustomerPoNo, x.CustomerName, + x.Status.ToString(), x.Etd, x.Eta, x.VesselName, x.BillOfLadingNo, x.DestinationPort, + x.Lines.Count, x.Containers.Count, x.TotalCartonCount, x.TotalCbm, x.TotalAmount, + x.Currency, x.UpdatedAt, x.CustomerId)).ToList(); + } + + public async Task GetBatchAsync(Guid id, CancellationToken ct = default) + => await ToDtoAsync(await LoadBatchAsync(id, ct), ct); + + /// Confirmed orders whose arrived finished goods are not fully in shipping batches yet. + public async Task> ListReadyOrdersAsync(CancellationToken ct = default) + { + var orders = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines).ThenInclude(x => x.Product) + .Where(x => x.Status == SalesOrderStatus.Confirmed) + .ToListAsync(ct); + var lineIds = orders.SelectMany(x => x.Lines).Select(x => x.Id).ToList(); + + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => lineIds.Contains(x.SalesOrderLineId) && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => new { x.SalesOrderLineId, x.Quantity, x.ArrivedQuantity }) + .ToListAsync(ct); + var arrivals = await db.PurchaseArrivals.AsNoTracking() + .Where(x => x.CartonLength != null && lineIds.Contains(x.PurchaseTask!.SalesOrderLineId)) + .Select(x => new + { + x.Id, x.PurchaseTask!.SalesOrderLineId, x.ArrivedDate, x.CreatedAt, x.PackingRate, + x.CartonLength, x.CartonWidth, x.CartonHeight, x.CartonGrossWeight, x.CartonNetWeight + }) + .ToListAsync(ct); + var shipped = await db.ShipmentLines.AsNoTracking() + .Where(x => lineIds.Contains(x.SalesOrderLineId) && x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .Select(x => new { x.SalesOrderLineId, x.Quantity }) + .ToListAsync(ct); + + var result = new List(); + foreach (var order in orders.OrderByDescending(x => x.OrderDate).ThenBy(x => x.OrderNumber, StringComparer.Ordinal)) + { + var lines = new List(); + foreach (var line in order.Lines.OrderBy(x => x.LineNumber)) + { + var lineTasks = tasks.Where(x => x.SalesOrderLineId == line.Id).ToList(); + if (lineTasks.Count == 0) continue; + var arrived = FinishedArrived(lineTasks.Select(x => (x.Quantity, x.ArrivedQuantity)), line.Quantity); + var shippedQuantity = shipped.Where(x => x.SalesOrderLineId == line.Id).Sum(x => x.Quantity); + var available = arrived - shippedQuantity; + if (available <= 0) continue; + + var arrival = arrivals.Where(x => x.SalesOrderLineId == line.Id) + .OrderByDescending(x => x.ArrivedDate).ThenByDescending(x => x.CreatedAt) + .FirstOrDefault(); + var product = line.Product; + lines.Add(new ShippingReadyLineDto( + line.Id, line.ProductInternalSku, line.ProductNameZh, line.Unit, + line.Quantity, arrived, shippedQuantity, available, arrival?.Id, + arrival?.PackingRate ?? line.PackingRate ?? product?.PackingRate, + arrival?.CartonLength ?? product?.CartonLength, + arrival?.CartonWidth ?? product?.CartonWidth, + arrival?.CartonHeight ?? product?.CartonHeight, + arrival?.CartonGrossWeight ?? product?.CartonGrossWeight, + arrival?.CartonNetWeight ?? product?.CartonNetWeight)); + } + if (lines.Count == 0) continue; + result.Add(new ShippingReadyOrderDto( + order.Id, order.OrderNumber, order.CustomerId, order.CustomerPoNumber, order.CustomerName, order.Currency, + order.OrderDate, order.RequiredDeliveryDate, order.LoadingPort, order.DestinationPort, order.DestinationCountry, + order.TransportMode, order.TradeTerm, lines)); + } + return result; + } + + public async Task CreateBatchAsync(CreateShippingBatchRequest request, CancellationToken ct = default) + { + var order = await db.SalesOrders.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == request.SalesOrderId, ct) + ?? throw new ShippingNotFoundException("销售订单不存在。"); + if (order.Status != SalesOrderStatus.Confirmed) + throw new ShippingConflictException("只有已确认的销售订单可以建立出货批次。"); + + var batchNo = string.IsNullOrWhiteSpace(request.BatchNo) + ? $"SH-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString("N")[..4].ToUpperInvariant()}" + : request.BatchNo.Trim(); + if (await db.ShippingBatches.AnyAsync(x => x.BatchNo == batchNo, ct)) + throw new ShippingConflictException($"出货批次号 {batchNo} 已存在。"); + + var batch = new ShippingBatch + { + BatchNo = batchNo, + SalesOrderId = order.Id, + CustomerId = order.CustomerId, + SalesOrderNo = order.OrderNumber, + CustomerName = order.CustomerName, + CustomerPoNo = order.CustomerPoNumber, + Currency = order.Currency, + LoadingPort = TrimOrNull(request.LoadingPort) ?? TrimOrNull(order.LoadingPort), + DestinationPort = TrimOrNull(request.DestinationPort) ?? TrimOrNull(order.DestinationPort), + DestinationCountry = TrimOrNull(request.DestinationCountry) ?? TrimOrNull(order.DestinationCountry), + TransportMode = TrimOrNull(request.TransportMode) ?? TrimOrNull(order.TransportMode), + TradeTerm = TrimOrNull(request.TradeTerm) ?? TrimOrNull(order.TradeTerm) + }; + ApplyHeader(batch, request.ShipmentDate, request.CutoffDate, request.Etd, request.Eta, + request.VesselName, request.VoyageNo, request.BillOfLadingNo, + request.LoadingPort ?? order.LoadingPort, request.DestinationPort ?? order.DestinationPort, + request.DestinationCountry ?? order.DestinationCountry, + request.TransportMode ?? order.TransportMode, request.TradeTerm ?? order.TradeTerm, + request.FreightForwarder, request.Remark); + ValidateDates(batch); + + db.ShippingBatches.Add(batch); + + if (request.Containers is not null) + { + foreach (var containerRequest in request.Containers) + { + var container = new ShippingContainer { ShippingBatchId = batch.Id }; + ApplyContainer(batch, container, containerRequest); + batch.Containers.Add(container); + db.ShippingContainers.Add(container); + } + } + + if (request.Lines is not null) + { + foreach (var lineRequest in request.Lines) + { + var line = new ShipmentLine { ShippingBatchId = batch.Id }; + await ApplyLineAsync(batch, line, lineRequest, ct); + batch.Lines.Add(line); + db.ShipmentLines.Add(line); + } + } + + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task UpdateBatchAsync( + Guid id, UpdateShippingBatchRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(id, ct); + EnsureDraft(batch); + + if (!string.IsNullOrWhiteSpace(request.BatchNo)) + { + var batchNo = request.BatchNo.Trim(); + if (!string.Equals(batchNo, batch.BatchNo, StringComparison.Ordinal) && + await db.ShippingBatches.AnyAsync(x => x.Id != id && x.BatchNo == batchNo, ct)) + throw new ShippingConflictException($"出货批次号 {batchNo} 已存在。"); + batch.BatchNo = batchNo; + } + + ApplyHeader(batch, request.ShipmentDate, request.CutoffDate, request.Etd, request.Eta, + request.VesselName, request.VoyageNo, request.BillOfLadingNo, + request.LoadingPort, request.DestinationPort, request.DestinationCountry, + request.TransportMode, request.TradeTerm, request.FreightForwarder, request.Remark); + ValidateDates(batch); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + public async Task ConfirmBatchAsync(Guid id, string? confirmedBy, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(id, ct); + EnsureDraft(batch); + if (batch.Lines.Count == 0) + throw new ShippingValidationException(nameof(batch.Lines), "出货批次至少需要一条出货明细。"); + if (string.IsNullOrWhiteSpace(batch.LoadingPort)) + throw new ShippingValidationException(nameof(batch.LoadingPort), "确认出货前必须填写起运港。"); + if (string.IsNullOrWhiteSpace(batch.DestinationPort)) + throw new ShippingValidationException(nameof(batch.DestinationPort), "确认出货前必须填写目的港。"); + + foreach (var line in batch.Lines) + { + if (line.CartonCount is null or <= 0 || line.CartonLength is null or <= 0 || + line.CartonWidth is null or <= 0 || line.CartonHeight is null or <= 0 || + line.CartonGrossWeight is null or <= 0 || line.CartonNetWeight is null or <= 0) + throw new ShippingValidationException(nameof(line.CartonCount), + $"出货明细「{line.InternalSku}」的实际包装快照不完整(箱数、单箱尺寸、单箱毛净重必填)。"); + await ValidateCumulativeAsync(batch, line, line.Quantity, ct); + } + + try { batch.Confirm(confirmedBy); } + catch (InvalidOperationException ex) { throw new ShippingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + public async Task CancelBatchAsync(Guid id, string? reason, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(id, ct); + try { batch.Cancel(reason); } + catch (InvalidOperationException ex) { throw new ShippingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + } + + // ---------- Containers ---------- + + public async Task AddContainerAsync( + Guid batchId, SaveShippingContainerRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var container = new ShippingContainer { ShippingBatchId = batch.Id }; + ApplyContainer(batch, container, request); + batch.Containers.Add(container); + db.ShippingContainers.Add(container); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task UpdateContainerAsync( + Guid batchId, Guid containerId, SaveShippingContainerRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var container = batch.Containers.SingleOrDefault(x => x.Id == containerId) + ?? throw new ShippingNotFoundException("集装箱不存在。"); + ApplyContainer(batch, container, request, excluding: container); + container.Touch(); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + public async Task RemoveContainerAsync( + Guid batchId, Guid containerId, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var container = batch.Containers.SingleOrDefault(x => x.Id == containerId) + ?? throw new ShippingNotFoundException("集装箱不存在。"); + foreach (var line in batch.Lines.Where(x => x.ShippingContainerId == containerId)) + { + line.ShippingContainerId = null; + line.ShippingContainer = null; + line.Touch(); + } + + batch.Containers.Remove(container); + db.ShippingContainers.Remove(container); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + // ---------- Shipment lines ---------- + + public async Task AddLineAsync( + Guid batchId, SaveShipmentLineRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var line = new ShipmentLine { ShippingBatchId = batch.Id }; + await ApplyLineAsync(batch, line, request, ct); + batch.Lines.Add(line); + db.ShipmentLines.Add(line); + batch.Touch(); + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task UpdateLineAsync( + Guid batchId, Guid lineId, SaveShipmentLineRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var line = batch.Lines.SingleOrDefault(x => x.Id == lineId) + ?? throw new ShippingNotFoundException("出货明细不存在。"); + await ApplyLineAsync(batch, line, request, ct); + line.Touch(); + batch.Touch(); + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task RemoveLineAsync( + Guid batchId, Guid lineId, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var line = batch.Lines.SingleOrDefault(x => x.Id == lineId) + ?? throw new ShippingNotFoundException("出货明细不存在。"); + batch.Lines.Remove(line); + db.ShipmentLines.Remove(line); + batch.Touch(); + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + // ---------- Helpers ---------- + + /// + /// Batch order number / PO become the list of every order its lines come + /// from (e.g. "SC-1 / SC-2"); with no lines the primary order is kept. + /// + private async Task RefreshOrderReferencesAsync(ShippingBatch batch, CancellationToken ct) + { + var orderIds = batch.Lines.Select(x => x.SalesOrderId).Append(batch.SalesOrderId).Distinct().ToList(); + var orders = await db.SalesOrders.AsNoTracking() + .Where(x => orderIds.Contains(x.Id)) + .Select(x => new { x.Id, x.OrderNumber, x.CustomerPoNumber }) + .ToListAsync(ct); + var used = batch.Lines.Count == 0 ? [batch.SalesOrderId] : batch.Lines.Select(x => x.SalesOrderId).Distinct().ToList(); + var ordered = orders.Where(x => used.Contains(x.Id)).OrderBy(x => x.OrderNumber, StringComparer.Ordinal).ToList(); + if (ordered.Count == 0) return; + batch.SalesOrderNo = string.Join(" / ", ordered.Select(x => x.OrderNumber)); + batch.CustomerPoNo = string.Join(" / ", ordered.Select(x => x.CustomerPoNumber).Where(x => !string.IsNullOrWhiteSpace(x))); + } + + private async Task ApplyLineAsync( + ShippingBatch batch, ShipmentLine line, SaveShipmentLineRequest request, CancellationToken ct) + { + var salesLine = await db.SalesOrderLines.AsNoTracking() + .Include(x => x.Product) + .Include(x => x.SalesOrder) + .SingleOrDefaultAsync(x => x.Id == request.SalesOrderLineId, ct) + ?? throw new ShippingValidationException(nameof(request.SalesOrderLineId), "订单明细不存在。"); + // One container may carry several orders of the same customer and currency. + var lineOrder = salesLine.SalesOrder!; + if (lineOrder.Status != SalesOrderStatus.Confirmed) + throw new ShippingConflictException($"订单 {lineOrder.OrderNumber} 未确认,不能出货。"); + if (lineOrder.CustomerId != batch.CustomerId) + throw new ShippingValidationException(nameof(request.SalesOrderLineId), $"订单 {lineOrder.OrderNumber} 不属于客户 {batch.CustomerName},不能拼在同一出货批次。"); + if (!string.Equals(lineOrder.Currency, batch.Currency, StringComparison.OrdinalIgnoreCase)) + throw new ShippingValidationException(nameof(request.SalesOrderLineId), $"订单 {lineOrder.OrderNumber} 的币种 {lineOrder.Currency} 与出货批次 {batch.Currency} 不同。"); + + if (request.Quantity <= 0) + throw new ShippingValidationException(nameof(request.Quantity), "出货数量必须大于 0。"); + if (request.UnitPrice is < 0) + throw new ShippingValidationException(nameof(request.UnitPrice), "出货单价不能小于 0。"); + if (request.PackingRate is <= 0) + throw new ShippingValidationException(nameof(request.PackingRate), "实际装箱率必须大于 0。"); + if (request.CartonCount is <= 0) + throw new ShippingValidationException(nameof(request.CartonCount), "实际箱数必须大于 0。"); + foreach (var (value, field) in new[] + { + (request.CartonLength, nameof(request.CartonLength)), + (request.CartonWidth, nameof(request.CartonWidth)), + (request.CartonHeight, nameof(request.CartonHeight)), + (request.CartonGrossWeight, nameof(request.CartonGrossWeight)), + (request.CartonNetWeight, nameof(request.CartonNetWeight)) + }) + { + if (value is < 0) + throw new ShippingValidationException(field, "实际包装尺寸和重量不能小于 0。"); + } + + ShippingContainer? container = null; + if (request.ShippingContainerId is { } containerId) + { + container = batch.Containers.SingleOrDefault(x => x.Id == containerId); + if (container is null && + !await db.ShippingContainers.AsNoTracking() + .AnyAsync(x => x.Id == containerId && x.ShippingBatchId == batch.Id, ct)) + throw new ShippingValidationException(nameof(request.ShippingContainerId), "集装箱不属于该出货批次。"); + } + else if (!string.IsNullOrWhiteSpace(request.ContainerNo)) + { + container = batch.Containers.SingleOrDefault(x => + string.Equals(x.ContainerNo, request.ContainerNo.Trim(), StringComparison.OrdinalIgnoreCase)) + ?? throw new ShippingValidationException(nameof(request.ContainerNo), $"集装箱 {request.ContainerNo} 不在该出货批次中。"); + } + + PurchaseTask? task = null; + if (request.PurchaseTaskId is { } taskId) + { + task = await db.PurchaseTasks.AsNoTracking().SingleOrDefaultAsync(x => x.Id == taskId, ct) + ?? throw new ShippingValidationException(nameof(request.PurchaseTaskId), "采购任务不存在。"); + if (task.SalesOrderLineId != salesLine.Id) + throw new ShippingValidationException(nameof(request.PurchaseTaskId), "采购任务不属于该订单明细。"); + if (task.Status == PurchaseTaskStatus.Cancelled) + throw new ShippingValidationException(nameof(request.PurchaseTaskId), "采购任务已取消,不能用于出货。"); + } + + PurchaseArrival? arrival = null; + if (request.PurchaseArrivalId is { } arrivalId) + { + arrival = await db.PurchaseArrivals.AsNoTracking() + .Include(x => x.PurchaseTask) + .SingleOrDefaultAsync(x => x.Id == arrivalId, ct) + ?? throw new ShippingValidationException(nameof(request.PurchaseArrivalId), "采购到货记录不存在。"); + if (arrival.PurchaseTask is null || arrival.PurchaseTask.SalesOrderLineId != salesLine.Id) + throw new ShippingValidationException(nameof(request.PurchaseArrivalId), "采购到货记录不属于该订单明细。"); + if (task is not null && task.Id != arrival.PurchaseTaskId) + throw new ShippingValidationException(nameof(request.PurchaseArrivalId), "采购到货记录与采购任务不一致。"); + task ??= arrival.PurchaseTask; + } + + await ValidateCumulativeAsync(batch, line, request.Quantity, ct, salesLine); + + var product = salesLine.Product; + line.SalesOrderId = salesLine.SalesOrderId; + line.SalesOrderLineId = salesLine.Id; + line.ShippingContainerId = container?.Id ?? request.ShippingContainerId; + line.ShippingContainer = container; + line.PurchaseTaskId = task?.Id ?? request.PurchaseTaskId; + line.PurchaseArrivalId = arrival?.Id; + line.InternalSku = salesLine.ProductInternalSku; + line.ProductNameZh = salesLine.ProductNameZh; + line.ProductNameEn = salesLine.ProductNameEn; + line.CustomerSku = salesLine.CustomerSku; + line.CustomerProductName = salesLine.EffectiveCustomerProductName; + line.HsCode = salesLine.ProductHsCode ?? product?.HsCode; + line.OrderedQuantity = salesLine.Quantity; + line.Quantity = request.Quantity; + line.Unit = salesLine.Unit; + line.UnitPrice = request.UnitPrice ?? salesLine.UnitPrice; + + // Actual packing: explicit input wins, then the linked arrival's + // actuals, then product-master defaults (frozen into this line). + line.PackingRate = request.PackingRate ?? arrival?.PackingRate ?? salesLine.PackingRate ?? product?.PackingRate; + line.CartonLength = request.CartonLength ?? arrival?.CartonLength ?? product?.CartonLength; + line.CartonWidth = request.CartonWidth ?? arrival?.CartonWidth ?? product?.CartonWidth; + line.CartonHeight = request.CartonHeight ?? arrival?.CartonHeight ?? product?.CartonHeight; + line.CartonGrossWeight = request.CartonGrossWeight ?? arrival?.CartonGrossWeight ?? product?.CartonGrossWeight; + line.CartonNetWeight = request.CartonNetWeight ?? arrival?.CartonNetWeight ?? product?.CartonNetWeight; + line.CartonCount = request.CartonCount + ?? (line.PackingRate is { } rate ? (int?)decimal.Ceiling(request.Quantity / rate) : null) + ?? (arrival is not null && arrival.Quantity == request.Quantity ? arrival.CartonCount : null); + line.Remark = TrimOrNull(request.Remark); + line.RecalculateAmount(); + line.RecalculatePackingTotals(); + } + + /// + /// Enforces ordered-quantity and purchase-completion limits for one line: + /// cumulative shipped (all non-cancelled batches, including this batch's + /// other lines) may not exceed the ordered quantity, and — when finished- + /// goods purchase tasks exist for the sales line — may not exceed their + /// cumulative arrived quantity. + /// + private async Task ValidateCumulativeAsync( + ShippingBatch batch, ShipmentLine current, decimal newQuantity, + CancellationToken ct, SalesOrderLine? knownSalesLine = null) + { + var salesLine = knownSalesLine ?? await db.SalesOrderLines.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == current.SalesOrderLineId, ct) + ?? throw new ShippingValidationException(nameof(current.SalesOrderLineId), "订单明细不存在。"); + + var shippedInOtherBatches = await db.ShipmentLines.AsNoTracking() + .Where(x => x.SalesOrderLineId == salesLine.Id && + x.ShippingBatchId != batch.Id && + x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .SumAsync(x => (decimal?)x.Quantity, ct) ?? 0; + var shippedInThisBatch = batch.Lines + .Where(x => x.Id != current.Id && x.SalesOrderLineId == salesLine.Id) + .Sum(x => x.Quantity); + var cumulative = shippedInOtherBatches + shippedInThisBatch + newQuantity; + if (cumulative > salesLine.Quantity) + throw new ShippingValidationException(nameof(newQuantity), + $"出货数量累计 {cumulative} 超过订单数量 {salesLine.Quantity}。"); + + var (hasTasks, arrived) = await GetFinishedArrivedAsync(salesLine.Id, salesLine.Quantity, ct); + if (hasTasks && cumulative > arrived) + throw new ShippingValidationException(nameof(newQuantity), + $"出货数量累计 {cumulative} 超过成品已到货数量 {arrived}。"); + } + + /// + /// Finished quantity arrived for a sales line: every part (purchase task) + /// is needed for one finished unit, so the least-arrived part limits it. + /// + private async Task<(bool HasTasks, decimal Arrived)> GetFinishedArrivedAsync( + Guid salesOrderLineId, decimal lineQuantity, CancellationToken ct) + { + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => x.SalesOrderLineId == salesOrderLineId && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => new { x.Quantity, x.ArrivedQuantity }) + .ToListAsync(ct); + return tasks.Count == 0 + ? (false, 0) + : (true, FinishedArrived(tasks.Select(x => (x.Quantity, x.ArrivedQuantity)), lineQuantity)); + } + + private static decimal FinishedArrived(IEnumerable<(decimal Quantity, decimal Arrived)> parts, decimal lineQuantity) + { + var ratio = parts.Min(x => x.Quantity <= 0 ? 0 : x.Arrived / x.Quantity); + return Math.Floor(Math.Min(ratio, 1) * lineQuantity); + } + + private static void ApplyContainer( + ShippingBatch batch, ShippingContainer container, + SaveShippingContainerRequest request, ShippingContainer? excluding = null) + { + if (string.IsNullOrWhiteSpace(request.ContainerNo)) + throw new ShippingValidationException(nameof(request.ContainerNo), "集装箱号不能为空。"); + var containerNo = request.ContainerNo.Trim(); + if (batch.Containers.Any(x => x != excluding && + string.Equals(x.ContainerNo, containerNo, StringComparison.OrdinalIgnoreCase))) + throw new ShippingConflictException($"集装箱号 {containerNo} 已在该出货批次中。"); + container.ContainerNo = containerNo; + container.ContainerType = TrimOrNull(request.ContainerType); + container.SealNo = TrimOrNull(request.SealNo); + container.Remark = TrimOrNull(request.Remark); + } + + private static void ApplyHeader( + ShippingBatch batch, DateOnly? shipmentDate, DateOnly? cutoffDate, DateOnly? etd, DateOnly? eta, + string? vesselName, string? voyageNo, string? billOfLadingNo, + string? loadingPort, string? destinationPort, string? destinationCountry, + string? transportMode, string? tradeTerm, string? freightForwarder, string? remark) + { + batch.ShipmentDate = shipmentDate; + batch.CutoffDate = cutoffDate; + batch.Etd = etd; + batch.Eta = eta; + batch.VesselName = TrimOrNull(vesselName); + batch.VoyageNo = TrimOrNull(voyageNo); + batch.BillOfLadingNo = TrimOrNull(billOfLadingNo); + batch.LoadingPort = TrimOrNull(loadingPort); + batch.DestinationPort = TrimOrNull(destinationPort); + batch.DestinationCountry = TrimOrNull(destinationCountry); + batch.TransportMode = TrimOrNull(transportMode); + batch.TradeTerm = TrimOrNull(tradeTerm); + batch.FreightForwarder = TrimOrNull(freightForwarder); + batch.Remark = TrimOrNull(remark); + } + + private static void ValidateDates(ShippingBatch batch) + { + if (batch.Eta is not null && batch.Etd is not null && batch.Eta < batch.Etd) + throw new ShippingValidationException(nameof(batch.Eta), "ETA 不能早于 ETD。"); + if (batch.CutoffDate is not null && batch.Etd is not null && batch.CutoffDate > batch.Etd) + throw new ShippingValidationException(nameof(batch.CutoffDate), "截关日期不能晚于 ETD。"); + } + + private static void EnsureDraft(ShippingBatch batch) + { + try { batch.EnsureDraft(); } + catch (InvalidOperationException ex) { throw new ShippingConflictException(ex.Message); } + } + + private async Task LoadBatchAsync(Guid id, CancellationToken ct) + => await db.ShippingBatches + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new ShippingNotFoundException("出货批次不存在。"); + + private async Task ToDtoAsync(ShippingBatch batch, CancellationToken ct) + { + var arrivedByLine = new Dictionary(); + var otherShippedByLine = new Dictionary(); + foreach (var salesLineId in batch.Lines.Select(x => x.SalesOrderLineId).Distinct()) + { + var (_, arrived) = await GetFinishedArrivedAsync(salesLineId, batch.Lines.First(x => x.SalesOrderLineId == salesLineId).OrderedQuantity, ct); + arrivedByLine[salesLineId] = arrived; + otherShippedByLine[salesLineId] = await db.ShipmentLines.AsNoTracking() + .Where(x => x.SalesOrderLineId == salesLineId && + x.ShippingBatchId != batch.Id && + x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .SumAsync(x => (decimal?)x.Quantity, ct) ?? 0; + } + + return new ShippingBatchDto( + batch.Id, batch.BatchNo, batch.SalesOrderId, batch.CustomerId, batch.SalesOrderNo, + batch.CustomerName, batch.CustomerPoNo, batch.Currency, batch.Status.ToString(), + batch.ShipmentDate, batch.CutoffDate, batch.Etd, batch.Eta, batch.VesselName, + batch.VoyageNo, batch.BillOfLadingNo, batch.LoadingPort, batch.DestinationPort, + batch.DestinationCountry, batch.TransportMode, batch.TradeTerm, batch.FreightForwarder, + batch.Remark, batch.TotalQuantity, batch.TotalCartonCount, batch.TotalGrossWeight, + batch.TotalNetWeight, batch.TotalCbm, batch.TotalAmount, batch.ConfirmedAt, + batch.ConfirmedBy, batch.CancelledAt, batch.CancellationReason, + batch.CreatedAt, batch.UpdatedAt, + batch.Containers.OrderBy(x => x.CreatedAt).Select(x => new ShippingContainerDto( + x.Id, x.ShippingBatchId, x.ContainerNo, x.ContainerType, x.SealNo, x.Remark, + x.CreatedAt, x.UpdatedAt)).ToList(), + batch.Lines.OrderBy(x => x.CreatedAt).Select(x => new ShipmentLineDto( + x.Id, x.ShippingBatchId, x.ShippingContainerId, x.SalesOrderId, x.SalesOrderLineId, + x.PurchaseTaskId, x.PurchaseArrivalId, x.InternalSku, x.ProductNameZh, x.ProductNameEn, + x.CustomerSku, x.CustomerProductName, x.HsCode, x.OrderedQuantity, x.Quantity, x.Unit, + x.UnitPrice, x.Amount, + arrivedByLine.GetValueOrDefault(x.SalesOrderLineId), + otherShippedByLine.GetValueOrDefault(x.SalesOrderLineId), + x.PackingRate, x.CartonCount, x.CartonLength, x.CartonWidth, x.CartonHeight, + x.CartonGrossWeight, x.CartonNetWeight, x.TotalGrossWeight, x.TotalNetWeight, + x.TotalCbm, x.Remark, x.CreatedAt, x.UpdatedAt)).ToList()); + } + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/src/Leiren.Erp.Backup/Leiren.Erp.Backup.csproj b/src/Leiren.Erp.Backup/Leiren.Erp.Backup.csproj new file mode 100644 index 0000000..8bd9d69 --- /dev/null +++ b/src/Leiren.Erp.Backup/Leiren.Erp.Backup.csproj @@ -0,0 +1,14 @@ + + + + + + + + Exe + net11.0 + enable + enable + + + diff --git a/src/Leiren.Erp.Backup/Program.cs b/src/Leiren.Erp.Backup/Program.cs new file mode 100644 index 0000000..5f89cf5 --- /dev/null +++ b/src/Leiren.Erp.Backup/Program.cs @@ -0,0 +1,262 @@ +using System.Text.Json; +using Leiren.Erp.Infrastructure.Backup; + +internal static class Program +{ + private const int ExitOk = 0; + private const int ExitFailure = 1; + private const int ExitUsage = 2; + + private static async Task Main(string[] args) + { + if (args.Length == 0 || IsHelp(args[0])) + { + PrintUsage(); + return args.Length == 0 ? ExitUsage : ExitOk; + } + + try + { + return args[0].ToLowerInvariant() switch + { + "backup" => await RunBackupAsync(args[1..]).ConfigureAwait(false), + "verify" => await RunVerifyAsync(args[1..]).ConfigureAwait(false), + _ => UnknownCommand(args[0]), + }; + } + catch (BackupException ex) + { + Console.Error.WriteLine($"备份失败:{ex.Message}"); + return ExitFailure; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) + { + Console.Error.WriteLine($"备份失败:{ex.Message}"); + return ExitFailure; + } + } + + private static async Task RunBackupAsync(string[] args) + { + var parsed = CliArgs.Parse(args); + var options = await LoadOptionsAsync(parsed).ConfigureAwait(false); + ApplyOverrides(options, parsed); + var dryRun = parsed.HasFlag("--dry-run"); + + // The database connection string may be injected by the scheduler via + // environment instead of a config file or a shell-visible argument. + if (options.IncludeDatabase && string.IsNullOrWhiteSpace(options.DatabaseConnectionString)) + { + options.DatabaseConnectionString = Environment.GetEnvironmentVariable("LEIREN_ERP_CONNECTION_STRING"); + } + + var service = new FileBackupService(); + var result = await service.RunAsync(options, dryRun).ConfigureAwait(false); + + if (result.DryRun) + { + Console.WriteLine("DRY-RUN:仅枚举并校验源文件,未写入任何备份文件。"); + } + else + { + Console.WriteLine($"备份完成:{result.BackupId}"); + Console.WriteLine($"备份目录:{result.BackupDirectory}"); + Console.WriteLine($"清单文件:{result.ManifestPath}"); + } + + Console.WriteLine($"文件数:{result.FileCount}"); + Console.WriteLine($"文件总字节:{result.TotalFileBytes}"); + Console.WriteLine(result.DatabaseIncluded + ? $"数据库已包含:{result.DatabaseBytes} 字节" + : "数据库未包含(IncludeDatabase=false)。"); + return ExitOk; + } + + private static async Task RunVerifyAsync(string[] args) + { + var parsed = CliArgs.Parse(args); + var backupDirectory = parsed.GetValue("--backup") ?? parsed.GetValue("--path"); + if (string.IsNullOrWhiteSpace(backupDirectory)) + { + Console.Error.WriteLine("verify 需要 --backup <备份目录>。"); + PrintUsage(); + return ExitUsage; + } + + var service = new FileBackupService(); + var result = await service.VerifyAsync(backupDirectory).ConfigureAwait(false); + if (!result.IsValid) + { + Console.Error.WriteLine($"备份校验失败:{result.BackupDirectory}"); + foreach (var error in result.Errors) + { + Console.Error.WriteLine($" - {error}"); + } + + return ExitFailure; + } + + Console.WriteLine($"备份校验通过:{result.BackupId}"); + Console.WriteLine($"已校验文件:{result.CheckedFiles} 个,{result.CheckedBytes} 字节"); + Console.WriteLine(result.DatabaseChecked ? "数据库备份已校验。" : "清单中无数据库备份。"); + return ExitOk; + } + + private static async Task LoadOptionsAsync(CliArgs args) + { + var configPath = args.GetValue("--config"); + if (string.IsNullOrWhiteSpace(configPath)) + { + return new BackupOptions(); + } + + if (!File.Exists(configPath)) + { + throw new BackupException($"备份配置文件不存在:{configPath}"); + } + + try + { + var json = await File.ReadAllTextAsync(configPath).ConfigureAwait(false); + return JsonSerializer.Deserialize(json, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true, + }) ?? throw new BackupException($"备份配置文件为空:{configPath}"); + } + catch (JsonException ex) + { + throw new BackupException($"备份配置文件 JSON 无效:{ex.Message}", ex); + } + } + + private static void ApplyOverrides(BackupOptions options, CliArgs args) + { + foreach (var source in args.GetValues("--source")) + { + var separator = source.IndexOf('='); + if (separator <= 0) + { + throw new BackupException($"--source 格式应为 Name=Path,收到:{source}"); + } + + options.Sources.Add(new BackupSourceOptions + { + Name = source[..separator], + Path = source[(separator + 1)..], + }); + } + + if (args.GetValue("--destination") is { } destination) + { + options.DestinationPath = destination; + } + + if (args.HasFlag("--include-database")) + { + options.IncludeDatabase = true; + } + + if (args.GetValue("--database-provider") is { } provider) + { + options.DatabaseProvider = provider; + } + + if (args.GetValue("--database-connection-string") is { } connectionString) + { + options.DatabaseConnectionString = connectionString; + } + + if (args.GetValue("--pg-dump-path") is { } pgDumpPath) + { + options.PgDumpPath = pgDumpPath; + } + + if (args.HasFlag("--allow-empty")) + { + options.AllowEmpty = true; + } + } + + private static int UnknownCommand(string command) + { + Console.Error.WriteLine($"未知命令:{command}"); + PrintUsage(); + return ExitUsage; + } + + private static bool IsHelp(string arg) => arg is "--help" or "-h" or "help"; + + private static void PrintUsage() + { + Console.WriteLine(""" + Leiren.Erp.Backup - 文件/模板与数据库备份工具 + + 用法: + Leiren.Erp.Backup backup [--config backup.json] [选项] + Leiren.Erp.Backup verify --backup <备份目录> + + backup 选项: + --config JSON 配置文件(见 deploy/windows/backup.example.json) + --source 备份源目录,可重复;Name 仅字母/数字/-/_/. + --destination 备份根目录(其下按时间戳建子目录) + --include-database 同时包含数据库备份 + --database-provider + --database-connection-string 建议改用配置文件或环境变量 LEIREN_ERP_CONNECTION_STRING + --pg-dump-path pg_dump 完整路径(默认从 PATH 查找) + --allow-empty 允许空备份(默认拒绝) + --dry-run 仅枚举/哈希源文件,不写入任何内容 + + 退出码:0 成功,1 备份或校验失败,2 用法错误。 + 失败时不会生成可被误认的完成备份;完成前会按 manifest.json 的 SHA-256 自校验。 + """); + } + + private sealed class CliArgs + { + private readonly Dictionary> _values = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _flags = new(StringComparer.OrdinalIgnoreCase); + + public static CliArgs Parse(string[] args) + { + var parsed = new CliArgs(); + for (var i = 0; i < args.Length; i++) + { + var arg = args[i]; + if (arg is "--dry-run" or "--include-database" or "--allow-empty") + { + parsed._flags.Add(arg); + continue; + } + + if (arg.StartsWith("--", StringComparison.Ordinal)) + { + if (i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) + { + throw new BackupException($"选项 {arg} 缺少值。"); + } + + if (!parsed._values.TryGetValue(arg, out var list)) + { + list = []; + parsed._values[arg] = list; + } + + list.Add(args[++i]); + continue; + } + + throw new BackupException($"无法识别的参数:{arg}"); + } + + return parsed; + } + + public bool HasFlag(string name) => _flags.Contains(name); + + public string? GetValue(string name) + => _values.TryGetValue(name, out var list) && list.Count > 0 ? list[^1] : null; + + public IReadOnlyList GetValues(string name) + => _values.TryGetValue(name, out var list) ? list : []; + } +} diff --git a/src/Leiren.Erp.Client/ApiClient.cs b/src/Leiren.Erp.Client/ApiClient.cs new file mode 100644 index 0000000..917bfe2 --- /dev/null +++ b/src/Leiren.Erp.Client/ApiClient.cs @@ -0,0 +1,259 @@ +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; + +namespace Leiren.Erp.Client; + +public sealed record LoginResponse(Guid UserId, string UserName, string DisplayName, string AccessToken, string RefreshToken); + +public sealed class ApiException : Exception +{ + public ApiException(string message) : base(message) { } + public ApiException(string message, Exception innerException) : base(message, innerException) { } + public ApiException(string message, int statusCode) : base(message) => StatusCode = statusCode; + public int? StatusCode { get; } + public bool IsForbidden => StatusCode == (int)HttpStatusCode.Forbidden; +} + +public sealed class ApiClient +{ + private readonly HttpClient httpClient; + private readonly SemaphoreSlim refreshGate = new(1, 1); + public ApiClient(string? baseUrl = null) + { + var address = string.IsNullOrWhiteSpace(baseUrl) ? "http://127.0.0.1:5118" : baseUrl.Trim(); + httpClient = new HttpClient + { + BaseAddress = new Uri(address, UriKind.Absolute), + Timeout = TimeSpan.FromSeconds(15) + }; + } + + public string? AccessToken { get; private set; } + public string? RefreshToken { get; private set; } + public LoginResponse? CurrentUser { get; private set; } + public bool IsAuthenticated => !string.IsNullOrWhiteSpace(AccessToken); + public event Action? SessionChanged; + + public async Task LoginAsync(string userName, string password, CancellationToken cancellationToken = default) + { + var result = await SendAsync(HttpMethod.Post, "/api/auth/login", + new { userName, password }, cancellationToken); + return ApplySession(result); + } + + public async Task RefreshAsync(string refreshToken, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(refreshToken)) throw new ApiException("保持登录凭据为空。"); + await refreshGate.WaitAsync(cancellationToken); + try + { + return await RefreshCoreAsync(refreshToken, cancellationToken); + } + finally { refreshGate.Release(); } + } + + private async Task RefreshAccessTokenAsync(CancellationToken cancellationToken) + { + await refreshGate.WaitAsync(cancellationToken); + try + { + var refreshToken = RefreshToken; + if (string.IsNullOrWhiteSpace(refreshToken)) + throw new ApiException("登录已失效,请重新登录。"); + await RefreshCoreAsync(refreshToken, cancellationToken); + } + finally { refreshGate.Release(); } + } + + private async Task RefreshCoreAsync(string refreshToken, CancellationToken cancellationToken) + { + var result = await SendAsync(HttpMethod.Post, "/api/auth/refresh", + new { refreshToken }, cancellationToken); + return ApplySession(result); + } + + public async Task RevokeRefreshTokenAsync(string? refreshToken, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(refreshToken)) return; + try + { + using var response = await SendRawAsync(HttpMethod.Post, "/api/auth/logout", new { refreshToken }, cancellationToken); + } + catch (ApiException) { } + } + + private LoginResponse ApplySession(LoginResponse result) + { + if (string.IsNullOrWhiteSpace(result.AccessToken) || string.IsNullOrWhiteSpace(result.RefreshToken)) + throw new ApiException("服务器返回了空的登录凭据。"); + AccessToken = result.AccessToken; + RefreshToken = result.RefreshToken; + CurrentUser = result; + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); + SessionChanged?.Invoke(result); + return result; + } + + public Task GetAsync(string url, CancellationToken cancellationToken = default) + => SendAsync(HttpMethod.Get, url, null, cancellationToken); + + public Task PostAsync(string url, object? body = null, CancellationToken cancellationToken = default) + => SendAsync(HttpMethod.Post, url, body, cancellationToken); + + /// POST for endpoints that answer 204 No Content. + public async Task PostAsync(string url, object? body = null, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Post, url, body, cancellationToken); + } + + public Task PutAsync(string url, object? body = null, CancellationToken cancellationToken = default) + => SendAsync(HttpMethod.Put, url, body, cancellationToken); + + public async Task DeleteAsync(string url, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Delete, url, null, cancellationToken); + } + + public async Task GetBytesAsync(string url, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Get, url, null, cancellationToken); + return await response.Content.ReadAsByteArrayAsync(cancellationToken); + } + + /// POST whose response is a file (e.g. a rendered preview workbook). + public async Task PostBytesAsync(string url, object? body, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Post, url, body, cancellationToken); + return await response.Content.ReadAsByteArrayAsync(cancellationToken); + } + + /// Uploads one file as multipart/form-data (field "file") with extra text fields. + public Task UploadAsync(string url, string filePath, IReadOnlyDictionary fields, CancellationToken cancellationToken = default) + { + var bytes = File.ReadAllBytes(filePath); + HttpContent Build() + { + var form = new MultipartFormDataContent(); + foreach (var (key, value) in fields) + if (!string.IsNullOrWhiteSpace(value)) form.Add(new StringContent(value), key); + var file = new ByteArrayContent(bytes); + file.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + form.Add(file, "file", Path.GetFileName(filePath)); + return form; + } + return SendAsync(HttpMethod.Post, url, (Func)Build, cancellationToken); + } + + public void Logout() + { + AccessToken = null; + CurrentUser = null; + httpClient.DefaultRequestHeaders.Authorization = null; + } + + private async Task SendAsync(HttpMethod method, string url, object? body, CancellationToken cancellationToken) + { + using var response = await SendRawAsync(method, url, body, cancellationToken); + try + { + return await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken) + ?? throw new ApiException("服务器返回了空结果。"); + } + catch (JsonException ex) + { + throw new ApiException("服务器返回的数据格式不正确。", ex); + } + } + + private async Task SendRawAsync(HttpMethod method, string url, object? body, CancellationToken cancellationToken) + { + try + { + using var request = new HttpRequestMessage(method, url); + if (body is Func contentFactory) + request.Content = contentFactory(); // rebuilt when the request is retried after a token refresh + else if (body is not null) + request.Content = JsonContent.Create(body); + + var response = await httpClient.SendAsync(request, cancellationToken); + if (response.IsSuccessStatusCode) return response; + if (response.StatusCode == HttpStatusCode.Unauthorized && + !string.Equals(url, "/api/auth/refresh", StringComparison.OrdinalIgnoreCase) && + !string.IsNullOrWhiteSpace(RefreshToken)) + { + response.Dispose(); + await RefreshAccessTokenAsync(cancellationToken); + return await SendRawAsync(method, url, body, cancellationToken); + } + + using (response) + { + var message = await ReadErrorAsync(response, cancellationToken); + if (response.StatusCode == HttpStatusCode.Forbidden && !message.Contains("403", StringComparison.Ordinal)) + message = $"无权限(403):{message}"; + throw new ApiException(message, (int)response.StatusCode); + } + } + catch (ApiException) + { + throw; + } + catch (HttpRequestException ex) + { + throw new ApiException("无法连接服务器,请确认服务器已启动后重试。", ex); + } + catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested) + { + throw new ApiException("连接服务器超时,请稍后重试。", ex); + } + catch (JsonException ex) + { + throw new ApiException("服务器返回的数据格式不正确。", ex); + } + } + + private static async Task ReadErrorAsync(HttpResponseMessage response, CancellationToken cancellationToken) + { + try + { + var text = await response.Content.ReadAsStringAsync(cancellationToken); + if (!string.IsNullOrWhiteSpace(text)) + { + using var document = JsonDocument.Parse(text); + var root = document.RootElement; + var message = GetString(root, "detail") ?? GetString(root, "title"); + if (root.TryGetProperty("errors", out var errors) && errors.ValueKind == JsonValueKind.Object) + { + var parts = new List(); + foreach (var field in errors.EnumerateObject()) + { + var messages = field.Value.ValueKind == JsonValueKind.Array + ? string.Join(" ", field.Value.EnumerateArray().Select(x => x.GetString()).Where(x => !string.IsNullOrWhiteSpace(x))) + : field.Value.GetString() ?? string.Empty; + if (!string.IsNullOrWhiteSpace(messages)) parts.Add(messages); + } + + if (parts.Count > 0) return string.Join(" ", parts); + } + + if (!string.IsNullOrWhiteSpace(message)) return message; + } + } + catch (JsonException) + { + } + + return response.StatusCode == HttpStatusCode.Unauthorized + ? "用户名或密码不正确,或登录已失效。" + : $"服务器请求失败({(int)response.StatusCode})。"; + } + + private static string? GetString(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; +} diff --git a/src/Leiren.Erp.Client/App.xaml b/src/Leiren.Erp.Client/App.xaml new file mode 100644 index 0000000..a45cc4f --- /dev/null +++ b/src/Leiren.Erp.Client/App.xaml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Leiren.Erp.Client/App.xaml.cs b/src/Leiren.Erp.Client/App.xaml.cs new file mode 100644 index 0000000..e072ca2 --- /dev/null +++ b/src/Leiren.Erp.Client/App.xaml.cs @@ -0,0 +1,70 @@ +using System.Windows; + +namespace Leiren.Erp.Client; + +/// +/// Start-up: restore a kept session silently; only when that is not possible +/// show the login window, then open the main window. +/// +public partial class App : Application +{ + private ClientSettings settings = null!; + private ApiClient api = null!; + + protected override async void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + ShutdownMode = ShutdownMode.OnExplicitShutdown; + settings = ClientSettings.Load(); + settings.Save(); + api = new ApiClient(settings.ApiBaseUrl); + api.SessionChanged += SaveSession; + + var (session, message) = await RestoreSessionAsync(); + session ??= SignIn(message); + if (session is null) + { + Shutdown(); + return; + } + + var main = new MainWindow(api, settings, session, SignIn); + MainWindow = main; + ShutdownMode = ShutdownMode.OnMainWindowClose; + main.Show(); + } + + /// Shows the login window; null when the user closes it. + private LoginResponse? SignIn(string? message) + { + var login = new LoginWindow(api, settings, message); + return login.ShowDialog() == true ? login.Result : null; + } + + private async Task<(LoginResponse? Session, string? Message)> RestoreSessionAsync() + { + if (!settings.KeepSignedIn || string.IsNullOrWhiteSpace(settings.RefreshToken)) return (null, null); + try + { + return (await api.RefreshAsync(settings.RefreshToken), null); + } + catch (ApiException) + { + api.Logout(); + settings.ClearSession(); + return (null, "保持登录已失效,请重新登录。"); + } + catch + { + return (null, "无法恢复登录,请检查服务器连接。"); + } + } + + /// Persists (or forgets) the refresh token whenever the session changes. + private void SaveSession(LoginResponse result) + { + settings.UserName = settings.KeepSignedIn ? result.UserName : settings.UserName; + settings.RefreshToken = settings.KeepSignedIn ? result.RefreshToken : null; + settings.Save(); + } +} diff --git a/src/Leiren.Erp.Client/AssemblyInfo.cs b/src/Leiren.Erp.Client/AssemblyInfo.cs new file mode 100644 index 0000000..cc29e7f --- /dev/null +++ b/src/Leiren.Erp.Client/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly:ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/src/Leiren.Erp.Client/ClientSettings.cs b/src/Leiren.Erp.Client/ClientSettings.cs new file mode 100644 index 0000000..8f33b12 --- /dev/null +++ b/src/Leiren.Erp.Client/ClientSettings.cs @@ -0,0 +1,120 @@ +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Leiren.Erp.Client; + +public sealed class ClientSettings +{ + private const string Section = "Client"; + private readonly Dictionary values = new(StringComparer.OrdinalIgnoreCase); + + private ClientSettings(string filePath) + { + FilePath = filePath; + } + + public string FilePath { get; } + + public string ApiBaseUrl + { + get => Get("ApiBaseUrl") ?? "http://127.0.0.1:5118"; + set => Set("ApiBaseUrl", string.IsNullOrWhiteSpace(value) ? "http://127.0.0.1:5118" : value.Trim()); + } + + public bool KeepSignedIn + { + get => !values.TryGetValue("KeepSignedIn", out var text) || + !bool.TryParse(text, out var value) || value; + set => Set("KeepSignedIn", value.ToString()); + } + + public string? UserName + { + get => Get("UserName"); + set => Set("UserName", value); + } + + public string? RefreshToken + { + get + { + var protectedValue = Get("RefreshToken"); + if (string.IsNullOrWhiteSpace(protectedValue)) return null; + try + { + var protectedBytes = Convert.FromBase64String(protectedValue); + var plainBytes = ProtectedData.Unprotect(protectedBytes, null, DataProtectionScope.CurrentUser); + return Encoding.UTF8.GetString(plainBytes); + } + catch (FormatException) { return null; } + catch (CryptographicException) { return null; } + } + set + { + if (string.IsNullOrWhiteSpace(value)) + { + values.Remove("RefreshToken"); + return; + } + + var plainBytes = Encoding.UTF8.GetBytes(value); + var protectedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser); + Set("RefreshToken", Convert.ToBase64String(protectedBytes)); + } + } + + public static ClientSettings Load() + { + var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LeirenErp"); + var settings = new ClientSettings(Path.Combine(directory, "settings.ini")); + if (!File.Exists(settings.FilePath)) return settings; + + string? section = null; + foreach (var rawLine in File.ReadLines(settings.FilePath, Encoding.UTF8)) + { + var line = rawLine.Trim(); + if (line.Length == 0 || line.StartsWith(';') || line.StartsWith('#')) continue; + if (line.StartsWith('[') && line.EndsWith(']')) + { + section = line[1..^1].Trim(); + continue; + } + if (!string.Equals(section, Section, StringComparison.OrdinalIgnoreCase)) continue; + var separator = line.IndexOf('='); + if (separator <= 0) continue; + settings.values[line[..separator].Trim()] = line[(separator + 1)..].Trim(); + } + return settings; + } + + /// Forgets the session; the user name and the "保持登录" choice stay for the next sign-in. + public void ClearSession() + { + RefreshToken = null; + Save(); + } + + public void Save() + { + var directory = Path.GetDirectoryName(FilePath)!; + Directory.CreateDirectory(directory); + var content = new StringBuilder() + .AppendLine("; Leiren ERP client settings") + .AppendLine("[Client]") + .Append("ApiBaseUrl=").AppendLine(ApiBaseUrl) + .Append("KeepSignedIn=").AppendLine(KeepSignedIn.ToString()) + .Append("UserName=").AppendLine(UserName ?? string.Empty); + var refreshToken = Get("RefreshToken"); + if (!string.IsNullOrWhiteSpace(refreshToken)) content.Append("RefreshToken=").AppendLine(refreshToken); + File.WriteAllText(FilePath, content.ToString(), new UTF8Encoding(false)); + } + + private string? Get(string key) => values.TryGetValue(key, out var value) ? value : null; + + private void Set(string key, string? value) + { + if (string.IsNullOrWhiteSpace(value)) values.Remove(key); + else values[key] = value; + } +} diff --git a/src/Leiren.Erp.Client/Controls/DialogKit.cs b/src/Leiren.Erp.Client/Controls/DialogKit.cs new file mode 100644 index 0000000..6bffd16 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/DialogKit.cs @@ -0,0 +1,84 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; + +namespace Leiren.Erp.Client.Controls; + +/// Shared look for the code-built dialogs (template editor, container numbers). +public static class DialogKit +{ + public static readonly Brush Ink = Freeze(Color.FromRgb(0x18, 0x21, 0x2F)); + public static readonly Brush Muted = Freeze(Color.FromRgb(0x77, 0x83, 0x97)); + public static readonly Brush Line = Freeze(Color.FromRgb(0xD6, 0xDE, 0xEA)); + public static readonly Brush Blue = Freeze(Color.FromRgb(0x26, 0x67, 0xE8)); + public static readonly Brush Error = Freeze(Color.FromRgb(0xB4, 0x23, 0x18)); + public static readonly Brush Orange = Freeze(Color.FromRgb(0xB9, 0x68, 0x17)); + public static readonly Brush Green = Freeze(Color.FromRgb(0x16, 0x84, 0x5B)); + public static readonly Brush Wash = Freeze(Color.FromRgb(0xF5, 0xF6, 0xF8)); + + private static Brush Freeze(Color color) + { + var brush = new SolidColorBrush(color); + brush.Freeze(); + return brush; + } + + public static Window Window(Window? owner, string title, double width, double height) => new() + { + Title = title, + Width = width, + Height = height, + MinWidth = Math.Min(width, 640), + MinHeight = Math.Min(height, 420), + Owner = owner, + WindowStartupLocation = owner is null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner, + Background = Wash, + }; + + public static TextBlock Heading(string text) => new() + { + Text = text, FontSize = 16, FontWeight = FontWeights.SemiBold, Foreground = Ink, TextWrapping = TextWrapping.Wrap, + }; + + public static TextBlock Note(string text, Brush? color = null) => new() + { + Text = text, FontSize = 12, Foreground = color ?? Muted, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 4, 0, 0), + }; + + public static StackPanel Field(string label, UIElement control) + { + var panel = new StackPanel { Margin = new Thickness(0, 0, 0, 12) }; + panel.Children.Add(new TextBlock { Text = label, FontSize = 11, Foreground = Muted, FontWeight = FontWeights.SemiBold, Margin = new Thickness(0, 0, 0, 5) }); + panel.Children.Add(control); + return panel; + } + + public static TextBox TextBox(string text = "") => new() + { + Text = text, Height = 32, VerticalContentAlignment = VerticalAlignment.Center, Padding = new Thickness(8, 0, 8, 0), BorderBrush = Line, + }; + + public static Button Primary(string label) => new() + { + Content = label, MinWidth = 90, Height = 34, Padding = new Thickness(14, 0, 14, 0), Background = Blue, + Foreground = Brushes.White, BorderThickness = new Thickness(0), FontWeight = FontWeights.SemiBold, + }; + + public static Button Secondary(string label) => new() + { + Content = label, MinWidth = 90, Height = 34, Padding = new Thickness(14, 0, 14, 0), Background = Brushes.White, + Foreground = Ink, BorderBrush = Line, + }; + + /// Right-aligned button row with spacing. + public static StackPanel Buttons(params Button[] buttons) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 12, 0, 0) }; + for (var i = 0; i < buttons.Length; i++) + { + if (i > 0) buttons[i].Margin = new Thickness(10, 0, 0, 0); + row.Children.Add(buttons[i]); + } + return row; + } +} diff --git a/src/Leiren.Erp.Client/Controls/DisplayTextConverter.cs b/src/Leiren.Erp.Client/Controls/DisplayTextConverter.cs new file mode 100644 index 0000000..3abc1a5 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/DisplayTextConverter.cs @@ -0,0 +1,20 @@ +using System.Globalization; +using System.Windows.Data; +using Leiren.Erp.Client.Pages; + +namespace Leiren.Erp.Client.Controls; + +/// Shows stored enum / flag values in Chinese (part and product types, yes/no). +public sealed class DisplayTextConverter : IValueConverter +{ + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value switch + { + bool flag => flag ? "是" : "否", + string text => ProductPage.TypeName(text), + null => "-", + _ => value.ToString() ?? "-", + }; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) + => throw new NotSupportedException(); +} diff --git a/src/Leiren.Erp.Client/Controls/FluentIcons.cs b/src/Leiren.Erp.Client/Controls/FluentIcons.cs new file mode 100644 index 0000000..c927898 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/FluentIcons.cs @@ -0,0 +1,43 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; + +namespace Leiren.Erp.Client.Controls; + +/// +/// Glyphs of the installed Segoe Fluent Icons font (Windows 11; falls back to +/// Segoe MDL2 Assets on Windows 10, which shares the code points used here). +/// Icons inherit the foreground of the button or text they sit in. +/// +public static class FluentIcons +{ + public static readonly FontFamily Font = new("Segoe Fluent Icons, Segoe MDL2 Assets"); + + public const string Add = "\uE710"; + public const string Refresh = "\uE72C"; + public const string Edit = "\uE70F"; + public const string Delete = "\uE74D"; + public const string Download = "\uE896"; + public const string CheckMark = "\uE73E"; + public const string Close = "\uE711"; + public const string Forward = "\uE72A"; + public const string SignOut = "\uF3B1"; + + public static TextBlock Glyph(string glyph, double size = 14, Brush? foreground = null) + { + var block = new TextBlock { Text = glyph, FontFamily = Font, FontSize = size, VerticalAlignment = VerticalAlignment.Center }; + if (foreground is not null) block.Foreground = foreground; + return block; + } + + /// Button content: an icon followed by a label. + public static StackPanel Label(string glyph, string text, double size = 13) + { + var panel = new StackPanel { Orientation = Orientation.Horizontal }; + var icon = Glyph(glyph, size); + icon.Margin = new Thickness(0, 1, 7, 0); + panel.Children.Add(icon); + panel.Children.Add(new TextBlock { Text = text, VerticalAlignment = VerticalAlignment.Center }); + return panel; + } +} diff --git a/src/Leiren.Erp.Client/Controls/PageFrame.cs b/src/Leiren.Erp.Client/Controls/PageFrame.cs new file mode 100644 index 0000000..919b447 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/PageFrame.cs @@ -0,0 +1,35 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using Leiren.Erp.Client.Pages; + +namespace Leiren.Erp.Client.Controls; + +/// +/// Gives the master-data pages (products, customers, suppliers, settings) the +/// same dark header band as the workflow workspace: only the page title. +/// +public sealed class PageFrame : UserControl, ILoadablePage +{ + private readonly UIElement page; + + public PageFrame(string title, UIElement page) + { + this.page = page; + var root = new Grid { Background = new SolidColorBrush(Color.FromRgb(0xF5, 0xF6, 0xF8)) }; + root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); + + // Same padding, size and height as the workspace header (whose action buttons are 34 px tall). + var titleText = new TextBlock { Text = title, Foreground = Brushes.White, FontSize = 24, FontWeight = FontWeights.SemiBold, VerticalAlignment = VerticalAlignment.Center }; + var band = new Grid { MinHeight = 34, Children = { titleText } }; + root.Children.Add(new Border { Background = new SolidColorBrush(Color.FromRgb(0x12, 0x20, 0x33)), Padding = new Thickness(28, 20, 28, 20), Child = band }); + + var content = new Border { Padding = new Thickness(28, 22, 28, 24), Child = page }; + Grid.SetRow(content, 1); + root.Children.Add(content); + Content = root; + } + + public Task ActivateAsync() => page is ILoadablePage loadable ? loadable.ActivateAsync() : Task.CompletedTask; +} diff --git a/src/Leiren.Erp.Client/Controls/XlsxPreviewView.cs b/src/Leiren.Erp.Client/Controls/XlsxPreviewView.cs new file mode 100644 index 0000000..53a9713 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/XlsxPreviewView.cs @@ -0,0 +1,233 @@ +using System.IO; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Effects; +using System.Windows.Media.Imaging; +using ExcelRenderer; +using ExcelRenderer.Fonts; +using ExcelRenderer.Rendering; + +namespace Leiren.Erp.Client.Controls; + +/// +/// Real-rendered XLSX preview: ExcelRenderer draws the first worksheet +/// (merges, borders, fills, row heights) as one continuous image. The page +/// fits the view by default; a click zooms to 100 % keeping the clicked point +/// under the cursor, dragging pans, and another click returns to fit. +/// +public sealed class XlsxPreviewView : UserControl +{ + private const double Dpi = 144; + private const double DragThreshold = 4; + + private readonly ScrollViewer scroll; + private readonly TextBlock placeholder; + private readonly Border page; + private readonly Image image = new() { Stretch = Stretch.Uniform, Cursor = Cursors.Hand }; + + // Natural (100 %) size in WPF units: the bitmap is rendered at 144 DPI, layout is 96. + private Size naturalSize; + private bool actualSize; + private bool pressed; + private bool dragged; + private Point pressPoint; + private Point pressOffset; + + public XlsxPreviewView() + { + placeholder = new TextBlock + { + Text = "尚未生成预览", + Foreground = new SolidColorBrush(Color.FromRgb(0x66, 0x70, 0x85)), + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(0, 40, 0, 0), + }; + page = new Border + { + Background = Brushes.White, + Margin = new Thickness(16), + Padding = new Thickness(16), + Visibility = Visibility.Collapsed, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Effect = new DropShadowEffect { BlurRadius = 8, ShadowDepth = 1, Opacity = 0.25 }, + Child = image, + }; + var content = new Grid(); + content.Children.Add(placeholder); + content.Children.Add(page); + scroll = new ScrollViewer + { + Background = new SolidColorBrush(Color.FromRgb(0xE4, 0xE7, 0xEC)), + HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, + VerticalScrollBarVisibility = ScrollBarVisibility.Disabled, + Content = content, + }; + scroll.PreviewMouseLeftButtonDown += OnMouseDown; + scroll.PreviewMouseMove += OnMouseMove; + scroll.PreviewMouseLeftButtonUp += OnMouseUp; + Content = scroll; + } + + public bool HasImage => image.Source is not null; + + /// Shows a status text instead of the page (loading, empty, error). + public void ShowMessage(string text) + { + image.Source = null; + page.Visibility = Visibility.Collapsed; + placeholder.Text = text; + placeholder.Visibility = Visibility.Visible; + } + + /// Renders the workbook off the UI thread and shows it fitted to the view. + public async Task ShowAsync(byte[] xlsx) + { + ShowMessage("正在渲染预览…"); + var images = await Task.Run(() => RenderAsync(xlsx)); + if (images.Count == 0) throw new InvalidOperationException("工作表没有可渲染的内容。"); + + var bitmap = new BitmapImage(); + bitmap.BeginInit(); + bitmap.CacheOption = BitmapCacheOption.OnLoad; + bitmap.StreamSource = new MemoryStream(images[0]); + bitmap.EndInit(); + bitmap.Freeze(); + + naturalSize = new Size(bitmap.PixelWidth * 96 / Dpi, bitmap.PixelHeight * 96 / Dpi); + image.Source = bitmap; + placeholder.Visibility = Visibility.Collapsed; + page.Visibility = Visibility.Visible; + SetActualSize(false, null); + } + + /// + /// Fit mode scales the page down to the visible area (never above 100 %); + /// actual-size mode shows it at 100 % with scrolling, keeping the clicked + /// point under the cursor. + /// + private void SetActualSize(bool value, Point? anchorInViewport) + { + Point? relative = null; + if (value && anchorInViewport is { } anchor && image.ActualWidth > 0) + { + var onImage = scroll.TranslatePoint(anchor, image); + relative = new Point( + Math.Clamp(onImage.X / image.ActualWidth, 0, 1), + Math.Clamp(onImage.Y / image.ActualHeight, 0, 1)); + } + + actualSize = value; + var visibility = value ? ScrollBarVisibility.Auto : ScrollBarVisibility.Disabled; + scroll.HorizontalScrollBarVisibility = visibility; + scroll.VerticalScrollBarVisibility = visibility; + image.Width = value ? naturalSize.Width : double.NaN; + image.Height = value ? naturalSize.Height : double.NaN; + image.MaxWidth = naturalSize.Width; + image.MaxHeight = naturalSize.Height; + image.Cursor = value ? Cursors.SizeAll : Cursors.Hand; + scroll.UpdateLayout(); + + if (relative is { } r && anchorInViewport is { } a) + { + var target = image.TranslatePoint(new Point(r.X * naturalSize.Width, r.Y * naturalSize.Height), scroll); + scroll.ScrollToHorizontalOffset(scroll.HorizontalOffset + target.X - a.X); + scroll.ScrollToVerticalOffset(scroll.VerticalOffset + target.Y - a.Y); + } + } + + private void OnMouseDown(object sender, MouseButtonEventArgs e) + { + if (image.Source is null || IsInScrollBar(e.OriginalSource as DependencyObject)) return; + pressed = true; + dragged = false; + pressPoint = e.GetPosition(scroll); + pressOffset = new Point(scroll.HorizontalOffset, scroll.VerticalOffset); + scroll.CaptureMouse(); + e.Handled = true; + } + + private static bool IsInScrollBar(DependencyObject? element) + { + for (; element is not null; element = element is Visual ? VisualTreeHelper.GetParent(element) : null) + if (element is ScrollBar) return true; + return false; + } + + private void OnMouseMove(object sender, MouseEventArgs e) + { + if (!pressed) return; + var delta = e.GetPosition(scroll) - pressPoint; + if (!dragged && Math.Abs(delta.X) < DragThreshold && Math.Abs(delta.Y) < DragThreshold) return; + dragged = true; + if (!actualSize) return; + scroll.ScrollToHorizontalOffset(pressOffset.X - delta.X); + scroll.ScrollToVerticalOffset(pressOffset.Y - delta.Y); + } + + private void OnMouseUp(object sender, MouseButtonEventArgs e) + { + if (!pressed) return; + pressed = false; + scroll.ReleaseMouseCapture(); + if (!dragged) SetActualSize(!actualSize, e.GetPosition(scroll)); + e.Handled = true; + } + + private static async Task> RenderAsync(byte[] xlsx) + { + using var input = new MemoryStream(xlsx); + var sink = new MemorySink(); + await ExcelConverter.RenderAsync(input, new RenderRequest + { + OutputFormat = OutputFormat.Png, + ImageLayout = ImageLayoutMode.Continuous, + Dpi = Dpi, + // The package's bundled fonts are Japanese, and scanning every + // system font costs seconds; register the Windows Simplified + // Chinese face (DengXian, regular + bold) explicitly instead. + FontOptions = new FontOptions + { + UseFontPack = false, + AllowSystemFonts = false, + Policy = FontPolicy.PreferRequested, + FontFiles = [WindowsFont("Deng.ttf"), WindowsFont("Dengb.ttf")], + FallbackFamilies = ["DengXian"], + }, + }, sink); + return sink.Images; + } + + private static string WindowsFont(string file) + => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), file); + + /// Collects each rendered PNG in memory; the renderer serialises sink calls. + private sealed class MemorySink : IRenderOutputSink + { + private MemoryStream? current; + public List Images { get; } = []; + + public ValueTask OpenAsync(ArtifactDescriptor artifact, CancellationToken cancellationToken) + { + current = new MemoryStream(); + return ValueTask.FromResult(current); + } + + public ValueTask CompleteAsync(ArtifactDescriptor artifact, long byteLength, CancellationToken cancellationToken) + { + Images.Add(current!.ToArray()); + current = null; + return ValueTask.CompletedTask; + } + + public ValueTask AbortAsync(ArtifactDescriptor artifact, Exception error, CancellationToken cancellationToken) + { + current = null; + return ValueTask.CompletedTask; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/BillingAllocationWindow.cs b/src/Leiren.Erp.Client/Documents/BillingAllocationWindow.cs new file mode 100644 index 0000000..0792e17 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/BillingAllocationWindow.cs @@ -0,0 +1,223 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Splits each customs item of a shipped batch between its suppliers: per +/// supplier the invoiced quantity and tax-included amount (unit price is +/// derived). One supplier may take the whole quantity (others 0). Each item's +/// quantities must add up to the declared quantity before saving. +/// +public sealed class BillingAllocationWindow +{ + private sealed class Row(SupplierInvoiceNoticeDto notice, SupplierInvoiceNoticeLineDto line) + { + public SupplierInvoiceNoticeDto Notice { get; } = notice; + public SupplierInvoiceNoticeLineDto Line { get; } = line; + public TextBox Quantity { get; } = DialogKit.TextBox(line.Quantity.ToString("0.###", CultureInfo.InvariantCulture)); + public TextBox Amount { get; } = DialogKit.TextBox(line.AmountIncludingTax.ToString("0.00", CultureInfo.InvariantCulture)); + public TextBlock Price { get; } = DialogKit.Note(""); + } + + private sealed class Item + { + public required string Name { get; init; } + public required string Unit { get; init; } + public required decimal Target { get; init; } + public List Rows { get; } = []; + public TextBlock Status { get; } = DialogKit.Note(""); + } + + private readonly ApiClient api; + private readonly Guid batchId; + private readonly IReadOnlyList noticeIds; + private readonly Window window; + private readonly StackPanel body = new(); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存分配"); + private readonly List items = []; + + public BillingAllocationWindow(ApiClient api, Guid batchId, string batchNo, IReadOnlyList noticeIds, Window? owner) + { + this.api = api; + this.batchId = batchId; + this.noticeIds = noticeIds; + window = DialogKit.Window(owner, $"分配开票数量 · {batchNo}", 900, 700); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"分配开票数量 · {batchNo}")); + top.Children.Add(DialogKit.Note( + "每个报关品名可以由一个或多个供应商开票:数量合计必须等于报关数量;金额为该供应商的含税开票金额,单价自动计算。某供应商不开该品名时数量和金额都填 0;一个供应商所有品名都为 0 时其开票通知作废。")); + top.Children.Add(new Border { Height = 10 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = body }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + try + { + var notices = new List(); + foreach (var id in noticeIds) notices.Add(await api.GetAsync($"/api/billing/notices/{id}")); + foreach (var group in notices + .SelectMany(n => n.Lines.Select(l => (Notice: n, Line: l))) + .GroupBy(x => x.Line.ShipmentLineId ?? x.Line.Id)) + { + var first = group.First().Line; + var item = new Item { Name = first.ContentDescription, Unit = first.Unit, Target = group.Sum(x => x.Line.Quantity) }; + foreach (var (notice, line) in group.OrderBy(x => x.Notice.SupplierName, StringComparer.CurrentCulture)) + item.Rows.Add(new Row(notice, line)); + items.Add(item); + } + Render(); + save.IsEnabled = items.Count > 0; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private static decimal? Parse(TextBox box) + => decimal.TryParse(box.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var value) ? value : null; + + private void Render() + { + body.Children.Clear(); + foreach (var item in items) + { + var card = new StackPanel(); + card.Children.Add(new TextBlock + { + Text = $"{item.Name} · 报关数量 {item.Target:0.###} {item.Unit}", + FontSize = 13, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink, Margin = new Thickness(0, 0, 0, 8), + }); + var grid = new Grid(); + foreach (var width in new[] { 2.2, 1, 1, 1, 0.6 }) + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(width, GridUnitType.Star) }); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + string[] headers = ["供应商", $"数量({item.Unit})", "含税金额(元)", "含税单价", ""]; + for (var c = 0; c < headers.Length; c++) + { + var header = DialogKit.Note(headers[c]); + Grid.SetColumn(header, c); + grid.Children.Add(header); + } + for (var r = 0; r < item.Rows.Count; r++) + { + var row = item.Rows[r]; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var all = DialogKit.Secondary("全部给它"); + all.MinWidth = 0; + all.Height = 32; + all.Click += (_, _) => GiveAll(item, row); + UIElement[] cells = + [ + new TextBlock { Text = row.Notice.SupplierName, VerticalAlignment = VerticalAlignment.Center, Foreground = DialogKit.Ink, TextWrapping = TextWrapping.Wrap }, + row.Quantity, row.Amount, row.Price, all, + ]; + for (var c = 0; c < cells.Length; c++) + { + if (cells[c] is FrameworkElement fe) fe.Margin = new Thickness(c == 0 ? 0 : 8, 6, 0, 0); + Grid.SetRow(cells[c], r + 1); + Grid.SetColumn(cells[c], c); + grid.Children.Add(cells[c]); + } + row.Quantity.TextChanged += (_, _) => Update(item); + row.Amount.TextChanged += (_, _) => Update(item); + } + card.Children.Add(grid); + card.Children.Add(item.Status); + body.Children.Add(new Border + { + Background = System.Windows.Media.Brushes.White, BorderBrush = DialogKit.Line, BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), Padding = new Thickness(14), Margin = new Thickness(0, 0, 0, 10), Child = card, + }); + Update(item); + } + } + + /// One supplier invoices the whole item: it takes the quantity and the item's total amount. + private static void GiveAll(Item item, Row target) + { + var total = item.Rows.Sum(x => Parse(x.Amount) ?? 0); + foreach (var row in item.Rows) + { + var isTarget = row == target; + row.Quantity.Text = (isTarget ? item.Target : 0).ToString("0.###", CultureInfo.InvariantCulture); + row.Amount.Text = (isTarget ? total : 0).ToString("0.00", CultureInfo.InvariantCulture); + } + } + + private static void Update(Item item) + { + foreach (var row in item.Rows) + { + var q = Parse(row.Quantity); + var a = Parse(row.Amount); + row.Price.Text = q is > 0 && a is not null ? (a.Value / q.Value).ToString("0.0000", CultureInfo.InvariantCulture) : "—"; + row.Price.VerticalAlignment = VerticalAlignment.Center; + } + var sum = item.Rows.Sum(x => Parse(x.Quantity) ?? 0); + var diff = item.Target - sum; + item.Status.Text = diff == 0 + ? $"合计 {sum:0.###} {item.Unit},与报关数量一致。" + : $"合计 {sum:0.###} {item.Unit},{(diff > 0 ? "还差" : "多出")} {Math.Abs(diff):0.###} {item.Unit}。"; + item.Status.Foreground = diff == 0 ? DialogKit.Green : DialogKit.Orange; + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + var lines = new List(); + foreach (var item in items) + { + foreach (var row in item.Rows) + { + if (Parse(row.Quantity) is not { } q || q < 0 || Parse(row.Amount) is not { } a || a < 0) + { + error.Text = $"{item.Name} · {row.Notice.SupplierName}:请填写不小于 0 的数量和金额。"; + return; + } + lines.Add(new BillingAllocationLineRequest(row.Line.Id, q, a)); + } + if (item.Rows.Sum(x => Parse(x.Quantity) ?? 0) != item.Target) + { + error.Text = $"{item.Name}:各供应商数量合计必须等于报关数量 {item.Target:0.###}。"; + return; + } + } + save.IsEnabled = false; + try + { + await api.PutAsync>($"/api/billing/notices/shipping-batches/{batchId}/allocation", + new ReallocateBillingRequest(lines)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/BillingNoticeEditWindow.cs b/src/Leiren.Erp.Client/Documents/BillingNoticeEditWindow.cs new file mode 100644 index 0000000..99bc065 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/BillingNoticeEditWindow.cs @@ -0,0 +1,146 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Edits a draft 开票通知's header (supplier contact, invoice title, mailing +/// and requirements). Quantities and amounts are changed in the batch +/// allocation window so every customs item stays consistent. +/// +public sealed class BillingNoticeEditWindow +{ + private readonly ApiClient api; + private readonly Guid noticeId; + private readonly Window window; + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存"); + private readonly Dictionary boxes = []; + private SupplierInvoiceNoticeDto? notice; + + private static readonly (string Key, string Label)[] FieldList = + [ + ("exportInvoiceNo", "外销发票号"), ("noticeDate", "通知日期 (yyyy-MM-dd)"), + ("supplierContact", "供应商联系人"), ("supplierPhone", "供应商电话"), + ("supplierFax", "供应商传真"), ("supplierAddress", "供应商地址"), + ("invoiceTitle", "发票抬头"), ("invoiceTitleAddress", "地址"), + ("invoiceTitlePhone", "电话"), ("invoiceTitleBankName", "开户银行"), + ("invoiceTitleBankAccount", "帐号"), ("invoiceTitleTaxNo", "税号"), + ("invoiceTitleCustomsCode", "海关代码"), ("mailingAddress", "寄件地址"), + ("contactName", "联系人"), ("invoicingRequirement", "开票要求"), + ("stampRequirement", "盖章要求"), ("remark", "备注"), + ]; + + public BillingNoticeEditWindow(ApiClient api, Guid noticeId, string title, Window? owner) + { + this.api = api; + this.noticeId = noticeId; + window = DialogKit.Window(owner, $"编辑开票通知 · {title}", 760, 760); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"编辑开票通知 · {title}")); + top.Children.Add(DialogKit.Note("开票数量和金额在批次的“分配数量”中调整,保证各供应商合计与报关单一致。")); + top.Children.Add(new Border { Height = 12 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + + var grid = new Grid(); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + for (var i = 0; i < FieldList.Length; i++) + { + if (i % 2 == 0) grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var box = DialogKit.TextBox(); + boxes[FieldList[i].Key] = box; + var field = DialogKit.Field(FieldList[i].Label, box); + field.Margin = new Thickness(i % 2 == 0 ? 0 : 10, 0, 0, 12); + Grid.SetRow(field, i / 2); + Grid.SetColumn(field, i % 2); + grid.Children.Add(field); + } + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = grid }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + try + { + var n = notice = await api.GetAsync($"/api/billing/notices/{noticeId}"); + void Set(string key, string? value) => boxes[key].Text = value ?? string.Empty; + Set("exportInvoiceNo", n.ExportInvoiceNo); + Set("noticeDate", n.NoticeDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); + Set("supplierContact", n.SupplierContact); + Set("supplierPhone", n.SupplierPhone); + Set("supplierFax", n.SupplierFax); + Set("supplierAddress", n.SupplierAddress); + Set("invoiceTitle", n.InvoiceTitle); + Set("invoiceTitleAddress", n.InvoiceTitleAddress); + Set("invoiceTitlePhone", n.InvoiceTitlePhone); + Set("invoiceTitleBankName", n.InvoiceTitleBankName); + Set("invoiceTitleBankAccount", n.InvoiceTitleBankAccount); + Set("invoiceTitleTaxNo", n.InvoiceTitleTaxNo); + Set("invoiceTitleCustomsCode", n.InvoiceTitleCustomsCode); + Set("mailingAddress", n.MailingAddress); + Set("contactName", n.ContactName); + Set("invoicingRequirement", n.InvoicingRequirement); + Set("stampRequirement", n.StampRequirement); + Set("remark", n.Remark); + save.IsEnabled = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private string? Value(string key) => boxes[key].Text.Trim() is { Length: > 0 } text ? text : null; + + private async Task SaveAsync() + { + if (notice is null) return; + error.Text = string.Empty; + DateOnly? date = null; + if (Value("noticeDate") is { } raw) + { + if (!DateOnly.TryParse(raw, CultureInfo.InvariantCulture, out var parsed)) { error.Text = "通知日期格式应为 yyyy-MM-dd。"; return; } + date = parsed; + } + if (Value("invoiceTitle") is null) { error.Text = "请填写发票抬头。"; return; } + save.IsEnabled = false; + try + { + var request = new UpdateSupplierInvoiceNoticeRequest( + Value("exportInvoiceNo"), notice.PurchaseContractId, notice.PurchaseContractNo, notice.SupplierId, notice.SupplierName, + Value("supplierContact"), Value("supplierPhone"), Value("supplierFax"), Value("supplierAddress"), + Value("invoiceTitle"), Value("invoiceTitleAddress"), Value("invoiceTitlePhone"), Value("invoiceTitleBankName"), + Value("invoiceTitleBankAccount"), Value("invoiceTitleTaxNo"), Value("invoiceTitleCustomsCode"), notice.Currency, + Value("invoicingRequirement"), Value("stampRequirement"), Value("contactName"), Value("mailingAddress"), + Value("remark"), date, null); + await api.PutAsync($"/api/billing/notices/{noticeId}", request); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/BillingNoticeWindow.cs b/src/Leiren.Erp.Client/Documents/BillingNoticeWindow.cs new file mode 100644 index 0000000..dd98d52 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/BillingNoticeWindow.cs @@ -0,0 +1,138 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Generates the supplier 开票通知 (one per supplier, each with its 开票购销合同) +/// for a shipped batch. Lines come from the confirmed customs declaration on +/// the server; here only the invoice title, mailing and contract details are +/// entered — prefilled from the most recent notice, so they are typed once. +/// +public sealed class BillingNoticeWindow +{ + private readonly ApiClient api; + private readonly ShippingBatchListItemDto batch; + private readonly Window window; + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("生成开票通知"); + private readonly Dictionary boxes = []; + + private static readonly (string Key, string Label)[] FieldList = + [ + ("exportInvoiceNo", "外销发票号(空则取报关资料的发票编号)"), + ("invoiceTitle", "发票抬头"), + ("invoiceTitleAddress", "地址"), + ("invoiceTitlePhone", "电话"), + ("invoiceTitleBankName", "开户银行"), + ("invoiceTitleBankAccount", "帐号"), + ("invoiceTitleTaxNo", "税号"), + ("invoiceTitleCustomsCode", "海关代码"), + ("mailingAddress", "寄件地址"), + ("contactName", "联系人"), + ("signedPlace", "合同签订地点"), + ]; + + /// Notices created by the dialog (one per supplier). + public IReadOnlyList Created { get; private set; } = []; + + public BillingNoticeWindow(ApiClient api, ShippingBatchListItemDto batch, Window? owner) + { + this.api = api; + this.batch = batch; + window = DialogKit.Window(owner, $"生成开票通知 · {batch.BatchNo}", 760, 760); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading("生成供应商开票通知")); + top.Children.Add(DialogKit.Note( + "每个供应商生成一份开票通知和开票用购销合同。品名、单位取自已确认的报关资料;一个产品有多个供应商时,报关数量按各供应商采购金额比例拆分,合计与报关单一致,金额为各供应商自己的含税采购金额。")); + top.Children.Add(new Border { Height = 12 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + + var grid = new Grid(); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + for (var i = 0; i < FieldList.Length; i++) + { + if (i % 2 == 0) grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var box = DialogKit.TextBox(); + boxes[FieldList[i].Key] = box; + var field = DialogKit.Field(FieldList[i].Label, box); + field.Margin = new Thickness(i % 2 == 0 ? 0 : 10, 0, 0, 12); + Grid.SetRow(field, i / 2); + Grid.SetColumn(field, i % 2); + grid.Children.Add(field); + } + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = grid }); + window.Content = root; + window.Loaded += async (_, _) => await PrefillAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task PrefillAsync() + { + try + { + var latest = (await api.GetAsync>("/api/billing/notices?page=1&pageSize=200")) + .OrderByDescending(x => x.NoticeDate).ThenByDescending(x => x.NoticeNo, StringComparer.Ordinal).FirstOrDefault(); + if (latest is null) return; + var n = await api.GetAsync($"/api/billing/notices/{latest.Id}"); + boxes["invoiceTitle"].Text = n.InvoiceTitle ?? ""; + boxes["invoiceTitleAddress"].Text = n.InvoiceTitleAddress ?? ""; + boxes["invoiceTitlePhone"].Text = n.InvoiceTitlePhone ?? ""; + boxes["invoiceTitleBankName"].Text = n.InvoiceTitleBankName ?? ""; + boxes["invoiceTitleBankAccount"].Text = n.InvoiceTitleBankAccount ?? ""; + boxes["invoiceTitleTaxNo"].Text = n.InvoiceTitleTaxNo ?? ""; + boxes["invoiceTitleCustomsCode"].Text = n.InvoiceTitleCustomsCode ?? ""; + boxes["mailingAddress"].Text = n.MailingAddress ?? ""; + boxes["contactName"].Text = n.ContactName ?? ""; + } + catch (ApiException ex) + { + error.Text = $"读取上一份开票通知失败:{ex.Message}"; + } + } + + private string? Value(string key) => boxes[key].Text.Trim() is { Length: > 0 } text ? text : null; + + private async Task SaveAsync() + { + error.Text = string.Empty; + if (Value("invoiceTitle") is null) { error.Text = "请填写发票抬头。"; return; } + save.IsEnabled = false; + try + { + var request = new GenerateBillingNoticesRequest( + batch.Id, Value("exportInvoiceNo"), null, null, + Value("invoiceTitle"), Value("invoiceTitleAddress"), Value("invoiceTitlePhone"), Value("invoiceTitleBankName"), + Value("invoiceTitleBankAccount"), Value("invoiceTitleTaxNo"), Value("invoiceTitleCustomsCode"), + null, null, Value("contactName"), Value("mailingAddress"), Value("signedPlace"), null, + null, null, null, null, null, null); + var result = await api.PostAsync("/api/billing/notices/generate-from-shipping-batch", request); + Created = result.Notices; + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + finally + { + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/ContainerNumbersWindow.cs b/src/Leiren.Erp.Client/Documents/ContainerNumbersWindow.cs new file mode 100644 index 0000000..04f8903 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/ContainerNumbersWindow.cs @@ -0,0 +1,119 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Records the real container and seal numbers of a draft shipping batch +/// after loading; the packing wizard creates the containers with placeholder +/// numbers marked "柜号待补". +/// +public sealed class ContainerNumbersWindow +{ + private const string PendingRemark = "柜号待补"; + + private sealed record Row(ShippingContainerDto Container, TextBox Number, TextBox Seal); + + private readonly ApiClient api; + private readonly Guid batchId; + private readonly Window window; + private readonly StackPanel rows = new(); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存"); + private readonly List rowControls = []; + + public ContainerNumbersWindow(ApiClient api, Guid batchId, string batchNo, Window? owner) + { + this.api = api; + this.batchId = batchId; + window = DialogKit.Window(owner, $"柜号 / 封条号 · {batchNo}", 640, 460); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading("补录柜号与封条号")); + top.Children.Add(DialogKit.Note("装柜后填写实际集装箱号和封条号;确认出货前可以随时修改。")); + top.Children.Add(new Border { Height = 12 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = rows }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + try + { + var batch = await api.GetAsync($"/api/shipping-batches/{batchId}"); + foreach (var container in batch.Containers) + { + var pending = container.Remark == PendingRemark; + var number = DialogKit.TextBox(pending ? string.Empty : container.ContainerNo); + var seal = DialogKit.TextBox(container.SealNo ?? string.Empty); + var grid = new Grid { Margin = new Thickness(0, 0, 0, 6) }; + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(110) }); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(12) }); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.Children.Add(new TextBlock { Text = $"{container.ContainerType ?? "集装箱"}{(pending ? $"({container.ContainerNo})" : "")}", VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, 20), Foreground = DialogKit.Ink }); + var numberField = DialogKit.Field("集装箱号", number); + Grid.SetColumn(numberField, 1); + grid.Children.Add(numberField); + var sealField = DialogKit.Field("封条号", seal); + Grid.SetColumn(sealField, 3); + grid.Children.Add(sealField); + rows.Children.Add(grid); + rowControls.Add(new Row(container, number, seal)); + } + if (rowControls.Count == 0) rows.Children.Add(DialogKit.Note("该批次没有集装箱。")); + save.IsEnabled = rowControls.Count > 0; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + save.IsEnabled = false; + try + { + foreach (var row in rowControls) + { + var number = row.Number.Text.Trim(); + var seal = row.Seal.Text.Trim(); + var pending = number.Length == 0; + var request = new SaveShippingContainerRequest( + pending ? row.Container.ContainerNo : number, + row.Container.ContainerType, + seal.Length == 0 ? null : seal, + pending ? PendingRemark : null); + if (request.ContainerNo == row.Container.ContainerNo && request.SealNo == row.Container.SealNo && request.Remark == row.Container.Remark) + continue; + await api.PutAsync($"/api/shipping-batches/{batchId}/containers/{row.Container.Id}", request); + } + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/CustomsDeclarationWindow.cs b/src/Leiren.Erp.Client/Documents/CustomsDeclarationWindow.cs new file mode 100644 index 0000000..ff54537 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/CustomsDeclarationWindow.cs @@ -0,0 +1,299 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// 报关资料 of one shipped batch. Opening a batch without a live declaration +/// creates a draft snapshot; the server prefills customs names, HS codes, +/// declaration elements, trade mode etc. from the latest confirmed +/// declaration of the same product / customer. Drafts are edited and saved +/// here; confirming (with a second confirmation) locks the declaration so the +/// customs documents and supplier billing read from it. A confirmed +/// declaration can only be voided, after which reopening creates a new +/// version. +/// +public sealed class CustomsDeclarationWindow +{ + private sealed record LineControls( + CustomsDeclarationLineDto Line, TextBox HsCode, TextBox NameZh, TextBox NameEn, TextBox Unit, + TextBox Elements, TextBox Origin, TextBox SourcePlace, TextBox Exemption, TextBox Quantity, TextBox UnitPrice); + + private readonly ApiClient api; + private readonly Guid batchId; + private readonly Window window; + private readonly StackPanel body = new(); + private readonly TextBlock status = DialogKit.Note(""); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button voidButton = DialogKit.Secondary("作废"); + private readonly Button save = DialogKit.Primary("保存"); + private readonly Button confirm = DialogKit.Primary("确认报关单"); + private readonly TextBox declarationNo = DialogKit.TextBox(); + private readonly TextBox invoiceNo = DialogKit.TextBox(); + private readonly TextBox exportDate = DialogKit.TextBox(); + private readonly TextBox declarationDate = DialogKit.TextBox(); + private readonly TextBox tradeMode = DialogKit.TextBox(); + private readonly TextBox exemptionNature = DialogKit.TextBox(); + private readonly TextBox remark = DialogKit.TextBox(); + private readonly List lines = []; + private CustomsDeclarationDto? declaration; + + public bool Changed { get; private set; } + + public CustomsDeclarationWindow(ApiClient api, Guid batchId, string batchNo, Window? owner) + { + this.api = api; + this.batchId = batchId; + window = DialogKit.Window(owner, $"报关资料 · {batchNo}", 1180, 820); + + var close = DialogKit.Secondary("关闭"); + close.Click += (_, _) => window.Close(); + voidButton.Click += async (_, _) => await VoidAsync(); + save.Click += async (_, _) => await SaveAsync(showToast: true); + confirm.Click += async (_, _) => await ConfirmAsync(); + confirm.Background = DialogKit.Green; + foreach (var b in new[] { voidButton, save, confirm }) b.IsEnabled = false; + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"报关资料 · {batchNo}")); + top.Children.Add(status); + top.Children.Add(new Border { Height = 10 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(voidButton, close, save, confirm)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = body }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public void ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + error.Text = string.Empty; + try + { + var list = await api.GetAsync>($"/api/customs/?shippingBatchId={batchId}&page=1&pageSize=50"); + var live = list.Where(x => x.Status != "Voided").OrderByDescending(x => x.Version).FirstOrDefault(); + if (live is null) + { + declaration = await api.PostAsync("/api/customs/", + new CreateCustomsDeclarationRequest(batchId, null, null, null, null, null, null, null)); + Changed = true; + } + else + { + declaration = await api.GetAsync($"/api/customs/{live.Id}"); + } + Render(); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private void Render() + { + if (declaration is not { } d) return; + var draft = d.Status == "Draft"; + status.Text = draft + ? $"第 {d.Version} 版 · 草稿。报关品名、HS 编码、申报要素等已按该产品最近一次确认的报关单预填,没有历史的取产品资料。" + : $"第 {d.Version} 版 · 已确认({d.ConfirmedAt?.ToLocalTime():yyyy-MM-dd HH:mm} {d.ConfirmedBy})。报关单证和开票取数以此为准;如需修改请先作废,再重新打开生成新版本。"; + status.Foreground = draft ? DialogKit.Muted : DialogKit.Green; + save.IsEnabled = draft; + confirm.IsEnabled = draft; + save.Visibility = confirm.Visibility = draft ? Visibility.Visible : Visibility.Collapsed; + voidButton.IsEnabled = true; + + body.Children.Clear(); + lines.Clear(); + + body.Children.Add(Section("基本信息")); + body.Children.Add(DialogKit.Note( + $"{d.CustomerName} · 订单 {d.SalesOrderNo} · PO {d.CustomerPoNo ?? "—"} · {d.LoadingPort ?? "—"} → {d.DestinationPort ?? "—"} · 柜号 {d.ContainerNumbers ?? "—"}")); + body.Children.Add(new Border { Height = 8 }); + var header = Columns(4); + Place(header, 0, 0, "报关单号", Set(declarationNo, d.DeclarationNo, draft)); + Place(header, 0, 1, "发票编号(空则用出货批次号)", Set(invoiceNo, d.InvoiceNo, draft)); + Place(header, 0, 2, "出口日期 (yyyy-MM-dd)", Set(exportDate, d.ExportDate?.ToString("yyyy-MM-dd"), draft)); + Place(header, 0, 3, "申报日期 (yyyy-MM-dd)", Set(declarationDate, d.DeclarationDate?.ToString("yyyy-MM-dd"), draft)); + Place(header, 1, 0, "监管方式 / 贸易方式", Set(tradeMode, d.TradeMode, draft)); + Place(header, 1, 1, "征免性质", Set(exemptionNature, d.ExemptionNature, draft)); + Place(header, 1, 2, "备注", Set(remark, d.Remark, draft)); + body.Children.Add(header); + + body.Children.Add(Section($"报关明细({d.Lines.Count} 项 · 合计 {d.TotalQuantity:N0} · {d.Currency} {d.TotalAmount:N2} · {d.TotalCartonCount} 箱 · 毛重 {d.TotalGrossWeight:N1} kg)")); + foreach (var line in d.Lines.OrderBy(x => x.LineNumber)) + { + var controls = new LineControls(line, + Set(DialogKit.TextBox(), line.HsCode, draft), Set(DialogKit.TextBox(), line.CustomsNameZh, draft), + Set(DialogKit.TextBox(), line.CustomsNameEn, draft), Set(DialogKit.TextBox(), line.Unit, draft), + Set(DialogKit.TextBox(), line.DeclarationElements, draft), Set(DialogKit.TextBox(), line.OriginCountry, draft), + Set(DialogKit.TextBox(), line.DomesticSourcePlace, draft), Set(DialogKit.TextBox(), line.ExemptionInfo, draft), + Set(DialogKit.TextBox(), line.Quantity.ToString("0.####", CultureInfo.InvariantCulture), draft), + Set(DialogKit.TextBox(), line.UnitPrice.ToString("0.####", CultureInfo.InvariantCulture), draft)); + lines.Add(controls); + + var card = new StackPanel(); + card.Children.Add(new TextBlock + { + Text = $"{line.LineNumber}. {line.InternalSku} · {line.ProductNameZh} · {line.CartonCount} 箱 · 毛重 {line.TotalGrossWeight:N1} kg · 净重 {line.TotalNetWeight:N1} kg", + FontSize = 13, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink, Margin = new Thickness(0, 0, 0, 8), + }); + var grid = Columns(5); + Place(grid, 0, 0, "HS 编码", controls.HsCode); + Place(grid, 0, 1, "中文品名", controls.NameZh); + Place(grid, 0, 2, "英文品名", controls.NameEn); + Place(grid, 0, 3, "报关单位", controls.Unit); + Place(grid, 0, 4, "原产国", controls.Origin); + Place(grid, 1, 0, "境内货源地", controls.SourcePlace); + Place(grid, 1, 1, "征免", controls.Exemption); + Place(grid, 1, 2, "数量", controls.Quantity); + Place(grid, 1, 3, $"单价 ({d.Currency})", controls.UnitPrice); + Place(grid, 1, 4, "金额", new TextBlock { Text = line.Amount.ToString("N2"), FontSize = 13, Foreground = DialogKit.Ink, VerticalAlignment = VerticalAlignment.Center, Height = 32, Padding = new Thickness(0, 7, 0, 0) }); + card.Children.Add(grid); + card.Children.Add(DialogKit.Field("申报要素", controls.Elements)); + body.Children.Add(new Border + { + Background = System.Windows.Media.Brushes.White, BorderBrush = DialogKit.Line, BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), Padding = new Thickness(14), Margin = new Thickness(0, 0, 0, 10), Child = card, + }); + } + } + + private static TextBlock Section(string text) => new() + { + Text = text, FontSize = 13, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink, Margin = new Thickness(0, 10, 0, 8), + }; + + private static TextBox Set(TextBox box, string? value, bool editable) + { + box.Text = value ?? string.Empty; + box.IsReadOnly = !editable; + box.Background = editable ? System.Windows.Media.Brushes.White : DialogKit.Wash; + return box; + } + + private static Grid Columns(int count) + { + var grid = new Grid(); + for (var i = 0; i < count; i++) grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + return grid; + } + + private static void Place(Grid grid, int row, int column, string label, UIElement control) + { + var field = DialogKit.Field(label, control); + field.Margin = new Thickness(column == 0 ? 0 : 8, 0, 0, 10); + Grid.SetRow(field, row); + Grid.SetColumn(field, column); + grid.Children.Add(field); + } + + private static string? Optional(TextBox box) => box.Text.Trim() is { Length: > 0 } text ? text : null; + + private bool TryBuildRequest(out UpdateCustomsDeclarationRequest request) + { + request = null!; + DateOnly? ParseDate(TextBox box, string label) + { + if (Optional(box) is not { } text) return null; + if (DateOnly.TryParse(text, CultureInfo.InvariantCulture, out var date)) return date; + throw new FormatException($"{label}格式应为 yyyy-MM-dd。"); + } + try + { + var lineRequests = lines.Select(x => + { + if (!decimal.TryParse(x.Quantity.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var quantity) || quantity <= 0) + throw new FormatException($"第 {x.Line.LineNumber} 项数量必须是大于 0 的数字。"); + if (!decimal.TryParse(x.UnitPrice.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var price) || price < 0) + throw new FormatException($"第 {x.Line.LineNumber} 项单价必须是不小于 0 的数字。"); + return new UpdateCustomsLineRequest(x.Line.Id, Optional(x.HsCode), Optional(x.NameZh), Optional(x.NameEn), Optional(x.Unit), + Optional(x.Elements), Optional(x.Origin), Optional(x.SourcePlace), Optional(x.Exemption), quantity, price, x.Line.Remark); + }).ToList(); + request = new UpdateCustomsDeclarationRequest( + Optional(declarationNo), ParseDate(exportDate, "出口日期"), ParseDate(declarationDate, "申报日期"), + Optional(tradeMode), Optional(exemptionNature), Optional(remark), lineRequests, Optional(invoiceNo)); + return true; + } + catch (FormatException ex) + { + error.Text = ex.Message; + return false; + } + } + + private async Task SaveAsync(bool showToast) + { + if (declaration is null) return false; + error.Text = string.Empty; + if (!TryBuildRequest(out var request)) return false; + save.IsEnabled = confirm.IsEnabled = false; + try + { + declaration = await api.PutAsync($"/api/customs/{declaration.Id}", request); + Changed = true; + Render(); + if (showToast) status.Text = "已保存。" + status.Text; + return true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = confirm.IsEnabled = true; + return false; + } + } + + private async Task ConfirmAsync() + { + if (declaration is null) return; + if (!await SaveAsync(showToast: false)) return; + var answer = MessageBox.Show(window, + $"确认报关单 {declaration.DeclarationNo ?? declaration.ShippingBatchNo}?确认后不能再修改,报关单证和开票将以此为准。", + "确认报关单", MessageBoxButton.YesNo, MessageBoxImage.Warning); + if (answer != MessageBoxResult.Yes) return; + try + { + declaration = await api.PostAsync($"/api/customs/{declaration.Id}/confirm", + new ConfirmCustomsDeclarationRequest(api.CurrentUser?.DisplayName ?? api.CurrentUser?.UserName)); + Changed = true; + Render(); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private async Task VoidAsync() + { + if (declaration is null) return; + var answer = MessageBox.Show(window, + $"作废第 {declaration.Version} 版报关资料?作废后重新打开会按历史信息生成新版本。", + "作废报关资料", MessageBoxButton.YesNo, MessageBoxImage.Warning); + if (answer != MessageBoxResult.Yes) return; + try + { + await api.PostAsync($"/api/customs/{declaration.Id}/void", null); + Changed = true; + window.Close(); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/PayableConfirmWindow.cs b/src/Leiren.Erp.Client/Documents/PayableConfirmWindow.cs new file mode 100644 index 0000000..3f23fa6 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/PayableConfirmWindow.cs @@ -0,0 +1,82 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Confirms payment of one supplier payable. Entering the payment details is +/// the first confirmation; a second explicit dialog follows because a recorded +/// payment cannot be undone. +/// +public sealed class PayableConfirmWindow +{ + private readonly ApiClient api; + private readonly SupplierPayableDto payable; + private readonly Window window; + private readonly DatePicker paidDate = new() { SelectedDate = DateTime.Today, DisplayDateEnd = DateTime.Today, Height = 32 }; + private readonly TextBox reference = DialogKit.TextBox(); + private readonly TextBox remark = DialogKit.TextBox(); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button pay = DialogKit.Primary("确认付款"); + + public PayableConfirmWindow(ApiClient api, SupplierPayableDto payable, Window? owner) + { + this.api = api; + this.payable = payable; + window = DialogKit.Window(owner, $"确认付款 · {payable.ContractNo}", 560, 470); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + pay.Click += async (_, _) => await PayAsync(); + + var panel = new StackPanel { Margin = new Thickness(20) }; + panel.Children.Add(DialogKit.Heading($"{payable.SupplierName}")); + panel.Children.Add(DialogKit.Note($"采购合同 {payable.ContractNo} · 客户订单 {payable.CustomerOrderNo ?? "—"} · 付款条件 {payable.PaymentTerms ?? "未填"}")); + panel.Children.Add(new TextBlock + { + Text = $"{payable.Currency} {payable.Amount:N2}", + FontSize = 24, + FontWeight = FontWeights.SemiBold, + Foreground = DialogKit.Blue, + Margin = new Thickness(0, 12, 0, 14), + }); + panel.Children.Add(DialogKit.Field("付款日期", paidDate)); + panel.Children.Add(DialogKit.Field("付款凭证号 / 银行流水号(可选)", reference)); + panel.Children.Add(DialogKit.Field("备注(可选)", remark)); + panel.Children.Add(error); + panel.Children.Add(DialogKit.Buttons(cancel, pay)); + window.Content = panel; + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task PayAsync() + { + error.Text = string.Empty; + if (paidDate.SelectedDate is not { } date) { error.Text = "请选择付款日期。"; return; } + if (date.Date > DateTime.Today) { error.Text = "付款日期不能晚于今天。"; return; } + + var answer = MessageBox.Show(window, + $"确认已向 {payable.SupplierName} 支付 {payable.Currency} {payable.Amount:N2}({date:yyyy-MM-dd})?\n\n付款记录保存后不能撤销。", + "二次确认付款", MessageBoxButton.YesNo, MessageBoxImage.Warning); + if (answer != MessageBoxResult.Yes) return; + + pay.IsEnabled = false; + try + { + await api.PostAsync($"/api/payables/{payable.Id}/pay", new PaySupplierPayableRequest( + DateOnly.FromDateTime(date), + string.IsNullOrWhiteSpace(reference.Text) ? null : reference.Text.Trim(), + string.IsNullOrWhiteSpace(remark.Text) ? null : remark.Text.Trim(), + api.CurrentUser?.DisplayName ?? api.CurrentUser?.UserName)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + pay.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/SupplierInvoiceRegisterWindow.cs b/src/Leiren.Erp.Client/Documents/SupplierInvoiceRegisterWindow.cs new file mode 100644 index 0000000..daa4a8d --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/SupplierInvoiceRegisterWindow.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Registers the VAT invoice a supplier returned for a confirmed 开票通知. +/// The amount defaults to what is still un-invoiced; excluding-tax amount and +/// tax are derived from the tax rate. +/// +public sealed class SupplierInvoiceRegisterWindow +{ + private readonly ApiClient api; + private readonly SupplierInvoiceNoticeListItemDto notice; + private readonly Window window; + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly TextBlock split = DialogKit.Note(""); + private readonly Button save = DialogKit.Primary("登记发票"); + private readonly TextBox invoiceNo = DialogKit.TextBox(); + private readonly TextBox invoiceDate = DialogKit.TextBox(DateTime.Today.ToString("yyyy-MM-dd")); + private readonly TextBox amount; + private readonly TextBox taxRate = DialogKit.TextBox("13"); + private readonly TextBox remark = DialogKit.TextBox(); + + public SupplierInvoiceRegisterWindow(ApiClient api, SupplierInvoiceNoticeListItemDto notice, Window? owner) + { + this.api = api; + this.notice = notice; + amount = DialogKit.TextBox(notice.RemainingAmountIncludingTax.ToString("0.00", CultureInfo.InvariantCulture)); + window = DialogKit.Window(owner, $"登记供应商发票 · {notice.SupplierName}", 620, 560); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.Click += async (_, _) => await SaveAsync(); + amount.TextChanged += (_, _) => UpdateSplit(); + taxRate.TextChanged += (_, _) => UpdateSplit(); + + var panel = new StackPanel { Margin = new Thickness(20) }; + panel.Children.Add(DialogKit.Heading($"登记供应商发票 · {notice.SupplierName}")); + panel.Children.Add(DialogKit.Note( + $"开票通知 {notice.NoticeNo} · 应开 {notice.Currency} {notice.TotalAmountIncludingTax:N2} · 已登记 {notice.InvoicedAmountIncludingTax:N2} · 待开 {notice.RemainingAmountIncludingTax:N2}")); + panel.Children.Add(new Border { Height = 12 }); + var grid = new Grid(); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + (string, UIElement)[] fields = [("发票号码", invoiceNo), ("开票日期 (yyyy-MM-dd)", invoiceDate), ("含税金额(元)", amount), ("税率 (%)", taxRate)]; + for (var i = 0; i < fields.Length; i++) + { + if (i % 2 == 0) grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var field = DialogKit.Field(fields[i].Item1, fields[i].Item2); + field.Margin = new Thickness(i % 2 == 0 ? 0 : 10, 0, 0, 12); + Grid.SetRow(field, i / 2); + Grid.SetColumn(field, i % 2); + grid.Children.Add(field); + } + panel.Children.Add(grid); + panel.Children.Add(split); + panel.Children.Add(new Border { Height = 8 }); + panel.Children.Add(DialogKit.Field("备注", remark)); + panel.Children.Add(error); + panel.Children.Add(DialogKit.Buttons(cancel, save)); + window.Content = panel; + UpdateSplit(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private static decimal? Parse(TextBox box) + => decimal.TryParse(box.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var value) ? value : null; + + private (decimal Excluding, decimal Tax)? Split() + { + if (Parse(amount) is not { } total || Parse(taxRate) is not { } rate) return null; + var excluding = decimal.Round(total / (1 + rate / 100m), 2, MidpointRounding.AwayFromZero); + return (excluding, total - excluding); + } + + private void UpdateSplit() + => split.Text = Split() is { } s ? $"不含税金额 {s.Excluding:N2} · 税额 {s.Tax:N2}" : "请填写有效的金额和税率。"; + + private async Task SaveAsync() + { + error.Text = string.Empty; + if (invoiceNo.Text.Trim().Length == 0) { error.Text = "请填写发票号码。"; return; } + if (!DateOnly.TryParse(invoiceDate.Text.Trim(), CultureInfo.InvariantCulture, out var date)) { error.Text = "开票日期格式应为 yyyy-MM-dd。"; return; } + if (Parse(amount) is not { } total || total <= 0 || Split() is not { } s) { error.Text = "含税金额必须大于 0,税率必须是数字。"; return; } + save.IsEnabled = false; + try + { + await api.PostAsync($"/api/billing/notices/{notice.Id}/invoices", new RegisterSupplierInvoiceRequest( + invoiceNo.Text.Trim(), null, "VatSpecial", date, DateOnly.FromDateTime(DateTime.Today), notice.Currency, + Parse(taxRate), s.Excluding, s.Tax, total, null, remark.Text.Trim() is { Length: > 0 } r ? r : null)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/TemplateImportWindow.cs b/src/Leiren.Erp.Client/Documents/TemplateImportWindow.cs new file mode 100644 index 0000000..8a11ad4 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/TemplateImportWindow.cs @@ -0,0 +1,147 @@ +using System.IO; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Imports an XLSX template of any supported type, or uploads a new version +/// of an existing template (type fixed). The server scans the workbook and +/// rejects files without {{...}} placeholders. +/// +public sealed class TemplateImportWindow +{ + private readonly ApiClient api; + private readonly DocumentTemplateListItemDto? existing; + private readonly Window window; + private readonly TextBox path = DialogKit.TextBox(); + private readonly TextBox name = DialogKit.TextBox(); + private readonly ComboBox kind = new() { Height = 32, DisplayMemberPath = nameof(DocumentTemplateKindDto.DisplayName) }; + private readonly ComboBox customer = new() { Height = 32, DisplayMemberPath = nameof(CustomerChoice.Label) }; + + /// Customer a template is dedicated to; Id null = 通用(所有客户). + private sealed record CustomerChoice(Guid? Id, string Label); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("导入"); + + /// The uploaded template version, set when the dialog returns true. + public DocumentTemplateUploadResultDto? Result { get; private set; } + + public TemplateImportWindow(ApiClient api, IReadOnlyList kinds, Window? owner, DocumentTemplateListItemDto? existing = null) + { + this.api = api; + this.existing = existing; + window = DialogKit.Window(owner, existing is null ? "导入模板" : $"上传新版本 · {existing.Name}", 620, 500); + + path.IsReadOnly = true; + var browse = DialogKit.Secondary("选择文件…"); + browse.Margin = new Thickness(8, 0, 0, 0); + browse.Click += (_, _) => Browse(); + var pathRow = new DockPanel(); + DockPanel.SetDock(browse, Dock.Right); + pathRow.Children.Add(browse); + pathRow.Children.Add(path); + + kind.ItemsSource = kinds; + kind.SelectedItem = existing is null ? kinds.FirstOrDefault() : kinds.FirstOrDefault(x => x.Key == existing.DocumentKind); + kind.IsEnabled = existing is null; + name.Text = existing?.Name ?? string.Empty; + customer.IsEnabled = existing is null; + customer.ItemsSource = new[] { new CustomerChoice(existing?.CustomerId, existing?.CustomerName ?? "通用(所有客户)") }; + customer.SelectedIndex = 0; + kind.SelectionChanged += (_, _) => UpdateCustomerState(); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.Content = existing is null ? "导入" : "上传新版本"; + save.Click += async (_, _) => await SaveAsync(); + + var panel = new StackPanel { Margin = new Thickness(20) }; + panel.Children.Add(DialogKit.Heading(existing is null ? "导入单证模板" : "上传模板新版本")); + panel.Children.Add(DialogKit.Note(existing is null + ? "支持报关单证、客户 CI/PL、采购合同、开票通知和开票购销合同模板(.xlsx)。单元格中用 {{字段}} 标出要填充的位置,明细行占位符所在行会按明细逐行复制。" + : "新版本保留模板类型;已用于生成单证的旧版本映射被锁定,新版本需要重新确认字段映射(会自动带入同名占位符的旧映射)。")); + panel.Children.Add(new Border { Height = 14 }); + panel.Children.Add(DialogKit.Field("模板文件(.xlsx)", pathRow)); + panel.Children.Add(DialogKit.Field("模板类型", kind)); + panel.Children.Add(DialogKit.Field("模板名称(可选,默认取文件名)", name)); + panel.Children.Add(DialogKit.Field("适用客户(客户专用模板生成单证时按批次客户自动勾选)", customer)); + panel.Children.Add(error); + panel.Children.Add(DialogKit.Buttons(cancel, save)); + window.Content = panel; + if (existing is null) window.Loaded += async (_, _) => await LoadCustomersAsync(); + UpdateCustomerState(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadCustomersAsync() + { + try + { + var customers = await api.GetAsync>("/api/customers/?page=1&pageSize=200"); + customer.ItemsSource = new[] { new CustomerChoice(null, "通用(所有客户)") } + .Concat(customers.Where(x => x.IsActive).OrderBy(x => x.Name).Select(x => new CustomerChoice(x.Id, x.Name))) + .ToList(); + customer.SelectedIndex = 0; + } + catch (ApiException ex) + { + error.Text = $"加载客户失败:{ex.Message}"; + } + } + + /// Purchase-contract templates are never customer specific. + private void UpdateCustomerState() + { + var shipping = kind.SelectedItem is DocumentTemplateKindDto { UsesFieldMapping: true }; + customer.IsEnabled = existing is null && shipping; + if (!shipping && existing is null) customer.SelectedIndex = 0; + } + + private void Browse() + { + var dialog = new Microsoft.Win32.OpenFileDialog { Filter = "Excel 模板 (*.xlsx)|*.xlsx", CheckFileExists = true }; + if (dialog.ShowDialog(window) != true) return; + path.Text = dialog.FileName; + if (name.Text.Length == 0) name.Text = Path.GetFileNameWithoutExtension(dialog.FileName); + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + if (!File.Exists(path.Text)) { error.Text = "请选择要导入的 .xlsx 模板文件。"; return; } + if (kind.SelectedItem is not DocumentTemplateKindDto selected) { error.Text = "请选择模板类型。"; return; } + + save.IsEnabled = false; + try + { + var fields = new Dictionary + { + ["name"] = name.Text.Trim(), + ["documentKind"] = selected.Key, + ["customerId"] = (customer.SelectedItem as CustomerChoice)?.Id?.ToString("D"), + ["uploadedBy"] = api.CurrentUser?.DisplayName ?? api.CurrentUser?.UserName, + }; + var url = existing is null + ? "/api/document-templates/upload" + : $"/api/document-templates/{existing.TemplateVersionId}/versions"; + Result = await api.UploadAsync(url, path.Text, fields); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + catch (IOException ex) + { + error.Text = $"读取文件失败:{ex.Message}"; + } + finally + { + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/TemplateMappingWindow.cs b/src/Leiren.Erp.Client/Documents/TemplateMappingWindow.cs new file mode 100644 index 0000000..3c8b4e9 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/TemplateMappingWindow.cs @@ -0,0 +1,191 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Maps every placeholder of one template version to a business field. Rows +/// are prefilled from the saved mapping, else from the previous template +/// version's mapping, else from a business field with the same key. A mapping +/// already used to generate documents is locked and shown read-only. +/// +public sealed class TemplateMappingWindow +{ + private sealed record FieldOption(string? Key, string Label); + private sealed record Row(TemplatePlaceholderDto Placeholder, ComboBox Combo); + + private readonly ApiClient api; + private readonly DocumentTemplateListItemDto template; + private readonly Window window; + private readonly StackPanel rows = new(); + private readonly TextBlock status = DialogKit.Note("正在读取模板…"); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存映射"); + private readonly List rowControls = []; + private DocumentTemplateMappingProfileDto? profile; + + public TemplateMappingWindow(ApiClient api, DocumentTemplateListItemDto template, Window? owner) + { + this.api = api; + this.template = template; + window = DialogKit.Window(owner, $"字段映射 · {template.Name}", 860, 720); + + var cancel = DialogKit.Secondary("关闭"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"{template.Name} · v{template.Version}")); + top.Children.Add(DialogKit.Note("为每个 {{占位符}} 选择要填入的业务字段。选了“明细”字段的占位符所在行会按出货明细逐行复制填充;表头和合计字段只填一次。")); + top.Children.Add(status); + top.Children.Add(new Border { Height = 10 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + + root.Children.Add(new ScrollViewer + { + VerticalScrollBarVisibility = ScrollBarVisibility.Auto, + Content = new Border { Background = System.Windows.Media.Brushes.White, BorderBrush = DialogKit.Line, BorderThickness = new Thickness(1), Padding = new Thickness(12), Child = rows }, + }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task TryGetProfileAsync(Guid templateVersionId) + { + try + { + return await api.GetAsync($"/api/document-templates/{templateVersionId}/mapping-profile"); + } + catch (ApiException ex) when (ex.StatusCode == 404) + { + return null; + } + } + + private async Task LoadAsync() + { + try + { + var fields = await api.GetAsync>("/api/document-templates/fields"); + var scan = await api.GetAsync($"/api/document-templates/{template.TemplateVersionId}/scan"); + profile = await TryGetProfileAsync(template.TemplateVersionId); + + // A new template version starts from the previous version's choices. + Dictionary suggestions = new(StringComparer.OrdinalIgnoreCase); + var source = profile; + if (source is null) + { + var file = await api.GetAsync($"/api/files/{template.TemplateVersionId}"); + if (file.PreviousVersionId is { } previous) source = await TryGetProfileAsync(previous); + } + foreach (var m in source?.Mappings ?? []) suggestions[m.Placeholder] = m.BusinessField; + + var options = Options(fields.OrderBy(x => x.Scope switch { "Header" => 0, "Line" => 1, _ => 2 })); + foreach (var placeholder in scan.Placeholders) + { + var preferred = suggestions.GetValueOrDefault(placeholder.Name) + ?? fields.FirstOrDefault(x => string.Equals(x.Key, placeholder.Name, StringComparison.OrdinalIgnoreCase))?.Key; + var combo = new ComboBox + { + Height = 30, + ItemsSource = options, + DisplayMemberPath = nameof(FieldOption.Label), + SelectedItem = options.FirstOrDefault(x => x.Key is not null && string.Equals(x.Key, preferred, StringComparison.OrdinalIgnoreCase)) ?? options[0], + IsEnabled = profile?.IsLocked != true, + }; + combo.SelectionChanged += (_, _) => UpdateStatus(); + rowControls.Add(new Row(placeholder, combo)); + rows.Children.Add(RowView(placeholder, combo)); + } + + save.IsEnabled = profile?.IsLocked != true && rowControls.Count > 0; + UpdateStatus(); + } + catch (ApiException ex) + { + status.Text = string.Empty; + error.Text = ex.Message; + } + } + + private static List Options(IEnumerable fields) + { + var scopeName = new Dictionary { ["Header"] = "表头", ["Line"] = "明细", ["Total"] = "合计" }; + var list = new List { new(null, "(未映射)") }; + list.AddRange(fields.Select(x => new FieldOption(x.Key, $"{scopeName.GetValueOrDefault(x.Scope, x.Scope)} · {x.DisplayName}({x.Key})"))); + return list; + } + + private static UIElement RowView(TemplatePlaceholderDto placeholder, ComboBox combo) + { + var grid = new Grid { Margin = new Thickness(0, 0, 0, 8) }; + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1.4, GridUnitType.Star) }); + var info = new StackPanel { VerticalAlignment = VerticalAlignment.Center }; + info.Children.Add(new TextBlock { Text = placeholder.RawToken, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink }); + var where = placeholder.Locations.FirstOrDefault(); + info.Children.Add(new TextBlock + { + Text = $"{where?.Worksheet}!{where?.CellAddress}{(placeholder.OccurrenceCount > 1 ? $" 等 {placeholder.OccurrenceCount} 处" : "")}", + FontSize = 11, + Foreground = DialogKit.Muted, + }); + grid.Children.Add(info); + Grid.SetColumn(combo, 1); + grid.Children.Add(combo); + return grid; + } + + private void UpdateStatus() + { + var mapped = rowControls.Count(x => (x.Combo.SelectedItem as FieldOption)?.Key is not null); + status.Text = profile?.IsLocked == true + ? "该版本已用于生成单证,映射已锁定;如需修改请上传模板新版本。" + : $"已映射 {mapped} / {rowControls.Count} 个占位符{(mapped < rowControls.Count ? ",未映射的占位符在预览中保持原样,生成单证前必须全部映射" : ",可以用于生成单证")}。"; + status.Foreground = profile?.IsLocked == true || mapped < rowControls.Count ? DialogKit.Orange : DialogKit.Green; + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + save.IsEnabled = false; + try + { + var mappings = rowControls + .Where(x => (x.Combo.SelectedItem as FieldOption)?.Key is not null) + .Select(x => new SaveDocumentTemplateFieldMappingRequest( + x.Placeholder.Name, + ((FieldOption)x.Combo.SelectedItem).Key, + profile?.Mappings.FirstOrDefault(m => string.Equals(m.Placeholder, x.Placeholder.Name, StringComparison.OrdinalIgnoreCase))?.NumberFormat)) + .ToList(); + profile = profile is null + ? await api.PostAsync( + $"/api/document-templates/{template.TemplateVersionId}/mapping-profile", + new CreateDocumentTemplateMappingProfileRequest( + template.TemplateId, null, template.DocumentKind, + rowControls.Select(x => x.Placeholder.Name).ToList(), mappings)) + : await api.PutAsync( + $"/api/document-templates/{template.TemplateVersionId}/mappings", + new ReplaceDocumentTemplateFieldMappingsRequest(mappings)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/TemplatePreviewWindow.cs b/src/Leiren.Erp.Client/Documents/TemplatePreviewWindow.cs new file mode 100644 index 0000000..718a728 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/TemplatePreviewWindow.cs @@ -0,0 +1,163 @@ +using System.IO; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Renders a template against chosen test data (a shipping batch, or a +/// purchase contract for purchase-contract templates) with the real XLSX +/// renderer. Nothing is stored; unmapped placeholders stay visible. +/// +public sealed class TemplatePreviewWindow +{ + private sealed record TestData(Guid Id, string Label); + + private readonly ApiClient api; + private readonly DocumentTemplateListItemDto template; + private readonly DocumentTemplateKindDto kind; + private readonly Window window; + private readonly ComboBox data = new() { Height = 32, MinWidth = 420, DisplayMemberPath = nameof(TestData.Label) }; + private readonly Button render = DialogKit.Primary("预览"); + private readonly Button saveAs = DialogKit.Secondary("另存为 xlsx"); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly XlsxPreviewView preview = new(); + private byte[]? lastRendered; + + private bool UsesContract => kind.DataSource == "PurchaseContract"; + private bool UsesNotice => kind.DataSource == "SupplierInvoiceNotice"; + private string DataLabel => UsesContract ? "测试采购合同" : UsesNotice ? "测试开票通知" : "测试出货批次"; + + public TemplatePreviewWindow(ApiClient api, DocumentTemplateListItemDto template, DocumentTemplateKindDto kind, Window? owner) + { + this.api = api; + this.template = template; + this.kind = kind; + window = DialogKit.Window(owner, $"预览测试 · {template.Name}", 1200, 840); + + render.Click += async (_, _) => await RenderAsync(); + saveAs.IsEnabled = false; + saveAs.Click += async (_, _) => await SaveAsAsync(); + + var bar = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 10, 0, 8) }; + bar.Children.Add(new TextBlock { Text = DataLabel, VerticalAlignment = VerticalAlignment.Center, Foreground = DialogKit.Muted, Margin = new Thickness(0, 0, 8, 0) }); + bar.Children.Add(data); + render.Margin = new Thickness(10, 0, 0, 0); + bar.Children.Add(render); + saveAs.Margin = new Thickness(10, 0, 0, 0); + bar.Children.Add(saveAs); + + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"{kind.DisplayName} · {template.Name} · v{template.Version}")); + top.Children.Add(DialogKit.Note(template.UnmappedPlaceholders.Count == 0 + ? "选择测试数据后预览。单击预览放大到 100%,按住拖动查看,再次单击恢复适应窗口。" + : $"还有 {template.UnmappedPlaceholders.Count} 个占位符未{(kind.UsesFieldMapping ? "映射" : "识别")}({string.Join("、", template.UnmappedPlaceholders.Take(8).Select(x => "{{" + x + "}}"))}),预览中保持原样。", + template.UnmappedPlaceholders.Count == 0 ? null : DialogKit.Orange)); + top.Children.Add(bar); + top.Children.Add(error); + + var close = DialogKit.Secondary("关闭"); + close.Click += (_, _) => window.Close(); + + var root = new DockPanel { Margin = new Thickness(16) }; + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var buttons = DialogKit.Buttons(close); + DockPanel.SetDock(buttons, Dock.Bottom); + root.Children.Add(buttons); + root.Children.Add(preview); + window.Content = root; + preview.ShowMessage("选择测试数据后点击“预览”。"); + window.Loaded += async (_, _) => await LoadDataAsync(); + } + + public void ShowDialog() => window.ShowDialog(); + + private async Task LoadDataAsync() + { + try + { + List items; + if (UsesContract) + { + var contracts = await api.GetAsync>("/api/purchase-contracts/?page=1&pageSize=200"); + items = contracts + .Where(x => x.Status != "Voided" && x.TaskCount > 0) + .Select(x => new TestData(x.Id, $"{x.ContractNo} · {x.SupplierName} · {x.CustomerOrderNo} · {x.Status}")) + .ToList(); + } + else if (UsesNotice) + { + var notices = await api.GetAsync>("/api/billing/notices?page=1&pageSize=200"); + items = notices + .Where(x => x.Status != "Voided") + .Select(x => new TestData(x.Id, $"{x.NoticeNo} · {x.SupplierName} · 出货 {x.ShipmentNo ?? "—"}")) + .ToList(); + } + else + { + var batches = await api.GetAsync>("/api/shipping-batches?page=1&pageSize=200"); + items = batches + .Where(x => x.Status != "Cancelled" && x.LineCount > 0) + .Select(x => new TestData(x.Id, $"{x.BatchNo} · {x.SalesOrderNo} · {x.CustomerName} · {(x.Status == "Confirmed" ? "已出货" : "待确认出货")}")) + .ToList(); + } + data.ItemsSource = items; + data.SelectedItem = items.FirstOrDefault(); + render.IsEnabled = items.Count > 0; + if (items.Count == 0) + preview.ShowMessage(UsesContract ? "没有可用作测试数据的采购合同。" + : UsesNotice ? "没有可用作测试数据的开票通知,请先在出货与报关中为已出货批次生成开票通知。" + : "没有可用作测试数据的出货批次,请先在出货与报关中装箱。"); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private async Task RenderAsync() + { + if (data.SelectedItem is not TestData selected) return; + error.Text = string.Empty; + render.IsEnabled = false; + try + { + var request = UsesContract ? new PreviewDocumentTemplateRequest(null, selected.Id) + : UsesNotice ? new PreviewDocumentTemplateRequest(null, null, selected.Id) + : new PreviewDocumentTemplateRequest(selected.Id, null); + preview.ShowMessage("正在生成预览…"); + lastRendered = await api.PostBytesAsync($"/api/document-templates/{template.TemplateVersionId}/preview", request); + await preview.ShowAsync(lastRendered); + saveAs.IsEnabled = true; + } + catch (ApiException ex) + { + preview.ShowMessage("预览失败"); + error.Text = ex.Message; + } + catch (Exception ex) + { + preview.ShowMessage("预览失败"); + error.Text = $"渲染预览失败:{ex.Message}"; + } + finally + { + render.IsEnabled = true; + } + } + + private async Task SaveAsAsync() + { + if (lastRendered is null) return; + var dialog = new Microsoft.Win32.SaveFileDialog + { + FileName = $"{template.Name}-预览.xlsx", + Filter = "Excel 工作簿 (*.xlsx)|*.xlsx", + }; + if (dialog.ShowDialog(window) != true) return; + await File.WriteAllBytesAsync(dialog.FileName, lastRendered); + } +} diff --git a/src/Leiren.Erp.Client/Leiren.Erp.Client.csproj b/src/Leiren.Erp.Client/Leiren.Erp.Client.csproj new file mode 100644 index 0000000..bfc647f --- /dev/null +++ b/src/Leiren.Erp.Client/Leiren.Erp.Client.csproj @@ -0,0 +1,18 @@ + + + + WinExe + net11.0-windows + enable + enable + true + + + + + + + + + + diff --git a/src/Leiren.Erp.Client/LoginWindow.xaml b/src/Leiren.Erp.Client/LoginWindow.xaml new file mode 100644 index 0000000..c9cf7c6 --- /dev/null +++ b/src/Leiren.Erp.Client/LoginWindow.xaml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Leiren.Erp.Client/MainWindow.xaml.cs b/src/Leiren.Erp.Client/MainWindow.xaml.cs new file mode 100644 index 0000000..f75b588 --- /dev/null +++ b/src/Leiren.Erp.Client/MainWindow.xaml.cs @@ -0,0 +1,176 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Client.Pages; +using Leiren.Erp.Client.Wizards; + +namespace Leiren.Erp.Client; + +public partial class MainWindow : Window +{ + private static readonly Brush ActiveNavBackground = new SolidColorBrush(Color.FromRgb(0x20, 0x3B, 0x5E)); + private static readonly Brush InactiveNavForeground = new SolidColorBrush(Color.FromRgb(0xA9, 0xB8, 0xCA)); + + private readonly ClientSettings clientSettings; + private readonly ApiClient apiClient; + private readonly Func signIn; + private FlowWorkspace? workspace; + private Button? activeNavButton; + + /// Shows the login window again after logout; null result closes the app. + public MainWindow(ApiClient apiClient, ClientSettings clientSettings, LoginResponse session, Func signIn) + { + this.apiClient = apiClient; + this.clientSettings = clientSettings; + this.signIn = signIn; + InitializeComponent(); + ShowShell(session); + } + + private void ShowShell(LoginResponse result) + { + var display = string.IsNullOrWhiteSpace(result.DisplayName) ? result.UserName : result.DisplayName; + SideUserText.Text = display; + SideAccountText.Text = $"账号 {result.UserName}"; + UserAvatarText.Text = string.IsNullOrWhiteSpace(display) ? "?" : display[..1]; + ToastText.Text = string.Empty; + workspace ??= new FlowWorkspace(apiClient, HandleWorkspaceNavigation, ShowToast); + PageHost.Content = workspace; + var first = NavPanel.Children.OfType