diff --git a/.impeccable/design.json b/.impeccable/design.json index 95595d70..73962735 100644 --- a/.impeccable/design.json +++ b/.impeccable/design.json @@ -115,16 +115,16 @@ }, "typographyMeta": { "title": { - "displayName": "页面与一级导航标题", - "purpose": "右侧页面标题和一级导航,固定 14px,不随视口流体缩放。" + "displayName": "页面标题", + "purpose": "右侧页面标题,固定 14px,不随视口流体缩放。" }, "body": { "displayName": "业务正文", "purpose": "表单、说明、按钮和常规业务文字。" }, "label": { - "displayName": "字段与二级导航标签", - "purpose": "筛选字段、状态标签和二级菜单,固定 12px。" + "displayName": "字段与导航标签", + "purpose": "筛选字段、状态标签和一、二级菜单,固定 12px。" }, "data": { "displayName": "表格与金额数据", @@ -197,7 +197,7 @@ "refersTo": "sidebar-item-active", "description": "浅黑功能栏上的单一圆形 chevron 活动状态。", "html": "
店铺收款账户账单›
", - "css": ".ds-sidebar { width: 240px; padding: 8px; background: #1D1D1F; } .ds-sidebar-item { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border-radius: 4px; color: #F0E4BF; font: 500 14px/1.25 'JetBrains Mono', 'Microsoft YaHei', monospace; text-decoration: none; transition: background 150ms cubic-bezier(.22,1,.36,1); } .ds-sidebar-item:hover { background: rgba(240,228,191,.10); } .ds-sidebar-item.is-active { background: #2A2927; color: #F2E7C5; } .ds-sidebar-icon { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; } .ds-active-indicator { display: inline-flex; width: 16px; height: 16px; margin-left: auto; align-items: center; justify-content: center; border: 1px solid rgba(246,233,194,.72); border-radius: 999px; background: rgba(246,233,194,.14); color: #F6E9C2; font-size: 14px; } .ds-sidebar-item:focus-visible { outline: 2px solid #F2E7C5; outline-offset: 2px; }" + "css": ".ds-sidebar { width: 224px; padding: 8px; background: #1D1D1F; } .ds-sidebar-item { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border-radius: 4px; color: #F0E4BF; font: 500 12px/16px 'JetBrains Mono', 'Microsoft YaHei', monospace; text-decoration: none; transition: background 150ms cubic-bezier(.22,1,.36,1); } .ds-sidebar-item:hover { background: rgba(240,228,191,.10); } .ds-sidebar-item.is-active { background: #2A2927; color: #F2E7C5; } .ds-sidebar-icon { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; } .ds-active-indicator { display: inline-flex; width: 16px; height: 16px; margin-left: auto; align-items: center; justify-content: center; border: 1px solid rgba(246,233,194,.72); border-radius: 999px; background: rgba(246,233,194,.14); color: #F6E9C2; font-size: 14px; } .ds-sidebar-item:focus-visible { outline: 2px solid #F2E7C5; outline-offset: 2px; }" }, { "name": "Workspace Tabs", @@ -205,7 +205,7 @@ "refersTo": "tab-active", "description": "白色工作区内使用深金活动文字和单一金色下划线的局部标签切换。", "html": "", - "css": ".ds-tabs { display: flex; align-items: center; gap: 36px; min-height: 80px; padding: 0 32px; overflow-x: auto; border: 1px solid #D8D2C7; border-radius: 16px; background: #fff; } .ds-tab { position: relative; display: inline-flex; min-height: 80px; align-items: center; color: #595959; font: 600 14px/1.25 'JetBrains Mono', 'Microsoft YaHei', monospace; text-decoration: none; white-space: nowrap; transition: color 150ms cubic-bezier(.22,1,.36,1); } .ds-tab:hover, .ds-tab.is-active { color: #856632; } .ds-tab.is-active::after { position: absolute; right: 0; bottom: 0; left: 0; height: 3px; border-radius: 999px 999px 0 0; background: #B9954F; content: ''; } .ds-tab:focus-visible { outline: 2px solid #856632; outline-offset: 3px; }" + "css": ".ds-tabs { display: flex; align-items: center; gap: 36px; min-height: 34px; padding: 0 32px; overflow-x: auto; border: 1px solid #D8D2C7; border-radius: 16px; background: #fff; } .ds-tab { position: relative; display: inline-flex; min-height: 34px; align-items: center; color: #595959; font: 600 14px/1.25 'JetBrains Mono', 'Microsoft YaHei', monospace; text-decoration: none; white-space: nowrap; transition: color 150ms cubic-bezier(.22,1,.36,1); } .ds-tab:hover, .ds-tab.is-active { color: #856632; } .ds-tab.is-active::after { position: absolute; right: 0; bottom: 0; left: 0; height: 3px; border-radius: 999px 999px 0 0; background: #B9954F; content: ''; } .ds-tab:focus-visible { outline: 2px solid #856632; outline-offset: 3px; }" }, { "name": "Business Panel", @@ -225,7 +225,7 @@ { "name": "Finance Data Table", "kind": "custom", - "description": "紧凑、可扫描、数字右对齐的财务数据表。", + "description": "紧凑、可扫描、数字右对齐的财务数据表。支持列显示/隐藏、拖动排序、恢复默认及按用户和具体表格保存;冻结多层表头,横向滚动条始终可达。导出明确筛选范围和可见列顺序,保留精度并排除密码;允许导入的业务提供模板、预览、校验及失败反馈,只读镜像不写回。", "html": "
订单号收入余额
20260722001¥1,280.00¥8,460.00
", "css": ".ds-table { width: 100%; border-collapse: collapse; overflow: hidden; border: 1px solid #D8D2C7; border-radius: 12px; background: #fff; color: #171717; font: 400 12.5px/1.5 'JetBrains Mono', 'Microsoft YaHei', monospace; } .ds-table th { padding: 9px 10px; border-bottom: 1px solid #D8D2C7; background: #FBF8F1; color: #595959; font-size: 12px; font-weight: 600; text-align: left; } .ds-table td { padding: 9px 10px; border-bottom: 1px solid #EEE9DF; } .ds-table tbody tr:hover { background: #F7F0DE; } .ds-table .ds-num { text-align: right; font-variant-numeric: tabular-nums; } .ds-table .ds-income { color: #B80000; font-weight: 600; }" } @@ -237,8 +237,8 @@ "深黑工具轨道、浅黑功能栏、浅色内容区,三层边界清楚。", "浅金用于深色导航,深金用于浅色内容区的文字与主要操作。", "全站使用 JetBrains Mono,标题和数据采用固定字号,不使用流体放大。", - "页面标题位于内容区右侧,保持 14px,与侧边栏一级标题同级。", - "一级导航 14px,二级导航 12px;同一层级的图标、字号和交互状态必须一致。", + "页面标题位于内容区右侧,保持 14px;导航使用统一的紧凑字号。", + "一、二级导航统一 12px;同一层级的图标、字号和交互状态必须一致。", "表格、筛选器和状态反馈优先,装饰性卡片、阴影和动画受到严格限制。", "标签切换是局部状态变化,不触发整页刷新;加载前后字号和布局不得跳变。" ], @@ -254,26 +254,10 @@ { "name": "The No-Nested-Cards Rule", "body": "卡片只用于真实分组;卡片内部不能再套同样外观的卡片。优先使用标题、间距、分隔线和表格分组表达层级。", "section": "elevation" } ], "dos": [ - "**Do** 在所有前端任务开始前读取根目录 `DESIGN.md`,并优先复用全局 `--vip-*` 令牌和既有组件。", - "**Do** 保持深黑工具轨道、浅黑功能栏、浅色内容区的三层结构。", - "**Do** 在深色导航使用浅金,在浅色内容区使用对比度合格的深金。", - "**Do** 将页面标题放在右侧,使用 14px 字号和匹配业务语义的统一图标。", - "**Do** 让一级导航保持 14px、二级导航保持 12px,并为所有交互实现 hover、focus、active、disabled、loading 和 error 状态。", - "**Do** 让标签切换、筛选和分页保持局部更新,并使用 History API 维护可分享 URL。", - "**Do** 对正文、小号标签、按钮和占位文字检查至少 4.5:1 的对比度。", - "**Do** 在设计规则确需改变时,先更新 `DESIGN.md` 和 `.impeccable/design.json`,再修改页面代码。" + "复用已有令牌和组件,按 DESIGN.md 保持同类页面一致;常规排版和交互细节自主决定,不增加额外设计审批。", + "临时截图和 design-qa.md 仅作验收证据;规则变化时同步现有设计文档,不另建规范文件。", + "保持首屏布局稳定、焦点可见,正文和小号文字对比度至少 4.5:1;不添加与业务无关的装饰或宣传内容。" ], - "donts": [ - "**Don't** 把遗留的紫色、靛蓝、亮蓝硬编码(例如 `#4F46E5`、`#4338CA`、`#2563EB`)复制到新页面;信息状态蓝色除外。", - "**Don't** 在白色或浅灰背景上把亮金 `colors.content-accent` 用作小号正文或白字按钮底色;改用 `colors.content-accent-dark`。", - "**Don't** 在内容区使用大面积黑色背景和金色正文;黑底金字只属于导航、浮层或明确的高层级控制区域。", - "**Don't** 同时显示竖条、圆点和圆形 chevron 等多个选中标识;每个菜单项只能有一个活动指示器。", - "**Don't** 在业务内容内部重复页面 H1,或让首次加载时出现远大于 14px 的标题闪烁。", - "**Don't** 用普通 `` 默认导航实现站内标签切换,导致整个文档重新加载。", - "**Don't** 给有边框的卡片叠加宽而软的大阴影,也不要使用超过 16px 的卡片圆角。", - "**Don't** 使用渐变文字、玻璃拟态、装饰网格、斜纹背景、彩色侧边条或与任务无关的动画。", - "**Don't** 恢复“Akaunting 提供支持”之类的供应商页脚文字,或在业务页面加入非业务宣传信息。", - "**Don't** 把临时截图路径、个人电脑路径或 `design-qa.md` 当成团队视觉规范。" - ] + "donts": [] } } diff --git a/AGENTS.md b/AGENTS.md index 66d62242..1883d235 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,8 +6,9 @@ - 默认使用中文,先给结论;以当前代码、配置、数据和日志为准,旧文档和历史结论仅作参考。 - 用户说“先看、排查、审计”时先只读说明事实和影响;用户说“修改、修复、实现”时,Codex 可直接完成范围内的本地改动、测试、提交和 PR,不必为正常开发步骤逐项请示。 -- 一次只处理一个明确任务,优先复用现有模式和解决根因;不顺手重构、升级依赖或修改无关模块。 -- 只有以下情况需要停止并说明:产品方向存在会改变结果的歧义;与其他任务发生实际写入冲突;需要生产发布、生产数据写入、迁移、删除或其他不可逆操作;缺少完成任务必需的外部权限。 +- 围绕用户当前目标持续完成实现和必要验证,常规实现细节自主决定;优先复用现有模式,不顺手重构、升级依赖或修改无关模块。 +- 仅在缺失信息会实质改变业务目标、实际写入冲突无法自行安全解决、缺少必需权限,或高风险操作尚未获授权时暂停依赖该条件的步骤;其余工作继续。 +- 明确授权在同一任务、目标和影响范围内持续有效,不重复确认;范围、风险或费用实质变化时再确认。不得把 Skill 流程建议当成额外审批要求,也不自行增加团队契约、负责人审批或强制流程。 - 不为理论上可能、但正常使用无法触发的问题增加复杂框架、兜底层或重复检查。 ## 2. 开工与多人协作 @@ -15,8 +16,8 @@ - 开工先核对项目目录、`git status --short --branch`、`origin`、Git 身份和最新 `main`;保护现有未提交内容,不覆盖、不顺带提交。 - 开发从最新 `main` 建立独立任务分支:功能用 `feature/用户名-任务名`,修复用 `fix/用户名-问题名`,紧急修复用 `hotfix/用户名-问题名`。 - 只改独立页面、独立测试或文档时,不强制运行重型预检或提前建立 WIP PR;确认没有明显同名任务后即可开发。 -- 当任务会修改共享路由、Controller、Repository、数据表/视图、`source_key`、`scope`、权限名、菜单键或公共组件,或远程已有相同区域任务时,才运行 `scripts/codex-task-preflight.ps1`,列明“将修改”和“仅复用”内容,并尽早推送 WIP PR。 -- 只有双方会写同一契约或同一文件时才算冲突。仅调用现有路由、组件、Repository 或读取同一数据源不构成阻塞。 +- 涉及多人正在修改的共享文件时,可用 `scripts/codex-task-preflight.ps1` 辅助检查;不把预检或提前创建 WIP PR 设为普通开发的必经步骤。 +- 冲突以当前实际改动为准。结合 PR 合并状态和文件差异排除旧分支、squash 合并造成的误报;仅复用组件或读取同一数据源不阻塞开发。 - 多代理只用于边界清楚且不修改同一批文件的独立工作;主 Codex 负责最终复核。 ## 3. Git、PR 与合并 @@ -34,6 +35,7 @@ - 前端改动至少检查目标页面、关键交互和错误状态;后端改动至少运行相关测试或走一次目标接口;纯文档改动检查内容、链接和 diff 即可。 - 涉及金额、权限、导入、审批或数据库结构时,增加对应边界和回归验证。 - 已确认且状态未变化的内容不重复检查。未验证或验证失败时如实说明,不能写“应该没问题”。 +- 数据页面按本次影响验证代表性数据量下的首页、翻页和筛选耗时;明显长时间等待不能以“返回正确”判定通过。低风险改动不增加重复或仅复述实现的测试。 - 明确区分:本地已验证、已提交/推送、已合并、已上线和仍需生产验收。 ## 5. 前端与视觉 @@ -57,11 +59,8 @@ ## 7. 新人本地开发 -- 新人只需要启动 Docker Desktop、在网页登录,以及输入一次负责人提供的系统数据库密码;拉取代码、初始化、缓存、容器和连接排错由 Codex 完成。 -- 标准初始化由 Codex 在最新 `main` 上运行不带参数的 `deploy/local-init.sh`。不要让新人判断 `--build`、手工迁移共享数据库、复制他人 `.env` 或配置上游连接。 -- 本地连接系统数据库后,用户、菜单、设置和上游登记继续使用团队系统数据库,不把主连接切回本机临时 MySQL。 -- 与数据库无关的普通页面或业务功能可以直接开发,不要求开发者先理解或验证全部上游、镜像和生产部署链路。 -- 只有接入新上游数据时,才需要验证对应来源的只读查询、镜像同步状态、总数及代表性分页/筛选;无需每个普通任务重复验证两套数据库。 +- 新人只需启动 Docker Desktop、网页登录并输入负责人提供的系统数据库密码;Codex 按 SOP 运行不带参数的 `deploy/local-init.sh`,完成初始化和排错,不让新人选择构建或迁移参数。 +- 连接团队系统数据库后保留该连接,不切回临时库、不复制他人 `.env`;普通功能开发无需检查全部上游链路,仅接入新数据时验证对应来源。 ## 8. 构建与生产部署 diff --git a/DESIGN.md b/DESIGN.md index 047b9ed4..9daed852 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -86,13 +86,13 @@ components: sidebar-item: backgroundColor: "{colors.sidebar-black}" textColor: "{colors.sidebar-gold}" - typography: "{typography.title}" + typography: "{typography.label}" rounded: "{rounded.sm}" padding: "8px 10px" sidebar-item-active: backgroundColor: "{colors.sidebar-active}" textColor: "{colors.rail-gold}" - typography: "{typography.title}" + typography: "{typography.label}" rounded: "{rounded.sm}" padding: "8px 10px" tab-default: @@ -100,13 +100,13 @@ components: textColor: "{colors.content-muted}" typography: "{typography.title}" padding: "0 4px" - height: "80px" + minHeight: "34px" tab-active: backgroundColor: "{colors.surface}" textColor: "{colors.content-accent-dark}" typography: "{typography.title}" padding: "0 4px" - height: "80px" + minHeight: "34px" panel: backgroundColor: "{colors.surface}" textColor: "{colors.content-ink}" @@ -131,8 +131,8 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视 - 深黑工具轨道、浅黑功能栏、浅色内容区,三层边界清楚。 - 浅金用于深色导航,深金用于浅色内容区的文字与主要操作。 - 全站使用 JetBrains Mono,标题和数据采用固定字号,不使用流体放大。 -- 页面标题位于内容区右侧,保持 14px,与侧边栏一级标题同级。 -- 一级导航 14px,二级导航 12px;同一层级的图标、字号和交互状态必须一致。 +- 页面标题位于内容区右侧,保持 14px;导航使用统一的紧凑字号。 +- 一、二级导航统一 12px;同一层级的图标、字号和交互状态必须一致。 - 表格、筛选器和状态反馈优先,装饰性卡片、阴影和动画受到严格限制。 - 标签切换是局部状态变化,不触发整页刷新;加载前后字号和布局不得跳变。 @@ -191,8 +191,8 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视 ### Hierarchy - **页面标题** (600, 14px, 1.25): 固定在内容头部右侧,与配套图标同行;禁止在业务内容内部重复放置大号 H1。 -- **侧边栏一级标题** (500–600, 14px, 1.25): 模块和一级功能名称。 -- **侧边栏二级标题** (400–500, 12px, 16px): 比一级标题小一档,保持单行和稳定缩进。 +- **侧边栏一级标题** (500–600, 12px, 16px): 模块和一级功能名称。 +- **侧边栏二级标题** (400–500, 12px, 16px): 通过缩进区分层级,保持单行和稳定行高。 - **正文** (400, 13px, 1.5): 表单说明、面板正文和常规业务文字。 - **标签** (500, 12px, 16px): 筛选条件、字段名、状态标签和辅助说明。 - **表格与金额** (400–600, 12.5px, 1.5): 启用等宽数字 `tabular-nums`,金额和数量右对齐。 @@ -233,8 +233,8 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视 ### Navigation -- 一级导航 14px,二级导航 12px;文字和对应 Material 图标使用同一浅金色。 -- 图标统一采用 Material Icons Outlined/Round,常规尺寸 20–24px;同一业务语义不得在不同页面更换图标体系。 +- 一、二级导航统一 12px;文字和对应 Material 图标使用同一浅金色。 +- 图标统一采用 Material Icons Outlined/Round,导航图标统一 16px;同一业务语义不得在不同页面更换图标体系。 - 当前二级菜单只显示一个 16px 圆形浅金 chevron 指示器;禁止同时保留竖条、圆点或第二个箭头。 - 悬停使用轻微浅金透明底,选中使用 `colors.sidebar-active`;状态变化为 150–200ms。 @@ -246,7 +246,7 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视 ### Tabs -- 桌面标签栏高度 80px,白色表面,标签间距以可点击性和单行展示为准。 +- 标签栏采用白色表面,按所在区域保持紧凑高度和足够点击空间;同类页面一致,不把主标签栏的 80px 高度套用到局部标签。 - 默认文字使用辅助墨色;活动文字使用 `colors.content-accent-dark`,底部使用 3px `colors.content-accent` 下划线。 - 标签图标与文字同色;切换只更新内容、URL History 和活动状态,不触发 document 级刷新。 - 标签变化使用 150ms 状态过渡;`prefers-reduced-motion` 下立即切换。 @@ -277,6 +277,12 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视 - 行悬停使用极浅金/中性背景;选中状态同时提供图标、文字或边界,不只改变底色。 - 收入、支出、错误和成功色遵循业务语义;不得为了“好看”交换红绿含义。 +- 各业务表格支持列显示/隐藏、拖动排序和恢复默认;按用户及页面、标签页、表格分别保存,表头、数据和合计同步排列,必要操作列可固定。 +- 单层或多层表头随纵向滚动保持可见;横向滚动条在浏览数据时始终可达,不得落到屏幕外或必须滚至整表底部才能操作。 +- 合理设置表格滚动容器,适配视口、缩放和侧栏变化,避免多层滚动互相干扰。优先复用现有组件,具体实现自主选择。 +- 导出明确范围,支持当前筛选结果及可见列顺序,不把当前页冒充全部;保留金额精度、日期和长编号格式,遵守字段权限,密码不导出,大数据量沿用分批或后台机制。 +- 允许导入的业务提供模板、预览、字段校验、重复处理和逐行失败反馈,不静默覆盖数据;只读上游镜像不增加写回入口。业务规则不明时只澄清必要问题。 + ### Scrollbars - 内容滚动条为 8px,轨道使用浅中性色,滑块使用 VIP 金;悬停使用更深金色。 @@ -288,28 +294,8 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视 - 空状态说明“为什么没有数据”和“下一步能做什么”,不能只写“暂无数据”。 - 错误状态保留重试入口和明确原因;局部失败不能清空整个页面或触发整页刷新。 -## 6. Do's and Don'ts +## 6. 使用原则 -### Do: - -- **Do** 在所有前端任务开始前读取根目录 `DESIGN.md`,并优先复用全局 `--vip-*` 令牌和既有组件。 -- **Do** 保持深黑工具轨道、浅黑功能栏、浅色内容区的三层结构。 -- **Do** 在深色导航使用浅金,在浅色内容区使用对比度合格的深金。 -- **Do** 将页面标题放在右侧,使用 14px 字号和匹配业务语义的统一图标。 -- **Do** 让一级导航保持 14px、二级导航保持 12px,并为所有交互实现 hover、focus、active、disabled、loading 和 error 状态。 -- **Do** 让标签切换、筛选和分页保持局部更新,并使用 History API 维护可分享 URL。 -- **Do** 对正文、小号标签、按钮和占位文字检查至少 4.5:1 的对比度。 -- **Do** 在设计规则确需改变时,先更新 `DESIGN.md` 和 `.impeccable/design.json`,再修改页面代码。 - -### Don't: - -- **Don't** 把遗留的紫色、靛蓝、亮蓝硬编码(例如 `#4F46E5`、`#4338CA`、`#2563EB`)复制到新页面;信息状态蓝色除外。 -- **Don't** 在白色或浅灰背景上把亮金 `colors.content-accent` 用作小号正文或白字按钮底色;改用 `colors.content-accent-dark`。 -- **Don't** 在内容区使用大面积黑色背景和金色正文;黑底金字只属于导航、浮层或明确的高层级控制区域。 -- **Don't** 同时显示竖条、圆点和圆形 chevron 等多个选中标识;每个菜单项只能有一个活动指示器。 -- **Don't** 在业务内容内部重复页面 H1,或让首次加载时出现远大于 14px 的标题闪烁。 -- **Don't** 用普通 `` 默认导航实现站内标签切换,导致整个文档重新加载。 -- **Don't** 给有边框的卡片叠加宽而软的大阴影,也不要使用超过 16px 的卡片圆角。 -- **Don't** 使用渐变文字、玻璃拟态、装饰网格、斜纹背景、彩色侧边条或与任务无关的动画。 -- **Don't** 恢复“Akaunting 提供支持”之类的供应商页脚文字,或在业务页面加入非业务宣传信息。 -- **Don't** 把临时截图路径、个人电脑路径或 `design-qa.md` 当成团队视觉规范。 +- 复用已有令牌和组件,按上述标准保持同类页面一致;常规排版和交互细节自主决定,不增加额外设计审批。 +- 临时截图和 `design-qa.md` 仅作验收证据,不覆盖本文件;规则变化时同步 `.impeccable/design.json`,不另建规范文件。 +- 保持首屏布局稳定、焦点可见,正文和小号文字对比度至少 4.5:1;不添加与业务无关的装饰或宣传内容。 diff --git a/app/Console/Commands/SyncBusinessMirrors.php b/app/Console/Commands/SyncBusinessMirrors.php index 7c3bb48c..e894feff 100644 --- a/app/Console/Commands/SyncBusinessMirrors.php +++ b/app/Console/Commands/SyncBusinessMirrors.php @@ -104,6 +104,30 @@ class SyncBusinessMirrors extends Command Log::error('钉钉应付流程镜像同步失败。', ['exception' => $exception::class]); $this->error('operations_replica.rpt.ding_payable_workflows:同步失败,已保留上一版共享数据。'); } + + // 线上代发业务报销流程复用同一套钉钉流程镜像同步链路,接入此处后 + // 由现有生产 cron 自动断点续传,不额外维护调度脚本。 + try { + $daifaResult = $dingPayableWorkflows + ->forConfigKey('ding_online_daifa_price') + ->sync( + (bool) $this->option('full'), + $this->option('batch') === null ? null : (int) $this->option('batch'), + $this->option('max-batches') === null ? null : (int) $this->option('max-batches'), + ); + if ($daifaResult['status'] !== 'requires_full_sync') { + $this->info(sprintf( + 'operations_replica.rpt.ding_online_daifa_price:%s,本轮 %d 批,累计处理 %d 条明细。', + $daifaResult['status'] === 'succeeded' ? '同步完成' : '同步进行中', + $daifaResult['batches'], + $daifaResult['rows'], + )); + } + } catch (Throwable $exception) { + $failed = true; + Log::error('钉钉线上代发价格流程镜像同步失败。', ['exception' => $exception::class]); + $this->error('operations_replica.rpt.ding_online_daifa_price:同步失败,已保留上一版共享数据。'); + } } return $failed ? self::FAILURE : self::SUCCESS; diff --git a/app/Console/Commands/SyncDingOnlineDaifaPrice.php b/app/Console/Commands/SyncDingOnlineDaifaPrice.php new file mode 100644 index 00000000..b33cc6a0 --- /dev/null +++ b/app/Console/Commands/SyncDingOnlineDaifaPrice.php @@ -0,0 +1,49 @@ +option('full')) { + return self::SUCCESS; + } + + try { + $result = $synchronizer + ->forConfigKey('ding_online_daifa_price') + ->sync( + (bool) $this->option('full'), + $this->option('batch') === null ? null : (int) $this->option('batch'), + $this->option('max-batches') === null ? null : (int) $this->option('max-batches'), + ); + } catch (Throwable $exception) { + Log::error('钉钉线上代发价格流程镜像同步失败。', ['exception' => $exception::class]); + $this->error('钉钉线上代发价格流程同步失败,已保留上一版共享数据。'); + + return self::FAILURE; + } + + $this->info(sprintf( + '%s:本轮 %d 批,累计处理 %d 条明细。', + $result['status'] === 'succeeded' ? '同步完成' : '同步进行中', + $result['batches'], + $result['rows'], + )); + + return self::SUCCESS; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 09f0d5ad..c403c1e1 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -35,6 +35,14 @@ class Kernel extends ConsoleKernel $schedule->command('storage-temp:clear')->dailyAt('17:00'); $schedule->command('model:prune')->dailyAt('17:00'); + // 线上代发价格:每天凌晨 00:00 全量/增量同步一次钉钉线上代发业务报销流程。 + // 生产环境由 business-mirror:sync-tables 的 cron 持续增量覆盖,此处保证 + // 一个固定的每日零点刷新入口;命令本身在非刷新环境会安全跳过。 + $schedule->command('business-mirror:sync-ding-online-daifa-price') + ->dailyAt('00:00') + ->withoutOverlapping(60) + ->runInBackground(); + if ((bool) config('services.esign.polling_enabled', false)) { $schedule->command('esign:poll-signatures --quiet') ->cron('*/2 * * * *') diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 0b142a08..712c8e08 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -38,6 +38,7 @@ use Modules\EcommerceFinance\Repositories\ProductCatalogMirrorRepository; use Modules\EcommerceFinance\Repositories\ProductPriceMirrorRepository; use Modules\EcommerceFinance\Repositories\RawBoardPayablesRepository; use Modules\EcommerceFinance\Repositories\DingPayableWorkflowMirrorRepository; +use Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository; use Modules\EcommerceFinance\Repositories\SmallPaymentWorkOrderMirrorRepository; use Modules\EcommerceFinance\Repositories\SupplierPayableReportRepository; use Modules\EcommerceFinance\Repositories\TmallTaobaoSpreadBillRepository; @@ -78,6 +79,7 @@ class Pages extends Controller private readonly CourierFreightReconciliationMirrorRepository $courierFreightReconciliations, private readonly RawBoardPayablesRepository $rawBoardPayables, private readonly DingPayableWorkflowMirrorRepository $dingPayableWorkflows, + private readonly DingOnlineDaifaPriceMirrorRepository $onlineDaifaPrices, private readonly SupplierPayableReportRepository $supplierPayableReports, private readonly UpstreamQueryCacheFactory $upstreamCaches, private readonly CourierSurchargeQuoteRepository $courierSurchargeQuotes, @@ -579,6 +581,7 @@ class Pages extends Controller 'board-deductions' => $this->contentForBoardDeductions(), 'supplier-payables-report' => $this->contentForSupplierPayablesReport(), 'payable-cloud-warehouse-vehicle-fee' => $this->contentForDingPayableWorkflows(), + 'online-daifa-price' => $this->contentForOnlineDaifaPrice(), 'courier-surcharge' => $this->contentForCourierSurcharge(), 'bill-offset' => app(\Modules\EcommerceFinance\View\BillOffsetPageData::class)->page(), default => null, @@ -737,6 +740,61 @@ class Pages extends Controller } } + protected function contentForOnlineDaifaPrice(): array + { + $clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length); + $date = static function (mixed $value): string { + $value = trim((string) $value); + return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1 ? $value : ''; + }; + $status = strtoupper(mb_substr(trim((string) request('status', '')), 0, 30)); + $filters = [ + 'keyword' => $clean(request('keyword', ''), 80), + 'product_id' => $clean(request('product_id', ''), 64), + 'shop_name' => $clean(request('shop_name', ''), 120), + 'status' => preg_match('/^[A-Z_]+$/', $status) === 1 ? $status : '', + 'created_from' => $date(request('created_from', '')), + 'created_to' => $date(request('created_to', '')), + ]; + $page = max((int) request('page', 1), 1); + $limit = min(max((int) setting('default.list_limit', 25), 1), 100); + + try { + $result = $this->onlineDaifaPrices->paginate($filters, $page, $limit); + $rows = new LengthAwarePaginator( + Collection::make($result['data'] ?? []), + (int) ($result['total'] ?? 0), + $limit, + $page, + ['path' => request()->url(), 'query' => request()->except('page')], + ); + + return [ + 'view' => 'business.pages.product-inventory.online-daifa-price', + 'onlineDaifaRows' => $rows, + 'onlineDaifaFilters' => $filters, + 'onlineDaifaStatus' => $result['status'] ?? 'unknown', + 'onlineDaifaSyncedAt' => $result['last_synced_at'] ?? null, + 'onlineDaifaSummary' => $result['summary'] ?? [], + 'onlineDaifaError' => null, + ]; + } catch (Throwable $exception) { + report($exception); + + return [ + 'view' => 'business.pages.product-inventory.online-daifa-price', + 'onlineDaifaRows' => new LengthAwarePaginator([], 0, $limit, $page, [ + 'path' => request()->url(), 'query' => request()->except('page'), + ]), + 'onlineDaifaFilters' => $filters, + 'onlineDaifaStatus' => 'unavailable', + 'onlineDaifaSyncedAt' => null, + 'onlineDaifaSummary' => [], + 'onlineDaifaError' => '线上代发价格镜像尚未完成同步,请稍后重试。', + ]; + } + } + protected function contentForJingxiRefundData(): array { return [ diff --git a/app/Http/Controllers/Business/StoreAccountPasswords.php b/app/Http/Controllers/Business/StoreAccountPasswords.php index 582c73e5..767239fe 100644 --- a/app/Http/Controllers/Business/StoreAccountPasswords.php +++ b/app/Http/Controllers/Business/StoreAccountPasswords.php @@ -4,7 +4,6 @@ namespace App\Http\Controllers\Business; use App\Services\StoreAccountPasswordClient; use App\Utilities\SidebarPermissions; -use App\Utilities\SystemAccess; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\DB; @@ -39,11 +38,7 @@ class StoreAccountPasswords extends Controller $result = ['status' => 503]; try { - $pages = collect(SidebarPermissions::navigationFor($request->user()))->firstWhere('slug', 'store-management'); - // Re-read role membership for every secret request; a cached admin - // role must not survive a permission revocation. - if (! $request->user()->roles()->whereIn('roles.name', [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN])->exists() - || ! collect($pages['pages'] ?? [])->contains('slug', 'store-accounts')) { + if (! $this->canReveal($request)) { $result = ['status' => 403]; } elseif (RateLimiter::tooManyAttempts('store-password:'.$request->user()->id, 10)) { $result = ['status' => 429]; @@ -70,6 +65,83 @@ class StoreAccountPasswords extends Controller return $this->respond($result['status'], $requestId, $result['password'] ?? null); } + public function revealVisiblePage(Request $request, StoreAccountMirrorRepository $accounts, StoreAccountPasswordClient $client) + { + if (app()->bound('debugbar')) { + app('debugbar')->disable(); + } + $batchRequestId = (string) Str::uuid(); + $accountIds = $request->input('accounts'); + if (array_diff(array_keys($request->all()), ['accounts', '_token']) !== [] + || $request->query() !== [] || ! is_array($accountIds) + || count($accountIds) < 1 || count($accountIds) > 50 + || count(array_unique($accountIds, SORT_REGULAR)) !== count($accountIds) + || collect($accountIds)->contains(fn ($id) => ! is_string($id) || ! preg_match('/^[A-Za-z0-9_-]{1,128}$/D', $id))) { + return $this->respondVisiblePage(422, $batchRequestId); + } + $accountIds = array_values($accountIds); + $requestIds = collect($accountIds)->mapWithKeys(fn ($id) => [$id => (string) Str::uuid()])->all(); + try { + DB::table('store_account_password_audits')->insert(collect($accountIds)->map(fn ($id) => [ + 'request_id' => $requestIds[$id], 'actor_user_id' => $request->user()->id, + 'company_id' => company_id(), 'store_account_id' => $id, + 'purpose' => 'view', 'created_at' => now(), + ])->all()); + } catch (Throwable) { + return $this->respondVisiblePage(503, $batchRequestId); + } + + $result = ['status' => 503]; + try { + if (! $this->canReveal($request)) { + $result = ['status' => 403]; + } elseif (RateLimiter::tooManyAttempts('store-password-page:'.$request->user()->id, 5)) { + $result = ['status' => 429]; + } else { + RateLimiter::hit('store-password-page:'.$request->user()->id, 60); + $result = $accounts->containsAccounts($accountIds) + ? $client->revealVisiblePage($accountIds, $request->user()->id) + : ['status' => 404]; + } + } catch (Throwable) { + $result = ['status' => 503]; + } + + $items = []; + try { + DB::transaction(function () use ($accountIds, $requestIds, $result, &$items) { + foreach ($accountIds as $accountId) { + $upstream = $result['status'] === 200 + ? ($result['items'][$accountId] ?? ['status' => 503]) + : ['status' => $result['status']]; + $saved = DB::table('store_account_password_audits')->where('request_id', $requestIds[$accountId])->update([ + 'status' => $upstream['status'], 'upstream_request_id' => $upstream['upstream_request_id'] ?? null, + 'completed_at' => now(), + ]); + if ($saved !== 1) { + throw new \RuntimeException('store_password_audit_update_failed'); + } + $items[$accountId] = [ + 'status' => $upstream['status'], 'requestId' => $requestIds[$accountId], + 'password' => $upstream['status'] === 200 ? $upstream['password'] : null, + ]; + } + }); + } catch (Throwable) { + return $this->respondVisiblePage(503, $batchRequestId); + } + if ($result['status'] !== 200) { + return $this->respondVisiblePage($result['status'], $batchRequestId); + } + return $this->respondVisiblePage(200, $batchRequestId, $items); + } + + private function canReveal(Request $request): bool + { + $section = collect(SidebarPermissions::navigationFor($request->user()))->firstWhere('slug', 'store-management'); + return collect($section['pages'] ?? [])->contains('slug', 'store-accounts'); + } + private function respond(int $status, string $requestId, ?string $password = null) { $messages = [403 => '当前账号没有查看店铺密码的权限。', 404 => '该账号暂无可读取的密码。', @@ -81,4 +153,22 @@ class StoreAccountPasswords extends Controller ->withHeaders(['Cache-Control' => 'no-store, private', 'Pragma' => 'no-cache', 'X-Content-Type-Options' => 'nosniff', 'Referrer-Policy' => 'no-referrer']); } + + private function respondVisiblePage(int $status, string $requestId, array $items = []) + { + $messages = [403 => '当前账号没有查看店铺密码的页面权限。', 404 => '当前页包含无效账号,请刷新后重试。', + 422 => '请求无效,请刷新页面后重试。', 429 => '自动读取过于频繁,请稍后刷新。', + 503 => '密码服务暂不可用,请稍后刷新或联系管理员。']; + $body = $status === 200 + ? ['items' => collect($items)->map(fn ($item, $accountId) => array_filter([ + 'accountId' => $accountId, 'status' => $item['status'], 'requestId' => $item['requestId'], + 'password' => $item['status'] === 200 ? $item['password'] : null, + 'message' => $item['status'] === 200 ? null : ($messages[$item['status']] ?? $messages[503]), + ], fn ($value) => $value !== null))->values()->all()] + : ['message' => $messages[$status] ?? $messages[503], 'requestId' => $requestId]; + return response()->json($body, $status)->withHeaders([ + 'Cache-Control' => 'no-store, private', 'Pragma' => 'no-cache', + 'X-Content-Type-Options' => 'nosniff', 'Referrer-Policy' => 'no-referrer', + ]); + } } diff --git a/app/Http/Middleware/AddXHeader.php b/app/Http/Middleware/AddXHeader.php index aac4d5f0..4feb100f 100644 --- a/app/Http/Middleware/AddXHeader.php +++ b/app/Http/Middleware/AddXHeader.php @@ -27,7 +27,7 @@ class AddXHeader } $response->header('X-XSS-Protection', '0'); $response->header('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); - if ($request->routeIs('login.dingtalk', 'login.dingtalk.callback', 'business.store-account-passwords.reveal')) { + if ($request->routeIs('login.dingtalk', 'login.dingtalk.callback', 'business.store-account-passwords.reveal', 'business.store-account-passwords.reveal-visible-page')) { $response->header('Cache-Control', 'no-store'); $response->header('Pragma', 'no-cache'); $response->header('Referrer-Policy', 'no-referrer'); diff --git a/app/Services/Auth/DingTalkClosedAccess.php b/app/Services/Auth/DingTalkClosedAccess.php index c785bd72..753f0b59 100644 --- a/app/Services/Auth/DingTalkClosedAccess.php +++ b/app/Services/Auth/DingTalkClosedAccess.php @@ -92,7 +92,9 @@ class DingTalkClosedAccess return null; } - $role = Role::where('name', SystemAccess::USER)->firstOrFail(); + $roleName = FinanceRoster::isDesignatedSuperAdmin((string) $profile['dingtalk_user_id']) + ? SystemAccess::SUPER_ADMIN : SystemAccess::USER; + $role = Role::where('name', $roleName)->firstOrFail(); $email = $this->normalizeEmail($profile['email'] ?? null); if (! $email || User::withTrashed()->where('email', $email)->exists()) { $email = 'ding-'.hash('sha256', $profile['union_id']).'@dingtalk.invalid'; @@ -112,7 +114,7 @@ class DingTalkClosedAccess 'created_from' => 'dingtalk_roster', ]); $account->roles()->attach($role->id); - // Shell access only; no financial pages or administrative privileges. + // Explicit designation controls the role; ordinary roster users get shell access. $account->permissions()->attach(Permission::where('name', 'read-admin-panel')->firstOrFail()->id); $account->companies()->attach($companies->first()->id); if ($mobile = $this->normalizeMobile($profile['mobile'] ?? null)) { diff --git a/app/Services/Auth/FinanceRoster.php b/app/Services/Auth/FinanceRoster.php index 474555d7..a6ee0c39 100644 --- a/app/Services/Auth/FinanceRoster.php +++ b/app/Services/Auth/FinanceRoster.php @@ -7,6 +7,11 @@ use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory; /** Single-person, current HR authorization lookup; no HR rows or stale grants are cached. */ class FinanceRoster { + public static function isDesignatedSuperAdmin(string $userId): bool + { + return $userId !== '' && in_array($userId, config('dingtalk.super_admin_user_ids', []), true); + } + public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) { } @@ -77,7 +82,8 @@ class FinanceRoster return null; } $allowed = array_map('strval', config('dingtalk.finance_department_ids', [])); - if (! array_intersect($allowed, array_map('strval', array_column($ancestors, 'Id')))) { + if (! self::isDesignatedSuperAdmin($userId) + && ! array_intersect($allowed, array_map('strval', array_column($ancestors, 'Id')))) { return null; } diff --git a/app/Services/StoreAccountPasswordClient.php b/app/Services/StoreAccountPasswordClient.php index 3f40932e..a139fcc1 100644 --- a/app/Services/StoreAccountPasswordClient.php +++ b/app/Services/StoreAccountPasswordClient.php @@ -61,4 +61,109 @@ class StoreAccountPasswordClient return ['status' => 503]; } } + + public function revealVisiblePage(array $accountIds, int $actorId): array + { + $url = (string) config('store_account_password.visible_page_url'); + $token = (string) config('store_account_password.token'); + $accountIds = array_values($accountIds); + if (parse_url($url, PHP_URL_SCHEME) !== 'https' + || ! preg_match('/^[A-Za-z0-9_-]{43,128}$/D', $token) + || count($accountIds) < 1 || count($accountIds) > 50 + || count(array_unique($accountIds)) !== count($accountIds) + || collect($accountIds)->contains(fn ($id) => ! is_string($id) || ! preg_match('/^[A-Za-z0-9_-]{1,128}$/D', $id))) { + return ['status' => 503]; + } + + $requesterId = 'finance-user-'.$actorId; + $chunks = []; + $chunk = []; + foreach ($accountIds as $accountId) { + $candidate = [...$chunk, $accountId]; + $payload = ['requesterId' => $requesterId, 'purpose' => 'view', 'accountIds' => $candidate]; + if ($chunk !== [] && (count($candidate) > 25 || strlen((string) json_encode($payload)) > 1000)) { + $chunks[] = $chunk; + $chunk = [$accountId]; + } else { + $chunk = $candidate; + } + } + $chunks[] = $chunk; + + $items = []; + foreach ($chunks as $accountIdChunk) { + $result = $this->revealVisiblePageChunk($url, $token, $requesterId, $accountIdChunk); + if (($result['status'] ?? 503) !== 200) { + foreach ($items as &$item) { + unset($item['password']); + } + unset($item, $items); + + return ['status' => $result['status'] ?? 503]; + } + $items += $result['items']; + } + + return ['status' => 200, 'items' => $items]; + } + + private function revealVisiblePageChunk(string $url, string $token, string $requesterId, array $accountIds): array + { + try { + $response = $this->http->request('POST', $url, [ + 'headers' => ['Authorization' => 'Bearer '.$token, 'Accept' => 'application/json'], + 'json' => ['requesterId' => $requesterId, 'purpose' => 'view', 'accountIds' => $accountIds], + 'verify' => true, 'allow_redirects' => false, 'http_errors' => false, + 'connect_timeout' => 3, 'timeout' => 10, + 'sink' => fopen('php://memory', 'w+'), + ]); + $status = $response->getStatusCode(); + if ($response->getBody()->isSeekable()) { + $response->getBody()->rewind(); + } + $body = $response->getBody()->read(131073); + $response->getBody()->close(); + if (strlen($body) > 131072) { + return ['status' => 503]; + } + $data = json_decode($body, true); + unset($body); + if ($status !== 200) { + return ['status' => $status === 429 ? 429 : 503]; + } + if (! preg_match('/(?:^|,)\s*no-store\s*(?:,|$)/i', $response->getHeaderLine('Cache-Control')) + || ! $this->uuid($data['requestId'] ?? null) || ! is_array($data['items'] ?? null) + || count($data['items']) !== count($accountIds)) { + return ['status' => 503]; + } + $items = []; + foreach ($data['items'] as $item) { + $accountId = $item['accountId'] ?? null; + $itemStatus = $item['status'] ?? null; + if (! is_string($accountId) || ! in_array($accountId, $accountIds, true) || isset($items[$accountId]) + || ! $this->uuid($item['requestId'] ?? null) + || ! in_array($itemStatus, [200, 404, 429, 503], true) + || ($itemStatus === 200 && (! is_string($item['password'] ?? null) || $item['password'] === '')) + || ($itemStatus !== 200 && array_key_exists('password', $item))) { + return ['status' => 503]; + } + $items[$accountId] = [ + 'status' => $itemStatus, + 'password' => $itemStatus === 200 ? $item['password'] : null, + 'upstream_request_id' => $item['requestId'], + ]; + } + if (array_keys($items) !== $accountIds) { + return ['status' => 503]; + } + return ['status' => 200, 'items' => $items]; + } catch (Throwable) { + return ['status' => 503]; + } + } + + private function uuid(mixed $value): bool + { + return is_string($value) && (bool) preg_match('/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/iD', $value); + } } diff --git a/config/business_navigation.php b/config/business_navigation.php index 3a9c1f93..1f4afbe8 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -244,7 +244,7 @@ return [ 'directory' => [ 'icon' => 'key', 'status' => '共享镜像', - 'description' => '账号资料来自共享镜像。管理员可按需查看或复制密码,密码不会随表格导出。', + 'description' => '账号资料来自共享镜像。拥有本页面权限的用户可直接查看当前页密码,密码不会随表格导出。', 'empty' => '共享镜像中暂未读取到店铺账号数据,请检查账号数据同步状态。', 'fields' => [ ['name' => 'store_name', 'label' => '店铺名称'], @@ -295,6 +295,7 @@ return [ 'icon' => 'inventory_2', 'pages' => [ ['slug' => 'normal-products', 'title' => '普通商品资料'], + ['slug' => 'online-daifa-price', 'title' => '线上代发价格'], ], ], [ diff --git a/config/dingtalk.php b/config/dingtalk.php index 0ef36a9e..6fe50220 100644 --- a/config/dingtalk.php +++ b/config/dingtalk.php @@ -15,6 +15,10 @@ return [ // When omitted, automatic provisioning requires exactly one enabled company. 'company_id' => env('DINGTALK_COMPANY_ID'), + // Explicitly approved enterprise user IDs only; never names or departments. + // Applies the highest role on first provisioning, not on subsequent logins. + 'super_admin_user_ids' => array_values(array_filter(array_map('trim', explode(',', env('DINGTALK_SUPER_ADMIN_USER_IDS', ''))))), + 'authorize_url' => env('DINGTALK_AUTHORIZE_URL', 'https://login.dingtalk.com/oauth2/auth'), 'token_url' => env('DINGTALK_TOKEN_URL', 'https://api.dingtalk.com/v1.0/oauth2/userAccessToken'), 'user_url' => env('DINGTALK_USER_URL', 'https://api.dingtalk.com/v1.0/contact/users/me'), diff --git a/config/store_account_password.php b/config/store_account_password.php index 22510491..5a871d93 100644 --- a/config/store_account_password.php +++ b/config/store_account_password.php @@ -2,5 +2,6 @@ return [ 'url' => env('STORE_ACCOUNT_REVEAL_URL', 'https://cp.jiansun.vip/internal/store-accounts/{id}/password/reveal'), + 'visible_page_url' => env('STORE_ACCOUNT_REVEAL_VISIBLE_PAGE_URL', 'https://cp.jiansun.vip/internal/store-accounts/visible-page/password/reveal'), 'token' => env('STORE_ACCOUNT_REVEAL_TOKEN'), ]; diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index ad37961a..e286e124 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -14,6 +14,59 @@ return [ 'max_batches_per_run' => (int) env('DING_PAYABLE_WORKFLOW_MIRROR_MAX_BATCHES', 2), ], + // 线上代发业务报销流程(钉钉 OA 审批):数据源为 operations_replica 的 + // rpt.ding_Workflow 中固定流程编码。明细按“商品ID”关联到共享业务镜像的 + // 商品目录(ops_jst_sku_map / ops_jst_sku)做匹配。页面从共享镜像读取, + // 不在 HTTP 请求中直连上游。process_code 由环境变量注入,避免在代码中 + // 硬编码审批模板编码;填入前不会同步任何数据。 + 'ding_online_daifa_price' => [ + 'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price', + 'source_key' => 'operations_replica', + 'process_code' => env('DING_ONLINE_DAIFA_PRICE_PROCESS_CODE', ''), + 'target_table' => 'ding_online_daifa_price_mirror', + 'extend_columns' => true, + // 同步阶段按商品ID(钉钉表单“商品ID”即 shop_i_id)关联商品目录并写入 + // product_name 列,页面只读镜像、不临时 JOIN 2500 万行的 ops_jst_sku_map。 + 'resolve_product_name' => true, + // 钉钉表单字段名 -> 镜像宽表列。下方列名依据用户提供的演示数据校验, + // 若实际审批模板字段名不同,仅需调整此映射即可,无需改动同步与页面代码。 + 'column_map' => [ + 'payee_name' => '收款人全称', + 'product_id' => '商品ID', + 'daifa_trade_no' => '代发交易单号', + 'shop_trade_no' => '店铺交易单号', + 'shop_name' => '店铺名称', + 'supplier_name' => '供应商名称', + 'material_no' => '料号', + 'ship_qty' => '订单发货数量', + 'paid_amount' => '订单实付金额', + 'daifa_amount' => '代发订单金额', + 'price_diff' => '差价', + ], + // 宽表列类型,决定抽取时的强制转换;字符串列留空即可。 + 'column_types' => [ + 'ship_qty' => 'int', + 'paid_amount' => 'decimal', + 'daifa_amount' => 'decimal', + 'price_diff' => 'decimal', + ], + // 若审批模板把“一个商品一行”放在明细表格里,填写该表格的字段名, + // 同步器会按明细行展开为多条镜像记录;留空则整张表单视为单行。 + 'detail_table' => env('DING_ONLINE_DAIFA_PRICE_DETAIL_TABLE', ''), + // 仅保留“收款人全称”为指定公司的报销明细。收款人全称在钉钉表单中是 + // 顶层字段,同步器会把它并入每条明细行;此处按值精确匹配(去首尾空白), + // 不匹配的明细行不写入镜像。默认限定“宁波顾家望业家居有限公司”,切换 + // 收款人只需调整 env,无需改动同步与页面代码;置空该值即不过滤。 + 'row_filters' => [ + 'payee_name' => env('DING_ONLINE_DAIFA_PRICE_PAYEE', '宁波顾家望业家居有限公司'), + ], + // 只同步指定审批状态的单据(默认只要“已完成/已通过”,与页面状态口径一致); + // 未通过/已拒绝/撤回等整单暂不写入镜像。置空则不限状态。 + 'only_status' => env('DING_ONLINE_DAIFA_PRICE_ONLY_STATUS', 'COMPLETED'), + 'batch_size' => (int) env('DING_ONLINE_DAIFA_PRICE_MIRROR_BATCH_SIZE', 100), + 'max_batches_per_run' => (int) env('DING_ONLINE_DAIFA_PRICE_MIRROR_MAX_BATCHES', 2), + ], + // 只有生产刷新节点写镜像;开发环境和网页请求只读共享结果。 'refresh_enabled' => env( 'BUSINESS_MIRROR_REFRESH_ENABLED', diff --git a/database/migrations/2026_09_08_000000_create_ding_online_daifa_price_mirror_tables.php b/database/migrations/2026_09_08_000000_create_ding_online_daifa_price_mirror_tables.php new file mode 100644 index 00000000..81deeafa --- /dev/null +++ b/database/migrations/2026_09_08_000000_create_ding_online_daifa_price_mirror_tables.php @@ -0,0 +1,61 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('ding_online_daifa_price_mirror')) { + $schema->create('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->string('process_instance_id', 100); + $table->unsignedTinyInteger('detail_index')->default(0); + // 宽表列:按钉钉表单字段抽取,建立索引供页面筛选与按商品ID关联。 + $table->string('product_id', 64)->nullable()->index(); + $table->string('daifa_trade_no', 64)->nullable()->index(); + $table->string('shop_trade_no', 64)->nullable()->index(); + $table->string('shop_name', 120)->nullable()->index(); + $table->string('payee_name', 120)->nullable()->index(); + $table->string('supplier_name', 120)->nullable(); + $table->string('material_no', 120)->nullable(); + $table->unsignedInteger('ship_qty')->nullable(); + $table->decimal('paid_amount', 14, 2)->nullable(); + $table->decimal('daifa_amount', 14, 2)->nullable(); + $table->decimal('price_diff', 14, 2)->nullable(); + // 原始载荷保留,页面可展开核对原始表单,避免因模板改版丢数据。 + $table->json('workflow_payload'); + $table->json('scheme_payload'); + $table->json('task_payload')->nullable(); + $table->string('workflow_created_at', 32)->nullable()->index(); + $table->uuid('sync_generation')->nullable()->index(); + $table->dateTime('synced_at', 6); + + $table->primary(['process_instance_id', 'detail_index']); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + Schema::connection($this->connection())->dropIfExists('ding_online_daifa_price_mirror'); + } +}; diff --git a/database/migrations/2026_09_08_000100_add_daifa_product_name_and_skumap_index.php b/database/migrations/2026_09_08_000100_add_daifa_product_name_and_skumap_index.php new file mode 100644 index 00000000..0127519b --- /dev/null +++ b/database/migrations/2026_09_08_000100_add_daifa_product_name_and_skumap_index.php @@ -0,0 +1,80 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->mirrorConnection()); + + // 1) 线上代发价格镜像宽表增加“已匹配商品名称”列。 + // 商品名称在同步阶段按商品ID关联商品目录后写入,页面只读镜像, + // 不在此处临时 JOIN 2500 万行的 ops_jst_sku_map,避免页面查询超时。 + if ($schema->hasTable('ding_online_daifa_price_mirror') + && ! $schema->hasColumn('ding_online_daifa_price_mirror', 'product_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->string('product_name', 255)->nullable()->comment('按商品ID关联商品目录得到的名称'); + }); + } + + // 2) ops_jst_sku_map 是 2500 万行的共享镜像,原来没有 shop_i_id 单列索引, + // 按商品ID(钉钉表单“商品ID”即 shop_i_id)匹配只能全表扫描。这里补建 + // 单列索引,使按商品ID的关联在同步阶段可秒级完成。 + $this->ensureShopIIdIndex(); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->mirrorConnection()); + + if ($schema->hasTable('ding_online_daifa_price_mirror') + && $schema->hasColumn('ding_online_daifa_price_mirror', 'product_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->dropColumn('product_name'); + }); + } + + if ($this->hasIndex('ops_jst_sku_map', 'idx_shop_i_id')) { + $schema->table('ops_jst_sku_map', function (Blueprint $table): void { + $table->dropIndex('idx_shop_i_id'); + }); + } + } + + private function hasIndex(string $table, string $index): bool + { + $rows = DB::connection($this->mirrorConnection()) + ->select("SELECT 1 FROM information_schema.statistics WHERE TABLE_SCHEMA='caiwu_business_mirror' AND TABLE_NAME=? AND INDEX_NAME=? LIMIT 1", [$table, $index]); + + return count($rows) > 0; + } + + private function ensureShopIIdIndex(): void + { + if (! $this->hasIndex('ops_jst_sku_map', 'idx_shop_i_id')) { + Schema::connection($this->mirrorConnection()) + ->table('ops_jst_sku_map', function (Blueprint $table): void { + $table->index('shop_i_id', 'idx_shop_i_id'); + }); + } + } +}; diff --git a/database/migrations/2026_09_08_000200_add_daifa_payee_name.php b/database/migrations/2026_09_08_000200_add_daifa_payee_name.php new file mode 100644 index 00000000..0cb4dac7 --- /dev/null +++ b/database/migrations/2026_09_08_000200_add_daifa_payee_name.php @@ -0,0 +1,50 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + // 线上代发价格镜像宽表增加“收款人全称”列。同步阶段按钉钉表单“收款人全称” + // 抽取该列,并据此把镜像限定到指定收款人(默认宁波顾家望业家居有限公司)。 + // 已建表但缺列时补列;建表迁移已含该列则跳过,保证幂等。 + if ($schema->hasTable('ding_online_daifa_price_mirror') + && ! $schema->hasColumn('ding_online_daifa_price_mirror', 'payee_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->string('payee_name', 120)->nullable()->index()->after('shop_name'); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if ($schema->hasTable('ding_online_daifa_price_mirror') + && $schema->hasColumn('ding_online_daifa_price_mirror', 'payee_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->dropColumn('payee_name'); + }); + } + } +}; diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 30956928..bd2f4262 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -20,8 +20,8 @@ | 本次建立 | `config/upstream_mirrors.php` 中登记全部当前代码引用的原表;通用表级同步框架负责建表、稳定游标、断点续传、增量重叠和全量校准。 | | 已开始逐域切换 | 公司、店铺、商标页面在对应镜像完成首次全量后自动改读完整镜像表;首次全量前保留旧快照作为兼容回滚。其他业务域仍需逐项切换,不得宣称全项目已经完成。 | | 中央同步接入 | 店铺维度报表从 `jiansun.dbo.jst_originalBillInfo` 和 `dbo.fys_shopInfo_flow` 自动、可断点同步;不再依赖开发者电脑、SQLite 或人工 XLSX。 | -| 已登记,待首次同步 | `operations_replica/rpt.jst_originalBillInfo` 登记为通用原始账单镜像 `ops_jst_original_bill_info`;保留当前 19 个业务字段,按 `Id` 断点全量、按 `updateTime` 重叠增量。部署迁移只创建空表,不自动启动约 1400 万行的首次同步。 | -| 已登记,待首次同步 | 店铺收款账单的淘系支付宝账户已登记 `jiansun.dbo.alipay_Bill_Detail`,页面按共享镜像分页、筛选和汇总;首次全量完成前显示同步中状态。 | +| 已完成 | `operations_replica/rpt.jst_originalBillInfo` 已进入通用原始账单镜像 `ops_jst_original_bill_info`;保留当前 19 个业务字段,按 `Id` 断点全量、按 `updateTime` 重叠增量。 | +| 页面已切换 | 店铺收款账单的淘系支付宝账户读取 `operations_replica.rpt.jst_originalBillInfo`,并关联 `rpt.jst_shopInfo` 展示店铺;分页、筛选、汇总和导出统一读取共享业务镜像。 | ## 经营分析副本库(operations_replica) @@ -52,7 +52,7 @@ | 业务范围 | 上游对象 | | --- | --- | -| 店铺收款账单 | `dbo.alipay_Bill_Detail` | +| 店铺收款账单旧来源(已停用) | `dbo.alipay_Bill_Detail` | | 营销账户 | `dbo.tmall_spread_bills`、`dbo.pdd_spread_bills`、`dbo.alibaba_bill`、`dbo.jd_spreadBills`、`dbo.jd_costBills` | | 供应商应付 | `dbo.finance_purchaseReturn`、`dbo.finance_invoiceDeduction`、`dbo.fys_supplierPaymentSummary`、`dbo.finance_advanceLoans`、`dbo.pm_unOrderDetails`、`dbo.finance_sampleDeduction`、`dbo.fys_express_courier_settlement` | | 安装明细 | `dbo.fys_Ticketing_install_view`、`dbo.fys_Ticketing_install_item` | diff --git a/docs/店铺密码按需读取.md b/docs/店铺密码按需读取.md index 90a47553..bfe4ae4e 100644 --- a/docs/店铺密码按需读取.md +++ b/docs/店铺密码按需读取.md @@ -1,39 +1,37 @@ -# 店铺密码按需读取 +# 店铺密码直接显示 -## 使用方式 +## 使用与权限 -现有管理员使用原财务账号密码登录,在“店铺账号密码”页面点击查看或复制。首版仅允许数据库中仍持有 `super_admin` 或 `admin` 角色,且拥有该页面访问范围的用户。每次请求重新查询角色,不信任旧权限缓存。普通用户和钉钉自动创建的普通账号不能读取密码。 +“店铺账号密码”页面打开后,系统自动批量读取当前页最多 50 个已设置密码的账号,并把密码直接显示在原表格单元格内。用户无需再点击“查看”;“复制”仍保留为独立操作,便于形成准确的复制审计。未设置、读取受限和服务失败会分别显示固定状态,失败项可由用户重新读取。 -列表仍从 `database_4.external_store_accounts.accounts_v1` 的共享镜像读取。只有安全布尔字段 `passwordConfigured` 进入列表;镜像尚未新增该列时保持未知状态,管理员仍可按需请求,空密码由上游返回 404。镜像中的稳定账号 ID 是唯一请求目标,镜像未就绪时拒绝访问。 +密码读取与该页面使用同一访问边界:只要当前用户的页面权限包含 `store-management/store-accounts`,就可以直接显示和复制密码,不再额外要求 `admin` 或 `super_admin` 身份。主管理员可在“权限管理 → 页面权限设置”通过用户、分组或角色收回此页面;显式用户配置优先于分组,多个分组取并集。当前系统对尚未配置的用户默认开放全部业务页面,因此上线前应确认需要限制的用户或分组已经排除该页面。 -查看在表格之外的独立弹窗中显示,30 秒、关闭、离开页面或隐藏标签页时清除;不写浏览器存储。复制单独请求 `purpose=copy`,成功后写入用户剪贴板,不自动清除剪贴板以免覆盖用户后续内容。每次操作独立读取,没有预取、批量读取、重试或密码缓存。表格和 CSV 只包含配置状态,不包含弹窗密码。 +列表仍从 `database_4.external_store_accounts.accounts_v1` 的共享镜像读取。镜像只保存 `passwordConfigured` 布尔状态和稳定账号 ID,不保存密码。当前页账号 ID 必须全部存在于镜像,财务端才会调用上游。 -## 后端与审计 +## 接口与审计 -- 财务路由:`POST /{company_id}/store-account-passwords/{account}/reveal`,请求体仅允许 `purpose=view|copy` 和框架 CSRF 字段。 -- 使用可信会话中的用户 ID 生成 `requesterId=finance-user-{id}`,拒绝客户端额外提供操作者信息;验证公司、管理员角色、页面范围和镜像账号存在性。 -- 上游:`POST https://cp.jiansun.vip/internal/store-accounts/{id}/password/reveal`,专用 Bearer 令牌。完整契约来自上游 PR #17。 -- 专用 Guzzle 客户端不接入 Laravel HTTP 事件采集器,不记录请求、响应或异常对象。验证 TLS,总超时 10 秒、连接超时 3 秒,不跟随重定向、不重试,响应只缓存在本次请求内存中。 -- 上游 404/429 对应财务端 404/429;上游 403 表示服务凭据或网关配置故障,财务端返回固定 503 提示,避免误导为当前人员权限问题。上游 503、重定向、错误 JSON、缺少 `no-store` 或无效追踪 ID 均拒绝返回密码。财务权限拒绝为 403。 -- 财务端每用户 10 次/分钟;上游还按服务、人员、账号执行持久限流,查看和复制共享额度。 -- 新增 `store_account_password_audits`:只记录财务追踪 ID、操作者、公司、账号 ID、用途、状态、上游追踪 ID 和时间。开始审计失败不调用上游;成功审计无法落库时不向浏览器返回密码。审计成功表示服务器交付响应,不表示浏览器已经复制完成。 -- 响应 `Cache-Control: no-store`、`Pragma: no-cache`、`nosniff`、`no-referrer`。真实密码不进入日志、镜像、ClickHouse、Parquet、缓存或消息队列。网关/APM 必须排除该精确密码路由的请求/响应正文采集及响应落盘缓存。 +- 当前页批量路由:`POST /{company_id}/store-account-passwords/visible-page/reveal`,请求体仅允许 `accounts` 和框架 CSRF 字段;账号 ID 必须是 1 至 50 个互不重复的合法字符串。 +- 单账号复制路由:`POST /{company_id}/store-account-passwords/{account}/reveal`,请求体仅允许 `purpose=view|copy` 和框架 CSRF 字段。前端复制使用 `purpose=copy`。 +- 财务后端从可信会话生成 `requesterId=finance-user-{id}`,不接受浏览器提供操作者身份。每次请求重新计算页面权限并验证镜像账号。 +- 上游批量路由:`POST https://cp.jiansun.vip/internal/store-accounts/visible-page/password/reveal`;单账号路由保持原契约。两者使用同一专用 Bearer 凭据。财务后端把当前页请求拆成最多 25 个账号、JSON 请求体不超过 1000 字节的分片,常规 50 条页面会顺序发出两个上游请求,以适配公网入口的 1 KiB 请求体限制。 +- 批量响应按账号返回独立的 `200/404/429/503` 状态和追踪 ID。任何协议错误、缺少 `no-store`、无效追踪 ID、重复或遗漏账号都会使本批次在财务端按失败处理,密码不会返回浏览器。 +- 财务端每用户每分钟最多自动读取当前页 5 次,单账号复制仍为每分钟 10 次。上游分片批次限制为每服务每分钟 20 次、每天 1000 次,每人员每分钟 10 次;每账号每分钟 5 次的限制保持不变。 +- `store_account_password_audits` 为当前页每个账号写入一条 `view` 审计,复制写入 `copy` 审计。开始审计失败时不调用上游;完成审计无法落库时不向浏览器返回密码。审计只保存操作者、公司、账号 ID、用途、状态、追踪 ID和时间。 -## 配置及发布 +## 密码处理 -后端环境变量为 `STORE_ACCOUNT_REVEAL_URL`(含 `{id}` 的完整 HTTPS 模板)和 `STORE_ACCOUNT_REVEAL_TOKEN`。令牌已在负责人提供的受保护文件中,不在文档或 PR 中复制。财务工作区已将两项配置保存到经 `git check-ignore` 核验的 `runtime/private/store-account-password.env`,仅供后端部署读取。 +专用 Guzzle 客户端不接入 Laravel HTTP 事件采集器,不记录请求、响应或异常对象;验证 TLS,总超时 10 秒、连接超时 3 秒,不跟随重定向、不重试。上游和财务响应均发送 `Cache-Control: no-store`、`Pragma: no-cache`、`nosniff` 和 `no-referrer`。 -上线需要单独批准以下范围: +密码只存在于上游进程、财务请求内存和当前浏览器页面 DOM。页面隐藏、离开或卸载时清空当前页内容,再次显示页面时重新读取。密码不进入共享镜像、CSV 导出、日志、ClickHouse、Parquet、缓存、浏览器存储或消息队列。网关和 APM 必须继续排除两个精确密码路由的请求及响应正文采集。 -1. 备份生产系统库结构和当前应用配置;运行新增迁移 `2026_09_08_080000_create_store_account_password_audits`,只新增无密码审计表。 -2. 将上述两个变量安全加载到财务后端运行环境,禁止进入镜像、前端或发布输出。确认生产未启用响应正文采集。 -3. 如需显示上游新的布尔状态,按既有通用镜像登记/刷新流程更新该精确数据集的字段与镜像,核对 958 条资料仍完整。此步骤只涉及安全状态,不能加入密码字段。 -4. 使用已合并最新 main 及工作站发布脚本发布。生产验收需另行安排虚构上游账号,不能用真实店铺密码进行自动化抓取或截图。 +## 配置与发布 -回滚使用上一应用镜像、移除新服务凭据即可;新增审计表保留,不自动删除审计或用户资料。不需要修改钉钉配置,也不需要新增管理员账号。 +财务后端使用以下环境变量: -## 验证 +- `STORE_ACCOUNT_REVEAL_URL`:含 `{id}` 的单账号 HTTPS 地址。 +- `STORE_ACCOUNT_REVEAL_VISIBLE_PAGE_URL`:当前页批量 HTTPS 地址;未配置时使用正式默认地址。 +- `STORE_ACCOUNT_REVEAL_TOKEN`:专用服务令牌。 -18 项后端/镜像测试通过,覆盖管理员查看与复制、可信操作者、普通用户与受限管理员拒绝、镜像无账号、403/404/429/503/重定向、限流、缺失令牌、缺少 no-store、审计失败不返回密码,以及审计不含虚构密码。 +令牌只保存在受保护的运行时配置中,不能进入 Git、镜像、前端或发布输出。本次财务改动复用现有审计表,不增加数据库迁移。发布顺序必须先让上游批量接口可用,再发布财务页面;回滚时先回滚财务应用,再回滚上游接口。 -浏览器使用实际 Blade 渲染的虚构账号页面和独立本地假接口检查:查看、关闭清空、30 秒自动清空、复制后实际粘贴、桌面与 390px 窄屏弹窗。未调用上游真实店铺密码接口,未执行财务生产迁移或发布。 +验收使用虚构账号和虚构密码,检查当前页自动显示、部分失败、整体失败重试、复制、窄屏和页面隐藏清空。不得用真实店铺密码制作自动化快照、日志或截图。 diff --git a/docs/钉钉花名册登录.md b/docs/钉钉花名册登录.md index 6a94f5ff..435c2429 100644 --- a/docs/钉钉花名册登录.md +++ b/docs/钉钉花名册登录.md @@ -13,6 +13,8 @@ 已绑定的启用账号继续使用原账号及原权限。姓名、花名、邮箱和手机号不会用于自动认领其他账号。已拒绝、解绑或停用的身份不会通过再次授权自动恢复。 +负责人明确指定的主管理员可通过受保护的运行时配置 `DINGTALK_SUPER_ADMIN_USER_IDS` 登记企业 userid(逗号分隔,默认空)。仅这些精确身份可以不受财务部门范围限制,首次开户赋予 `super_admin`;仍必须通过唯一花名册、在职、非离职、有效组织链和钉钉企业成员核验。既有账号角色不因该配置在登录时被覆盖。移除指定身份会恢复财务部门准入要求,但不直接改写既有角色。配置不得使用姓名、手机号或整部门,也不得把真实身份值提交到仓库。 + 新账号使用钉钉接口返回的姓名、可用邮箱和手机号;邮箱缺失或已被其他账号使用时,生成稳定的 `@dingtalk.invalid` 内部占位地址。系统生成不可预知的随机本地密码,不展示或发送密码,不发送注册邀请。花名册显示名仅作为姓名缺失时的后备。 新账号赋予现有 `user` 角色及进入应用外壳所需的 `read-admin-panel` 权限,不添加管理权限。按负责人最新要求,尚无页面权限配置时默认显示完整业务导航;主管理员随后可在“侧边栏管理”中设置指定用户的业务范围。配置优先级为指定用户、角色、默认完整导航;显式配置为空时没有业务页面,不回退到完整导航。管理员专属操作(包括店铺密码读取)继续单独鉴权。 diff --git a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php index 10fa1b90..7cdcf6bc 100644 --- a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php @@ -57,6 +57,40 @@ class AlipayBills extends Controller } } + public function export(Request $request, StoreReceivingAlipayBillMirrorRepository $repository) + { + $this->authorizeStoreReceivingBills(); + $filters = $request->validate([ + 'store_name' => ['nullable', 'string', 'max:255'], + 'alipay_account' => ['nullable', 'string', 'max:128'], + 'bill_item' => ['nullable', 'string', 'max:255'], + 'business_type' => ['nullable', 'string', 'max:255'], + 'start' => ['nullable', 'date_format:Y-m-d'], + 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], + 'keyword' => ['nullable', 'string', 'max:255'], + ]); + + try { + $rows = $repository->exportRows(array_map(static fn (mixed $value): string => trim((string) $value), $filters)); + } catch (RuntimeException $exception) { + if ($exception->getMessage() !== 'store_receiving_alipay_bill_mirror_not_ready') { + throw $exception; + } + + return response()->json(['message' => '淘系支付宝账单共享业务镜像正在首次同步,完成后将自动显示。'], 503); + } + + return response()->streamDownload(function () use ($rows): void { + $csv = fopen('php://output', 'w'); + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, ['记录编码', '原始店铺', '平台渠道', '账单项目', '账务订单号', '业务流水号', '商户订单号', '业务基础订单号', '商品编码', '发生时间', '收入(元)', '支出(元)', '收支净额(元)', '收支类型', '线上单号', '业务描述', '业务账单来源', '创建时间', '修改时间']); + foreach ($rows as $row) { + fputcsv($csv, [$row['record_code'], $row['store_name'], $row['alipay_account'], $row['bill_item'], $row['account_order_no'], $row['business_serial_no'], $row['merchant_order_no'], $row['business_base_order_no'], $row['goods_name'], $row['occurred_at'], $row['income'], $row['expense'], $row['balance'], $row['business_type'], $row['online_order_no'], $row['business_description'], $row['business_bill_source'], $row['created_at'], $row['updated_at']]); + } + fclose($csv); + }, 'taobao_alipay_bills.csv', ['Content-Type' => 'text/csv; charset=UTF-8']); + } + public function show(AlipayBill $bill) { $this->authorizeStoreReceivingBills(); diff --git a/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php new file mode 100644 index 00000000..301c24b8 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php @@ -0,0 +1,176 @@ +connection = $mirror->connection(); + } + + public function ready(): bool + { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable(self::TARGET_TABLE) || ! $schema->hasTable('business_mirror_table_states')) { + return false; + } + + $state = $this->connection->table('business_mirror_table_states') + ->where('dataset_key', self::DATASET_KEY)->first(); + + return $state !== null && $state->initial_completed_at !== null; + } + + /** @return array{data:list>,total:int,status:string,last_synced_at:?string,summary:array} */ + public function paginate(array $filters, int $page, int $perPage): array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + $state = $this->connection->table('business_mirror_table_states')->where('dataset_key', self::DATASET_KEY)->first(); + + $query = $this->connection->table(self::TARGET_TABLE); + + if (($filters['product_id'] ?? '') !== '') { + $query->where('product_id', (string) $filters['product_id']); + } + if (($filters['shop_name'] ?? '') !== '') { + $query->where('shop_name', (string) $filters['shop_name']); + } + if (($filters['keyword'] ?? '') !== '') { + $keyword = (string) $filters['keyword']; + $query->where(function ($q) use ($keyword): void { + $q->where('process_instance_id', 'like', '%' . $keyword . '%') + ->orWhere('daifa_trade_no', 'like', '%' . $keyword . '%') + ->orWhere('shop_trade_no', 'like', '%' . $keyword . '%'); + }); + } + if (($filters['created_from'] ?? '') !== '') { + $query->where('workflow_created_at', '>=', (string) $filters['created_from']); + } + if (($filters['created_to'] ?? '') !== '') { + $query->where('workflow_created_at', '<', \Illuminate\Support\Carbon::parse((string) $filters['created_to'])->addDay()->startOfDay()->format('Y-m-d H:i:s')); + } + + $rows = $query->orderByDesc('workflow_created_at')->orderByDesc('process_instance_id')->orderByDesc('detail_index')->get(); + + $statusFilter = strtoupper(trim((string) ($filters['status'] ?? ''))); + $matched = []; + foreach ($rows as $row) { + $workflow = $this->decode((string) $row->workflow_payload, []); + if ($statusFilter !== '' && DingPayableWorkflowStatus::key($workflow) !== $statusFilter) { + continue; + } + $matched[] = $row; + } + + $total = count($matched); + $pageRows = array_slice($matched, ($page - 1) * $perPage, $perPage); + + $data = []; + foreach ($pageRows as $row) { + $workflow = $this->decode((string) $row->workflow_payload, []); + $productId = (string) ($row->product_id ?? ''); + // 商品名称已在同步阶段按 商品ID 关联商品目录并写入镜像宽表 product_name 列, + // 页面直接读取,避免对 2500 万行的 ops_jst_sku_map 做临时 JOIN 导致超时。 + $resolvedName = $this->cleanName($row->product_name ?? null); + $product = $productId !== '' && $resolvedName !== null + ? ['matched' => true, 'name' => $resolvedName, 'sku_id' => null, 'i_id' => null] + : ['matched' => false, 'name' => null, 'sku_id' => null, 'i_id' => null]; + $data[] = [ + 'process_instance_id' => (string) $row->process_instance_id, + 'detail_index' => (int) $row->detail_index, + 'product_id' => $productId, + 'daifa_trade_no' => (string) ($row->daifa_trade_no ?? ''), + 'shop_trade_no' => (string) ($row->shop_trade_no ?? ''), + 'shop_name' => (string) ($row->shop_name ?? ''), + 'payee_name' => (string) ($row->payee_name ?? ''), + 'supplier_name' => (string) ($row->supplier_name ?? ''), + 'material_no' => (string) ($row->material_no ?? ''), + 'ship_qty' => $row->ship_qty === null ? null : (int) $row->ship_qty, + 'paid_amount' => $row->paid_amount === null ? null : (float) $row->paid_amount, + 'daifa_amount' => $row->daifa_amount === null ? null : (float) $row->daifa_amount, + 'price_diff' => $row->price_diff === null ? null : (float) $row->price_diff, + 'workflow' => $workflow, + 'scheme' => $this->decode((string) ($row->scheme_payload ?? '[]'), []), + 'tasks' => $this->decode((string) ($row->task_payload ?? '[]'), []), + 'status_key' => DingPayableWorkflowStatus::key($workflow), + 'status_label' => DingPayableWorkflowStatus::label($workflow), + 'matched_product' => $product, + 'workflow_created_at' => (string) ($row->workflow_created_at ?? ''), + ]; + } + + return [ + 'data' => $data, + 'total' => $total, + 'status' => (string) ($state->status ?? 'unknown'), + 'last_synced_at' => $state->last_succeeded_at ? (string) $state->last_succeeded_at : null, + 'summary' => $this->summary($matched), + ]; + } + + /** @param list $rows */ + private function summary(array $rows): array + { + $daifa = 0.0; + $paid = 0.0; + $diff = 0.0; + $matched = 0; + foreach ($rows as $row) { + $daifa += (float) ($row->daifa_amount ?? 0); + $paid += (float) ($row->paid_amount ?? 0); + $diff += (float) ($row->price_diff ?? 0); + if (! empty($row->product_id) && $this->cleanName($row->product_name ?? null) !== null) { + $matched++; + } + } + return [ + 'count' => count($rows), + 'matched_count' => $matched, + 'daifa_amount' => round($daifa, 2), + 'paid_amount' => round($paid, 2), + 'price_diff' => round($diff, 2), + ]; + } + + private function cleanName(mixed $value): ?string + { + if ($value === null) { + return null; + } + $name = trim((string) $value); + return $name === '' ? null : $name; + } + + private function decode(string $json, mixed $fallback): mixed + { + if ($json === '') { + return $fallback; + } + $decoded = json_decode($json, true); + return is_array($decoded) ? $decoded : $fallback; + } +} diff --git a/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php b/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php index f5b6e80c..27e307ed 100644 --- a/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php @@ -211,6 +211,9 @@ class SmallPaymentWorkOrderMirrorRepository $join->on('work_order_versions.woNo', '=', 'p.woNo'); }) ->join($workOrders . ' AS w', 'w.Id', '=', 'work_order_versions.Id') + // Match the leading columns of (woTypeId, woNo, Id), rather than + // rescanning all orders of this type for every payment-map row. + ->whereColumn('w.woNo', 'p.woNo') ->where('p.woTypeId', self::SMALL_PAYMENT_WORK_TYPE_ID) ->where('w.woTypeId', self::SMALL_PAYMENT_WORK_TYPE_ID); } diff --git a/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php index 7ec925fc..91ed7d7f 100644 --- a/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreAccountMirrorRepository.php @@ -61,6 +61,20 @@ class StoreAccountMirrorRepository return $this->mirror->connection()->table($dataset->targetTable())->where('id', $id)->exists(); } + public function containsAccounts(array $ids): bool + { + $ids = array_values(array_unique($ids)); + if ($ids === []) { + return false; + } + $dataset = $this->datasets->get(self::DATASET); + if (! $this->mirror->ready($dataset)) { + throw new RuntimeException('store_account_mirror_not_ready'); + } + return $this->mirror->connection()->table($dataset->targetTable()) + ->whereIn('id', $ids)->distinct()->count('id') === count($ids); + } + /** * 店铺维度报表的归属字段覆盖表,以店铺名称(storeName)为键。 * diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php index 5f83275b..5b7952c1 100644 --- a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php @@ -3,13 +3,15 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\Query\Builder; +use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry; use RuntimeException; -/** 店铺收款账单·淘系支付宝账户只读共享业务镜像。 */ +/** 店铺收款账单·淘系支付宝账户只读经营分析副本镜像。 */ class StoreReceivingAlipayBillMirrorRepository { - public const DATASET = 'jiansun.dbo.alipay_Bill_Detail'; + public const DATASET = 'operations_replica.rpt.jst_originalBillInfo'; + public const SHOP_DATASET = 'operations_replica.rpt.jst_shopInfo'; public function __construct( private readonly BusinessMirrorDatasetRegistry $datasets, @@ -20,7 +22,8 @@ class StoreReceivingAlipayBillMirrorRepository public function paginate(array $filters, string $sort, string $direction, int $page, int $perPage): array { $dataset = $this->datasets->get(self::DATASET); - if (! $this->mirror->ready($dataset)) { + if (! $this->mirror->ready($dataset) + || ! $this->mirror->ready($this->datasets->get(self::SHOP_DATASET))) { throw new RuntimeException('store_receiving_alipay_bill_mirror_not_ready'); } @@ -28,33 +31,38 @@ class StoreReceivingAlipayBillMirrorRepository $perPage = min(max($perPage, 1), 100); $direction = $direction === 'asc' ? 'asc' : 'desc'; $sortColumn = [ - 'record_code' => 'Id', - 'occurred_at' => 'happenTime', - 'income' => 'inAmount', - 'expense' => 'outAmount', - 'balance' => 'accountAmount', - ][$sort] ?? 'happenTime'; + 'record_code' => 'b.Id', + 'occurred_at' => 'b.fee_time', + 'income' => 'b.amount', + 'expense' => 'b.amount', + 'balance' => 'b.amount', + ][$sort] ?? 'b.fee_time'; - $query = $this->mirror->connection()->table($dataset->targetTable()); + $query = $this->billQuery(); $this->applyFilters($query, $filters); - $total = (clone $query)->count(); - $summaryRow = (clone $query)->selectRaw( - 'COALESCE(SUM(CASE WHEN inAmount > 0 THEN inAmount ELSE 0 END), 0) AS income, ' - . 'COALESCE(SUM(ABS(COALESCE(outAmount, 0))), 0) AS expense, COUNT(*) AS aggregate_count' - )->first(); - $latestBalance = (clone $query) - ->orderByDesc('happenTime') - ->orderByDesc('Id') - ->value('accountAmount'); + $state = $this->mirror->state($dataset) ?? []; + // The synchronizer persists an exact COUNT in the same transaction that + // marks a run successful. Never substitute a database row estimate. + $hasFilters = collect($filters)->contains(static fn (mixed $value): bool => $value !== null && trim((string) $value) !== ''); + $recordedCount = $state['mirror_row_count'] ?? null; + $useRecordedCount = ! $hasFilters && ($state['status'] ?? null) === 'succeeded' + && $recordedCount !== null && ctype_digit((string) $recordedCount); + $total = $useRecordedCount ? (int) $recordedCount : (clone $query)->count(); + $summary = $this->summary($query, $filters); - $rows = $query + $billRows = $query + ->select('b.*') ->orderBy($sortColumn, $direction) - ->orderBy('Id', $direction) + ->orderBy('b.Id', $direction) ->forPage($page, $perPage) ->get() - ->map(fn (object $row): array => $this->mapRow($row)) ->all(); - $state = $this->mirror->state($dataset) ?? []; + $shopNames = $this->shopNames($billRows); + $rows = collect($billRows) + ->map(fn (object $row): array => $this->mapRow($row, $shopNames[(string) $row->shop_id] ?? null)) + ->all(); + $income = $summary['income']; + $expense = $summary['expense']; return [ 'data' => $rows, @@ -63,10 +71,10 @@ class StoreReceivingAlipayBillMirrorRepository 'last_page' => max((int) ceil($total / $perPage), 1), 'per_page' => $perPage, 'summary' => [ - 'income' => (float) ($summaryRow->income ?? 0), - 'expense' => (float) ($summaryRow->expense ?? 0), - 'balance' => (float) ($latestBalance ?? 0), - 'count' => (int) ($summaryRow->aggregate_count ?? 0), + 'income' => $income, + 'expense' => $expense, + 'balance' => $income - $expense, + 'count' => $total, ], 'sync' => [ 'status' => $state['status'] ?? 'unknown', @@ -75,75 +83,210 @@ class StoreReceivingAlipayBillMirrorRepository ]; } + /** @return iterable> */ + public function exportRows(array $filters): iterable + { + $dataset = $this->datasets->get(self::DATASET); + if (! $this->mirror->ready($dataset) + || ! $this->mirror->ready($this->datasets->get(self::SHOP_DATASET))) { + throw new RuntimeException('store_receiving_alipay_bill_mirror_not_ready'); + } + + $query = $this->billQuery(); + $this->applyFilters($query, $filters); + $shopNames = $this->allShopNames(); + + return $query->select('b.*') + ->orderBy('b.fee_time')->orderBy('b.Id')->cursor() + ->map(fn (object $row): array => $this->mapRow($row, $shopNames[(string) $row->shop_id] ?? null)); + } + + private function billQuery(): Builder + { + return $this->mirror->connection()->table('ops_jst_original_bill_info as b'); + } + + /** @return array{income:float,expense:float} */ + private function summary(Builder $billQuery, array $filters): array + { + if ($this->dailySummarySupports($filters)) { + $summary = $this->dailySummary($filters); + if ($summary !== null) { + return $summary; + } + } + + $row = (clone $billQuery)->selectRaw( + "COALESCE(SUM(CASE WHEN b.inout_type = '1' THEN ABS(COALESCE(b.amount, 0)) ELSE 0 END), 0) AS income, " + . "COALESCE(SUM(CASE WHEN b.inout_type = '-1' THEN ABS(COALESCE(b.amount, 0)) ELSE 0 END), 0) AS expense" + )->first(); + + return [ + 'income' => round((float) ($row->income ?? 0), 2), + 'expense' => round((float) ($row->expense ?? 0), 2), + ]; + } + + private function dailySummarySupports(array $filters): bool + { + return ($filters['alipay_account'] ?? '') === '' + && ($filters['bill_item'] ?? '') === '' + && ($filters['keyword'] ?? '') === ''; + } + + /** @return array{income:float,expense:float}|null */ + private function dailySummary(array $filters): ?array + { + $connection = $this->mirror->connection(); + $schema = Schema::connection($connection->getName()); + if (! $schema->hasTable('store_report_import_states') || ! $schema->hasTable('store_report_daily_rows')) { + return null; + } + + $state = $connection->table('store_report_import_states') + ->where('dataset_key', 'store-report.daily-sales')->first(); + $generation = trim((string) ($state->active_generation ?? '')); + if ($generation === '' || empty($state->initial_completed_at)) { + return null; + } + + $query = $connection->table('store_report_daily_rows')->where('generation', $generation); + if (($filters['store_name'] ?? '') !== '') { + $query->where('store_name', $filters['store_name']); + } + if (($filters['start'] ?? '') !== '') { + $query->where('occurred_on', '>=', $filters['start']); + } + if (($filters['end'] ?? '') !== '') { + $query->where('occurred_on', '<=', $filters['end']); + } + $row = $query->selectRaw('COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense')->first(); + $income = round((float) ($row->income ?? 0), 2); + $expense = round((float) ($row->expense ?? 0), 2); + + return match ($this->directionCode((string) ($filters['business_type'] ?? ''))) { + '1' => ['income' => $income, 'expense' => 0.0], + '-1' => ['income' => 0.0, 'expense' => $expense], + default => ['income' => $income, 'expense' => $expense], + }; + } + private function applyFilters(Builder $query, array $filters): void { if (($filters['store_name'] ?? '') !== '') { - $query->where('shopName', $filters['store_name']); + $shopIds = $this->mirror->connection()->table('ops_jst_shop_info') + ->where('shop_name', $filters['store_name']) + ->pluck('shop_id') + ->filter(static fn (mixed $value): bool => $value !== null && $value !== '') + ->all(); + if ($shopIds === []) { + $query->whereRaw('1 = 0'); + } else { + $query->whereIn('b.shop_id', $shopIds); + } } if (($filters['alipay_account'] ?? '') !== '') { - $value = '%' . $this->escapeLike((string) $filters['alipay_account']) . '%'; - $query->where(function (Builder $query) use ($value): void { - $query->where('appId', 'like', $value) - ->orWhere('account', 'like', $value); - }); + $query->where('b.channel', 'like', '%' . $this->escapeLike((string) $filters['alipay_account']) . '%'); } if (($filters['bill_item'] ?? '') !== '') { - $query->where('tradeChannel', $filters['bill_item']); + $query->where('b.fee_name', $filters['bill_item']); } if (($filters['business_type'] ?? '') !== '') { - $query->where('businessType', $filters['business_type']); + $query->where('b.inout_type', $this->directionCode((string) $filters['business_type'])); } if (($filters['start'] ?? '') !== '') { - $query->where('happenTime', '>=', $filters['start'] . ' 00:00:00'); + $query->where('b.fee_time', '>=', $filters['start'] . ' 00:00:00'); } if (($filters['end'] ?? '') !== '') { - $query->where('happenTime', '<', date('Y-m-d', strtotime($filters['end'] . ' +1 day')) . ' 00:00:00'); + $query->where('b.fee_time', '<', date('Y-m-d', strtotime($filters['end'] . ' +1 day')) . ' 00:00:00'); } if (($filters['keyword'] ?? '') !== '') { $value = '%' . $this->escapeLike((string) $filters['keyword']) . '%'; $query->where(function (Builder $query) use ($value): void { - $query->where('commodityName', 'like', $value) - ->orWhere('accountNum', 'like', $value) - ->orWhere('businessNum', 'like', $value) - ->orWhere('merchantOrder', 'like', $value) - ->orWhere('storeNum', 'like', $value) - ->orWhere('remark', 'like', $value); + foreach (['b.fee_name', 'b.primary_key', 'b.p_auto_id', 'b.so_id', 'b.sku_id', 'b.shop_sku_id', 'b.shop_i_id', 'b.channel'] as $column) { + $query->orWhere($column, 'like', $value); + } }); } } - private function mapRow(object $row): array + /** @param array $rows @return array */ + private function shopNames(array $rows): array { + $shopIds = collect($rows)->pluck('shop_id')->filter()->unique()->values()->all(); + if ($shopIds === []) { + return []; + } + + return $this->mirror->connection()->table('ops_jst_shop_info') + ->whereIn('shop_id', $shopIds)->pluck('shop_name', 'shop_id') + ->mapWithKeys(static fn (mixed $name, mixed $id): array => [(string) $id => (string) $name]) + ->all(); + } + + /** @return array */ + private function allShopNames(): array + { + return $this->mirror->connection()->table('ops_jst_shop_info') + ->whereNotNull('shop_id')->pluck('shop_name', 'shop_id') + ->mapWithKeys(static fn (mixed $name, mixed $id): array => [(string) $id => (string) $name]) + ->all(); + } + + private function mapRow(object $row, ?string $shopName): array + { + $amount = abs((float) ($row->amount ?? 0)); + $income = (string) ($row->inout_type ?? '') === '1' ? $amount : 0.0; + $expense = (string) ($row->inout_type ?? '') === '-1' ? $amount : 0.0; + return [ 'id' => (string) $row->Id, 'record_code' => (string) $row->Id, - 'store_name' => $row->shopName, - 'custom_remark' => $row->buyerRemark, - 'bill_item' => $row->tradeChannel, - 'alipay_account' => $row->appId ?: $row->account, - 'account_order_no' => $row->accountNum, - 'business_serial_no' => $row->businessNum, - 'merchant_order_no' => $row->merchantOrder, - 'business_base_order_no' => $row->busiBasicNum, - 'goods_name' => $row->commodityName, - 'counterparty_account' => $row->oppAccount, - 'occurred_at' => $this->dateTime($row->happenTime), - 'income' => max((float) ($row->inAmount ?? 0), 0), - 'expense' => abs((float) ($row->outAmount ?? 0)), - 'balance' => (float) ($row->accountAmount ?? 0), - 'business_type' => $row->businessType, - 'remark' => $row->remark, - 'online_order_no' => $row->storeNum, - 'online_real_store' => $row->shopName, - 'business_description' => $row->busiDescription, - 'business_bill_source' => $row->busiBillSource, - 'business_order_no' => $row->busiNum, - 'created_at' => '', - 'updated_at' => '', + 'store_name' => $shopName, + 'custom_remark' => null, + 'bill_item' => $row->fee_name, + 'alipay_account' => $row->channel, + 'account_order_no' => $row->primary_key, + 'business_serial_no' => $row->auto_id, + 'merchant_order_no' => $row->p_auto_id, + 'business_base_order_no' => $row->so_id, + 'goods_name' => $row->sku_id ?: $row->shop_sku_id, + 'counterparty_account' => null, + 'occurred_at' => $this->dateTime($row->fee_time), + 'income' => $income, + 'expense' => $expense, + 'balance' => $income - $expense, + 'business_type' => $this->directionName($row->inout_type), + 'remark' => null, + 'online_order_no' => $row->so_id, + 'online_real_store' => $shopName, + 'business_description' => $row->combine_type, + 'business_bill_source' => $row->channel, + 'business_order_no' => $row->p_auto_id, + 'created_at' => $this->dateTime($row->createTime), + 'updated_at' => $this->dateTime($row->updateTime), 'modifier' => '', ]; } + private function directionCode(string $value): string + { + return match ($value) { + '收入', 'IN', 'in' => '1', + '支出', 'OUT', 'out' => '-1', + default => $value, + }; + } + + private function directionName(mixed $value): string + { + return match ((string) $value) { + '1' => '收入', + '-1' => '支出', + default => (string) ($value ?? ''), + }; + } + private function dateTime(mixed $value): string { return $value === null || $value === '' ? '' : date('Y-m-d H:i:s', strtotime((string) $value)); diff --git a/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php b/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php index 7f011d71..79ceec29 100644 --- a/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php +++ b/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php @@ -23,7 +23,7 @@ class BusinessMirrorSchemaManager $table->char('_mirror_key', 64)->primary(); foreach ($columns as $column) { - $this->addColumn($table, $column); + $this->addColumn($table, $column, $dataset); } $table->uuid('_mirror_generation')->nullable()->index(); @@ -49,9 +49,9 @@ class BusinessMirrorSchemaManager )); if ($missing !== []) { - $schema->table($dataset->targetTable(), function (Blueprint $table) use ($missing): void { + $schema->table($dataset->targetTable(), function (Blueprint $table) use ($missing, $dataset): void { foreach ($missing as $column) { - $this->addColumn($table, $column); + $this->addColumn($table, $column, $dataset); } }); } @@ -120,7 +120,7 @@ class BusinessMirrorSchemaManager return $rows; } - private function addColumn(Blueprint $table, array $column): void + private function addColumn(Blueprint $table, array $column, BusinessMirrorDataset $dataset): void { $name = (string) $column['column_name']; $type = strtolower((string) $column['data_type']); @@ -144,9 +144,11 @@ class BusinessMirrorSchemaManager // MariaDB counts every inline varchar column towards the 65,535-byte // row limit. Wide legacy SQL Server tables can contain dozens of // nvarchar columns even though each individual column looks small. - // Keep only genuinely short values inline; TEXT is stored off-page - // and lets the mirror preserve the complete source schema. - 'char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying' => $length > 0 && $length <= 64 + // Keep only genuinely short values inline. A declared lookup index + // may opt a bounded legacy identifier into VARCHAR; every other + // wide string remains TEXT and is stored off-page. + 'char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying' => $length > 0 + && ($length <= 64 || ($length <= 191 && $this->isConfiguredIndexColumn($dataset, $name))) ? $table->string($name, $length) : $table->longText($name), default => $table->longText($name), @@ -155,7 +157,7 @@ class BusinessMirrorSchemaManager $definition->nullable(); } - private function isIndexable(array $columns, string $name): bool + private function isIndexable(array $columns, string $name, ?BusinessMirrorDataset $dataset = null): bool { foreach ($columns as $column) { if (strcasecmp((string) $column['column_name'], $name) !== 0) { @@ -166,7 +168,8 @@ class BusinessMirrorSchemaManager $length = (int) ($column['max_length'] ?? 0); return ! in_array($type, ['text', 'ntext', 'xml', 'image', 'binary', 'varbinary', 'bytea', 'json', 'jsonb', 'array', 'user-defined'], true) - && (! in_array($type, ['char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying'], true) || ($length > 0 && $length <= 64)); + && (! in_array($type, ['char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying'], true) + || ($length > 0 && ($length <= 64 || ($length <= 191 && $dataset !== null && $this->isConfiguredIndexColumn($dataset, $name))))); } return false; @@ -188,7 +191,7 @@ class BusinessMirrorSchemaManager foreach ($dataset->indexDefinitions() as $index) { foreach ($index as $column) { if (! in_array(strtolower($column), $columnNames, true) - || ! $this->isIndexable($columns, $column)) { + || ! $this->isIndexable($columns, $column, $dataset)) { throw new RuntimeException('business_mirror_index_column_unsupported:' . $dataset->key()); } } @@ -197,6 +200,19 @@ class BusinessMirrorSchemaManager return $dataset->indexDefinitions(); } + private function isConfiguredIndexColumn(BusinessMirrorDataset $dataset, string $column): bool + { + foreach ($dataset->indexDefinitions() as $index) { + foreach ($index as $indexedColumn) { + if (strcasecmp((string) $indexedColumn, $column) === 0) { + return true; + } + } + } + + return false; + } + private function configuredIndexName(string $table, array $columns, int $position): string { $signature = implode('_', $columns) . '_' . $position; diff --git a/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php b/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php index 167b2894..233e88de 100644 --- a/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php @@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\Services; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Schema\Blueprint; +use Illuminate\Database\Schema\Builder; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Carbon; use Illuminate\Support\Str; @@ -11,15 +12,23 @@ use RuntimeException; use Throwable; /** - * 将钉钉应付申请流程的固定流程编码同步为按流程聚合的共享镜像。 + * 将钉钉审批流程(按固定流程编码)同步为按流程聚合的共享镜像。 * * 钉钉表单字段存放在 JSON 中,且历史版本字段不完全一致;镜像保留原始 * 主表、表单和审批任务 payload,页面只在镜像库中解析和筛选。 + * + * 同一套同步逻辑通过 configKey 支持多个钉钉流程:默认处理“应付申请流程”, + * 配置 ding_online_daifa_price 时按列映射抽取宽表列并(可选)按明细表格 + * 展开为多行,便于按商品ID关联商品目录。新增流程只需在 + * config/upstream_mirrors.php 增加一项,无需另造同步链路。 */ class DingPayableWorkflowMirrorSynchronizer { private readonly ConnectionInterface $connection; + /** 当前同步的钉钉流程配置键,默认“应付申请流程”。 */ + private string $configKey = 'ding_payable_workflows'; + public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) { $this->connection = app('db')->connection( @@ -27,10 +36,18 @@ class DingPayableWorkflowMirrorSynchronizer ); } + /** 切换要同步的钉钉流程配置键(复用同一套同步链路)。 */ + public function forConfigKey(string $configKey): self + { + $this->configKey = $configKey; + + return $this; + } + /** @return array{status:string,mode:string,batches:int,rows:int,dataset:string} */ public function sync(bool $full = false, ?int $batchSize = null, ?int $maxBatches = null): array { - $config = (array) config('upstream_mirrors.ding_payable_workflows', []); + $config = (array) config('upstream_mirrors.' . $this->configKey, []); $dataset = (string) ($config['dataset_key'] ?? 'operations_replica.rpt.ding_payable_workflows'); $target = (string) ($config['target_table'] ?? 'ding_payable_workflow_mirror'); $source = (string) ($config['source_key'] ?? 'operations_replica'); @@ -92,12 +109,24 @@ class DingPayableWorkflowMirrorSynchronizer $taskById = $this->groupBy($tasks, 'processInstanceId'); $now = now(); $payloads = []; + $extendColumns = ! empty($config['extend_columns']); + $columnMap = $extendColumns ? (array) ($config['column_map'] ?? []) : []; + $columnTypes = $extendColumns ? (array) ($config['column_types'] ?? []) : []; + $detailTable = $extendColumns ? trim((string) ($config['detail_table'] ?? '')) : ''; + $resolveProductName = $extendColumns && ! empty($config['resolve_product_name']); + $rowFilters = $extendColumns ? (array) ($config['row_filters'] ?? []) : []; + $onlyStatus = strtoupper(trim((string) ($config['only_status'] ?? ''))); foreach ($workflows as $workflow) { $id = (string) ($workflow['processInstanceId'] ?? ''); if ($id === '') { continue; } + // 工作流级状态过滤:只保留指定审批状态(默认只要“已完成/已通过”), + // 未通过/已拒绝/撤回等整单不写入镜像。置空 only_status 则不限状态。 + if ($onlyStatus !== '' && DingPayableWorkflowStatus::key($workflow) !== $onlyStatus) { + continue; + } $originatorId = trim((string) ($workflow['originatorUserId'] ?? '')); $originatorName = trim((string) ($originatorNames[$originatorId] ?? '')); if ($originatorName !== '') { @@ -105,15 +134,38 @@ class DingPayableWorkflowMirrorSynchronizer // 页面无需在请求期间再次直连上游或猜测标题内容。 $workflow['originatorUserName'] = $originatorName; } - $payloads[] = [ - 'process_instance_id' => $id, - 'workflow_payload' => json_encode($workflow, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), - 'scheme_payload' => json_encode($schemeById[$id] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), - 'task_payload' => json_encode($taskById[$id] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), - 'workflow_created_at' => isset($workflow['createAt']) ? (string) $workflow['createAt'] : null, - 'sync_generation' => $generation, - 'synced_at' => $now, - ]; + $schemeRows = $schemeById[$id] ?? []; + $detailFieldsList = $this->buildDetailRowFields($schemeRows, $detailTable); + $detailIndex = 0; + foreach ($detailFieldsList as $fields) { + $payload = [ + 'process_instance_id' => $id, + 'workflow_payload' => json_encode($workflow, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + 'scheme_payload' => json_encode($schemeRows, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + 'task_payload' => json_encode($taskById[$id] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + 'workflow_created_at' => isset($workflow['createAt']) ? (string) $workflow['createAt'] : null, + 'sync_generation' => $generation, + 'synced_at' => $now, + ]; + if ($extendColumns) { + foreach ($columnMap as $column => $label) { + $payload[$column] = $this->castColumn($fields[$label] ?? null, (string) ($columnTypes[$column] ?? 'string')); + } + // 行级过滤(如“收款人全称”限定):不匹配的明细行直接跳过, + // 不写入镜像,也不占用 detail_index,保证保留行编号连续。 + if ($rowFilters !== [] && ! $this->matchesRowFilters($payload, $rowFilters)) { + continue; + } + $payload['detail_index'] = $detailIndex; + } + $payloads[] = $payload; + $detailIndex++; + } + + } + + if ($resolveProductName && $payloads !== []) { + $this->resolveProductNames($payloads); } $nextCursor = $this->cursorFromWorkflow($workflows[array_key_last($workflows)]); @@ -123,12 +175,25 @@ class DingPayableWorkflowMirrorSynchronizer $cursor = $nextCursor; $rows += count($payloads); $batches++; - $this->connection->transaction(function () use ($dataset, $target, $payloads, $cursor, $generation, $rows, $now): void { + $upsertKeys = $extendColumns ? ['process_instance_id', 'detail_index'] : ['process_instance_id']; + $updateColumns = ['workflow_payload', 'scheme_payload', 'task_payload', 'workflow_created_at', 'sync_generation', 'synced_at']; + if ($extendColumns) { + $updateColumns = array_merge($updateColumns, array_keys($columnMap)); + if ($resolveProductName) { + $updateColumns[] = 'product_name'; + } + } + $this->connection->transaction(function () use ($dataset, $target, $payloads, $cursor, $generation, $rows, $now, $upsertKeys, $updateColumns, $extendColumns, $ids): void { + // A changed workflow may have fewer details or no longer match + // the approved status/payee. Replace its rows atomically. + if ($extendColumns && $ids !== []) { + $this->connection->table($target)->whereIn('process_instance_id', $ids)->delete(); + } if ($payloads !== []) { $this->connection->table($target)->upsert( $payloads, - ['process_instance_id'], - ['workflow_payload', 'scheme_payload', 'task_payload', 'workflow_created_at', 'sync_generation', 'synced_at'], + $upsertKeys, + $updateColumns, ); } $this->connection->table('business_mirror_table_states') @@ -166,6 +231,12 @@ class DingPayableWorkflowMirrorSynchronizer if ($schema->hasTable($target)) { return; } + $config = (array) config('upstream_mirrors.' . $this->configKey, []); + if (! empty($config['extend_columns'])) { + $this->createExtendedMirrorTable($schema, $target); + + return; + } $schema->create($target, function (Blueprint $table): void { $table->string('process_instance_id', 100)->primary(); $table->json('workflow_payload'); @@ -177,6 +248,37 @@ class DingPayableWorkflowMirrorSynchronizer }); } + /** + * 扩展镜像表:在原始 JSON 载荷之外抽取宽表列并建立索引,便于按商品ID + * 关联商品目录、按单据号/店铺筛选。结构与对应迁移保持一致。 + */ + private function createExtendedMirrorTable(Builder $schema, string $target): void + { + $schema->create($target, function (Blueprint $table): void { + $table->string('process_instance_id', 100); + $table->unsignedTinyInteger('detail_index')->default(0); + $table->string('product_id', 64)->nullable()->index(); + $table->string('daifa_trade_no', 64)->nullable()->index(); + $table->string('shop_trade_no', 64)->nullable()->index(); + $table->string('shop_name', 120)->nullable()->index(); + $table->string('payee_name', 120)->nullable()->index(); + $table->string('supplier_name', 120)->nullable(); + $table->string('material_no', 120)->nullable(); + $table->string('product_name', 255)->nullable()->comment('按商品ID关联商品目录得到的名称'); + $table->unsignedInteger('ship_qty')->nullable(); + $table->decimal('paid_amount', 14, 2)->nullable(); + $table->decimal('daifa_amount', 14, 2)->nullable(); + $table->decimal('price_diff', 14, 2)->nullable(); + $table->json('workflow_payload'); + $table->json('scheme_payload'); + $table->json('task_payload')->nullable(); + $table->string('workflow_created_at', 32)->nullable()->index(); + $table->uuid('sync_generation')->nullable()->index(); + $table->dateTime('synced_at', 6); + $table->primary(['process_instance_id', 'detail_index']); + }); + } + /** @return array|null */ private function state(string $dataset): ?array { @@ -438,4 +540,222 @@ class DingPayableWorkflowMirrorSynchronizer } return $grouped; } + + /** + * 从表单 scheme 解析每一行的“字段名 -> 值”映射。 + * + * 若配置了明细表格字段名,则按该表格的每一行展开(并合并顶层字段, + * 如店铺名称),否则整张表单视为单行。返回数组长度即镜像明细行数。 + * + * @param array> $schemeRows + * @return list> + */ + private function buildDetailRowFields(array $schemeRows, string $detailTable): array + { + $topLevel = $this->formFieldLookup($schemeRows); + if ($detailTable === '') { + return [$topLevel]; + } + + $grid = null; + foreach ($schemeRows as $row) { + if (! is_array($row)) { + continue; + } + if (trim((string) ($row['name'] ?? '')) === $detailTable) { + $value = $row['value'] ?? null; + // 钉钉明细表格在上游/镜像中以 JSON 字符串存储,需先解码为数组再按行展开。 + if (is_string($value)) { + $decoded = json_decode($value, true); + $value = is_array($decoded) ? $decoded : null; + } + $grid = is_array($value) ? $value : null; + break; + } + } + + if ($grid === null) { + return [$topLevel]; + } + + $rows = []; + foreach ($grid as $gridRow) { + if (! is_array($gridRow) || ! isset($gridRow['rowValue']) || ! is_array($gridRow['rowValue'])) { + continue; + } + $cellLookup = []; + foreach ($gridRow['rowValue'] as $cell) { + if (! is_array($cell) || ! isset($cell['label'])) { + continue; + } + $cellLookup[(string) $cell['label']] = $this->scalarValue($cell['value'] ?? null); + } + $rows[] = array_merge($topLevel, $cellLookup); + } + + return $rows === [] ? [$topLevel] : $rows; + } + + /** @param array> $schemeRows @return array */ + private function formFieldLookup(array $schemeRows): array + { + $lookup = []; + foreach ($schemeRows as $row) { + if (! is_array($row)) { + continue; + } + $name = trim((string) ($row['name'] ?? '')); + if ($name === '') { + continue; + } + $lookup[$name] = $this->scalarValue($row['value'] ?? null); + } + return $lookup; + } + + private function scalarValue(mixed $value): mixed + { + if (is_scalar($value) || $value === null) { + return $value; + } + return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } + + /** + * 行级过滤:按“镜像列 => 目标值”精确匹配(去首尾空白)。任一条件不满足即 + * 返回 false,该明细行不写入镜像。目标值为空表示不对该列过滤;过滤集合为 + * 空则全部通过。用于把“线上代发业务报销”限定到指定收款人全称等场景。 + * + * @param array $payload + * @param array $filters + */ + private function matchesRowFilters(array $payload, array $filters): bool + { + foreach ($filters as $column => $expected) { + $expected = trim((string) $expected); + if ($expected === '') { + continue; + } + if (trim((string) ($payload[$column] ?? '')) !== $expected) { + return false; + } + } + + return true; + } + + private function castColumn(mixed $value, string $type): mixed + { + if ($value === null || $value === '') { + return null; + } + return match ($type) { + 'int' => is_numeric($value) ? (int) $value : null, + 'decimal' => is_numeric($value) ? (float) $value : null, + default => is_scalar($value) ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + }; + } + + /** + * 同步阶段按商品ID(钉钉表单“商品ID”即 ops_jst_sku_map.shop_i_id)关联商品目录, + * 将已匹配的商品名称写入镜像宽表的 product_name 列。页面只读镜像,不在此处临时 + * JOIN 2500 万行的商品映射表,避免页面查询超时。所有商品ID一次性批量关联, + * 未命中的再回退到 ops_jst_sku 的 i_id/sku_id。 + * + * @param list> $payloads + */ + private function resolveProductNames(array &$payloads): void + { + $ids = []; + foreach ($payloads as $payload) { + $id = trim((string) ($payload['product_id'] ?? '')); + if ($id !== '' && ! isset($ids[$id])) { + $ids[$id] = true; + } + } + if ($ids === []) { + return; + } + $idList = array_keys($ids); + + $names = []; + if ($this->connection->getSchemaBuilder()->hasTable('ops_jst_sku_map')) { + $rows = $this->guardedQuery(4000, fn () => $this->connection->table('ops_jst_sku_map') + ->whereIn('shop_i_id', $idList) + ->select(['shop_i_id', 'sku_id', 'i_id', 'name']) + ->limit(5000) + ->get()); + foreach ($rows as $row) { + $id = (string) $row->shop_i_id; + if (! isset($names[$id])) { + $name = $this->cleanProductName($row->name ?? null); + if ($name !== null) { + $names[$id] = $name; + } + } + } + } + + $missing = array_values(array_filter($idList, static fn (string $id): bool => ! isset($names[$id]))); + if ($missing !== [] && $this->connection->getSchemaBuilder()->hasTable('ops_jst_sku')) { + $rows = $this->guardedQuery(4000, fn () => $this->connection->table('ops_jst_sku') + ->whereIn('i_id', $missing) + ->orWhereIn('sku_id', $missing) + ->select(['i_id', 'sku_id', 'name']) + ->limit(5000) + ->get()); + foreach ($rows as $row) { + foreach ([(string) $row->i_id, (string) $row->sku_id] as $candidate) { + if ($candidate !== '' && isset($names[$candidate]) === false) { + $name = $this->cleanProductName($row->name ?? null); + if ($name !== null) { + $names[$candidate] = $name; + } + } + } + } + } + + foreach ($payloads as &$payload) { + $id = trim((string) ($payload['product_id'] ?? '')); + $payload['product_name'] = $id !== '' && isset($names[$id]) ? $names[$id] : null; + } + unset($payload); + } + + private function cleanProductName(mixed $value): ?string + { + if ($value === null) { + return null; + } + $name = trim((string) $value); + return $name === '' ? null : $name; + } + + /** + * 对可能命中大表的查询加会话级超时,避免索引缺失时整批同步被拖垮。 + * 超时后该批商品名称留空,页面仍可正常展示(仅缺失匹配名),不影响同步完成。 + * + * @template T + * @param callable():T $callback + * @return T + */ + private function guardedQuery(int $milliseconds, callable $callback) + { + $conn = $this->connection; + try { + $conn->statement('SET SESSION MAX_EXECUTION_TIME=' . $milliseconds); + return $callback(); + } catch (Throwable $exception) { + // 超时(SQLSTATE HY000/3024)或其它只读异常:放弃匹配该批商品名称, + // 不让同步链路中断。 + return []; + } finally { + try { + $conn->statement('SET SESSION MAX_EXECUTION_TIME=0'); + } catch (Throwable) { + // 忽略重置失败。 + } + } + } } diff --git a/resources/assets/js/components/business/TaobaoAlipayBills.vue b/resources/assets/js/components/business/TaobaoAlipayBills.vue index 09823b67..6b5d9c6a 100644 --- a/resources/assets/js/components/business/TaobaoAlipayBills.vue +++ b/resources/assets/js/components/business/TaobaoAlipayBills.vue @@ -13,9 +13,9 @@
按当前筛选
-
期末余额(最新)
+
收支净额
{{ money(summary.balance) }}
-
最新一条记录
+
收入合计 - 支出合计
交易笔数
@@ -31,30 +31,19 @@
- - + +
- +
- +
@@ -65,12 +54,13 @@
- - + +
+
@@ -97,17 +87,17 @@ 原始店铺 自定义备注 账单项目 - 支付宝账号 + 平台渠道 账务订单号 业务流水号 商户订单号 业务基础订单号 - 商品名称 + 商品编码 对方账号 发生时间 ⇅ 收入 ⇅ 支出 ⇅ - 余额 ⇅ + 收支净额 ⇅ 业务类型 备注 线上单号 @@ -188,6 +178,7 @@ export default { props: { apiBase: { type: String, required: true }, + exportBase: { type: String, required: true }, }, data() { @@ -283,6 +274,11 @@ export default { this.fetch(); }, + exportRows() { + const params = new URLSearchParams(this.filters); + window.location.href = `${this.exportBase}?${params.toString()}`; + }, + toggleSort(key) { if (this.sort.key === key) { this.sort.dir = this.sort.dir === 'asc' ? 'desc' : 'asc'; diff --git a/resources/assets/js/views/business/pages.js b/resources/assets/js/views/business/pages.js index 3ca5bc28..ddd4f876 100644 --- a/resources/assets/js/views/business/pages.js +++ b/resources/assets/js/views/business/pages.js @@ -4,7 +4,7 @@ * 路由:/{company_id}/workspace/{section}/{page}/{tab} * * 店铺收款账户账单(store-receiving-bills)下各 tab: - * - taobao-alipay → 独立实现 TaobaoAlipayBills(表 ec_alipay_bills) + * - taobao-alipay → 独立实现 TaobaoAlipayBills(经营分析副本共享镜像) * - taobao-wechat / pinduoduo / jd-wallet / jd-transactions / douyin / dewu * → 通用实现 AccountBills(表 ec_account_bills,按 bill_type 区分,列配置由后端下发) */ @@ -43,7 +43,10 @@ function resolveComponent(context) { : `/ecommerce-finance/account-bills/type/${encodeURIComponent(context.tab)}`; // 店铺收款账户账单 › 淘系支付宝账户(独立实现) if (context.page === 'store-receiving-bills' && context.tab === 'taobao-alipay') { - return { Component: TaobaoAlipayBills, props: { apiBase: alipayBase } }; + const exportBase = context.companyId + ? `/${context.companyId}/ecommerce-finance/alipay-bills/export` + : '/ecommerce-finance/alipay-bills/export'; + return { Component: TaobaoAlipayBills, props: { apiBase: alipayBase, exportBase } }; } // 店铺收款账户账单 › 其它账户类型(通用实现) diff --git a/resources/views/business/pages/partials/directory-table.blade.php b/resources/views/business/pages/partials/directory-table.blade.php index bce18cb2..b84f83a6 100644 --- a/resources/views/business/pages/partials/directory-table.blade.php +++ b/resources/views/business/pages/partials/directory-table.blade.php @@ -494,11 +494,17 @@ @endphp @if (($page['slug'] ?? '') === 'store-accounts' && $field['name'] === 'password_configured') - {{ filled($display) ? $display : '—' }} - @if (\App\Utilities\SystemAccess::canOpenSettings() && $value !== false) - - - + {{ filled($display) ? $display : '—' }} + @if ($value === false) + 未设置 + @else + + 读取中… + @endif @else @@ -554,7 +560,7 @@ @endif -@if (($page['slug'] ?? '') === 'store-accounts' && \App\Utilities\SystemAccess::canOpenSettings()) +@if (($page['slug'] ?? '') === 'store-accounts') @include('business.pages.partials.store-account-password') @endif diff --git a/resources/views/business/pages/partials/store-account-password.blade.php b/resources/views/business/pages/partials/store-account-password.blade.php index 94d427dc..79f6c0c5 100644 --- a/resources/views/business/pages/partials/store-account-password.blade.php +++ b/resources/views/business/pages/partials/store-account-password.blade.php @@ -1,95 +1,169 @@ @once -

- -

店铺账号密码

-

- - -

30 秒后自动隐藏,关闭弹窗或离开页面也会清除显示。

-
-
+
+ 正在读取当前页密码… + +
@endonce diff --git a/resources/views/business/pages/product-inventory/online-daifa-price.blade.php b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php new file mode 100644 index 00000000..d7abafdc --- /dev/null +++ b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php @@ -0,0 +1,157 @@ +@php + $rows = $onlineDaifaRows ?? null; + $filters = $onlineDaifaFilters ?? []; + $status = (string) ($onlineDaifaStatus ?? 'unknown'); + $syncedAt = $onlineDaifaSyncedAt ?? null; + $summary = $onlineDaifaSummary ?? []; + $error = $onlineDaifaError ?? null; + $json = static fn (mixed $value): string => is_array($value) + ? (json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) ?: '-') + : (string) ($value ?? '-'); + $statusOptions = \Modules\EcommerceFinance\Services\DingPayableWorkflowStatus::filterOptions(); + $num = static fn (mixed $value): string => $value === null || $value === '' ? '-' : (string) $value; + $money = static fn (mixed $value): string => $value === null ? '-' : number_format((float) $value, 2); + $productName = static fn (array $row): string => $row['matched_product']['matched'] ?? false + ? (string) ($row['matched_product']['name'] ?? '-') + : '(未匹配)'; + $payeeScope = trim((string) config('upstream_mirrors.ding_online_daifa_price.row_filters.payee_name', '')); +@endphp + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + + +
+
+
+ + 重置 +
+
+ + @if ($error) + + @endif + +
+ 固定流程:线上代发业务报销流程(钉钉 OA 审批) + @if ($payeeScope !== '') 固定收款人:{{ $payeeScope }} @endif + 镜像状态:{{ $status }} + @if ($syncedAt) 最近同步:{{ $syncedAt }} @endif + 共 {{ $rows?->total() ?? 0 }} 条 +
+ +
+
代发订单金额合计{{ $money($summary['daifa_amount'] ?? null) }}
+
订单实付金额合计{{ $money($summary['paid_amount'] ?? null) }}
+
差价合计{{ $money($summary['price_diff'] ?? null) }}
+
已匹配商品目录{{ (int) ($summary['matched_count'] ?? 0) }} / {{ (int) ($summary['count'] ?? 0) }}
+
+ +
+ + + + + + + + + + @forelse ($rows ?? [] as $row) + @php($workflow = $row['workflow'] ?? []) + @php($approvalNumber = trim((string) ($workflow['businessId'] ?? '')) ?: (string) ($row['process_instance_id'] ?? '-')) + @php($originator = trim((string) ($workflow['originatorUserName'] ?? '')) ?: trim((string) ($workflow['originatorUserId'] ?? '-'))) + + + + + + + + + + + + + + + + + + + + + @empty + + @endforelse + +
审批编号标题状态申请人收款人全称商品ID商品名称(匹配)店铺名称代发交易单号店铺交易单号发货数量订单实付金额代发订单金额差价供应商名称料号创建时间原始表单
{{ $approvalNumber }}{{ $workflow['title'] ?? '-' }}{{ $row['status_label'] ?? '-' }}{{ $originator }}{{ $num($row['payee_name']) }}{{ $num($row['product_id']) }}{{ $productName($row) }}{{ $num($row['shop_name']) }}{{ $num($row['daifa_trade_no']) }}{{ $num($row['shop_trade_no']) }}{{ $num($row['ship_qty']) }}{{ $money($row['paid_amount']) }}{{ $money($row['daifa_amount']) }}{{ $money($row['price_diff']) }}{{ $num($row['supplier_name']) }}{{ $num($row['material_no']) }}{{ $row['workflow_created_at'] ?? '-' }}
展开表单({{ count($row['scheme'] ?? []) }} 项)
{{ $json($row['scheme'] ?? []) }}
{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的线上代发价格数据;同步完成后会自动显示。' }}
+
+ 当前页 {{ $rows?->count() ?? 0 }} 条 · 第 {{ $rows?->currentPage() ?? 1 }} 页 + + @if ($rows && !$rows->onFirstPage())上一页@endif + @if ($rows && $rows->hasMorePages())下一页@endif + +
+
+
diff --git a/routes/admin.php b/routes/admin.php index 4f46bcc7..0f044fba 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -11,11 +11,15 @@ use Modules\EcommerceFinance\Http\Controllers\AlipayBills; use Modules\EcommerceFinance\Http\Controllers\Api\GoodsReconciliations; use Modules\EcommerceFinance\Http\Controllers\Api\SupplierPayables; +Route::post('store-account-passwords/visible-page/reveal', 'Business\StoreAccountPasswords@revealVisiblePage') + ->name('business.store-account-passwords.reveal-visible-page'); Route::post('store-account-passwords/{account}/reveal', 'Business\StoreAccountPasswords@reveal') ->name('business.store-account-passwords.reveal'); Route::get('ecommerce-finance/alipay-bills', [AlipayBills::class, 'index']) ->name('ecommerce-finance.alipay-bills.index'); +Route::get('ecommerce-finance/alipay-bills/export', [AlipayBills::class, 'export']) + ->name('ecommerce-finance.alipay-bills.export'); Route::get('ecommerce-finance/alipay-bills/{bill}', [AlipayBills::class, 'show']) ->name('ecommerce-finance.alipay-bills.show'); diff --git a/tests/Feature/Auth/DingTalkLoginTest.php b/tests/Feature/Auth/DingTalkLoginTest.php index f3657056..de9acffc 100644 --- a/tests/Feature/Auth/DingTalkLoginTest.php +++ b/tests/Feature/Auth/DingTalkLoginTest.php @@ -131,6 +131,27 @@ class DingTalkLoginTest extends FeatureTestCase $this->get(route('dashboard', ['company_id' => $this->company->id]))->assertRedirectContains('/workspace/'); } + public function test_explicitly_designated_identity_gets_highest_role_only_on_first_provisioning(): void + { + config(['dingtalk.super_admin_user_ids' => ['ding-user-1']]); + Http::preventStrayRequests(); + Http::fake($this->dingtalkResponses('union-designated', 'open-designated')); + $state = $this->startAuthorization(); + $this->get(route('login.dingtalk.callback', ['code' => 'fixture', 'state' => $state])); + $created = auth()->user(); + $this->assertNotNull($created); + $this->assertTrue(\App\Utilities\SystemAccess::isSuperAdmin($created)); + $id = $created->id; + $created->syncRoles([\App\Models\Auth\Role::where('name', 'user')->firstOrFail()->id]); + $created->flushCache(); + auth()->logout(); + session()->invalidate(); + $state = $this->startAuthorization(); + $this->get(route('login.dingtalk.callback', ['code' => 'fixture-again', 'state' => $state])); + $this->assertSame($id, auth()->id()); + $this->assertFalse(\App\Utilities\SystemAccess::isSuperAdmin(auth()->user())); + } + public function test_shared_mobile_does_not_claim_an_existing_account(): void { Http::preventStrayRequests(); diff --git a/tests/Feature/Business/OnlineDaifaPricePageTest.php b/tests/Feature/Business/OnlineDaifaPricePageTest.php new file mode 100644 index 00000000..ff5e0979 --- /dev/null +++ b/tests/Feature/Business/OnlineDaifaPricePageTest.php @@ -0,0 +1,131 @@ +user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class); + $repository->shouldReceive('paginate')->once()->andReturn([ + 'data' => [[ + 'process_instance_id' => 'DEMO-6927049845766979458', + 'detail_index' => 0, + 'product_id' => '3821829253650055444', + 'daifa_trade_no' => '6927049845766979458', + 'shop_trade_no' => '6927049845766979458', + 'shop_name' => '抖音-HX旗舰店101', + 'payee_name' => '宁波顾家望业家居有限公司', + 'supplier_name' => '', + 'material_no' => '', + 'ship_qty' => 1, + 'paid_amount' => 616.61, + 'daifa_amount' => 375.0, + 'price_diff' => 241.61, + 'workflow' => [ + 'businessId' => '20260901001', + 'title' => '线上代发业务报销', + 'status' => 'COMPLETED', + 'result' => 'agree', + 'originatorUserName' => '扬灵', + 'createAt' => '2026-09-01 10:00:00', + ], + 'scheme' => [['name' => '商品ID', 'value' => '3821829253650055444']], + 'tasks' => [], + 'status_key' => 'COMPLETED', + 'status_label' => '已完成', + 'matched_product' => ['matched' => true, 'name' => '演示商品', 'sku_id' => null, 'i_id' => null], + 'workflow_created_at' => '2026-09-01 10:00:00', + ]], + 'total' => 1, + 'status' => 'succeeded', + 'last_synced_at' => '2026-09-08 00:00:05', + 'summary' => [ + 'count' => 1, + 'matched_count' => 1, + 'daifa_amount' => 375.0, + 'paid_amount' => 616.61, + 'price_diff' => 241.61, + ], + ]); + $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', + 'page' => 'online-daifa-price', + ]))->assertOk() + ->assertSee('线上代发价格') + ->assertSee('固定流程:线上代发业务报销流程(钉钉 OA 审批)') + ->assertSee('固定收款人:') + ->assertSee('宁波顾家望业家居有限公司') + ->assertSee('镜像状态:succeeded') + ->assertSee('3821829253650055444') + ->assertSee('演示商品') + ->assertSee('抖音-HX旗舰店101') + ->assertSee('6927049845766979458') + ->assertSee('已完成') + ->assertSee('扬灵') + ->assertSee('已匹配商品目录') + ->assertSee('展开表单(1 项)'); + } + + public function test_online_daifa_price_page_keeps_an_unavailable_mirror_readable(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class); + $repository->shouldReceive('paginate')->andThrow(new \RuntimeException('not ready')); + $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', + 'page' => 'online-daifa-price', + ]))->assertOk() + ->assertSee('线上代发价格镜像尚未完成同步,请稍后重试。') + ->assertSee('镜像读取失败,请稍后重试。'); + } + + public function test_online_daifa_price_page_passes_filters_to_repository(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class); + $repository->shouldReceive('paginate')->once()->with( + [ + 'keyword' => '6927049845766979458', + 'product_id' => '3821829253650055444', + 'shop_name' => '抖音-HX旗舰店101', + 'status' => '', + 'created_from' => '2026-09-01', + 'created_to' => '2026-09-07', + ], + 1, + Mockery::type('int'), + )->andReturn([ + 'data' => [], + 'total' => 0, + 'status' => 'succeeded', + 'last_synced_at' => '2026-09-08 00:00:05', + 'summary' => [], + ]); + $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', + 'page' => 'online-daifa-price', + 'keyword' => '6927049845766979458', + 'product_id' => '3821829253650055444', + 'shop_name' => '抖音-HX旗舰店101', + 'created_from' => '2026-09-01', + 'created_to' => '2026-09-07', + ]))->assertOk() + ->assertSee('商品ID') + ->assertSee('店铺名称') + ->assertSee('2026-09-01') + ->assertSee('2026-09-07'); + } +} diff --git a/tests/Feature/Business/PagesTest.php b/tests/Feature/Business/PagesTest.php index 26b1f90c..d8d037ca 100644 --- a/tests/Feature/Business/PagesTest.php +++ b/tests/Feature/Business/PagesTest.php @@ -117,6 +117,37 @@ class PagesTest extends FeatureTestCase ->assertSee('public/js/business/pages.min.js', false); } + public function testTaobaoAlipayBillsExportUsesTheMirrorRepository() + { + $this->user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + + $repository = Mockery::mock(StoreReceivingAlipayBillMirrorRepository::class); + $repository->shouldReceive('exportRows')->once()->with(Mockery::on( + static fn (array $filters): bool => ($filters['store_name'] ?? '') === '天猫-经营店' + && ($filters['start'] ?? '') === '2026-08-01' + && ($filters['end'] ?? '') === '2026-08-31' + ))->andReturn([[ + 'record_code' => '1', 'store_name' => '天猫-经营店', 'alipay_account' => 'CommonBillTGCPay', + 'bill_item' => '交易佣金', 'account_order_no' => 'KEY-1', 'business_serial_no' => '1001', + 'merchant_order_no' => 'P-1', 'business_base_order_no' => 'ORDER-1', 'goods_name' => 'SKU-1', + 'occurred_at' => '2026-08-01 09:00:00', 'income' => 100.25, 'expense' => 0, + 'balance' => 100.25, 'business_type' => '收入', 'online_order_no' => 'ORDER-1', + 'business_description' => 'double', 'business_bill_source' => 'CommonBillTGCPay', + 'created_at' => '2026-08-02 09:00:00', 'updated_at' => '2026-08-02 10:00:00', + ]]); + $this->app->instance(StoreReceivingAlipayBillMirrorRepository::class, $repository); + + $this->loginAs() + ->get(route('ecommerce-finance.alipay-bills.export', [ + 'store_name' => '天猫-经营店', 'start' => '2026-08-01', 'end' => '2026-08-31', + ])) + ->assertOk() + ->assertHeader('content-type', 'text/csv; charset=UTF-8') + ->assertDownload('taobao_alipay_bills.csv'); + } + public function testSupplierPayablesPageRendersItsSpecificContent() { $this->user->attachPermission( diff --git a/tests/Feature/Business/StoreAccountPasswordsTest.php b/tests/Feature/Business/StoreAccountPasswordsTest.php index 949b1806..ca97b2fd 100644 --- a/tests/Feature/Business/StoreAccountPasswordsTest.php +++ b/tests/Feature/Business/StoreAccountPasswordsTest.php @@ -23,8 +23,14 @@ class StoreAccountPasswordsTest extends FeatureTestCase protected function setUp(): void { parent::setUp(); - config(['store_account_password.token' => str_repeat('t', 43), 'store_account_password.url' => 'https://upstream.example.test/internal/store-accounts/{id}/password/reveal']); - $this->mock(StoreAccountMirrorRepository::class)->shouldReceive('containsAccount')->with('fixture-account')->andReturnTrue()->byDefault(); + config([ + 'store_account_password.token' => str_repeat('t', 43), + 'store_account_password.url' => 'https://upstream.example.test/internal/store-accounts/{id}/password/reveal', + 'store_account_password.visible_page_url' => 'https://upstream.example.test/internal/store-accounts/visible-page/password/reveal', + ]); + $mirror = $this->mock(StoreAccountMirrorRepository::class); + $mirror->shouldReceive('containsAccount')->with('fixture-account')->andReturnTrue()->byDefault(); + $mirror->shouldReceive('containsAccounts')->andReturnTrue()->byDefault(); } private function transport(int $status = 200, ?array $body = null, array $headers = ['Cache-Control' => 'no-store']): void @@ -41,6 +47,21 @@ class StoreAccountPasswordsTest extends FeatureTestCase return route('business.store-account-passwords.reveal', ['account' => 'fixture-account']); } + private function visiblePageEndpoint(): string + { + return route('business.store-account-passwords.reveal-visible-page'); + } + + private function visiblePageTransport(array $items, array $headers = ['Cache-Control' => 'private, no-store']): void + { + $handler = HandlerStack::create(new MockHandler([new Response(200, $headers, json_encode([ + 'requestId' => '12345678-1234-4123-8123-123456789012', + 'items' => $items, + ]))])); + $handler->push(Middleware::history($this->history)); + $this->app->instance(StoreAccountPasswordClient::class, new StoreAccountPasswordClient(new Client(['handler' => $handler]))); + } + public function test_admin_view_uses_trusted_actor_and_persists_password_free_audit(): void { $this->transport(); @@ -67,12 +88,13 @@ class StoreAccountPasswordsTest extends FeatureTestCase $this->assertDatabaseHas('store_account_password_audits', ['purpose' => 'copy', 'status' => 200]); } - public function test_regular_user_cannot_call_upstream(): void + public function test_regular_user_with_store_accounts_page_can_reveal_and_copy(): void { $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]); $this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id); - $this->mock(StoreAccountPasswordClient::class)->shouldNotReceive('reveal'); - $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertForbidden(); + $this->transport(); + $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'copy'])->assertOk()->assertJsonPath('password', $this->fixture); + $this->assertDatabaseHas('store_account_password_audits', ['purpose' => 'copy', 'status' => 200]); } public function test_restricted_admin_cannot_bypass_store_page_scope(): void @@ -83,6 +105,134 @@ class StoreAccountPasswordsTest extends FeatureTestCase $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertForbidden(); } + public function test_regular_user_without_store_accounts_page_cannot_call_upstream(): void + { + $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]); + $this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id); + setting()->set('system.sidebar_permissions', [ + 'configured' => ['user_'.$this->user->id], + 'subjects' => ['user_'.$this->user->id => ['store-management/basic-information']], + ]); + $client = $this->mock(StoreAccountPasswordClient::class); + $client->shouldNotReceive('reveal'); + $client->shouldNotReceive('revealVisiblePage'); + $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertForbidden(); + $this->postJson($this->visiblePageEndpoint(), ['accounts' => ['fixture-account']])->assertForbidden(); + } + + public function test_visible_page_loads_passwords_for_regular_user_and_audits_every_account(): void + { + $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]); + $this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id); + $this->visiblePageTransport([ + ['accountId' => 'fixture-account', 'status' => 200, 'requestId' => '12345678-1234-4123-8123-123456789013', 'password' => $this->fixture], + ['accountId' => 'fixture-empty', 'status' => 404, 'requestId' => '12345678-1234-4123-8123-123456789014'], + ]); + + $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), [ + 'accounts' => ['fixture-account', 'fixture-empty'], + ])->assertOk()->assertJsonCount(2, 'items') + ->assertJsonPath('items.0.password', $this->fixture) + ->assertJsonPath('items.1.status', 404) + ->assertJsonMissingPath('items.1.password'); + + $this->assertStringContainsString('no-store', $response->headers->get('Cache-Control')); + $this->assertSame(2, DB::table('store_account_password_audits')->count()); + $this->assertEqualsCanonicalizing([200, 404], DB::table('store_account_password_audits')->pluck('status')->all()); + $this->assertStringNotContainsString($this->fixture, json_encode(DB::table('store_account_password_audits')->get())); + $sent = json_decode((string) $this->history[0]['request']->getBody(), true); + $this->assertSame([ + 'requesterId' => 'finance-user-'.$this->user->id, + 'purpose' => 'view', + 'accountIds' => ['fixture-account', 'fixture-empty'], + ], $sent); + } + + public function test_fifty_visible_accounts_are_sent_as_two_gateway_safe_chunks(): void + { + $accountIds = array_map(fn ($index) => sprintf('fixture-account-%02d', $index), range(1, 50)); + $responses = []; + foreach (array_chunk($accountIds, 25) as $batchIndex => $batch) { + $items = []; + foreach ($batch as $index => $accountId) { + $items[] = [ + 'accountId' => $accountId, + 'status' => 200, + 'requestId' => sprintf('12345678-1234-4123-8123-%012d', ($batchIndex * 25) + $index + 1), + 'password' => $this->fixture, + ]; + } + $responses[] = new Response(200, ['Cache-Control' => 'private, no-store'], json_encode([ + 'requestId' => sprintf('22345678-1234-4123-8123-%012d', $batchIndex + 1), + 'items' => $items, + ])); + } + $handler = HandlerStack::create(new MockHandler($responses)); + $handler->push(Middleware::history($this->history)); + $this->app->instance(StoreAccountPasswordClient::class, new StoreAccountPasswordClient(new Client(['handler' => $handler]))); + + $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => $accountIds]) + ->assertOk()->assertJsonCount(50, 'items'); + + $this->assertCount(2, $this->history); + foreach ($this->history as $index => $transaction) { + $body = (string) $transaction['request']->getBody(); + $sent = json_decode($body, true); + $this->assertSame(array_slice($accountIds, $index * 25, 25), $sent['accountIds']); + $this->assertLessThanOrEqual(1024, strlen($body)); + } + $this->assertSame(50, DB::table('store_account_password_audits')->count()); + $this->assertSame(50, DB::table('store_account_password_audits')->where('status', 200)->count()); + $this->assertStringNotContainsString($this->fixture, json_encode(DB::table('store_account_password_audits')->get())); + $this->assertSame($this->fixture, $response->json('items.49.password')); + } + + public function test_later_chunk_failure_suppresses_passwords_from_earlier_chunks(): void + { + $accountIds = array_map(fn ($index) => sprintf('fixture-account-%02d', $index), range(1, 50)); + $items = array_map(fn ($accountId, $index) => [ + 'accountId' => $accountId, + 'status' => 200, + 'requestId' => sprintf('12345678-1234-4123-8123-%012d', $index + 1), + 'password' => $this->fixture, + ], array_slice($accountIds, 0, 25), range(0, 24)); + $handler = HandlerStack::create(new MockHandler([ + new Response(200, ['Cache-Control' => 'private, no-store'], json_encode([ + 'requestId' => '22345678-1234-4123-8123-123456789001', + 'items' => $items, + ])), + new Response(403, ['Cache-Control' => 'no-store'], json_encode(['message' => $this->fixture])), + ])); + $handler->push(Middleware::history($this->history)); + $this->app->instance(StoreAccountPasswordClient::class, new StoreAccountPasswordClient(new Client(['handler' => $handler]))); + + $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => $accountIds]) + ->assertStatus(503)->assertJsonMissingPath('items')->assertJsonMissingPath('password'); + + $this->assertCount(2, $this->history); + $this->assertStringNotContainsString($this->fixture, $response->getContent()); + $this->assertSame(50, DB::table('store_account_password_audits')->where('status', 503)->count()); + } + + public function test_visible_page_rejects_duplicates_and_more_than_fifty_accounts(): void + { + $this->mock(StoreAccountPasswordClient::class)->shouldNotReceive('revealVisiblePage'); + $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => ['fixture-account', 'fixture-account']])->assertUnprocessable(); + $this->postJson($this->visiblePageEndpoint(), ['accounts' => array_map(fn ($index) => 'account-'.$index, range(1, 51))])->assertUnprocessable(); + $this->assertSame(0, DB::table('store_account_password_audits')->count()); + } + + public function test_visible_page_rejects_malformed_or_cacheable_upstream_response(): void + { + $this->visiblePageTransport([ + ['accountId' => 'fixture-account', 'status' => 200, 'requestId' => 'bad-request-id', 'password' => $this->fixture], + ], []); + $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => ['fixture-account']])->assertStatus(503); + $response->assertJsonMissingPath('items')->assertJsonMissingPath('password'); + $this->assertStringNotContainsString($this->fixture, $response->getContent()); + $this->assertDatabaseHas('store_account_password_audits', ['store_account_id' => 'fixture-account', 'status' => 503]); + } + public function test_actor_spoofing_is_rejected(): void { $this->mock(StoreAccountPasswordClient::class)->shouldNotReceive('reveal'); @@ -150,17 +300,22 @@ class StoreAccountPasswordsTest extends FeatureTestCase $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertStatus(429); } - public function test_admin_page_has_explicit_actions_and_no_plaintext_in_table(): void + public function test_store_accounts_page_auto_loads_visible_password_cells_without_a_dialog(): void { $this->mock(\App\Business\UpstreamBusinessInformation::class)->shouldReceive('paginate')->andReturn( new \Illuminate\Pagination\LengthAwarePaginator([(object) [ 'id' => 'fixture-account', 'store_name' => '测试店铺', 'account' => 'fixture-login', 'password_configured' => true, ]], 1, 50, 1) ); + $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]); + $this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id); $response = $this->loginAs()->get(route('business.pages.show', ['section' => 'store-management', 'page' => 'store-accounts']))->assertOk(); - $response->assertSee('data-store-password="view"', false)->assertSee('data-store-password="copy"', false) - ->assertSee('data-password-dialog', false)->assertDontSee($this->fixture); - $html = $response->getContent(); - $this->assertGreaterThan(strpos($html, ''), strpos($html, 'assertSee('data-store-password-cell', false) + ->assertSee('data-password-page-url', false) + ->assertSee('data-store-password-copy', false) + ->assertSee('读取中…') + ->assertDontSee('data-password-dialog', false) + ->assertDontSee('data-store-password="view"', false) + ->assertDontSee($this->fixture); } } diff --git a/tests/Feature/SystemSettings/UserAccessGroupsTest.php b/tests/Feature/SystemSettings/UserAccessGroupsTest.php index 3d48bc4f..c19c0d87 100644 --- a/tests/Feature/SystemSettings/UserAccessGroupsTest.php +++ b/tests/Feature/SystemSettings/UserAccessGroupsTest.php @@ -95,12 +95,17 @@ class UserAccessGroupsTest extends FeatureTestCase $this->withExceptionHandling()->patchJson(route('system-settings.sidebar.update'), ['subject' => 'group_'.$group->id, 'permissions' => ['not-a-page']])->assertUnprocessable(); } - public function test_group_page_access_does_not_grant_store_password_access(): void + public function test_group_page_access_grants_store_password_access_without_an_admin_role(): void { $member = $this->member(); $this->group('店铺资料组', $member, ['store-management']); - $this->mock(\App\Services\StoreAccountPasswordClient::class)->shouldNotReceive('reveal'); - $this->withExceptionHandling()->loginAs($member)->postJson(route('business.store-account-passwords.reveal', ['account' => 'fixture-account']), ['purpose' => 'view'])->assertForbidden(); + $this->mock(\Modules\EcommerceFinance\Repositories\StoreAccountMirrorRepository::class) + ->shouldReceive('containsAccount')->with('fixture-account')->once()->andReturnTrue(); + $this->mock(\App\Services\StoreAccountPasswordClient::class) + ->shouldReceive('reveal')->with('fixture-account', $member->id, 'view')->once() + ->andReturn(['status' => 200, 'password' => 'fictional-only', 'upstream_request_id' => '12345678-1234-4123-8123-123456789012']); + $this->loginAs($member)->postJson(route('business.store-account-passwords.reveal', ['account' => 'fixture-account']), ['purpose' => 'view']) + ->assertOk()->assertJsonPath('password', 'fictional-only'); } public function test_group_membership_and_names_can_change_without_changing_permissions(): void diff --git a/tests/Unit/Auth/FinanceRosterTest.php b/tests/Unit/Auth/FinanceRosterTest.php index 99016eb8..0a30e0aa 100644 --- a/tests/Unit/Auth/FinanceRosterTest.php +++ b/tests/Unit/Auth/FinanceRosterTest.php @@ -15,6 +15,7 @@ class FinanceRosterTest extends TestCase public function test_roster_authorization(array $overrides, bool $expected): void { config(['dingtalk.finance_department_ids' => ['22848291', '994080505']]); + config(['dingtalk.super_admin_user_ids' => $overrides['designated_ids'] ?? []]); $data = array_replace([ 'flowers' => [['Id' => 123, 'name' => '测试员工', 'flowerName' => '测试花名', 'deptId' => '55248182', 'status' => '', 'empStatus' => '正式']], 'employees' => [['active' => 1, 'dept_id_list' => '[55248182]']], @@ -49,6 +50,11 @@ class FinanceRosterTest extends TestCase public static function rosterCases(): array { return [ + 'designated active administrator outside finance' => [['designated_ids' => ['ding-fixture-id'], 'ancestors' => [['Id' => '55248182', 'parent_id' => '1', 'depth' => 0]]], true], + 'designation does not cover another identity' => [['designated_ids' => ['another-id'], 'ancestors' => [['Id' => '55248182', 'parent_id' => '1', 'depth' => 0]]], false], + 'designated administrator still requires active employment' => [['designated_ids' => ['ding-fixture-id'], 'employees' => [['active' => 0]]], false], + 'designated administrator cannot bypass resignation' => [['designated_ids' => ['ding-fixture-id'], 'resignation' => ['userid' => 'ding-fixture-id']], false], + 'designated administrator needs roster identity' => [['designated_ids' => ['ding-fixture-id'], 'flowers' => []], false], 'finance descendant' => [[], true], 'second finance root' => [['ancestors' => [['Id' => '994080505', 'parent_id' => '994121400', 'depth' => 1]]], true], 'concurrent finance membership' => [['employees' => [['active' => 1, 'dept_id_list' => '[100,55248182]']]], true], diff --git a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php index a601244b..24cc92ec 100644 --- a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php @@ -246,6 +246,77 @@ class BusinessMirrorSynchronizerTest extends TestCase $this->assertSame('text', $types['longLabel']); } + public function test_small_payment_work_order_dataset_accepts_only_supported_indexes(): void + { + $datasets = (array) config('upstream_mirrors.datasets', []); + $datasets['jiansun.dbo.jst_workOrderInfo'] = [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'jst_workOrderInfo', + 'target' => 'test_small_payment_work_orders', + 'keys' => ['Id'], + 'watermark' => 'updateTime', + 'columns' => [ + 'Id', 'woNo', 'woTypeId', 'title', 'content', 'status', 'grade', + 'urging', 'createby', 'executors', 'beginTime', 'endTime', + 'completer', 'completeTime', 'updated', 'created', + 'businessFieldList', 'createTime', 'updateTime', + ], + 'indexes' => [ + ['woTypeId', 'woNo', 'Id'], + ['created', 'Id'], + ], + ]; + config(['upstream_mirrors.datasets' => $datasets]); + + $columns = [ + ['name' => 'Id', 'type' => 'int', 'length' => null], + ['name' => 'woNo', 'type' => 'nvarchar', 'length' => 100], + ['name' => 'woTypeId', 'type' => 'nvarchar', 'length' => 100], + ['name' => 'urging', 'type' => 'int', 'length' => null], + ['name' => 'created', 'type' => 'datetime2', 'length' => null], + ['name' => 'updateTime', 'type' => 'datetime2', 'length' => null], + ]; + $selected = $datasets['jiansun.dbo.jst_workOrderInfo']['columns']; + foreach ($selected as $position => $name) { + $definition = collect($columns)->firstWhere('name', $name) ?? [ + 'name' => $name, + 'type' => 'nvarchar', + 'length' => 120, + ]; + DB::table('upstream_schema_columns')->insert(array_replace($this->column( + $definition['name'], + $position + 1, + $definition['type'], + $definition['length'], + ), [ + 'source_key' => 'jiansun', + 'schema_name' => 'dbo', + 'object_name' => 'jst_workOrderInfo', + ])); + } + + $dataset = (new BusinessMirrorDatasetRegistry())->get('jiansun.dbo.jst_workOrderInfo'); + $this->assertSame([ + ['woTypeId', 'woNo', 'Id'], + ['created', 'Id'], + ], $dataset->indexDefinitions()); + + (new BusinessMirrorSchemaManager())->ensure($dataset); + + $indexes = collect(Schema::connection('business_mirror')->getIndexes($dataset->targetTable())) + ->map(static fn (array $index): array => array_map('strtolower', (array) ($index['columns'] ?? []))) + ->all(); + $types = collect(DB::connection('business_mirror')->select('PRAGMA table_info(test_small_payment_work_orders)')) + ->pluck('type', 'name') + ->map(static fn (string $type): string => strtolower($type)); + $this->assertSame('varchar', $types['woNo']); + $this->assertSame('varchar', $types['woTypeId']); + $this->assertSame('text', $types['businessFieldList']); + $this->assertContains(['wotypeid', 'wono', 'id'], $indexes); + $this->assertContains(['created', 'id'], $indexes); + } + public function test_empty_full_read_does_not_delete_previous_mirror_rows(): void { $this->query->batches = [[ diff --git a/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php index 0018d5d6..1badf847 100644 --- a/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php @@ -159,6 +159,54 @@ class DingPayableWorkflowMirrorSynchronizerTest extends TestCase $this->assertSame(2, DB::connection('business_mirror')->table('ding_payable_workflow_mirror')->count()); } + public function test_extended_workflow_update_removes_rows_that_no_longer_match(): void + { + config(['upstream_mirrors.ding_online_daifa_price' => [ + 'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price', + 'target_table' => 'ding_online_daifa_price_mirror', + 'source_key' => 'operations_replica', 'process_code' => 'PROC-TEST', + 'extend_columns' => true, 'only_status' => 'COMPLETED', + 'column_map' => ['product_id' => '商品ID'], + ]]); + $sync = $this->synchronizer->forConfigKey('ding_online_daifa_price'); + $this->query->workflowBatches = [[$this->workflow('changed', now()->subHour()->format('Y-m-d H:i:s.u'))]]; + $sync->sync(true, 10, 0); + $table = DB::connection('business_mirror')->table('ding_online_daifa_price_mirror'); + $this->assertSame(1, $table->count()); + $this->query->workflowBatches = [[$this->workflow('changed', now()->format('Y-m-d H:i:s.u'), 'RUNNING')]]; + $sync->sync(false, 10, 0); + $this->assertSame(0, $table->count()); + } + + public function test_daifa_repository_includes_end_date_and_counts_only_resolved_products(): void + { + config(['upstream_mirrors.ding_online_daifa_price' => [ + 'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price', + 'target_table' => 'ding_online_daifa_price_mirror', + 'source_key' => 'operations_replica', 'process_code' => 'PROC-TEST', + 'extend_columns' => true, 'column_map' => ['product_id' => '商品ID'], + ]]); + $this->query->workflowBatches = [[ + $this->workflow('A', '2026-08-01 00:00:00'), + $this->workflow('B', '2026-08-01 23:59:59'), + $this->workflow('C', '2026-08-02 00:00:00'), + ]]; + $this->synchronizer->forConfigKey('ding_online_daifa_price')->sync(true, 10, 0); + $db = DB::connection('business_mirror'); + $db->table('ding_online_daifa_price_mirror')->where('process_instance_id', 'A') + ->update(['product_id' => 'fixture-a', 'product_name' => '已匹配示例']); + $db->table('ding_online_daifa_price_mirror')->where('process_instance_id', 'B') + ->update(['product_id' => 'fixture-b', 'product_name' => null]); + $db->enableQueryLog(); + $result = app(\Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository::class) + ->paginate(['created_from' => '2026-08-01', 'created_to' => '2026-08-01'], 1, 25); + $this->assertSame(2, $result['total']); + $this->assertSame(1, $result['summary']['matched_count']); + $this->assertSame(['B', 'A'], array_column($result['data'], 'process_instance_id')); + $queries = array_filter($db->getQueryLog(), fn ($q) => str_contains($q['query'], 'workflow_created_at')); + $this->assertContains('2026-08-02 00:00:00', array_values($queries)[0]['bindings']); + } + /** @return array */ private function workflow(string $id, string $updateAt, string $status = 'COMPLETED'): array { diff --git a/tests/Unit/EcommerceFinance/StoreReceivingAlipayBillMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/StoreReceivingAlipayBillMirrorRepositoryTest.php index 7e0163e1..0b1c3355 100644 --- a/tests/Unit/EcommerceFinance/StoreReceivingAlipayBillMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/StoreReceivingAlipayBillMirrorRepositoryTest.php @@ -21,125 +21,200 @@ class StoreReceivingAlipayBillMirrorRepositoryTest extends TestCase config([ 'database.connections.business_mirror' => [ - 'driver' => 'sqlite', - 'database' => ':memory:', - 'prefix' => '', + 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ], 'upstream_mirrors.connection' => 'business_mirror', 'upstream_mirrors.datasets' => [ StoreReceivingAlipayBillMirrorRepository::DATASET => [ - 'source_key' => 'jiansun', - 'schema' => 'dbo', - 'object' => 'alipay_Bill_Detail', - 'target' => 'js_alipay_bill_detail', + 'source_key' => 'operations_replica', 'schema' => 'rpt', + 'object' => 'jst_originalBillInfo', 'target' => 'ops_jst_original_bill_info', 'keys' => ['Id'], ], + StoreReceivingAlipayBillMirrorRepository::SHOP_DATASET => [ + 'source_key' => 'operations_replica', 'schema' => 'rpt', + 'object' => 'jst_shopInfo', 'target' => 'ops_jst_shop_info', 'keys' => ['Id'], + ], ], ]); DB::purge('business_mirror'); - - Schema::connection('business_mirror')->create('business_mirror_table_states', function (Blueprint $table): void { + $schema = Schema::connection('business_mirror'); + $schema->create('business_mirror_table_states', function (Blueprint $table): void { $table->string('dataset_key')->primary(); $table->dateTime('initial_completed_at')->nullable(); $table->string('status')->nullable(); $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('mirror_row_count')->nullable(); }); - Schema::connection('business_mirror')->create('js_alipay_bill_detail', function (Blueprint $table): void { + $schema->create('ops_jst_original_bill_info', function (Blueprint $table): void { $table->integer('Id'); - foreach ([ - 'accountNum', 'businessNum', 'merchantOrder', 'commodityName', 'oppAccount', - 'tradeChannel', 'businessType', 'remark', 'shopName', 'busiBillSource', - 'busiDescription', 'busiNum', 'busiBasicNum', 'buyerRemark', 'storeNum', - 'appId', 'account', 'bindingType', - ] as $column) { + $table->integer('shop_id')->nullable(); + foreach (['channel', 'primary_key', 'fee_name', 'inout_type', 'p_auto_id', 'shop_i_id', 'shop_sku_id', 'sku_id', 'so_id', 'combine_type'] as $column) { $table->string($column)->nullable(); } - $table->dateTime('happenTime')->nullable(); - $table->date('date')->nullable(); - $table->decimal('inAmount', 20, 6)->nullable(); - $table->decimal('outAmount', 20, 6)->nullable(); - $table->decimal('accountAmount', 20, 6)->nullable(); + $table->dateTime('fee_time')->nullable(); + $table->dateTime('createTime')->nullable(); + $table->dateTime('updateTime')->nullable(); + $table->bigInteger('auto_id')->nullable(); + $table->decimal('amount', 20, 6)->nullable(); + }); + $schema->create('ops_jst_shop_info', function (Blueprint $table): void { + $table->integer('Id'); + $table->integer('shop_id')->nullable(); + $table->string('shop_name')->nullable(); }); $this->repository = new StoreReceivingAlipayBillMirrorRepository( - new BusinessMirrorDatasetRegistry(), - new GenericBusinessMirrorRepository(app('db')), + new BusinessMirrorDatasetRegistry(), new GenericBusinessMirrorRepository(app('db')), ); } - public function test_it_returns_filtered_pages_and_summary_using_attachment_field_names(): void + public function test_it_reads_operations_replica_rows_and_maps_shop_and_flow_fields(): void { $this->markReady(); - DB::connection('business_mirror')->table('js_alipay_bill_detail')->insert([ - $this->row(1, '天猫-测试店', '2026-08-01 09:00:00', 100.25, 0, 500.25), - $this->row(2, '天猫-测试店', '2026-08-02 09:00:00', 0, -20.10, 480.15), - $this->row(3, '其他店铺', '2026-08-03 09:00:00', 88, 0, 88), + DB::connection('business_mirror')->table('ops_jst_shop_info')->insert([ + ['Id' => 10, 'shop_id' => 7, 'shop_name' => '天猫-经营店'], + ['Id' => 11, 'shop_id' => 8, 'shop_name' => '淘宝-其他店'], + ]); + DB::connection('business_mirror')->table('ops_jst_original_bill_info')->insert([ + $this->row(1, 7, '2026-08-01 09:00:00', '1', 100.25), + $this->row(2, 7, '2026-08-02 09:00:00', '-1', 20.10), + $this->row(3, 8, '2026-08-03 09:00:00', '1', 88), ]); $result = $this->repository->paginate( - ['store_name' => '天猫-测试店', 'start' => '2026-08-01', 'end' => '2026-08-31'], - 'occurred_at', - 'desc', - 2, - 1, + ['store_name' => '天猫-经营店', 'start' => '2026-08-01', 'end' => '2026-08-31'], + 'occurred_at', 'desc', 1, 10, ); $this->assertSame(2, $result['total']); - $this->assertSame(2, $result['current_page']); - $this->assertSame('1', $result['data'][0]['record_code']); - $this->assertSame('2088000000000000', $result['data'][0]['alipay_account']); + $this->assertSame('2', $result['data'][0]['record_code']); + $this->assertSame('天猫-经营店', $result['data'][0]['store_name']); + $this->assertSame('支出', $result['data'][0]['business_type']); + $this->assertSame('CommonBillTGCPay', $result['data'][0]['alipay_account']); $this->assertSame(100.25, $result['summary']['income']); $this->assertSame(20.10, $result['summary']['expense']); - $this->assertSame(480.15, $result['summary']['balance']); + $this->assertSame(80.15, $result['summary']['balance']); $this->assertSame(2, $result['summary']['count']); - $this->assertSame('2026-09-07 09:00:00', $result['sync']['last_succeeded_at']); } public function test_it_rejects_an_unready_mirror_instead_of_querying_upstream_from_http(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('store_receiving_alipay_bill_mirror_not_ready'); - $this->repository->paginate([], 'occurred_at', 'desc', 1, 10); } + public function test_export_uses_the_same_filters_and_mapping_as_the_page(): void + { + $this->markReady(); + DB::connection('business_mirror')->table('ops_jst_shop_info')->insert([ + 'Id' => 10, 'shop_id' => 7, 'shop_name' => '天猫-经营店', + ]); + DB::connection('business_mirror')->table('ops_jst_original_bill_info')->insert([ + $this->row(1, 7, '2026-08-01 09:00:00', '1', 100.25), + $this->row(2, 7, '2026-08-02 09:00:00', '-1', 20.10), + ]); + + $rows = iterator_to_array($this->repository->exportRows([ + 'business_type' => '支出', 'alipay_account' => 'CommonBill', 'keyword' => 'SKU-2', + ])); + + $this->assertCount(1, $rows); + $this->assertSame('2', $rows[0]['record_code']); + $this->assertSame(20.10, $rows[0]['expense']); + } + + public function test_common_filters_use_the_existing_daily_summary_acceleration(): void + { + $this->markReady(); + DB::connection('business_mirror')->table('ops_jst_shop_info')->insert([ + 'Id' => 10, 'shop_id' => 7, 'shop_name' => '天猫-经营店', + ]); + DB::connection('business_mirror')->table('ops_jst_original_bill_info')->insert( + $this->row(1, 7, '2026-08-01 09:00:00', '1', 100.25), + ); + Schema::connection('business_mirror')->create('store_report_import_states', function (Blueprint $table): void { + $table->string('dataset_key')->primary(); + $table->string('active_generation')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + }); + Schema::connection('business_mirror')->create('store_report_daily_rows', function (Blueprint $table): void { + $table->string('generation'); + $table->string('store_name'); + $table->date('occurred_on'); + $table->decimal('income', 20, 4); + $table->decimal('expense', 20, 4); + }); + DB::connection('business_mirror')->table('store_report_import_states')->insert([ + 'dataset_key' => 'store-report.daily-sales', 'active_generation' => 'daily-v1', + 'initial_completed_at' => '2026-09-01 09:00:00', + ]); + DB::connection('business_mirror')->table('store_report_daily_rows')->insert([ + 'generation' => 'daily-v1', 'store_name' => '天猫-经营店', 'occurred_on' => '2026-08-01', + 'income' => 100.25, 'expense' => 20.10, + ]); + + $result = $this->repository->paginate([ + 'store_name' => '天猫-经营店', 'start' => '2026-08-01', 'end' => '2026-08-01', + ], 'occurred_at', 'desc', 1, 10); + + $this->assertSame(['income' => 100.25, 'expense' => 20.10, 'balance' => 80.15, 'count' => 1], $result['summary']); + } + + public function test_unfiltered_pages_reuse_exact_completed_count_and_observe_the_next_sync(): void + { + $this->markReady(); + $db = DB::connection('business_mirror'); + $db->table('ops_jst_original_bill_info')->insert([ + $this->row(1, 7, '2026-08-01 09:00:00', '1', 10), + $this->row(2, 7, '2026-08-02 09:00:00', '-1', 5), + ]); + $state = $db->table('business_mirror_table_states')->where('dataset_key', StoreReceivingAlipayBillMirrorRepository::DATASET); + $state->update(['mirror_row_count' => 2]); + $db->enableQueryLog(); + $first = $this->repository->paginate([], 'occurred_at', 'desc', 1, 1); + $second = $this->repository->paginate(['store_name' => '', 'start' => null], 'occurred_at', 'desc', 2, 1); + $this->assertSame(2, $first['total']); + $this->assertSame(2, $second['total']); + $this->assertNotSame($first['data'][0]['id'], $second['data'][0]['id']); + $this->assertCount(0, array_filter($db->getQueryLog(), fn ($q) => str_contains(strtolower($q['query']), 'count(*)'))); + $db->disableQueryLog(); + + $db->table('ops_jst_original_bill_info')->insert($this->row(3, 7, '2026-08-03 09:00:00', '1', 4)); + $state->update(['mirror_row_count' => 3, 'last_succeeded_at' => '2026-09-08 09:00:00']); + $this->assertSame(3, $this->repository->paginate([], 'occurred_at', 'desc', 1, 1)['total']); + $this->assertSame(1, $this->repository->paginate(['business_type' => '支出'], 'occurred_at', 'desc', 1, 1)['total']); + + $state->update(['status' => 'running', 'mirror_row_count' => 2]); + $this->assertSame(3, $this->repository->paginate([], 'occurred_at', 'desc', 1, 1)['total']); + $state->update(['status' => 'failed']); + $this->assertSame(3, $this->repository->paginate([], 'occurred_at', 'desc', 1, 1)['total']); + $state->update(['status' => 'succeeded', 'mirror_row_count' => null]); + $this->assertSame(3, $this->repository->paginate([], 'occurred_at', 'desc', 1, 1)['total']); + } + private function markReady(): void { - DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ - 'dataset_key' => StoreReceivingAlipayBillMirrorRepository::DATASET, - 'initial_completed_at' => '2026-09-07 09:00:00', - 'status' => 'succeeded', - 'last_succeeded_at' => '2026-09-07 09:00:00', - ]); + foreach ([StoreReceivingAlipayBillMirrorRepository::DATASET, StoreReceivingAlipayBillMirrorRepository::SHOP_DATASET] as $dataset) { + DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ + 'dataset_key' => $dataset, + 'initial_completed_at' => '2026-09-07 09:00:00', + 'status' => 'succeeded', + 'last_succeeded_at' => '2026-09-07 09:00:00', + ]); + } } - private function row(int $id, string $shop, string $time, float $income, float $expense, float $balance): array + private function row(int $id, int $shopId, string $time, string $direction, float $amount): array { return [ - 'Id' => $id, - 'accountNum' => 'ACCOUNT-' . $id, - 'businessNum' => 'BUSINESS-' . $id, - 'merchantOrder' => 'MERCHANT-' . $id, - 'commodityName' => '商品' . $id, - 'happenTime' => $time, - 'oppAccount' => '对方账号', - 'inAmount' => $income, - 'outAmount' => $expense, - 'accountAmount' => $balance, - 'tradeChannel' => '交易收款', - 'businessType' => '交易付款', - 'remark' => '备注', - 'shopName' => $shop, - 'date' => substr($time, 0, 10), - 'busiBillSource' => '支付宝', - 'busiDescription' => '业务说明', - 'busiNum' => 'BILL-' . $id, - 'busiBasicNum' => 'BASE-' . $id, - 'buyerRemark' => '自定义备注', - 'storeNum' => 'ORDER-' . $id, - 'appId' => '2088000000000000', - 'account' => 'account@example.test', - 'bindingType' => '淘系', + 'Id' => $id, 'shop_id' => $shopId, 'channel' => 'CommonBillTGCPay', + 'primary_key' => 'KEY-' . $id, 'fee_name' => '交易佣金', 'inout_type' => $direction, + 'p_auto_id' => 'P-' . $id, 'shop_i_id' => 'STYLE-' . $id, + 'shop_sku_id' => 'SHOP-SKU-' . $id, 'sku_id' => 'SKU-' . $id, + 'so_id' => 'ORDER-' . $id, 'combine_type' => 'double', + 'fee_time' => $time, 'createTime' => '2026-08-04 09:00:00', + 'updateTime' => '2026-08-04 10:00:00', 'auto_id' => 1000 + $id, 'amount' => $amount, ]; } } diff --git a/tests/Unit/View/TaobaoAlipayBillsTableTest.php b/tests/Unit/View/TaobaoAlipayBillsTableTest.php index 917eb89b..62e54c09 100644 --- a/tests/Unit/View/TaobaoAlipayBillsTableTest.php +++ b/tests/Unit/View/TaobaoAlipayBillsTableTest.php @@ -18,6 +18,9 @@ class TaobaoAlipayBillsTableTest extends TestCase $this->assertStringContainsString('assertStringContainsString('v-if="error" class="tb-error"', $source); $this->assertStringContainsString('e.response.data.message', $source); + $this->assertStringContainsString('', $source); + $this->assertStringContainsString('@click="exportRows">导出', $source); + $this->assertStringContainsString('收支净额', $source); $this->assertStringNotContainsString('财务备注', $source); $this->assertStringNotContainsString('订单号', $source); $this->assertStringNotContainsString('金额', $source);