Compare commits

..

12 Commits

Author SHA1 Message Date
2df9d046ac feat: 税金预测表页面标注逻辑配置入口 2026-10-05 11:17:30 +08:00
37e8892e8a feat: 新增税金预测表逻辑配置页面 2026-10-05 11:17:03 +08:00
3ac88cf43d feat: 新增税金预测表页面与取数口径说明 2026-10-05 11:13:22 +08:00
b8726c91f8 feat: 内部流转报表导入工作簿数据并支持查询导出
- 新增共享镜像表 business_internal_flow_records 与整份替换导入命令 internal-flow:import
- 按 Excel 表头展示抬头、标签、预计9月销量、开票、所需进项成本、收票、剩余缺口与开票比例
- 复用公司基础信息的字段查询、表头排序、筛选字段与导出 Excel 交互
- 新增导入与页面测试,覆盖合计行跳过、重导入替换、筛选排序与未导入空状态
2026-10-05 11:02:07 +08:00
967b62ca2f feat: 数据逻辑配置页面支持在线维护
- 店铺主体商标数据逻辑配置新增编辑页:多商标分隔符、同日主体冲突口径、
  商标号缺失处理、爬虫断更开关与天数、四类预警责任人
- 店铺维度报表逻辑配置新增期初数据编辑页:114 家变更店铺可增删改,
  期初生效日随设置保存
- 规则与期初数据改存系统库 settings(扁平键),首次打开自动从
  config/store_report_initial_periods.php 固化,之后不再依赖代码文件
- 控制台任务通过 bootCompanyContext() 读取同一份公司级配置
- 新增迁移清理早期嵌套设置键
- 新增 2 个测试覆盖配置保存与期初店铺增删
2026-10-03 21:52:43 +08:00
561c42d830 feat: 店铺主体期间与爬虫数据逻辑
- 店铺维度报表按期初数据+系统主体+爬虫新主体生成主体期间,一行一期间,修复流程历史重复行
- 变更日当天归新主体、老主体失效显示变更日前一天;关店和其他非正常状态两列显示 -
- 新增店铺维度报表逻辑配置页(R1-R8)、主体商标数据逻辑配置页和预警页面
- 爬虫店铺主体按税号归一,首次抓到的新主体写入期间变更表并自动生成新期间
- 店铺基础信息、商标展示按爬虫优先;新增爬虫数据质量检查与预警处理
2026-10-03 13:28:08 +08:00
fdf7f7ea85 fix: hide empty directory query form grid item 2026-09-29 11:25:45 +08:00
21a3393c7d feat: connect report query controls 2026-09-24 18:24:39 +08:00
e6a30137df feat: improve business directory filters and export 2026-09-24 00:00:26 +08:00
f0b22b5a24 feat: unify business table interactions 2026-09-09 14:35:07 +08:00
e33f22a24f fix: preserve lifecycle effective dates 2026-09-08 16:29:54 +08:00
f6f66b6ff1 feat: add internal flow report entry 2026-09-08 14:44:34 +08:00
1091 changed files with 8161 additions and 206629 deletions

View File

@ -10,7 +10,6 @@ runtime
*.md
JetBrainsMono-字体
node_modules
**/__pycache__
vendor
bootstrap/cache/*
.caiwu-build
@ -23,7 +22,6 @@ storage/debugbar
storage/framework/cache/data/*
storage/framework/sessions/*
storage/framework/views/*
storage/framework/testing
storage/logs/*
tests
test-data
@ -31,6 +29,3 @@ docs
scripts
npm-debug.log
yarn-error.log
public/net-layer-demo.html
public/perf-diff-plan.html
public/plan-a-changes-202608.csv

View File

@ -1,30 +0,0 @@
# ============================================================
# 聚水潭(聚石塔 / 奇门)开放平台接入 —— caiwu 直连发货数据
# 复用工作平台现有授权。把下列键补进 runtime/.env(勿提交 Git)。
# 值留空时同步器会安全拒绝请求,不会误拉。
# ============================================================
# 奇门网关地址(对应工作平台配置 ErpJSTUrl)
JST_QIMEN_URL=
# 授权凭证(复用现有一套)
JST_APP_KEY=
JST_APP_SECRET=
JST_CUSTOMER_ID=
# 奇门固定参数(一般无需改)
JST_API_VERSION=2
JST_FORMAT=json
JST_SIMPLIFY=true
# 同步参数(可选,均有默认值)
JST_SYNC_PAGE_LIMIT=100
JST_SYNC_OVERLAP_HOURS=48
JST_SYNC_WINDOW_HOURS=24
JST_SYNC_MAX_PAGES=0
JST_REQUEST_TIMEOUT=30
JST_RETRY_TIMES=5
JST_RETRY_SLEEP_MS=1000
# 定时增量总开关:凭证填好、迁移跑完、联调校准后再设为 true
JST_SYNC_ENABLED=false

View File

@ -38,14 +38,8 @@ jobs:
- name: Copy .env
run: cp .env.testing .env
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Install NPM
run: npm ci --legacy-peer-deps --no-audit --no-fund
run: npm install
- name: Compile assets
run: npm run production

4
.gitignore vendored
View File

@ -113,7 +113,3 @@ modules/*
.workbuddy/
runtime/.env
/.private/kaifa-progress-sync/
__pycache__/
public/net-layer-demo.html
public/perf-diff-plan.html
public/plan-a-changes-202608.csv

View File

@ -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": "<div class=\"ds-sidebar\"><a class=\"ds-sidebar-item is-active\" href=\"#\"><svg class=\"ds-sidebar-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 4h16v16H4zM8 9h8M8 13h8M8 17h5\"/></svg><span>店铺收款账户账单</span><span class=\"ds-active-indicator\" aria-hidden=\"true\">›</span></a></div>",
"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; }"
"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; }"
},
{
"name": "Workspace Tabs",
@ -205,7 +205,7 @@
"refersTo": "tab-active",
"description": "白色工作区内使用深金活动文字和单一金色下划线的局部标签切换。",
"html": "<nav class=\"ds-tabs\" aria-label=\"账户类型\"><a class=\"ds-tab is-active\" aria-current=\"page\" href=\"#\">淘系支付宝账户</a><a class=\"ds-tab\" href=\"#\">淘系微信账户</a></nav>",
"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; }"
"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; }"
},
{
"name": "Business Panel",
@ -225,7 +225,7 @@
{
"name": "Finance Data Table",
"kind": "custom",
"description": "紧凑、可扫描、数字右对齐的财务数据表。支持列显示/隐藏、拖动排序、恢复默认及按用户和具体表格保存;冻结多层表头,横向滚动条始终可达。导出明确筛选范围和可见列顺序,保留精度并排除密码;允许导入的业务提供模板、预览、校验及失败反馈,只读镜像不写回。",
"description": "紧凑、可扫描、数字右对齐的财务数据表。",
"html": "<table class=\"ds-table\"><thead><tr><th>订单号</th><th class=\"ds-num\">收入</th><th class=\"ds-num\">余额</th></tr></thead><tbody><tr><td>20260722001</td><td class=\"ds-num ds-income\">¥1,280.00</td><td class=\"ds-num\">¥8,460.00</td></tr></tbody></table>",
"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;导航使用统一的紧凑字号。",
"一、二级导航统一 12px;同一层级的图标、字号和交互状态必须一致。",
"页面标题位于内容区右侧,保持 14px,与侧边栏一级标题同级。",
"一级导航 14px,二级导航 12px;同一层级的图标、字号和交互状态必须一致。",
"表格、筛选器和状态反馈优先,装饰性卡片、阴影和动画受到严格限制。",
"标签切换是局部状态变化,不触发整页刷新;加载前后字号和布局不得跳变。"
],
@ -254,10 +254,26 @@
{ "name": "The No-Nested-Cards Rule", "body": "卡片只用于真实分组;卡片内部不能再套同样外观的卡片。优先使用标题、间距、分隔线和表格分组表达层级。", "section": "elevation" }
],
"dos": [
"复用已有令牌和组件,按 DESIGN.md 保持同类页面一致;常规排版和交互细节自主决定,不增加额外设计审批。",
"临时截图和 design-qa.md 仅作验收证据;规则变化时同步现有设计文档,不另建规范文件。",
"保持首屏布局稳定、焦点可见,正文和小号文字对比度至少 4.5:1;不添加与业务无关的装饰或宣传内容。"
"**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`,再修改页面代码。"
],
"donts": []
"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** 用普通 `<a>` 默认导航实现站内标签切换,导致整个文档重新加载。",
"**Don't** 给有边框的卡片叠加宽而软的大阴影,也不要使用超过 16px 的卡片圆角。",
"**Don't** 使用渐变文字、玻璃拟态、装饰网格、斜纹背景、彩色侧边条或与任务无关的动画。",
"**Don't** 恢复“Akaunting 提供支持”之类的供应商页脚文字,或在业务页面加入非业务宣传信息。",
"**Don't** 把临时截图路径、个人电脑路径或 `design-qa.md` 当成团队视觉规范。"
]
}
}

1
.nvmrc
View File

@ -1 +0,0 @@
24.22.1

View File

@ -6,9 +6,8 @@
- 默认使用中文,先给结论;以当前代码、配置、数据和日志为准,旧文档和历史结论仅作参考。
- 用户说“先看、排查、审计”时先只读说明事实和影响;用户说“修改、修复、实现”时,Codex 可直接完成范围内的本地改动、测试、提交和 PR,不必为正常开发步骤逐项请示。
- 围绕用户当前目标持续完成实现和必要验证,常规实现细节自主决定;优先复用现有模式,不顺手重构、升级依赖或修改无关模块。
- 仅在缺失信息会实质改变业务目标、实际写入冲突无法自行安全解决、缺少必需权限,或高风险操作尚未获授权时暂停依赖该条件的步骤;其余工作继续。
- 明确授权在同一任务、目标和影响范围内持续有效,不重复确认;范围、风险或费用实质变化时再确认。不得把 Skill 流程建议当成额外审批要求,也不自行增加团队契约、负责人审批或强制流程。
- 一次只处理一个明确任务,优先复用现有模式和解决根因;不顺手重构、升级依赖或修改无关模块。
- 只有以下情况需要停止并说明:产品方向存在会改变结果的歧义;与其他任务发生实际写入冲突;需要生产发布、生产数据写入、迁移、删除或其他不可逆操作;缺少完成任务必需的外部权限。
- 不为理论上可能、但正常使用无法触发的问题增加复杂框架、兜底层或重复检查。
## 2. 开工与多人协作
@ -16,8 +15,8 @@
- 开工先核对项目目录、`git status --short --branch`、`origin`、Git 身份和最新 `main`;保护现有未提交内容,不覆盖、不顺带提交。
- 开发从最新 `main` 建立独立任务分支:功能用 `feature/用户名-任务名`,修复用 `fix/用户名-问题名`,紧急修复用 `hotfix/用户名-问题名`。
- 只改独立页面、独立测试或文档时,不强制运行重型预检或提前建立 WIP PR;确认没有明显同名任务后即可开发。
- 涉及多人正在修改的共享文件时,可用 `scripts/codex-task-preflight.ps1` 辅助检查;不把预检或提前创建 WIP PR 设为普通开发的必经步骤。
- 冲突以当前实际改动为准。结合 PR 合并状态和文件差异排除旧分支、squash 合并造成的误报;仅复用组件或读取同一数据源不阻塞开发。
- 当任务会修改共享路由、Controller、Repository、数据表/视图、`source_key`、`scope`、权限名、菜单键或公共组件,或远程已有相同区域任务时,才运行 `scripts/codex-task-preflight.ps1`,列明“将修改”和“仅复用”内容,并尽早推送 WIP PR。
- 只有双方会写同一契约或同一文件时才算冲突。仅调用现有路由、组件、Repository 或读取同一数据源不构成阻塞。
- 多代理只用于边界清楚且不修改同一批文件的独立工作;主 Codex 负责最终复核。
## 3. Git、PR 与合并
@ -27,7 +26,7 @@
- 提交前检查 `git status`、实际 diff 和暂存区,只提交当前任务文件;不得带入 `.env`、凭据、日志、构建产物或他人的改动。
- PR 说明做了什么、修改文件、验证结果,以及是否涉及金额、权限、数据库或配置。小型低风险任务不要求冗长模板说明。
- 任务 Codex 在需求满足、相关测试通过且完整 diff 自审无误后,可直接执行 Squash merge、验证远程 `main` 并清理已合并分支,不需要另一位开发者或负责人再次操作。
- 普通代码发布在相关验证通过、完整 diff 自审并合并到最新 `main` 后,由任务 Codex 直接部署和验收,无需另行取得部署授权。上游接入和共享镜像同步按第 6 节自主完成;除此之外的生产迁移、数据修复、删除或覆盖配置仍需单独明确授权。
- 生产部署、生产迁移、数据修复、删除或覆盖配置仍需单独明确授权,不能因为代码已合并而自动执行。
## 4. 验证要求
@ -35,18 +34,8 @@
- 前端改动至少检查目标页面、关键交互和错误状态;后端改动至少运行相关测试或走一次目标接口;纯文档改动检查内容、链接和 diff 即可。
- 涉及金额、权限、导入、审批或数据库结构时,增加对应边界和回归验证。
- 已确认且状态未变化的内容不重复检查。未验证或验证失败时如实说明,不能写“应该没问题”。
- 数据页面按本次影响验证代表性数据量下的首页、翻页和筛选耗时;明显长时间等待不能以“返回正确”判定通过。低风险改动不增加重复或仅复述实现的测试。
- 明确区分:本地已验证、已提交/推送、已合并、已上线和仍需生产验收。
### 性能与资源验收(强制)
- 涉及查询、报表、导入导出、同步或后台任务时,开发前先确认实际数据规模、单次数据量、文件大小和运行频率,并据此选择实现与验收数据;不能只验证几十行样例。
- Excel/CSV 必须流式读取;表扫描、关联和排序使用合适索引,页面数据使用分页。分批写库只控制写入批次,不能据此声称读取过程内存受控。
- 重型任务复用项目现有独立批处理容器,完成命令登记,并明确内存上限、超时、互斥和失败恢复;不得占用网页服务资源执行全量处理。
- 禁止通过取消 `memory_limit`、无限重试、放大数据库参数或其他绕过资源边界的办法掩盖性能问题。
- 使用代表性数据测量耗时、进程峰值内存和数据库开销,并在交付说明中写明测量范围、数据量及未验证项。生产环境不运行压测,不随意重跑全量任务。
- 性能优化不得改变金额口径、筛选范围或现有业务结果;相关金额和功能回归必须同时通过。
## 5. 前端与视觉
- 只有前端任务需要先阅读根目录 `DESIGN.md`;`.impeccable/design.json` 是同源机器规范。
@ -59,7 +48,7 @@
- 密码、Token、SSH 私钥、数据库连接串、真实财务数据和生产日志不得进入 Git、PR 或公开文档。
- 需要长期保存的敏感信息写入被 Git 忽略的 `runtime/private/敏感信息.md`;写入前用 `git check-ignore` 确认。负责人明确要求时,可在当前一对一对话提供指定范围的敏感信息,但不得扩大传播。
- 本任务所需的上游只读排查、数据字典刷新、数据集登记和启用、共享镜像建表及索引迁移、首次全量、增量、历史回补和镜像校准,由开发者的 Codex 自主完成,无需负责人逐次授权或代执行。Codex 自行核对来源与范围、备份受影响的配置/镜像及同步状态,使用生产同步节点和现有互斥锁分批执行,并核对源数据、完成状态与真实页面;不把这些工作转交给新人。可从上游重建的镜像修复属于此范围;上游写入、原始业务/财务数据修改、无关数据删除、凭据轮换和覆盖生产连接配置仍需单独授权。
- 生产数据库写入、迁移、删除、批量导入和凭据轮换必须先说明影响,准备备份或回滚,并取得明确授权。普通本地只读排查和有限业务查询不需要额外审批。
- `caiwu_system_config` 保存用户、权限、设置、连接资料、数据字典和同步状态;`caiwu_business_mirror` 保存项目已正式接入的上游业务数据。二者不是 SQL Server 网络代理。
- 上游数据库统一按只读黑盒处理。业务查询使用固定、参数化的 Repository/查询执行器,禁止把用户输入拼成 SQL 或执行写操作。
- 正式页面优先读取共享业务镜像;尚未迁移的旧页面可继续使用现有快照兼容层。接入新数据时沿用现有镜像数据集、稳定游标、断点同步和同步状态模式,不另造一套链路。
@ -68,19 +57,19 @@
## 7. 新人本地开发
- 新人只需启动 Docker Desktop、网页登录并输入负责人提供的系统数据库密码;Codex 按 SOP 运行不带参数的 `deploy/local-init.sh`,完成初始化和排错,不让新人选择构建或迁移参数。
- 连接团队系统数据库后保留该连接,不切回临时库、不复制他人 `.env`;普通功能开发无需检查全部上游链路,仅接入新数据时验证对应来源。
- 新人只需要启动 Docker Desktop、在网页登录,以及输入一次负责人提供的系统数据库密码;拉取代码、初始化、缓存、容器和连接排错由 Codex 完成。
- 标准初始化由 Codex 在最新 `main` 上运行不带参数的 `deploy/local-init.sh`。不要让新人判断 `--build`、手工迁移共享数据库、复制他人 `.env` 或配置上游连接。
- 本地连接系统数据库后,用户、菜单、设置和上游登记继续使用团队系统数据库,不把主连接切回本机临时 MySQL。
- 与数据库无关的普通页面或业务功能可以直接开发,不要求开发者先理解或验证全部上游、镜像和生产部署链路。
- 只有接入新上游数据时,才需要验证对应来源的只读查询、镜像同步状态、总数及代表性分页/筛选;无需每个普通任务重复验证两套数据库。
## 8. 构建与生产部署
- 发布脚本会拒绝覆盖“不在本次版本里”的线上提交(防止互相冲掉已上线的改动)。热修复必须基于线上当前版本构建,发布后立即合入 `main`;遇到拦截先 `git fetch` 并合入最新 `main` 或线上热修复分支,不得随手加 `-AllowRollback`(`--allow-rollback`),撤回线上发布需负责人明确决定。
- 普通代码发布由任务 Codex 在完成验证与合并后直接执行,不要求用户再次说“部署、上线”;用户明确要求仅本地开发、仅审查或暂不上线时遵循其范围。正式发布只使用已合并的最新 `main`。
- Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`,macOS 开发机使用 `bash scripts/deploy-from-mac.sh`;两者流程一致(本机构建前端与镜像、迁移拦截、增量推送服务器本机 Registry、激活与健康检查、双版本保留)。服务器只运行开发机已构建的 `caiwu_akaunting:<commit>` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。
- 新人只需表达部署需求;Codex 使用默认生产入口运行脚本。首次通过本机窗口提供一次服务器密码后,加密保存在本人电脑供后续自动使用,不要求新人准备私钥、执行命令或每次重输密码。已有私钥认证仍兼容。
- 只有用户明确要求“部署、上线”时才执行生产发布;正式发布只使用已合并的最新 `main`。
- Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`。服务器只运行开发机已构建的 `caiwu_akaunting:<commit>` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。
- 当前生产入口为 `https://caiwu.jiansuntuzhi.cn:8442`;公网仍只使用 `8442`,日常发布不得改成无端口地址。
- 发布脚本检测到新增数据库迁移时,由 Codex 核对全部待执行迁移。仅涉及本任务共享镜像建表、字段、索引和同步登记的迁移,完成备份后自主使用 `-AllowMigrations`(macOS 为 `--allow-migrations`);其他迁移仍按第 6 节确认授权。不能因需要迁移开关就把镜像接入停给负责人。
- 发布脚本检测到新增数据库迁移时必须停止,取得负责人明确授权并完成备份后才能使用迁移开关。
- 容器内 Laravel 命令使用 `www-data`。发布后只需确认部署 SHA、应用容器健康、受影响的真实页面/接口、迁移是否执行,以及当前和上一版镜像可回滚。
- 生产重型 CLI 导入统一使用 `sh /opt/caiwuxitong/run-finance-batch.sh <命令> <原参数>`,不得在网页容器内直接执行或取消 PHP 内存限制。新增导入登记 `deploy/finance-batch-imports.json`;入口提供独立容器、互斥、资源与时间上限,主应用保留自己的内存边界。
- 程序静态资源随应用镜像同源发布;七牛只存用户上传的业务图片、票据和附件。
- 只有本地初始化、服务器维护、生产发布或数据库迁移任务需要读取 `docs/开发与部署SOP.md` 的对应章节;普通功能开发无需加载整份 SOP。

View File

@ -86,13 +86,13 @@ components:
sidebar-item:
backgroundColor: "{colors.sidebar-black}"
textColor: "{colors.sidebar-gold}"
typography: "{typography.label}"
typography: "{typography.title}"
rounded: "{rounded.sm}"
padding: "8px 10px"
sidebar-item-active:
backgroundColor: "{colors.sidebar-active}"
textColor: "{colors.rail-gold}"
typography: "{typography.label}"
typography: "{typography.title}"
rounded: "{rounded.sm}"
padding: "8px 10px"
tab-default:
@ -100,13 +100,13 @@ components:
textColor: "{colors.content-muted}"
typography: "{typography.title}"
padding: "0 4px"
minHeight: "34px"
height: "80px"
tab-active:
backgroundColor: "{colors.surface}"
textColor: "{colors.content-accent-dark}"
typography: "{typography.title}"
padding: "0 4px"
minHeight: "34px"
height: "80px"
panel:
backgroundColor: "{colors.surface}"
textColor: "{colors.content-ink}"
@ -131,8 +131,8 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视
- 深黑工具轨道、浅黑功能栏、浅色内容区,三层边界清楚。
- 浅金用于深色导航,深金用于浅色内容区的文字与主要操作。
- 全站使用 JetBrains Mono,标题和数据采用固定字号,不使用流体放大。
- 页面标题位于内容区右侧,保持 14px;导航使用统一的紧凑字号。
- 一、二级导航统一 12px;同一层级的图标、字号和交互状态必须一致。
- 页面标题位于内容区右侧,保持 14px,与侧边栏一级标题同级。
- 一级导航 14px,二级导航 12px;同一层级的图标、字号和交互状态必须一致。
- 表格、筛选器和状态反馈优先,装饰性卡片、阴影和动画受到严格限制。
- 标签切换是局部状态变化,不触发整页刷新;加载前后字号和布局不得跳变。
@ -191,8 +191,8 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视
### Hierarchy
- **页面标题** (600, 14px, 1.25): 固定在内容头部右侧,与配套图标同行;禁止在业务内容内部重复放置大号 H1。
- **侧边栏一级标题** (500–600, 12px, 16px): 模块和一级功能名称。
- **侧边栏二级标题** (400–500, 12px, 16px): 通过缩进区分层级,保持单行和稳定行高。
- **侧边栏一级标题** (500–600, 14px, 1.25): 模块和一级功能名称。
- **侧边栏二级标题** (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
- 一、二级导航统一 12px;文字和对应 Material 图标使用同一浅金色。
- 图标统一采用 Material Icons Outlined/Round,导航图标统一 16px;同一业务语义不得在不同页面更换图标体系。
- 一级导航 14px,二级导航 12px;文字和对应 Material 图标使用同一浅金色。
- 图标统一采用 Material Icons Outlined/Round,常规尺寸 20–24px;同一业务语义不得在不同页面更换图标体系。
- 当前二级菜单只显示一个 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,12 +277,6 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视
- 行悬停使用极浅金/中性背景;选中状态同时提供图标、文字或边界,不只改变底色。
- 收入、支出、错误和成功色遵循业务语义;不得为了“好看”交换红绿含义。
- 各业务表格支持列显示/隐藏、拖动排序和恢复默认;按用户及页面、标签页、表格分别保存,表头、数据和合计同步排列,必要操作列可固定。
- 单层或多层表头随纵向滚动保持可见;横向滚动条在浏览数据时始终可达,不得落到屏幕外或必须滚至整表底部才能操作。
- 合理设置表格滚动容器,适配视口、缩放和侧栏变化,避免多层滚动互相干扰。优先复用现有组件,具体实现自主选择。
- 导出明确范围,支持当前筛选结果及可见列顺序,不把当前页冒充全部;保留金额精度、日期和长编号格式,遵守字段权限,密码不导出,大数据量沿用分批或后台机制。
- 允许导入的业务提供模板、预览、字段校验、重复处理和逐行失败反馈,不静默覆盖数据;只读上游镜像不增加写回入口。业务规则不明时只澄清必要问题。
### Scrollbars
- 内容滚动条为 8px,轨道使用浅中性色,滑块使用 VIP 金;悬停使用更深金色。
@ -294,8 +288,28 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视
- 空状态说明“为什么没有数据”和“下一步能做什么”,不能只写“暂无数据”。
- 错误状态保留重试入口和明确原因;局部失败不能清空整个页面或触发整页刷新。
## 6. 使用原则
## 6. Do's and Don'ts
- 复用已有令牌和组件,按上述标准保持同类页面一致;常规排版和交互细节自主决定,不增加额外设计审批。
- 临时截图和 `design-qa.md` 仅作验收证据,不覆盖本文件;规则变化时同步 `.impeccable/design.json`,不另建规范文件。
- 保持首屏布局稳定、焦点可见,正文和小号文字对比度至少 4.5:1;不添加与业务无关的装饰或宣传内容。
### 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** 用普通 `<a>` 默认导航实现站内标签切换,导致整个文档重新加载。
- **Don't** 给有边框的卡片叠加宽而软的大阴影,也不要使用超过 16px 的卡片圆角。
- **Don't** 使用渐变文字、玻璃拟态、装饰网格、斜纹背景、彩色侧边条或与任务无关的动画。
- **Don't** 恢复“Akaunting 提供支持”之类的供应商页脚文字,或在业务页面加入非业务宣传信息。
- **Don't** 把临时截图路径、个人电脑路径或 `design-qa.md` 当成团队视觉规范。

View File

@ -145,10 +145,7 @@ docker compose -f docker-compose.local.yml start
## 修改后的生效方式
- PHP、配置、模块、页面模板和路由目录已经挂载到容器;开发环境关闭 PHP OPcache 和 Blade 编译缓存,刷新浏览器即可加载最新源码,无需重启 PHP 服务;
- 开发环境启动时只执行 `optimize:clear`,不会生成 Laravel 的配置、路由或视图缓存;生产环境仍保留原有缓存构建机制;
- 本地 Compose 会同时启动 `frontend` watcher。修改 `resources/assets` 下的 Vue、JavaScript 或 SCSS 后,Laravel Mix 会通过轮询自动重新编译,Apache 使用共享静态资源卷提供最新文件;浏览器刷新即可看到结果。
- 如果 watcher 构建失败,查看 `docker compose -f docker-compose.local.yml logs -f frontend`;修复源码后它会继续监听并重新编译。
- PHP、配置、模块、页面模板和路由目录已经挂载到容器,通常清理缓存或重启应用即可;
- Composer 依赖、前端依赖、Dockerfile 或构建资源发生变化时,重新执行 `bash deploy/local-init.sh`,脚本会自动重建;
- 修改 `runtime/.env` 后,执行:
@ -157,8 +154,6 @@ docker compose -f docker-compose.local.yml restart app
docker compose -f docker-compose.local.yml exec -u www-data app php artisan optimize:clear
```
停止本地环境时,`app`、`frontend` 和 `mysql` 会一起停止;再次运行初始化脚本会恢复 PHP 服务和前端 watcher。
## 相关文档
- 新电脑接续指南:[docs/新电脑开发接续指南.md](docs/新电脑开发接续指南.md)

View File

@ -1,169 +0,0 @@
<?php
namespace App\Business;
/**
* 经营报表页面顶部的小格子指标。
*
* 汇总卡片只描述当前表本身,不把其他目录的数据拼成跨表大看板。
*/
class BusinessSummaryCards
{
/**
* @param array<string,mixed> $summary
* @return list<array{label:string,value:mixed,hint:string,format:string,query:array<string,mixed>,tone:string}>
*/
public function forPage(string $key, array $summary = []): array
{
return match ($key) {
'store-management/store-report' => $summary === [] ? [] : $this->storeReportCards($summary),
'company-management/subject-operating-report' => $summary === [] ? [] : $this->subjectOperatingReportCards($summary),
'store-management/internal-flow-report' => $summary === [] ? [] : $this->internalFlowReportCards($summary),
'company-management/company-cost-arrangement' => $this->companyCostArrangementCards(),
'company-management/tax-forecast' => $this->taxForecastCards(),
'company-management/personnel-inventory' => $this->personnelInventoryCards(),
default => [],
};
}
/** @param array<string,mixed> $summary */
private function subjectOperatingReportCards(array $summary): array
{
$ready = (bool) ($summary['company_status_ready'] ?? false);
$previousLabel = (string) ($summary['previous_month_label'] ?? '上月');
$currentLabel = (string) ($summary['current_month_label'] ?? '当月');
$previousStores = (int) ($summary['previous_income_entities'] ?? 0);
$currentStores = (int) ($summary['current_income_entities'] ?? 0);
if (! $ready) {
return [
$this->card('正常存续主体', '—', '公司资料镜像未就绪,暂时无法剔除注销主体', [], 'text', 'warning'),
$this->card('上月收入', '—', '公司资料镜像未就绪', [], 'text', 'warning'),
$this->card('当月收入', '—', '公司资料镜像未就绪', [], 'text', 'warning'),
$this->card('小规模纳税人', '—', '公司资料镜像未就绪', [], 'text'),
$this->card('一般纳税人', '—', '公司资料镜像未就绪', [], 'text'),
];
}
return [
$this->card('正常存续主体', $summary['normal'] ?? 0, '只统计公司台账标签为保留的主体', ['company_status' => '正常'], 'integer', 'accent'),
$this->card($previousLabel . '收入', $summary['previous_income'] ?? 0, $previousStores . ' 个存续主体有收入', [
'company_status' => '正常',
'sort' => $summary['previous_month_key'] ?? null,
'direction' => 'desc',
], 'amount', 'success'),
$this->card($currentLabel . '收入', $summary['current_month_income'] ?? 0, $currentStores . ' 个存续主体有收入', [
'company_status' => '正常',
'sort' => $summary['current_month_key'] ?? null,
'direction' => 'desc',
], 'amount', 'warning'),
$this->card('小规模纳税人', $summary['small_taxpayer'] ?? 0, '正常存续主体中的小规模纳税人', [
'company_status' => '正常',
'tax_type' => '小规模纳税人',
]),
$this->card('一般纳税人', $summary['general_taxpayer'] ?? 0, '正常存续主体中的一般纳税人', [
'company_status' => '正常',
'tax_type' => '一般纳税人',
]),
];
}
/** @param array<string,mixed> $summary */
private function storeReportCards(array $summary): array
{
$previousLabel = (string) ($summary['previous_month_label'] ?? '上月');
$currentLabel = (string) ($summary['current_month_label'] ?? '当月');
$normalStores = (int) ($summary['normal_stores'] ?? 0);
$previousStores = (int) ($summary['previous_month_stores'] ?? 0);
$currentStores = (int) ($summary['current_month_stores'] ?? 0);
return [
$this->card('正常存续店铺', $normalStores, '只统计开店中店铺,不含关店和已注销', ['status' => '0'], 'integer', 'accent'),
$this->card($previousLabel . '销量', $summary['previous_month_sales'] ?? 0, $previousStores . ' 家存续店铺有销量', [
'status' => '0',
'sort' => $summary['previous_month_key'] ?? null,
'direction' => 'desc',
], 'amount', 'success'),
$this->card($currentLabel . '销量', $summary['current_month_sales'] ?? 0, $currentStores . ' 家存续店铺有销量', [
'status' => '0',
'sort' => $summary['current_month_key'] ?? null,
'direction' => 'desc',
], 'amount', 'warning'),
];
}
/** @param array<string,mixed> $summary */
private function internalFlowReportCards(array $summary): array
{
return [
$this->card('公司数', $summary['companies'] ?? 0, '当前筛选内内部流转公司', [], 'integer', 'accent'),
$this->card('预计销量合计', $summary['projected_sales'] ?? 0, '当前筛选内预计销量合计', [
'sort' => 'projected_sales',
'direction' => 'desc',
], 'amount'),
$this->card('已收票合计', $summary['receipt_total'] ?? 0, '供应商、关联公司与内部流转收票合计', [
'sort' => 'receipt_total',
'direction' => 'desc',
], 'amount', 'success'),
$this->card('剩余缺口合计', $summary['remaining_gap'] ?? 0, '金额越大越应优先处理', [
'sort' => 'remaining_gap',
'direction' => 'desc',
], 'amount', 'warning'),
$this->card('平均开票比例', $summary['average_invoicing_ratio'] ?? 0, '按有比例的公司简单平均', [], 'percent'),
];
}
private function companyCostArrangementCards(): array
{
return [
$this->card('数据状态', '待接入', '当前表尚无业务数据', [], 'text', 'warning'),
$this->card('完整表头', '11 列', '包含序号,收入、成本、税金、人工等字段全部保留', [], 'text'),
$this->card('核心结果', '预计结余 / 缺口', '当月收入预测减去成本与费用', [], 'text'),
$this->card('缺口提示', '负值标红', '成本或费用未覆盖收入时提醒', [], 'text', 'danger'),
$this->card('配平提示', '零或正结余标绿', '表示当月预算已覆盖', [], 'text', 'success'),
];
}
private function taxForecastCards(): array
{
return [
$this->card('数据状态', '待取数', '规则已定义,业务数据尚未接入', [], 'text', 'warning'),
$this->card('完整表头', '22 列', '包含序号、征管口径、收入、税额与备注', [], 'text'),
$this->card('计算税种', '4 类', '增值税、附加税、印花税、所得税', [], 'text'),
$this->card('计税口径', '3 项', '公司税务类型、工商类型和征收方式', [], 'text'),
$this->card('当前记录', '0 条', '数据接入后按完整字段展示', [], 'text'),
];
}
private function personnelInventoryCards(): array
{
return [
$this->card('数据状态', '待接入', '当前表尚无人员数据', [], 'text', 'warning'),
$this->card('完整表头', '17 列', '包含序号和全部人员、容量字段', [], 'text'),
$this->card('敏感字段', '4 项', '密码、身份证、实名手机和身份证地址只显示维护状态', [], 'text', 'danger'),
$this->card('容量规则', '3 档', '可担任公司数量按风险档位提示', [], 'text'),
$this->card('当前记录', '0 条', '接入后按正常在职人员汇总', [], 'text'),
];
}
/**
* @return array{label:string,value:mixed,hint:string,format:string,query:array<string,mixed>,tone:string}
*/
private function card(
string $label,
mixed $value,
string $hint,
array $query = [],
string $format = 'integer',
string $tone = 'neutral',
): array {
return [
'label' => $label,
'value' => $value,
'hint' => $hint,
'format' => $format,
'query' => ['page' => null, ...$query],
'tone' => $tone,
];
}
}

View File

@ -17,13 +17,6 @@ class BusinessTableImporter
string $page,
?string $tab = null,
): array {
if ($section === 'fund-management' && $page === 'fund-forecast') {
return app(FundForecastWorkbookImporter::class)->import(
$file,
(int) (company_id() ?: 1),
);
}
$spreadsheet = IOFactory::load($file->getRealPath());
[$rows, $headerRow, $columnMap] = $this->bestMatchingSheet($spreadsheet, $descriptor);

View File

@ -1,163 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\CourierAgreementSignature;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Throwable;
/** Read the signed snapshot directly: no duplicate contracts, attachment copies or archive backfill. */
class CourierContractPageData
{
public const REMINDER_DAYS = 30;
public const STATUSES = [
'due' => '即将到期',
'expired' => '约定期限已届满',
'active' => '有效期内',
'upcoming' => '未到开始日期',
'unknown' => '期限待核对',
];
public function page(bool $includeRows = true): array
{
$search = mb_substr(trim((string) request()->query('contract_search', '')), 0, 255);
$status = (string) request()->query('contract_status', '');
$status = array_key_exists($status, self::STATUSES) ? $status : '';
$from = $this->date(request()->query('contract_end_from'));
$to = $this->date(request()->query('contract_end_to'));
if ($from && $to && $from > $to) {
[$from, $to] = [$to, $from];
}
$filters = ['contract_search' => $search, 'contract_status' => $status,
'contract_end_from' => $from ?? '', 'contract_end_to' => $to ?? ''];
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
$page = max((int) request()->query('page', 1), 1);
$options = ['path' => request()->url(), 'query' => request()->except('page')];
$data = [
'courierContractFilters' => $filters,
'courierContractRows' => new LengthAwarePaginator([], 0, $limit, $page, $options),
'courierContractCounts' => array_fill_keys(array_keys(self::STATUSES), 0),
'courierContractUnreadable' => 0,
'courierContractError' => null,
];
try {
if (! Schema::hasTable('business_courier_agreement_signatures')) {
$data['courierContractError'] = '协议签署数据表尚未建立,合同管理暂时无法读取。';
return $data;
}
$matched = [];
$today = Carbon::today(config('app.timezone'));
// Dates and partner types are encrypted. Stream bounded chunks instead of SQL JSON queries
// or persisting a second, potentially stale copy of the signed business snapshot.
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
->select(['id', 'company_id', 'business_no', 'courier_name', 'payload', 'document_type', 'status',
'signed_pdf_path', 'certificate_path', 'archived_at', 'created_by', 'created_at'])
->lazyById(250);
foreach ($signatures as $signature) {
$payload = $signature->archivedCourierContractPayload();
if ($payload === null) {
try {
$signature->payload;
} catch (Throwable) {
$data['courierContractUnreadable']++;
}
continue;
}
$row = $this->snapshot($signature, $payload, $today);
$data['courierContractCounts'][$row['status']]++;
if (! $includeRows || ($status !== '' && $status !== $row['status'])) {
continue;
}
if (($from && (! $row['end_date'] || $row['end_date'] < $from))
|| ($to && (! $row['end_date'] || $row['end_date'] > $to))) {
continue;
}
if ($search !== '' && ! str_contains(mb_strtolower(implode(' ', [
$row['courier_name'], $row['number'], $row['business_no'], $row['party_a'], $row['party_b'],
])), mb_strtolower($search))) {
continue;
}
$matched[] = $row;
}
if ($includeRows) {
$priority = ['due' => 0, 'expired' => 1, 'unknown' => 2, 'active' => 3, 'upcoming' => 4];
usort($matched, static fn (array $a, array $b): int =>
[$priority[$a['status']], $a['end_date'] ?? '9999-12-31', -$a['id']]
<=> [$priority[$b['status']], $b['end_date'] ?? '9999-12-31', -$b['id']]);
$total = count($matched);
$items = array_slice($matched, ($page - 1) * $limit, $limit);
$owners = user_model_class()::query()->whereIn('id', array_filter(array_column($items, 'created_by')))
->pluck('name', 'id');
foreach ($items as &$row) {
$row['creator'] = $owners[$row['created_by']] ?? '未记录';
$row['has_signed_file'] = $this->listedFileAvailable($row['signed_path']);
$row['has_certificate'] = $this->listedFileAvailable($row['certificate_path']);
unset($row['signed_path'], $row['certificate_path']);
}
unset($row);
$data['courierContractRows'] = new LengthAwarePaginator($items, $total, $limit, $page, $options);
}
} catch (Throwable $exception) {
report($exception);
$data['courierContractCounts'] = array_fill_keys(array_keys(self::STATUSES), 0);
$data['courierContractError'] = '归档合同暂时无法读取,请稍后重试。';
}
return $data;
}
private function snapshot(CourierAgreementSignature $signature, array $payload, Carbon $today): array
{
$start = $this->date($payload['cooperation_start_date'] ?? null);
$end = $this->date($payload['cooperation_end_date'] ?? null);
$days = $end ? (int) $today->diffInDays(Carbon::parse($end, config('app.timezone')), false) : null;
$status = match (true) {
! $start || ! $end || $start > $end => 'unknown',
$end < $today->toDateString() => 'expired',
$start > $today->toDateString() => 'upcoming',
$days <= self::REMINDER_DAYS => 'due',
default => 'active',
};
$person = ($payload['counterparty_signer_type'] ?? 'organization') === 'person';
return [
'id' => (int) $signature->id,
'courier_name' => (string) $signature->courier_name,
'business_no' => (string) $signature->business_no,
'number' => trim((string) ($payload['cooperation_contract_number'] ?? '')),
'party_a' => trim((string) ($payload['cooperation_party_a_name'] ?? '')),
'party_b' => trim((string) ($payload['cooperation_party_b_name'] ?? '')),
'legal_representative' => $person ? '不适用(个人签署)' : trim((string) ($payload['cooperation_party_b_legal_representative'] ?? '')),
'start_date' => $start, 'end_date' => $end, 'days' => $status === 'unknown' ? null : $days,
'status' => $status, 'created_by' => $signature->created_by,
'created_at' => $signature->created_at, 'archived_at' => $signature->archived_at,
'signed_path' => $signature->signed_pdf_path, 'certificate_path' => $signature->certificate_path,
];
}
private function date(mixed $value): ?string
{
if (! is_string($value) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
return null;
}
[$year, $month, $day] = array_map('intval', explode('-', $value));
return checkdate($month, $day, $year) ? $value : null;
}
private function listedFileAvailable(?string $path): bool
{
if (blank($path)) {
return false;
}
// Do not issue up to 50 sequential object-storage HEAD requests for one list page.
// Downloads always verify the actual file; local files can be checked cheaply here.
return config('filesystems.disks.uploads.driver') !== 'local' || Storage::disk('uploads')->exists($path);
}
}

View File

@ -1,222 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Database\DatabaseManager;
use InvalidArgumentException;
use RuntimeException;
/**
* 快递运费导入(.xlsx / .csv)。
*
* 源表头(按表头名匹配,列顺序无关):
* - 必需:来源 / 成品配件(也接受「成品运费」)/ 交易单号 / 提供成本运费;
* - 可选:快递单号 / 条形码 / 店铺名称(「财务系统运费整理.xlsx」起提供的列,老文件没有也能导)。
* 快递方给的文件常见几十万行,xlsx 走 XlsxSheetReader 流式读取,不整表进内存。
*/
class CourierFreightImporter
{
/** 源表头 → 数据库列 */
private const COLUMNS = [
'来源' => 'source',
'成品配件' => 'part',
'成品运费' => 'part',
'交易单号' => 'transaction_no',
'快递单号' => 'express_no',
'条形码' => 'barcode',
'店铺名称' => 'shop_name',
'提供成本运费' => 'freight_amount',
];
private const HEADERS = ['来源', '成品配件', '交易单号', '提供成本运费'];
/** 可选列:文件里有就导入,没有就留空(老文件兼容)。 */
private const OPTIONAL_HEADERS = ['快递单号', '条形码', '店铺名称'];
/** 表头别名:源文件的列名写法不统一(成品配件 / 成品运费;店铺名称 / 店铺)。 */
private const HEADER_ALIASES = [
'成品配件' => ['成品配件', '成品运费'],
'店铺名称' => ['店铺名称', '店铺'],
];
private const CHUNK = 2000;
public function __construct(
private readonly DatabaseManager $databases,
private readonly ?XlsxSheetReader $reader = null,
) {}
/**
* @return array{file:string,rows:int,inserted:int,skipped:int,amount:string,sources:array<string,int>,seconds:float}
*/
public function import(string $path, int $companyId = 1, bool $replace = false, string $source = 'courier-freight-import'): array
{
if (! is_file($path)) {
throw new InvalidArgumentException('找不到要导入的文件:' . $path);
}
$target = $this->databases->connection();
$startedAt = microtime(true);
$now = now();
if ($replace) {
$target->table('courier_freight_rows')->where('company_id', $companyId)->delete();
}
$inserted = 0;
$skipped = 0;
$amount = 0.0;
$sources = [];
$buffer = [];
$flush = function () use (&$buffer, &$inserted, $target): void {
foreach (array_chunk($buffer, self::CHUNK) as $chunk) {
$target->table('courier_freight_rows')->insert($chunk);
$inserted += count($chunk);
}
$buffer = [];
};
foreach ($this->lines($path) as $line) {
$sourceValue = $this->text($line['来源'] ?? null, 64);
$transactionNo = $this->text($line['交易单号'] ?? null, 191);
if ($sourceValue === null && $transactionNo === null) {
$skipped++;
continue;
}
$value = $this->number($line['提供成本运费'] ?? null);
$sources[$sourceValue ?? ''] = ($sources[$sourceValue ?? ''] ?? 0) + 1;
$amount += $value;
$buffer[] = [
'company_id' => $companyId,
'source' => $sourceValue ?? '',
'part' => $this->text($line['成品配件'] ?? null, 191),
'transaction_no' => $transactionNo ?? '',
'express_no' => $this->text($line['快递单号'] ?? null, 64),
'barcode' => $this->text($line['条形码'] ?? null, 191),
'shop_name' => $this->text($line['店铺名称'] ?? null, 191),
'freight_amount' => number_format($value, 4, '.', ''),
'created_at' => $now,
'updated_at' => $now,
];
if (count($buffer) >= self::CHUNK * 4) {
$flush();
}
}
$flush();
arsort($sources);
return [
'file' => basename($path),
'rows' => $inserted + $skipped,
'inserted' => $inserted,
'skipped' => $skipped,
'amount' => number_format($amount, 2, '.', ''),
'sources' => $sources,
'seconds' => round(microtime(true) - $startedAt, 1),
];
}
/** @return \Generator<int, array<string,string>> */
private function lines(string $path): \Generator
{
if (mb_strtolower(pathinfo($path, PATHINFO_EXTENSION)) === 'csv') {
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('无法读取文件:' . $path);
}
try {
$header = null;
while (($cells = fgetcsv($handle)) !== false) {
if ($header === null) {
$cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) ($cells[0] ?? ''));
$header = array_map(static fn ($value): string => trim((string) $value), $cells);
$this->assertHeader($header);
continue;
}
$line = [];
foreach ($header as $index => $name) {
$line[$this->canonicalName($name)] = (string) ($cells[$index] ?? '');
}
yield $line;
}
} finally {
fclose($handle);
}
return;
}
if (mb_strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'xlsx') {
throw new InvalidArgumentException('只支持 xlsx、csv。');
}
$columns = array_map(
static fn (string $name): array|string => self::HEADER_ALIASES[$name] ?? $name,
self::HEADERS,
);
$optionalColumns = array_map(
static fn (string $name): array|string => self::HEADER_ALIASES[$name] ?? $name,
self::OPTIONAL_HEADERS,
);
yield from ($this->reader ?? app(XlsxSheetReader::class))->rows($path, $columns, $optionalColumns);
}
/** 把表头别名折回规范列名。 */
private function canonicalName(string $header): string
{
foreach (self::HEADER_ALIASES as $canonical => $names) {
if (in_array($header, $names, true)) {
return $canonical;
}
}
return $header;
}
/** @param list<string> $header */
private function assertHeader(array $header): void
{
foreach (self::HEADERS as $required) {
$names = self::HEADER_ALIASES[$required] ?? [$required];
if (array_intersect($names, $header) === []) {
throw new InvalidArgumentException('文件缺少列:' . $required);
}
}
}
private function text(mixed $value, int $limit): ?string
{
if ($value === null) {
return null;
}
$text = trim((string) (is_scalar($value) ? $value : ''));
return $text === '' ? null : mb_substr($text, 0, $limit);
}
private function number(mixed $value): float
{
if ($value === null || $value === '') {
return 0.0;
}
if (is_numeric($value)) {
return (float) $value;
}
$text = str_replace([',', ' ', '¥', '¥'], '', (string) $value);
return is_numeric($text) ? (float) $text : 0.0;
}
}

View File

@ -1,98 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\CourierOnboarding;
use App\Support\CourierOnboardingService;
use Illuminate\Pagination\LengthAwarePaginator;
/**
* 「快递入驻」列表页数据:状态统计、筛选和分页。
*/
class CourierOnboardingPageData
{
/** 列表页状态分组,键为页面筛选值。 */
public const STATUS_GROUPS = [
'pending' => ['label' => '待处理', 'statuses' => [CourierOnboarding::STATUS_SUBMITTED, CourierOnboarding::STATUS_FIRST_APPROVED, CourierOnboarding::STATUS_APPROVED]],
'filling' => ['label' => '待快递填写', 'statuses' => [CourierOnboarding::STATUS_INVITED, CourierOnboarding::STATUS_RETURNED]],
'activated' => ['label' => '已开通', 'statuses' => [CourierOnboarding::STATUS_ACTIVATED]],
'closed' => ['label' => '已关闭', 'statuses' => [CourierOnboarding::STATUS_REJECTED, CourierOnboarding::STATUS_CANCELLED]],
'all' => ['label' => '全部', 'statuses' => []],
];
public function __construct(private readonly CourierOnboardingService $service)
{
}
public function page(): array
{
$group = (string) request()->query('group', 'pending');
$group = array_key_exists($group, self::STATUS_GROUPS) ? $group : 'pending';
$search = trim((string) request()->query('search', ''));
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
$data = [
'view' => 'business.pages.courier-payables.courier-onboarding',
'onboardingReady' => $this->service->ready(),
'onboardingGroup' => $group,
'onboardingSearch' => $search,
'onboardingGroups' => self::STATUS_GROUPS,
'onboardingCounts' => [],
'onboardingRows' => new LengthAwarePaginator([], 0, $limit),
];
if (! $data['onboardingReady']) {
return $data;
}
$counts = $this->service->statusCounts();
$data['onboardingCounts'] = collect(self::STATUS_GROUPS)
->map(static fn (array $config): int => $config['statuses'] === []
? array_sum($counts)
: array_sum(array_intersect_key($counts, array_flip($config['statuses']))))
->all();
$query = CourierOnboarding::query()->withCount('files');
$statuses = self::STATUS_GROUPS[$group]['statuses'];
if ($statuses !== []) {
$query->whereIn('status', $statuses);
}
if ($search !== '') {
$like = '%' . addcslashes($search, '%_\\') . '%';
$query->where(static function ($builder) use ($like): void {
foreach (['number', 'invite_label', 'company_full_name', 'network_name', 'courier_name', 'contact_name', 'contact_phone'] as $column) {
$builder->orWhere($column, 'like', $like);
}
});
}
$data['onboardingRows'] = $query->latest('updated_at')->latest('id')
->paginate($limit)
->withQueryString();
return $data;
}
/**
* 快递资料页「入驻快递」页签:已开通的入驻快递,作为新快递的主数据。
*/
public function activated(int $page, int $limit): LengthAwarePaginator
{
if (! $this->service->ready()) {
return new LengthAwarePaginator([], 0, $limit, $page);
}
$search = trim((string) request()->query('search', ''));
$query = CourierOnboarding::query()->where('status', CourierOnboarding::STATUS_ACTIVATED);
if ($search !== '') {
$like = '%' . addcslashes($search, '%_\\') . '%';
$query->where(static function ($builder) use ($like): void {
foreach (['courier_name', 'company_full_name', 'network_name', 'contact_name'] as $column) {
$builder->orWhere($column, 'like', $like);
}
});
}
return $query->latest('activated_at')->paginate($limit, ['*'], 'page', $page)->withQueryString();
}
}

View File

@ -1,314 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\CourierOnboarding;
use App\Models\Business\CourierOnboardingFile;
use App\Support\CourierRequoteService;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use Throwable;
/**
* 快递总览:工作平台(钉钉流程 → wp_express)和财务系统快递入驻按快递合成一行。
*
* 字段各有归属:快递代码、发货账号、ERP账户ID 归工作平台;主体、对公/对私账户、证照、报价、签署归财务系统。
* 两边先按入驻里关联的「工作平台快递代码」对,没关联的按系统快递名称对。
*/
final class CourierOverviewData
{
public const SOURCES = [
'erp_pending' => '待 ERP 开通',
'both' => '入驻 + 工作平台',
'onboarding' => '只有入驻',
'platform' => '只在工作平台(缺入驻资料)',
'mismatch' => '账户对不上',
];
private ?Collection $onboardingCache = null;
public function __construct(
private readonly CourierInformationMirrorRepository $mirror,
private readonly CourierRequoteService $requotes,
) {
}
/**
* @return array{rows:LengthAwarePaginator,counts:array<string,int>,platform_ready:bool}
*/
public function page(array $filters, int $page, int $perPage): array
{
$all = $this->rows();
$platformReady = $all['platform_ready'];
$rows = collect($all['rows']);
$counts = [
'all' => $rows->count(),
'both' => $rows->where('source', 'both')->count(),
'platform' => $rows->where('source', 'platform')->count(),
'onboarding' => $rows->where('source', 'onboarding')->count(),
'mismatch' => $rows->where('account_status', 'mismatch')->count(),
'erp_pending' => $rows->where('erp_status', 'pending')->count(),
];
$source = (string) ($filters['source'] ?? '');
if ($source === 'mismatch') {
$rows = $rows->where('account_status', 'mismatch');
} elseif ($source === 'erp_pending') {
$rows = $rows->where('erp_status', 'pending');
} elseif (array_key_exists($source, self::SOURCES)) {
$rows = $rows->where('source', $source);
}
$keyword = trim((string) ($filters['search'] ?? ''));
if ($keyword !== '') {
$rows = $rows->filter(static fn (array $row): bool => str_contains(
mb_strtolower($row['name'] . ' ' . ($row['expcode'] ?? '') . ' ' . ($row['onboarding']?->company_full_name ?? '')),
mb_strtolower($keyword),
));
}
$rows = $rows->values();
return [
'rows' => new LengthAwarePaginator(
$rows->forPage($page, $perPage)->values(),
$rows->count(),
$perPage,
$page,
['path' => request()->url(), 'query' => request()->except('page')],
),
'counts' => $counts,
'platform_ready' => $platformReady,
];
}
/**
* @return array{rows:list<array<string,mixed>>,platform_ready:bool}
*/
public function rows(): array
{
try {
$platform = $this->mirror->overviewSource();
} catch (Throwable $exception) {
report($exception);
$platform = null;
}
$onboardings = Schema::hasTable('business_courier_onboardings')
? CourierOnboarding::query()
->with('files')
->whereNotIn('status', [CourierOnboarding::STATUS_CANCELLED, CourierOnboarding::STATUS_REJECTED])
->latest('id')
->get()
: collect();
$byCode = $onboardings->filter(static fn (CourierOnboarding $o): bool => filled($o->workplatform_expcode))
->keyBy(static fn (CourierOnboarding $o): string => (string) $o->workplatform_expcode);
$byName = $onboardings->filter(static fn (CourierOnboarding $o): bool => filled($o->courier_name))
->keyBy(static fn (CourierOnboarding $o): string => CourierOnboarding::normalizeName($o->courier_name));
$used = [];
$rows = [];
foreach ($platform['express'] ?? [] as $express) {
$code = (string) $express->expcode;
$onboarding = $byCode->get($code) ?? $byName->get(CourierOnboarding::normalizeName($express->expname));
if ($onboarding !== null && isset($used[$onboarding->id])) {
$onboarding = null;
}
if ($onboarding !== null) {
$used[$onboarding->id] = true;
}
$rows[] = $this->row($onboarding, $express, $platform['accounts'][$code] ?? []);
}
foreach ($onboardings as $onboarding) {
if (! isset($used[$onboarding->id])) {
$rows[] = $this->row($onboarding, null, []);
}
}
usort($rows, static fn (array $a, array $b): int => [$a['sort'], $a['name']] <=> [$b['sort'], $b['name']]);
return ['rows' => $rows, 'platform_ready' => $platform !== null];
}
/**
* @param list<object> $accounts
* @return array<string,mixed>
*/
private function row(?CourierOnboarding $onboarding, ?object $express, array $accounts): array
{
$source = $onboarding && $express ? 'both' : ($express ? 'platform' : 'onboarding');
$platformNumbers = collect($accounts)
->map(static fn ($account): string => preg_replace('/\D+/', '', (string) ($account->account ?? '')))
->filter()
->values();
$onboardingNumbers = collect([$onboarding?->bank_account_number, $onboarding?->private_account_number])
->map(static fn ($number): string => preg_replace('/\D+/', '', (string) $number))
->filter()
->values();
$accountStatus = match (true) {
$source !== 'both' => null,
$platformNumbers->isEmpty() => 'platform_missing',
$onboardingNumbers->isEmpty() => 'onboarding_missing',
$onboardingNumbers->diff($platformNumbers)->isEmpty() => 'match',
$onboardingNumbers->intersect($platformNumbers)->isNotEmpty() => 'partial',
default => 'mismatch',
};
$required = $onboarding ? CourierOnboardingFile::requiredKindsFor($onboarding->entity_type) : [];
$kinds = $onboarding ? $onboarding->files->pluck('kind')->unique()->all() : [];
$missingFiles = array_values(array_diff($required, $kinds));
$effective = $onboarding && filled($onboarding->courier_name) && Schema::hasTable('business_courier_quote_versions')
? $this->requotes->effectiveVersion((string) $onboarding->courier_name)
: null;
// ERP 开通:入驻开通后等钉钉「新建快递」流程回填快递代码;工作平台老快递视为已开通。
$erpStatus = match (true) {
$onboarding === null => 'opened',
$onboarding->status !== CourierOnboarding::STATUS_ACTIVATED => 'na',
$onboarding->erp_opened_at !== null || $express !== null => 'opened',
default => 'pending',
};
$erpAccountId = $onboarding?->erp_account_id
?: collect($accounts)->pluck('erpAccountId')->filter()->unique()->implode(' / ');
return [
'erp_status' => $erpStatus,
'erp_account_id' => $erpAccountId ?: null,
'erp_source' => $onboarding?->erpSourceLabel() ?: ($express ? '工作平台' : null),
'name' => (string) ($express->expname ?? $onboarding?->courier_name ?? $onboarding?->company_full_name ?? ''),
'expcode' => $express?->expcode ?? $onboarding?->workplatform_expcode,
'source' => $source,
'sort' => match (true) {
$erpStatus === 'pending' => 0,
$accountStatus === 'mismatch' => 1,
$source === 'onboarding' => 2,
$source === 'both' => 3,
default => 4,
},
'platform' => $express,
'platform_accounts' => $accounts,
'onboarding' => $onboarding,
'account_status' => $accountStatus,
'missing_files' => array_map(static fn (string $kind): string => CourierOnboardingFile::labelFor($kind, $onboarding?->entity_type), $missingFiles),
'effective_version' => $effective?->version_code,
'linked_by' => $onboarding && $express ? ((string) $onboarding->workplatform_expcode === (string) $express->expcode ? 'code' : 'name') : null,
];
}
/**
* 「快递资料」表格右侧接上的入驻信息:本页工作平台快递按快递代码 / 系统快递名称对上的入驻,
* 以及还没进工作平台(待 ERP 开通、或停用工作平台后新入驻)的快递,放在第一页最前面。
*
* @param list<object> $expressRows 本页工作平台快递
* @return array{matches:array<string,array<string,mixed>>,extra:list<array<string,mixed>>}
*/
public function expressAppend(array $expressRows, int $page, string $nameKeyword = '', string $codeFilter = ''): array
{
$onboardings = $this->onboardings();
if ($onboardings->isEmpty()) {
return ['matches' => [], 'extra' => []];
}
$byCode = $onboardings->filter(static fn (CourierOnboarding $o): bool => filled($o->workplatform_expcode))
->keyBy(static fn (CourierOnboarding $o): string => (string) $o->workplatform_expcode);
$byName = $onboardings->filter(static fn (CourierOnboarding $o): bool => filled($o->courier_name))
->keyBy(static fn (CourierOnboarding $o): string => CourierOnboarding::normalizeName($o->courier_name));
$matches = [];
foreach ($expressRows as $express) {
$onboarding = $byCode->get((string) ($express->expcode ?? '')) ?? $byName->get(CourierOnboarding::normalizeName($express->expname ?? ''));
if ($onboarding !== null) {
$matches[(string) ($express->Id ?? $express->expcode)] = $this->onboardingInfo($onboarding, true);
}
}
$extra = [];
if ($page === 1) {
try {
$platform = $this->mirror->overviewSource();
} catch (Throwable) {
$platform = null;
}
$codes = collect($platform['express'] ?? [])->pluck('expcode')->map(static fn ($code): string => (string) $code)->flip();
$names = collect($platform['express'] ?? [])->pluck('expname')->map(static fn ($name): string => CourierOnboarding::normalizeName($name))->flip();
foreach ($onboardings as $onboarding) {
$inPlatform = (filled($onboarding->workplatform_expcode) && $codes->has((string) $onboarding->workplatform_expcode))
|| (filled($onboarding->courier_name) && $names->has(CourierOnboarding::normalizeName($onboarding->courier_name)));
if ($inPlatform) {
continue;
}
if ($codeFilter !== '' && strcasecmp((string) $onboarding->workplatform_expcode, $codeFilter) !== 0) {
continue;
}
if ($nameKeyword !== '' && ! str_contains(mb_strtolower((string) $onboarding->courier_name . ' ' . $onboarding->company_full_name), mb_strtolower($nameKeyword))) {
continue;
}
$extra[] = $this->onboardingInfo($onboarding, false);
}
}
return ['matches' => $matches, 'extra' => $extra];
}
/** 快递资料里选中的一行对应的入驻(先按快递公司代码,再按系统快递名称)。 */
public function infoFor(?string $code, ?string $name): ?array
{
$onboardings = $this->onboardings();
$onboarding = (filled($code) ? $onboardings->first(static fn (CourierOnboarding $o): bool => strcasecmp((string) $o->workplatform_expcode, (string) $code) === 0) : null)
?? (filled($name) ? $onboardings->first(static fn (CourierOnboarding $o): bool => CourierOnboarding::normalizeName($o->courier_name) === CourierOnboarding::normalizeName($name)) : null);
return $onboarding !== null ? $this->onboardingInfo($onboarding, true) : null;
}
/** @return Collection<int,CourierOnboarding> */
private function onboardings(): Collection
{
return $this->onboardingCache ??= Schema::hasTable('business_courier_onboardings')
? CourierOnboarding::query()
->with('files')
->whereNotIn('status', [CourierOnboarding::STATUS_CANCELLED, CourierOnboarding::STATUS_REJECTED])
->latest('id')
->get()
: collect();
}
/** @return array<string,mixed> */
private function onboardingInfo(CourierOnboarding $onboarding, bool $inPlatform): array
{
$required = CourierOnboardingFile::requiredKindsFor($onboarding->entity_type);
$missing = array_values(array_diff($required, $onboarding->files->pluck('kind')->unique()->all()));
$effective = filled($onboarding->courier_name) && Schema::hasTable('business_courier_quote_versions')
? $this->requotes->effectiveVersion((string) $onboarding->courier_name)
: null;
// 合同起止:协议签署里「合作合同」已签署的那份(最新一份)上填的合作期限。
$contract = app(\App\Support\CourierOnboardingService::class)->agreementSignatures($onboarding)
->first(static fn (\App\Models\Business\CourierAgreementSignature $signature): bool => $signature->document_type === 'cooperation-contract'
&& in_array($signature->status, [\App\Models\Business\CourierAgreementSignature::STATUS_COMPLETED, \App\Models\Business\CourierAgreementSignature::STATUS_ARCHIVED], true));
$contractPayload = $contract !== null && is_array($contract->payload) ? $contract->payload : [];
return [
'contract_start' => $contractPayload['cooperation_start_date'] ?? null,
'contract_end' => $contractPayload['cooperation_end_date'] ?? null,
'onboarding' => $onboarding,
'erp_status' => match (true) {
$onboarding->status !== CourierOnboarding::STATUS_ACTIVATED => 'na',
$inPlatform || $onboarding->erp_opened_at !== null => 'opened',
default => 'pending',
},
'checks' => $onboarding->accountChecks(),
'missing_files' => array_map(static fn (string $kind): string => CourierOnboardingFile::labelFor($kind, $onboarding->entity_type), $missing),
'effective_version' => $effective?->version_code,
];
}
public static function mask(?string $number): string
{
$digits = preg_replace('/\s+/', '', (string) $number);
return $digits === '' ? '' : '尾号 ' . mb_substr($digits, -4);
}
}

View File

@ -1,120 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
class CourierPayableSummaryFilter
{
/** @return array{date:string,person:string,courier:string,keyword:string} */
public function fromRequest(Request $request): array
{
$clean = static function (string $key, int $maxLength) use ($request): string {
$value = $request->query($key, '');
if (! is_scalar($value)) {
return '';
}
return mb_substr(trim((string) $value), 0, $maxLength);
};
return [
'date' => $clean('date', 50),
'person' => $clean('person', 100),
'courier' => $clean('courier', 100),
'keyword' => $clean('keyword', 191),
];
}
/** @param array{date:string,person:string,courier:string,keyword:string} $filters */
public function hasFilters(array $filters): bool
{
return collect($filters)->contains(static fn (string $value): bool => $value !== '');
}
/**
* @param Collection<int, mixed> $rows
* @param list<string> $headers
* @param array{date:string,person:string,courier:string,keyword:string} $filters
* @return Collection<int, mixed>
*/
public function apply(Collection $rows, array $headers, array $filters): Collection
{
if (! $this->hasFilters($filters)) {
return $rows;
}
$dateColumn = $this->columnIndex($headers, ['日期', '结算月份', '结算月', '月份']);
$personColumn = $this->columnIndex($headers, ['负责人', '责任人']);
$courierColumn = $this->columnIndex($headers, ['快递公司', '快递名称', '快递名', '快递']);
return $rows->filter(function (mixed $row) use ($filters, $dateColumn, $personColumn, $courierColumn): bool {
if (! is_array($row)) {
return false;
}
if (! $this->columnMatches($row, $dateColumn, $filters['date'])
|| ! $this->columnMatches($row, $personColumn, $filters['person'])
|| ! $this->columnMatches($row, $courierColumn, $filters['courier'])) {
return false;
}
if ($filters['keyword'] === '') {
return true;
}
foreach ($row as $value) {
if ($this->contains($value, $filters['keyword'])) {
return true;
}
}
return false;
});
}
/** @param list<string> $headers */
public function dateColumnIndex(array $headers): ?int
{
return $this->columnIndex($headers, ['日期', '结算月份', '结算月', '月份']);
}
/** @param list<string> $headers */
private function columnIndex(array $headers, array $aliases): ?int
{
$normalizedAliases = array_map(
static fn (string $alias): string => mb_strtolower(preg_replace('/[\\s ]+/u', '', $alias) ?? $alias),
$aliases,
);
foreach ($headers as $index => $header) {
$normalizedHeader = mb_strtolower(preg_replace('/[\\s ]+/u', '', trim((string) $header)) ?? trim((string) $header));
if (in_array($normalizedHeader, $normalizedAliases, true)) {
return (int) $index;
}
}
return null;
}
private function columnMatches(array $row, ?int $column, string $needle): bool
{
if ($needle === '') {
return true;
}
return $column !== null && $this->contains($row[$column] ?? '', $needle);
}
private function contains(mixed $value, string $needle): bool
{
if (! is_scalar($value) && ! $value instanceof \Stringable) {
return false;
}
return mb_stripos((string) $value, $needle, 0, 'UTF-8') !== false;
}
}

View File

@ -1,139 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Throwable;
/**
* 快递应付的两个汇总页 → 「交易单号 ⇒ 金额类取值」映射。
*
* 这些数据都是财务在「应付款项 › 快递应付 › 运费差 / 其他附加费汇总 / 退件费」页面上传的汇总快照
* (JSON 文件,不是数据库表),快递运费页面按交易单号把对应金额带出来展示。
* 快照重新导入后文件时间会变,缓存键跟着变,自动失效。
*/
class CourierPayableSummaryMap
{
/** 运费差:差异(结算运费-提供成本运费)。 */
public const PAGE_FREIGHT_DIFFERENCE = 'freight-difference';
/** 其他附加费汇总:金额。 */
public const PAGE_OTHER_SURCHARGE = 'other-surcharge-summary';
/** 退件费:结算金额(单号列叫「交易订单」)。 */
public const PAGE_RETURN_FEE = 'return-fee';
/**
* 汇总页 → [单号列的关键字候选, 取值列的关键字候选]。
*
* 各页表头写法不统一(「交易单号」/「交易订单」、「金额」/「结算金额」),
* 所以按候选顺序找:先全等匹配,再退化成包含匹配。
*/
private const PAGES = [
self::PAGE_FREIGHT_DIFFERENCE => [['交易单号', '交易订单'], ['差异', '金额']],
self::PAGE_OTHER_SURCHARGE => [['交易单号', '交易订单'], ['金额']],
self::PAGE_RETURN_FEE => [['交易订单', '交易单号'], ['结算金额', '金额']],
];
private const CACHE_MINUTES = 10;
public function __construct(private readonly CourierPayableSummaryStore $store) {}
/**
* @param string $page self::PAGE_* 之一
* @return array<string,string> 交易单号 => 金额(保留源文件里的原值字符串)
*/
public function map(int $companyId, string $page): array
{
if (! isset(self::PAGES[$page])) {
return [];
}
$disk = Storage::disk('uploads');
$path = $this->store->path($companyId, $page);
if (! $disk->exists($path)) {
return [];
}
// 文件时间戳进缓存键:财务重新导入运费差后不用等缓存过期。
$key = sprintf('courier-payable-summary-map:v1:%s:%d:%d', $page, $companyId, (int) $disk->lastModified($path));
return Cache::remember($key, now()->addMinutes(self::CACHE_MINUTES), function () use ($companyId, $page): array {
try {
return $this->build($companyId, $page);
} catch (Throwable $exception) {
report($exception);
return [];
}
});
}
/** @return array<string,string> */
private function build(int $companyId, string $page): array
{
$snapshot = $this->store->snapshot($companyId, $page);
if ($snapshot === null) {
return [];
}
[$orderHeaders, $valueHeaders] = self::PAGES[$page];
$headers = array_map(static fn ($value): string => trim((string) $value), (array) $snapshot['headers']);
$orderColumn = $this->columnIndex($headers, $orderHeaders);
$valueColumn = $this->columnIndex($headers, $valueHeaders);
if ($orderColumn === null || $valueColumn === null) {
return [];
}
$map = [];
foreach ((array) $snapshot['rows'] as $row) {
$orderNos = trim((string) ($row[$orderColumn] ?? ''));
if ($orderNos === '') {
continue;
}
$value = trim((string) ($row[$valueColumn] ?? ''));
if ($value === '') {
continue;
}
// 源表一个格子可能放多个交易单号(逗号分隔),逐个挂到同一个金额上。
foreach (explode(',', $orderNos) as $orderNo) {
$orderNo = trim($orderNo);
if ($orderNo !== '' && ! isset($map[$orderNo])) {
$map[$orderNo] = $value;
}
}
}
return $map;
}
/**
* 按表头名定位:候选顺序优先,每个候选先找完全相等的表头,再退化成包含匹配
* (例如「差异(结算运费-提供成本运费)」只能靠包含匹配)。
*
* @param list<string> $needles
*/
private function columnIndex(array $headers, array $needles): ?int
{
foreach ($needles as $needle) {
foreach ($headers as $index => $header) {
if ($header === $needle) {
return (int) $index;
}
}
}
foreach ($needles as $needle) {
foreach ($headers as $index => $header) {
if ($header !== '' && mb_strpos($header, $needle) !== false) {
return (int) $index;
}
}
}
return null;
}
}

View File

@ -1,264 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\StringValueBinder;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
use Throwable;
class CourierPayableSummaryStore
{
public const PAGES = [
'freight-difference' => '运费差',
'other-surcharge-summary' => '其他附加费汇总',
'return-fee' => '退件费',
];
private const MAX_COLUMNS = 200;
private const MAX_ROWS_BY_PAGE = [
'freight-difference' => 500_000,
'other-surcharge-summary' => 500_000,
'return-fee' => 500_000,
];
private const MAX_CELL_LENGTH = 10000;
public function title(string $page): string
{
abort_unless(isset(self::PAGES[$page]), 404);
return self::PAGES[$page];
}
public function maxRows(string $page): int
{
$this->title($page);
return self::MAX_ROWS_BY_PAGE[$page];
}
/**
* @return array{version:int,headers:list<string>,rows:list<list<string>>,source_name:string,imported_at:string,imported_by:int|null}|null
*/
public function snapshot(int $companyId, string $page): ?array
{
$this->title($page);
$path = $this->path($companyId, $page);
$disk = Storage::disk('uploads');
if (! $disk->exists($path)) {
return null;
}
try {
$snapshot = json_decode($disk->get($path), true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable $exception) {
report($exception);
throw new RuntimeException('courier_payable_summary_unreadable', previous: $exception);
}
if (! is_array($snapshot)
|| ! is_array($snapshot['headers'] ?? null)
|| ! is_array($snapshot['rows'] ?? null)) {
throw new RuntimeException('courier_payable_summary_invalid');
}
return $snapshot;
}
/** @return array{rows:int,columns:int} */
public function import(UploadedFile $file, int $companyId, string $page, ?int $userId): array
{
$this->title($page);
$valueBinder = Cell::getValueBinder();
Cell::setValueBinder(new StringValueBinder());
try {
$reader = IOFactory::createReaderForFile($file->getRealPath());
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file->getRealPath());
[$headers, $rows] = $this->readSpreadsheet($spreadsheet, $page);
} catch (ValidationException $exception) {
throw $exception;
} catch (Throwable $exception) {
throw ValidationException::withMessages([
'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。',
]);
} finally {
Cell::setValueBinder($valueBinder);
if (isset($spreadsheet)) {
$spreadsheet->disconnectWorksheets();
}
}
$payload = json_encode([
'version' => 1,
'headers' => $headers,
'rows' => $rows,
'source_name' => mb_substr($file->getClientOriginalName(), 0, 255),
'imported_at' => now()->toIso8601String(),
'imported_by' => $userId,
], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
$disk = Storage::disk('uploads');
$path = $this->path($companyId, $page);
$previousPath = $this->previousPath($companyId, $page);
if ($disk->exists($path)) {
$previous = $disk->get($path);
if (! $disk->put($previousPath, $previous)) {
throw new RuntimeException('无法备份当前汇总数据。');
}
}
if (! $disk->put($path, $payload)) {
throw new RuntimeException('无法保存汇总数据。');
}
return ['rows' => count($rows), 'columns' => count($headers)];
}
public function path(int $companyId, string $page): string
{
$this->title($page);
return "courier-payable-summaries/{$companyId}/{$page}.json";
}
private function previousPath(int $companyId, string $page): string
{
return "courier-payable-summaries/{$companyId}/{$page}.previous.json";
}
/** @return array{0:list<string>,1:list<list<string>>} */
private function readSpreadsheet($spreadsheet, string $page): array
{
$maxRows = $this->maxRows($page);
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$rawRows = $worksheet->toArray(null, false, true, false);
$headerIndex = $this->headerIndex($rawRows);
if ($headerIndex === null) {
continue;
}
$lastColumn = $this->lastUsedColumn($rawRows, $headerIndex);
if ($lastColumn >= self::MAX_COLUMNS) {
throw ValidationException::withMessages([
'import' => '单个汇总表最多支持 ' . self::MAX_COLUMNS . ' 列。',
]);
}
$headers = [];
for ($column = 0; $column <= $lastColumn; $column++) {
$label = $this->cell($rawRows[$headerIndex][$column] ?? null);
$headers[] = $label !== '' ? $label : '未命名列' . ($column + 1);
}
$rows = [];
foreach (array_slice($rawRows, $headerIndex + 1) as $rawRow) {
$row = [];
$hasValue = false;
for ($column = 0; $column <= $lastColumn; $column++) {
$value = $this->cell($rawRow[$column] ?? null);
$row[] = $value;
$hasValue = $hasValue || $value !== '';
}
if (! $hasValue) {
continue;
}
$rows[] = $row;
if (count($rows) > $maxRows) {
throw ValidationException::withMessages([
'import' => '单次最多导入 ' . number_format($maxRows) . ' 条汇总数据,请拆分文件后重试。',
]);
}
}
if ($rows === []) {
throw ValidationException::withMessages(['import' => '表格中没有可导入的数据行。']);
}
return [$headers, $rows];
}
throw ValidationException::withMessages(['import' => '没有找到有效的表头和数据。']);
}
private function headerIndex(array $rows): ?int
{
$firstNonEmpty = null;
foreach (array_slice($rows, 0, 20, true) as $index => $row) {
$count = count(array_filter(
$row,
fn (mixed $value): bool => $this->cell($value) !== '',
));
if ($count === 0) {
continue;
}
$firstNonEmpty ??= $index;
if ($count >= 2) {
return $index;
}
}
return $firstNonEmpty;
}
private function lastUsedColumn(array $rows, int $headerIndex): int
{
$lastColumn = -1;
foreach (array_slice($rows, $headerIndex) as $row) {
foreach ($row as $column => $value) {
if ($this->cell($value) !== '') {
$lastColumn = max($lastColumn, (int) $column);
}
}
}
return max($lastColumn, 0);
}
private function cell(mixed $value): string
{
if ($value === null) {
return '';
}
if (is_bool($value)) {
return $value ? '是' : '否';
}
if (! is_scalar($value) && ! $value instanceof \Stringable) {
return '';
}
$value = trim((string) $value);
if (mb_strlen($value) > self::MAX_CELL_LENGTH) {
throw ValidationException::withMessages(['import' => '单元格内容过长,请精简后重试。']);
}
return $value;
}
}

View File

@ -1,382 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\CourierAgreementSignature;
use App\Models\Business\CourierOnboarding;
use App\Models\Business\CourierPaymentAccount;
use App\Models\Business\CourierProfile;
use App\Models\Business\CourierProfileEvent;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* 快递资料在财务系统这一侧的数据:编辑覆盖值、打款信息(入驻对公/对私 + 新增/变更记录)、操作日志。
* 工作平台镜像只读,这里的数据都存在财务系统自己的表里。
*/
final class CourierProfileData
{
/** @return array<string,array<string,mixed>> 快递代码 => 覆盖值 */
public function overrides(array $codes): array
{
$codes = array_values(array_unique(array_filter(array_map('strval', $codes), 'filled')));
if ($codes === [] || ! Schema::hasTable('business_courier_profiles')) {
return [];
}
return CourierProfile::query()->whereIn('expcode', $codes)->get()
->mapWithKeys(static fn (CourierProfile $profile): array => [(string) $profile->expcode => (array) $profile->overrides])
->all();
}
/** 把覆盖值盖到快递资料行上,`_overridden` 记下改过的字段。 */
public function apply(object $row, array $overrides): object
{
$row = clone $row;
$changed = [];
foreach ($overrides as $field => $value) {
if (array_key_exists($field, CourierProfile::EDITABLE)) {
$row->{$field} = $value;
$changed[] = $field;
}
}
$row->_overridden = $changed;
return $row;
}
/** 财务系统入驻(还没有工作平台记录)的快递,按快递资料的列铺成一行。 */
public function onboardingRow(array $info): object
{
/** @var CourierOnboarding $onboarding */
$onboarding = $info['onboarding'];
return (object) [
'Id' => null,
'expcode' => $onboarding->workplatform_expcode,
'expname' => $onboarding->courier_name,
'paymethod' => $onboarding->settlement_cycle,
'status' => $onboarding->status === CourierOnboarding::STATUS_ACTIVATED ? '1' : '0',
'kuaiyunsgn' => $onboarding->service_type === '快运' ? '1' : '0',
'tradebtime' => $info['contract_start'] ?? null,
'tradeetime' => $info['contract_end'] ?? null,
'linker' => $onboarding->contact_name,
'linkmobile' => $onboarding->contact_phone,
'dzqzjbr' => $onboarding->esign_account,
'undefined3' => $onboarding->deduction_method,
'modified' => $onboarding->updated_at?->toDateTimeString(),
'_onboarding_only' => true,
'_info' => $info,
];
}
/** 按快递公司代码取当前显示的一行主信息(工作平台镜像优先,没有则用财务系统入驻),已盖上编辑覆盖值。 */
public function currentRow(string $code): ?object
{
$mirror = app(\Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository::class);
$overview = app(CourierOverviewData::class);
$row = null;
try {
if ($mirror->available() && $mirror->ready()) {
$found = $mirror->paginate(array_merge(
array_fill_keys(['expname', 'undefined1', 'undefined2', 'undefined3', 'tradebtime_from', 'tradebtime_to', 'status'], ''),
['expcode' => $code],
), 1, 1)['data'][0] ?? null;
if ($found !== null) {
$row = clone $found;
$row->_info = $overview->infoFor($code, $found->expname ?? null);
}
}
} catch (Throwable $exception) {
report($exception);
}
if ($row === null && ($info = $overview->infoFor($code, null)) !== null) {
$row = $this->onboardingRow($info);
}
return $row !== null ? $this->apply($row, $this->overrides([$code])[$code] ?? []) : null;
}
/**
* 协议签署页预填:打款信息新增 → 收款账户证明;变更 → 收款账户变更。
*
* @return array<string,mixed>|null
*/
public static function agreementPrefill(mixed $id): ?array
{
if (! is_numeric($id) || ! Schema::hasTable('business_courier_payment_accounts')) {
return null;
}
$record = CourierPaymentAccount::query()->find((int) $id);
if ($record === null) {
return null;
}
$onboarding = app(CourierOverviewData::class)->infoFor($record->expcode, $record->courier_name)['onboarding'] ?? null;
$fields = $record->action === CourierPaymentAccount::ACTION_CHANGE
? [
'account_change_date' => $record->change_date?->toDateString(),
'old_account_name' => $record->old_account_name,
'old_account_number' => $record->old_account_number,
'old_account_stop_date' => $record->old_stop_date?->toDateString(),
'new_account_effective_date' => $record->effective_date?->toDateString(),
'new_account_name' => $record->account_name,
'new_bank_name' => $record->bank_name,
'new_bank_account' => $record->account_number,
]
: [
'account_proof_effective_date' => $record->effective_date?->toDateString(),
'account_proof_account_name' => $record->account_name,
'account_proof_bank_name' => $record->bank_name,
'account_proof_bank_account' => $record->account_number,
];
if ($onboarding !== null && filled($onboarding->company_full_name)) {
$fields['counterparty_organization_name'] = $onboarding->company_full_name;
}
return [
'id' => $record->id,
'action' => $record->actionLabel(),
'courier_name' => $record->courier_name,
'expcode' => $record->expcode,
'document_type' => $record->documentType(),
'signer_type' => $onboarding !== null && $onboarding->entity_type === CourierOnboarding::ENTITY_PERSON ? 'person' : 'organization',
'esign_account' => $onboarding?->esign_account,
'fields' => array_filter($fields, static fn ($value): bool => filled($value)),
];
}
/** 快递资料右侧接的入驻字段(我方填写;扣款方式对齐到左边「扣款方式」列,不重复显示)。 */
public const APPENDED_PROFILE_FIELDS = [
'courier_category', 'cooperation_mode', 'courier_attribute', 'waybill_type', 'shipping_mode',
'need_logistics_check', 'workplatform_account', 'courier_email', 'network_code', 'network_region',
];
/** 工作平台的行:扣款方式没填时用入驻里我方填的。 */
public function fillFromOnboarding(object $row): object
{
$onboarding = $row->_info['onboarding'] ?? null;
if ($onboarding !== null && blank($row->undefined3 ?? null) && filled($onboarding->deduction_method)) {
$row = clone $row;
$row->undefined3 = $onboarding->deduction_method;
}
return $row;
}
/** 入驻里填的网点,按工作平台网点表的列铺成一行(排在网点明细最前面)。 */
public function onboardingNetwork(CourierOnboarding $onboarding): ?object
{
if (blank($onboarding->network_code) && blank($onboarding->network_name) && blank($onboarding->network_region)) {
return null;
}
return (object) [
'id' => '入驻 ' . $onboarding->number,
'expcode' => $onboarding->workplatform_expcode,
'netcode' => $onboarding->network_code,
'netname' => $onboarding->network_name,
'address' => $onboarding->network_region,
'linker' => $onboarding->contact_name,
'linkermobile' => $onboarding->contact_phone,
'status' => $onboarding->status === CourierOnboarding::STATUS_ACTIVATED ? '1' : '0',
'created' => $onboarding->created_at?->toDateTimeString(),
];
}
/** 保存编辑:只记和当前显示值不同的字段,并写一条操作日志。 */
public function update(string $expcode, ?string $courierName, object $current, array $values, int $userId): int
{
$profile = CourierProfile::query()->firstOrNew(['company_id' => company_id(), 'expcode' => $expcode]);
$overrides = (array) ($profile->overrides ?? []);
$changes = [];
foreach (CourierProfile::EDITABLE as $field => $label) {
if (! array_key_exists($field, $values)) {
continue;
}
$new = $this->normalize($field, $values[$field]);
$old = $this->normalize($field, $current->{$field} ?? null);
if ($new === $old) {
continue;
}
$overrides[$field] = $new;
$changes[$field] = ['label' => $label, 'old' => $old, 'new' => $new];
}
if ($changes === []) {
return 0;
}
$profile->fill([
'courier_name' => $courierName ?: $profile->courier_name,
'overrides' => $overrides,
'updated_by' => $userId,
]);
$profile->created_by ??= $userId;
$profile->save();
$this->log($expcode, 'edit', '修改 ' . implode('、', array_column($changes, 'label')), $changes, $userId);
return count($changes);
}
public function log(string $expcode, string $action, string $summary, ?array $changes, int $userId): void
{
CourierProfileEvent::query()->create([
'company_id' => company_id(),
'expcode' => $expcode,
'action' => $action,
'summary' => mb_substr($summary, 0, 500),
'changes' => $changes,
'created_by' => $userId,
]);
}
/** @return Collection<int,CourierProfileEvent> */
public function events(?string $expcode = null, int $limit = 100): Collection
{
if (! Schema::hasTable('business_courier_profile_events')) {
return collect();
}
return CourierProfileEvent::query()
->with('creator')
->when(filled($expcode), static fn ($query) => $query->where('expcode', $expcode))
->latest('id')
->limit($limit)
->get();
}
/**
* 财务系统这一侧的打款信息(完整显示):入驻时填的对公/对私账户 + 打款信息新增/变更记录。
*
* @return list<array<string,mixed>>
*/
public function financeAccounts(?string $expcode = null, ?CourierOnboarding $onboarding = null): array
{
$rows = [];
if (Schema::hasTable('business_courier_payment_accounts')) {
$records = CourierPaymentAccount::query()
->when(filled($expcode), static fn ($query) => $query->where('expcode', $expcode))
->latest('id')
->get();
foreach ($records as $record) {
$status = $this->paymentStatus($record);
$rows[] = [
'source' => $record->actionLabel(),
'expcode' => $record->expcode,
'courier_name' => $record->courier_name,
'type' => $record->account_type,
'name' => $record->account_name,
'bank' => $record->bank_name,
'number' => $record->account_number,
'effective_date' => $record->effective_date?->toDateString(),
'old' => $record->action === CourierPaymentAccount::ACTION_CHANGE
? trim($record->old_account_name . ' ' . $record->old_account_number) . ($record->old_stop_date ? '(' . $record->old_stop_date->toDateString() . ' 停用)' : '')
: null,
'status' => $status['label'],
'tone' => $status['tone'],
'erp_account_id' => null,
'created_at' => $record->created_at?->toDateTimeString(),
'record' => $record,
];
}
}
$onboardings = $onboarding !== null
? collect([$onboarding])
: (Schema::hasTable('business_courier_onboardings')
? CourierOnboarding::query()
->whereNotIn('status', [CourierOnboarding::STATUS_CANCELLED, CourierOnboarding::STATUS_REJECTED])
->when(filled($expcode), static fn ($query) => $query->where('workplatform_expcode', $expcode))
->latest('id')
->get()
: collect());
foreach ($onboardings as $item) {
$checks = $item->accountChecks();
foreach ([
['对公', $item->bank_account_name, $item->bank_name, $item->bank_account_number, $checks['corporate'] ?? null],
['对私', $item->private_account_name, $item->private_bank_name, $item->private_account_number, $checks['private'] ?? null],
] as [$type, $name, $bank, $number, $check]) {
if (! filled($name) && ! filled($number)) {
continue;
}
$rows[] = [
'source' => '快递入驻 ' . $item->number,
'expcode' => $item->workplatform_expcode,
'courier_name' => $item->courier_name,
'type' => $type,
'name' => $name,
'bank' => $bank,
'number' => $number,
'effective_date' => $item->activated_at?->toDateString(),
'old' => null,
'status' => $check === false ? ($type === '对公' ? '户名与营业执照主体不一致' : '收款人与法定代表人不一致') : $item->statusLabel(),
'tone' => $check === false ? 'is-bad' : ($item->status === CourierOnboarding::STATUS_ACTIVATED ? 'is-ok' : 'is-warn'),
'erp_account_id' => $item->erp_account_id,
'created_at' => $item->created_at?->toDateTimeString(),
'onboarding' => $item,
];
}
}
return $rows;
}
/**
* 打款信息新增/变更的状态:按协议签署里同一快递、同类文件、同一新账号的签署任务推导。
*
* @return array{label:string,tone:string,signature:?CourierAgreementSignature}
*/
public function paymentStatus(CourierPaymentAccount $record): array
{
$signature = null;
if (Schema::hasTable('business_courier_agreement_signatures') && filled($record->courier_name)) {
$field = $record->action === CourierPaymentAccount::ACTION_CHANGE ? 'new_bank_account' : 'account_proof_bank_account';
$number = $this->digits($record->account_number);
$signature = CourierAgreementSignature::query()
->where('courier_name', $record->courier_name)
->where('document_type', $record->documentType())
->where('created_at', '>=', $record->created_at)
->latest('id')
->get()
->first(function (CourierAgreementSignature $signature) use ($field, $number): bool {
try {
return $this->digits((string) data_get($signature->payload, $field)) === $number;
} catch (Throwable) {
return false;
}
});
}
return match (true) {
$signature === null => ['label' => '待推送协议', 'tone' => 'is-warn', 'signature' => null],
in_array($signature->status, [CourierAgreementSignature::STATUS_COMPLETED, CourierAgreementSignature::STATUS_ARCHIVED], true) => ['label' => '已生效', 'tone' => 'is-ok', 'signature' => $signature],
in_array($signature->status, [CourierAgreementSignature::STATUS_REVOKED, CourierAgreementSignature::STATUS_EXPIRED, CourierAgreementSignature::STATUS_REJECTED, CourierAgreementSignature::STATUS_FAILED], true) => ['label' => '签署未完成,需重新推送', 'tone' => 'is-bad', 'signature' => $signature],
default => ['label' => '签署中', 'tone' => 'is-warn', 'signature' => $signature],
};
}
private function digits(?string $value): string
{
return (string) preg_replace('/[\s\-]+/u', '', (string) $value);
}
private function normalize(string $field, mixed $value): ?string
{
if ($value === null) {
return null;
}
$value = trim((string) $value);
if ($value === '' || $value === '-') {
return null;
}
if (in_array($field, CourierProfile::BOOLEAN_FIELDS, true)) {
return in_array(strtolower($value), ['1', 'true', 'yes', 'y', '是'], true) ? '1' : '0';
}
if (in_array($field, CourierProfile::DATE_FIELDS, true)) {
return substr($value, 0, 10);
}
return $value;
}
}

View File

@ -1,151 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\CourierSurchargeAuditLog;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
/**
* 快递附加费维护审计日志的固定入口。
*
* 日志只保存当前公司、操作人和报价/类型的安全字段快照,不保存密码、
* Token、连接串或原始请求内容。
*/
class CourierSurchargeAuditLogRepository
{
/** @var array<string,string> */
private const FIELD_LABELS = [
'courier' => '快递名称',
'scope' => '快递归属',
'reconciler' => '对账人',
'supplier' => '供应商',
'types' => '附加费类型',
'mode' => '结算方式',
'standard' => '计价标准',
'condition' => '生效条件',
'effective_at' => '生效日期',
'remark' => '备注',
'status' => '状态',
'name' => '类型名称',
];
/** @var array<string,string> */
private const ACTION_LABELS = [
CourierSurchargeAuditLog::ACTION_CREATED => '新增',
CourierSurchargeAuditLog::ACTION_UPDATED => '更改',
CourierSurchargeAuditLog::ACTION_ACTIVATED => '启用',
CourierSurchargeAuditLog::ACTION_DEACTIVATED => '停用',
];
/** @var array<string,string> */
private const TARGET_LABELS = [
CourierSurchargeAuditLog::TARGET_QUOTE => '报价规则',
CourierSurchargeAuditLog::TARGET_TYPE => '附加费类型',
];
public function ready(): bool
{
try {
return Schema::hasTable((new CourierSurchargeAuditLog())->getTable());
} catch (QueryException) {
return false;
}
}
/** @param array<string,mixed> $changes */
public function record(
string $action,
string $targetType,
?int $targetId,
string $targetLabel,
array $changes,
int $actorId,
): CourierSurchargeAuditLog {
abort_unless($this->ready(), 503, '附加费操作日志数据表尚未完成迁移。');
abort_unless(array_key_exists($action, self::ACTION_LABELS), 422, '附加费日志动作不合法。');
abort_unless(array_key_exists($targetType, self::TARGET_LABELS), 422, '附加费日志对象不合法。');
return CourierSurchargeAuditLog::query()->create([
'company_id' => company_id(),
'actor_id' => $actorId ?: null,
'action' => $action,
'target_type' => $targetType,
'target_id' => $targetId,
'target_label' => mb_substr(trim($targetLabel), 0, 191),
'changes' => $changes,
]);
}
/**
* @return Collection<int,array<string,mixed>>
*/
public function recent(int $limit = 50): Collection
{
if (! $this->ready()) {
return collect();
}
try {
return CourierSurchargeAuditLog::query()
->with('actor')
->orderByDesc('id')
->limit(max(1, min($limit, 200)))
->get()
->map(fn (CourierSurchargeAuditLog $log): array => [
'id' => $log->id,
'occurred_at' => optional($log->created_at)->format('Y-m-d H:i:s') ?: '',
'actor_name' => $log->actor?->name ?: '系统',
'action' => $log->action,
'action_label' => self::ACTION_LABELS[$log->action] ?? $log->action,
'target_type' => $log->target_type,
'target_id' => $log->target_id,
'target_type_label' => self::TARGET_LABELS[$log->target_type] ?? $log->target_type,
'target_label' => $log->target_label,
'changes_label' => $this->changesLabel($log),
])
->values();
} catch (QueryException) {
return collect();
}
}
private function changesLabel(CourierSurchargeAuditLog $log): string
{
$changes = (array) $log->changes;
if ($log->action === CourierSurchargeAuditLog::ACTION_CREATED) {
return '新增记录';
}
if (in_array($log->action, [CourierSurchargeAuditLog::ACTION_ACTIVATED, CourierSurchargeAuditLog::ACTION_DEACTIVATED], true)) {
$before = data_get($changes, 'before.status');
$after = data_get($changes, 'after.status');
return sprintf('状态:%s → %s', $before ?: '—', $after ?: '—');
}
$before = (array) ($changes['before'] ?? []);
$after = (array) ($changes['after'] ?? []);
$parts = [];
foreach (array_unique(array_merge(array_keys($before), array_keys($after))) as $field) {
$old = $this->valueLabel($before[$field] ?? null);
$new = $this->valueLabel($after[$field] ?? null);
if ($old !== $new) {
$parts[] = sprintf('%s:%s → %s', self::FIELD_LABELS[$field] ?? $field, $old, $new);
}
}
return $parts === [] ? '未改变字段' : implode(';', $parts);
}
private function valueLabel(mixed $value): string
{
if (is_array($value)) {
return implode('、', array_map(static fn (mixed $item): string => (string) $item, $value));
}
$value = trim((string) $value);
return $value === '' ? '—' : $value;
}
}

View File

@ -2,12 +2,10 @@
namespace App\Business;
use App\Models\Business\CourierSurchargeAuditLog;
use App\Models\Business\CourierSurchargeQuote;
use App\Models\Business\CourierSurchargeType;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
@ -30,21 +28,14 @@ class CourierSurchargeQuoteRepository
public const SCOPES = ['自有快递', '代发仓'];
public function __construct(
private readonly CourierSurchargeTypeRepository $types,
private readonly CourierSurchargeAuditLogRepository $audits,
)
public function __construct(private readonly CourierSurchargeTypeRepository $types)
{
}
public function ready(): bool
{
try {
$table = (new CourierSurchargeQuote())->getTable();
return Schema::hasTable($table)
&& Schema::hasColumn($table, 'supplier')
&& $this->types->ready();
return Schema::hasTable((new CourierSurchargeQuote())->getTable()) && $this->types->ready();
} catch (QueryException) {
return false;
}
@ -67,7 +58,8 @@ class CourierSurchargeQuoteRepository
try {
$all = CourierSurchargeQuote::query()
->orderBy('id')
->orderByDesc('effective_at')
->orderByDesc('id')
->get();
} catch (QueryException) {
return [
@ -79,7 +71,7 @@ class CourierSurchargeQuoteRepository
}
$filtered = $all->filter(function (CourierSurchargeQuote $quote) use ($filters): bool {
foreach (['courier', 'scope', 'reconciler', 'supplier', 'mode'] as $key) {
foreach (['courier', 'scope', 'reconciler', 'mode'] as $key) {
if (($filters[$key] ?? '') !== '' && (string) $quote->{$key} !== $filters[$key]) {
return false;
}
@ -99,7 +91,6 @@ class CourierSurchargeQuoteRepository
$quote->courier,
$quote->scope,
$quote->reconciler,
(string) $quote->supplier,
$quote->typeLabel(),
$quote->mode,
$quote->standard,
@ -143,7 +134,6 @@ class CourierSurchargeQuoteRepository
'modes' => collect(self::MODES),
'scopes' => self::SCOPES,
'reconcilers' => $all->pluck('reconciler')->filter()->unique()->sort()->values(),
'suppliers' => $all->pluck('supplier')->filter()->unique()->sort()->values(),
'statuses' => ['已启用', '已停用'],
],
];
@ -161,147 +151,30 @@ class CourierSurchargeQuoteRepository
return $this->types->activeNames();
}
/** @param array<string,mixed> $data */
public function findImportDuplicate(array $data, bool $lockForUpdate = false): ?CourierSurchargeQuote
{
$query = CourierSurchargeQuote::query()
->where('company_id', company_id())
->where('courier', trim((string) $data['courier']))
->where('scope', trim((string) $data['scope']))
->where('reconciler', trim((string) $data['reconciler']))
->where('mode', trim((string) $data['mode']))
->where('condition', trim((string) $data['condition']))
->whereDate('effective_at', (string) $data['effective_at']);
$supplier = trim((string) ($data['supplier'] ?? ''));
$supplier === '' ? $query->whereNull('supplier') : $query->where('supplier', $supplier);
if ($lockForUpdate) {
$query->lockForUpdate();
}
$types = $this->normalizedTypes((array) $data['types']);
return $query->get()->first(
fn (CourierSurchargeQuote $quote): bool => $this->normalizedTypes((array) $quote->types) === $types,
);
}
/** @param array<string,mixed> $data */
public function importIdentity(array $data): string
{
return hash('sha256', json_encode([
trim((string) ($data['courier'] ?? '')),
trim((string) ($data['scope'] ?? '')),
trim((string) ($data['reconciler'] ?? '')),
trim((string) ($data['supplier'] ?? '')),
$this->normalizedTypes((array) ($data['types'] ?? [])),
trim((string) ($data['mode'] ?? '')),
trim((string) ($data['effective_at'] ?? '')),
trim((string) ($data['condition'] ?? '')),
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
/** @param array<string,mixed> $data */
public function create(array $data, int $userId): CourierSurchargeQuote
{
return DB::transaction(function () use ($data, $userId): CourierSurchargeQuote {
$quote = CourierSurchargeQuote::query()->create($this->attributes($data, $userId) + [
'status' => CourierSurchargeQuote::STATUS_ACTIVE,
'created_by' => $userId,
]);
$this->audits->record(
CourierSurchargeAuditLog::ACTION_CREATED,
CourierSurchargeAuditLog::TARGET_QUOTE,
(int) $quote->id,
$this->targetLabel($quote),
['after' => $this->snapshot($quote)],
$userId,
);
return $quote;
});
return CourierSurchargeQuote::query()->create($this->attributes($data, $userId) + [
'status' => CourierSurchargeQuote::STATUS_ACTIVE,
'created_by' => $userId,
]);
}
/** @param array<string,mixed> $data */
public function update(CourierSurchargeQuote $quote, array $data, int $userId): CourierSurchargeQuote
{
return DB::transaction(function () use ($quote, $data, $userId): CourierSurchargeQuote {
$before = $this->snapshot($quote);
$quote->update($this->attributes($data, $userId));
$fresh = $quote->fresh();
$quote->update($this->attributes($data, $userId));
$this->audits->record(
CourierSurchargeAuditLog::ACTION_UPDATED,
CourierSurchargeAuditLog::TARGET_QUOTE,
(int) $fresh->id,
$this->targetLabel($fresh),
['before' => $before, 'after' => $this->snapshot($fresh)],
$userId,
);
return $fresh;
});
return $quote->fresh();
}
public function setStatus(CourierSurchargeQuote $quote, string $status, int $userId): CourierSurchargeQuote
{
abort_unless(in_array($status, [CourierSurchargeQuote::STATUS_ACTIVE, CourierSurchargeQuote::STATUS_INACTIVE], true), 422, '报价规则状态不合法。');
return DB::transaction(function () use ($quote, $status, $userId): CourierSurchargeQuote {
$oldStatus = $quote->status;
$quote->forceFill(['status' => $status, 'updated_by' => $userId])->save();
$fresh = $quote->fresh();
$quote->forceFill(['status' => $status, 'updated_by' => $userId])->save();
if ($oldStatus !== $status) {
$this->audits->record(
$status === CourierSurchargeQuote::STATUS_ACTIVE
? CourierSurchargeAuditLog::ACTION_ACTIVATED
: CourierSurchargeAuditLog::ACTION_DEACTIVATED,
CourierSurchargeAuditLog::TARGET_QUOTE,
(int) $fresh->id,
$this->targetLabel($fresh),
[
'before' => ['status' => $this->statusLabel($oldStatus)],
'after' => ['status' => $this->statusLabel($status)],
],
$userId,
);
}
return $fresh;
});
}
private function targetLabel(CourierSurchargeQuote $quote): string
{
$type = $quote->typeLabel();
return trim(sprintf('%s%s', $quote->courier, $type === '' ? '' : ' · ' . $type));
}
/** @return array<string,mixed> */
private function snapshot(CourierSurchargeQuote $quote): array
{
return [
'courier' => $quote->courier,
'scope' => $quote->scope,
'reconciler' => $quote->reconciler,
'supplier' => $quote->supplier,
'types' => array_values((array) $quote->types),
'mode' => $quote->mode,
'standard' => $quote->standard,
'condition' => $quote->condition,
'effective_at' => optional($quote->effective_at)->format('Y-m-d'),
'status' => $this->statusLabel($quote->status),
'remark' => $quote->remark,
];
}
private function statusLabel(?string $status): string
{
return $status === CourierSurchargeQuote::STATUS_ACTIVE ? '已启用' : '已停用';
return $quote->fresh();
}
/** @param array<string,mixed> $data */
@ -312,7 +185,6 @@ class CourierSurchargeQuoteRepository
'courier' => trim((string) $data['courier']),
'scope' => trim((string) $data['scope']),
'reconciler' => trim((string) $data['reconciler']),
'supplier' => trim((string) ($data['supplier'] ?? '')) ?: null,
'types' => array_values(array_unique(array_map('strval', $data['types']))),
'mode' => trim((string) $data['mode']),
'standard' => trim((string) $data['standard']),
@ -323,18 +195,6 @@ class CourierSurchargeQuoteRepository
];
}
/** @param array<int,mixed> $types @return list<string> */
private function normalizedTypes(array $types): array
{
$types = array_values(array_unique(array_filter(array_map(
static fn (mixed $type): string => trim((string) $type),
$types,
))));
sort($types, SORT_STRING);
return $types;
}
/** @return array<string,mixed> */
private function present(CourierSurchargeQuote $quote): array
{
@ -344,7 +204,6 @@ class CourierSurchargeQuoteRepository
'courier' => $quote->courier,
'scope' => $quote->scope,
'reconciler' => $quote->reconciler,
'supplier' => $quote->supplier,
'types' => array_values((array) $quote->types),
'type' => $quote->typeLabel(),
'mode' => $quote->mode,
@ -368,7 +227,6 @@ class CourierSurchargeQuoteRepository
'modes' => collect(self::MODES),
'scopes' => self::SCOPES,
'reconcilers' => collect(),
'suppliers' => collect(),
'statuses' => ['已启用', '已停用'],
];
}

View File

@ -1,386 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\CourierSurchargeQuote;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
class CourierSurchargeQuoteWorkbookImporter
{
public const MAX_ROWS = 500;
public const DUPLICATE_SKIP = 'skip';
public const DUPLICATE_UPDATE = 'update';
public const HEADERS = [
'快递名称',
'快递归属',
'对账人',
'供应商',
'附加费类型',
'结算方式',
'计价标准',
'生效条件',
'生效日期',
'状态',
'备注',
];
public function __construct(private readonly CourierSurchargeQuoteRepository $quotes)
{
}
public function template(): StreamedResponse
{
$types = $this->quotes->activeTypeNames();
return response()->streamDownload(function () use ($types): void {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('附加费报价');
$sheet->fromArray(self::HEADERS, null, 'A1');
$lastColumn = Coordinate::stringFromColumnIndex(count(self::HEADERS));
$headerRange = 'A1:' . $lastColumn . '1';
$sheet->getStyle($headerRange)->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'D8D2C7']]],
]);
$sheet->getRowDimension(1)->setRowHeight(24);
$sheet->freezePane('A2');
$sheet->setAutoFilter($headerRange);
$widths = [18, 14, 14, 20, 24, 18, 30, 32, 14, 12, 30];
foreach ($widths as $index => $width) {
$column = Coordinate::stringFromColumnIndex($index + 1);
$sheet->getColumnDimension($column)->setWidth($width);
$sheet->getStyle($column . '2:' . $column . (self::MAX_ROWS + 1))
->getNumberFormat()
->setFormatCode('@');
}
$instructions = $spreadsheet->createSheet();
$instructions->setTitle('填写说明');
$instructions->fromArray([
['项目', '填写要求'],
['必填字段', '快递名称、快递归属、对账人、附加费类型、结算方式、计价标准、生效条件、生效日期、状态。'],
['供应商', '选填;没有供应商时保持空白。'],
['附加费类型', '多种类型使用“、”分隔;只能填写当前已启用类型。当前可选:' . implode('、', $types)],
['快递归属', '自有快递 或 代发仓。'],
['结算方式', implode('、', CourierSurchargeQuoteRepository::MODES)],
['生效日期', '使用 YYYY-MM-DD,例如 2026-09-22。'],
['状态', '已启用 或 已停用;也可填写 active 或 inactive。'],
['重复规则', '预览后必须明确选择跳过已有规则或更新已有规则,系统不会静默覆盖。'],
['单次上限', '最多 ' . self::MAX_ROWS . ' 条非空数据。'],
], null, 'A1');
$instructions->getStyle('A1:B1')->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']],
]);
$instructions->getColumnDimension('A')->setWidth(18);
$instructions->getColumnDimension('B')->setWidth(90);
$instructions->getStyle('A1:B10')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER)->setWrapText(true);
foreach (range(1, 10) as $row) {
$instructions->getRowDimension($row)->setRowHeight($row === 1 ? 24 : 34);
}
$spreadsheet->setActiveSheetIndex(0);
(new Xlsx($spreadsheet))->save('php://output');
$spreadsheet->disconnectWorksheets();
}, '附加费报价导入模板_' . now()->format('Ymd') . '.xlsx', [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Cache-Control' => 'private, no-store',
]);
}
/**
* @return array{
* rows:list<array{line:int,data:array<string,mixed>,display:array<string,string>,errors:list<string>,result:string,result_label:string,existing_id:?int}>,
* summary:array{total:int,valid:int,new:int,duplicate:int,invalid:int}
* }
*/
public function preview(UploadedFile $file): array
{
$extension = mb_strtolower($file->getClientOriginalExtension());
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
throw ValidationException::withMessages(['import' => '仅支持 xlsx、xls 或 csv 文件。']);
}
try {
$reader = IOFactory::createReader(match ($extension) {
'xlsx' => 'Xlsx',
'xls' => 'Xls',
'csv' => 'Csv',
});
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file->getRealPath());
$rows = $spreadsheet->getActiveSheet()->toArray(null, false, false, false);
} catch (Throwable) {
throw ValidationException::withMessages([
'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。',
]);
} finally {
if (isset($spreadsheet)) {
$spreadsheet->disconnectWorksheets();
}
}
$headers = array_map(fn (mixed $value): string => $this->text($value), $rows[0] ?? []);
while ($headers !== [] && end($headers) === '') {
array_pop($headers);
}
if ($headers !== self::HEADERS) {
throw ValidationException::withMessages([
'import' => '表头不正确。请下载最新模板,并保持 11 个字段名称及顺序不变。',
]);
}
$dataRows = [];
foreach (array_slice($rows, 1, null, true) as $index => $row) {
$row = array_slice(array_pad($row, count(self::HEADERS), null), 0, count(self::HEADERS));
if (collect($row)->every(fn (mixed $value): bool => $this->text($value) === '')) {
continue;
}
$dataRows[] = ['line' => $index + 1, 'values' => $row];
if (count($dataRows) > self::MAX_ROWS) {
throw ValidationException::withMessages([
'import' => '单次最多导入 ' . self::MAX_ROWS . ' 条非空数据,请拆分文件后重试。',
]);
}
}
if ($dataRows === []) {
throw ValidationException::withMessages(['import' => '表格中没有可预览的数据行。']);
}
$previewRows = array_map(fn (array $row): array => $this->normalizeRow($row['values'], $row['line']), $dataRows);
$signatures = [];
foreach ($previewRows as $index => $row) {
if ($row['errors'] === []) {
$signatures[$this->quotes->importIdentity($row['data'])][] = $index;
}
}
foreach ($signatures as $indexes) {
if (count($indexes) < 2) {
continue;
}
$lines = implode('、', array_map(fn (int $index): int => $previewRows[$index]['line'], $indexes));
foreach ($indexes as $index) {
$previewRows[$index]['errors'][] = '文件内规则重复(行号:' . $lines . ')。';
}
}
foreach ($previewRows as &$row) {
if ($row['errors'] !== []) {
$row['result'] = 'invalid';
$row['result_label'] = '校验失败';
continue;
}
$existing = $this->quotes->findImportDuplicate($row['data']);
$row['existing_id'] = $existing?->id;
$row['result'] = $existing ? 'duplicate' : 'new';
$row['result_label'] = $existing ? '已有规则' : '可新增';
}
unset($row);
$collection = collect($previewRows);
return [
'rows' => $previewRows,
'summary' => [
'total' => $collection->count(),
'valid' => $collection->where('result', '!=', 'invalid')->count(),
'new' => $collection->where('result', 'new')->count(),
'duplicate' => $collection->where('result', 'duplicate')->count(),
'invalid' => $collection->where('result', 'invalid')->count(),
],
];
}
/**
* @param list<array{line:int,data:array<string,mixed>,errors:list<string>}> $rows
* @return array{created:int,updated:int,skipped:int,total:int}
*/
public function commit(array $rows, string $duplicatePolicy, int $userId): array
{
if (! in_array($duplicatePolicy, [self::DUPLICATE_SKIP, self::DUPLICATE_UPDATE], true)) {
throw ValidationException::withMessages(['duplicate_policy' => '请选择已有规则的处理方式。']);
}
if ($rows === [] || count($rows) > self::MAX_ROWS || collect($rows)->contains(fn (array $row): bool => ($row['errors'] ?? []) !== [])) {
throw ValidationException::withMessages(['import' => '预览数据无效或包含错误,请重新上传文件。']);
}
$activeTypes = $this->quotes->activeTypeNames();
foreach ($rows as $row) {
$inactive = array_values(array_diff((array) ($row['data']['types'] ?? []), $activeTypes));
if ($inactive !== []) {
throw ValidationException::withMessages([
'import' => '附加费类型“' . implode('、', $inactive) . '”已停用或不存在,请重新预览。',
]);
}
}
$counts = ['created' => 0, 'updated' => 0, 'skipped' => 0, 'total' => count($rows)];
DB::transaction(function () use ($rows, $duplicatePolicy, $userId, &$counts): void {
foreach ($rows as $row) {
$data = $row['data'];
$status = $data['status'];
unset($data['status']);
$existing = $this->quotes->findImportDuplicate($data, true);
if ($existing && $duplicatePolicy === self::DUPLICATE_SKIP) {
$counts['skipped']++;
continue;
}
if ($existing) {
$quote = $this->quotes->update($existing, $data, $userId);
$counts['updated']++;
} else {
$quote = $this->quotes->create($data, $userId);
$counts['created']++;
}
if ($quote->status !== $status) {
$this->quotes->setStatus($quote, $status, $userId);
}
}
});
return $counts;
}
/** @return array{line:int,data:array<string,mixed>,display:array<string,string>,errors:list<string>,result:string,result_label:string,existing_id:?int} */
private function normalizeRow(array $values, int $line): array
{
$raw = array_combine(self::HEADERS, $values);
$display = [];
foreach ($raw as $header => $value) {
$display[$header] = $this->text($value);
}
$errors = [];
foreach (['快递名称', '快递归属', '对账人', '附加费类型', '结算方式', '计价标准', '生效条件', '生效日期', '状态'] as $header) {
if ($display[$header] === '') {
$errors[] = $header . '不能为空。';
}
}
$this->checkLength($display, '快递名称', 191, $errors);
$this->checkLength($display, '对账人', 100, $errors);
$this->checkLength($display, '供应商', 191, $errors);
$this->checkLength($display, '计价标准', 2000, $errors);
$this->checkLength($display, '生效条件', 2000, $errors);
$this->checkLength($display, '备注', 2000, $errors);
$types = array_values(array_unique(array_filter(array_map(
'trim',
preg_split('/[、,,;;]+/u', $display['附加费类型']) ?: [],
))));
if (count($types) > 50) {
$errors[] = '附加费类型最多 50 项。';
}
$validTypes = $this->quotes->validTypeNames();
$activeTypes = $this->quotes->activeTypeNames();
$unknownTypes = array_values(array_diff($types, $validTypes));
$inactiveTypes = array_values(array_diff(array_intersect($types, $validTypes), $activeTypes));
if ($unknownTypes !== []) {
$errors[] = '附加费类型不存在:' . implode('、', $unknownTypes) . '。';
}
if ($inactiveTypes !== []) {
$errors[] = '附加费类型已停用:' . implode('、', $inactiveTypes) . '。';
}
if ($display['快递归属'] !== '' && ! in_array($display['快递归属'], CourierSurchargeQuoteRepository::SCOPES, true)) {
$errors[] = '快递归属只能填写“自有快递”或“代发仓”。';
}
if ($display['结算方式'] !== '' && ! in_array($display['结算方式'], CourierSurchargeQuoteRepository::MODES, true)) {
$errors[] = '结算方式不在允许范围内。';
}
$effectiveAt = $this->date($raw['生效日期']);
if ($display['生效日期'] !== '' && $effectiveAt === null) {
$errors[] = '生效日期必须是有效的 YYYY-MM-DD 日期。';
}
$status = match (mb_strtolower($display['状态'])) {
'已启用', CourierSurchargeQuote::STATUS_ACTIVE => CourierSurchargeQuote::STATUS_ACTIVE,
'已停用', CourierSurchargeQuote::STATUS_INACTIVE => CourierSurchargeQuote::STATUS_INACTIVE,
default => null,
};
if ($display['状态'] !== '' && $status === null) {
$errors[] = '状态只能填写“已启用/active”或“已停用/inactive”。';
}
if ($effectiveAt !== null) {
$display['生效日期'] = $effectiveAt;
}
return [
'line' => $line,
'data' => [
'courier' => $display['快递名称'],
'scope' => $display['快递归属'],
'reconciler' => $display['对账人'],
'supplier' => $display['供应商'] !== '' ? $display['供应商'] : null,
'types' => $types,
'mode' => $display['结算方式'],
'standard' => $display['计价标准'],
'condition' => $display['生效条件'],
'effective_at' => $effectiveAt,
'status' => $status,
'remark' => $display['备注'],
],
'display' => $display,
'errors' => array_values(array_unique($errors)),
'result' => 'invalid',
'result_label' => '校验失败',
'existing_id' => null,
];
}
/** @param array<string,string> $values @param list<string> $errors */
private function checkLength(array $values, string $field, int $max, array &$errors): void
{
if (mb_strlen($values[$field]) > $max) {
$errors[] = $field . '不能超过 ' . $max . ' 个字符。';
}
}
private function date(mixed $value): ?string
{
if (is_numeric($value) && (float) $value > 0) {
try {
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d');
} catch (Throwable) {
return null;
}
}
$value = $this->text($value);
if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value, $matches)) {
return null;
}
return checkdate((int) $matches[2], (int) $matches[3], (int) $matches[1]) ? $value : null;
}
private function text(mixed $value): string
{
return trim(str_replace("\xEF\xBB\xBF", '', (string) ($value ?? '')));
}
}

View File

@ -2,12 +2,10 @@
namespace App\Business;
use App\Models\Business\CourierSurchargeAuditLog;
use App\Models\Business\CourierSurchargeQuote;
use App\Models\Business\CourierSurchargeType;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
@ -19,10 +17,6 @@ use Illuminate\Validation\ValidationException;
*/
class CourierSurchargeTypeRepository
{
public function __construct(private readonly CourierSurchargeAuditLogRepository $audits)
{
}
/** @var list<string> */
public const DEFAULT_NAMES = [
'退回费', '拦截费', '改地址', '异形件', '超长费',
@ -95,27 +89,14 @@ class CourierSurchargeTypeRepository
$sortOrder = ((int) CourierSurchargeType::query()->max('sort_order')) + 1;
return DB::transaction(function () use ($name, $sortOrder, $userId): CourierSurchargeType {
$type = CourierSurchargeType::query()->create([
'company_id' => company_id(),
'name' => $name,
'status' => CourierSurchargeType::STATUS_ACTIVE,
'sort_order' => $sortOrder,
'created_by' => $userId,
'updated_by' => $userId,
]);
$this->audits->record(
CourierSurchargeAuditLog::ACTION_CREATED,
CourierSurchargeAuditLog::TARGET_TYPE,
(int) $type->id,
$type->name,
['after' => ['name' => $type->name, 'status' => '已启用']],
$userId,
);
return $type;
});
return CourierSurchargeType::query()->create([
'company_id' => company_id(),
'name' => $name,
'status' => CourierSurchargeType::STATUS_ACTIVE,
'sort_order' => $sortOrder,
'created_by' => $userId,
'updated_by' => $userId,
]);
} catch (QueryException $exception) {
if ((int) $exception->getCode() === 23000) {
throw ValidationException::withMessages(['name' => '当前公司已有同名附加费类型。']);
@ -129,37 +110,12 @@ class CourierSurchargeTypeRepository
{
abort_unless(in_array($status, [CourierSurchargeType::STATUS_ACTIVE, CourierSurchargeType::STATUS_INACTIVE], true), 422, '附加费类型状态不合法。');
return DB::transaction(function () use ($type, $status, $userId): CourierSurchargeType {
$oldStatus = $type->status;
$type->forceFill([
'status' => $status,
'updated_by' => $userId,
])->save();
$fresh = $type->fresh();
$type->forceFill([
'status' => $status,
'updated_by' => $userId,
])->save();
if ($oldStatus !== $status) {
$this->audits->record(
$status === CourierSurchargeType::STATUS_ACTIVE
? CourierSurchargeAuditLog::ACTION_ACTIVATED
: CourierSurchargeAuditLog::ACTION_DEACTIVATED,
CourierSurchargeAuditLog::TARGET_TYPE,
(int) $fresh->id,
$fresh->name,
[
'before' => ['status' => $this->statusLabel($oldStatus)],
'after' => ['status' => $this->statusLabel($status)],
],
$userId,
);
}
return $fresh;
});
}
private function statusLabel(?string $status): string
{
return $status === CourierSurchargeType::STATUS_ACTIVE ? '已启用' : '已停用';
return $type->fresh();
}
private function ensureDefaults(int $companyId): void

View File

@ -1,160 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\FundForecast;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Schema;
class FundForecastPage
{
public const GROUPS = [
['key' => 'balance', 'label' => '余额', 'fields' => FundForecast::BALANCE_FIELDS],
['key' => 'income', 'label' => '收入', 'fields' => FundForecast::INCOME_FIELDS],
['key' => 'expense', 'label' => '支出', 'fields' => FundForecast::EXPENSE_FIELDS],
['key' => 'summary', 'label' => '汇总', 'fields' => FundForecast::SUMMARY_FIELDS],
];
public function data(Request $request): array
{
$filters = $this->filters($request);
if (! Schema::hasColumns('business_fund_forecast', ['company_name', 'balance_bank', 'gap_surplus'])) {
return $this->pendingData($request, $filters);
}
$base = FundForecast::query();
$this->applyFilters($base, $filters);
$scopeCounts = [
'all' => (clone $base)->count(),
'gap' => $this->applyScope(clone $base, 'gap')->count(),
'unreported' => $this->applyScope(clone $base, 'unreported')->count(),
'pending_review' => $this->applyScope(clone $base, 'pending_review')->count(),
];
$query = $this->applyScope(clone $base, $filters['view']);
$summaryQuery = clone $query;
$rows = $query
->orderByDesc('budget_month')
->orderBy('company_name')
->orderByDesc('id')
->paginate(50)
->withQueryString();
$labels = FundForecast::columnLabels();
$groups = array_map(function (array $group) use ($labels): array {
$group['columns'] = array_map(
fn (string $field): array => ['field' => $field, 'label' => $labels[$field]],
$group['fields'],
);
return $group;
}, self::GROUPS);
return [
'ready' => true,
'filters' => $filters,
'months' => FundForecast::query()->whereNotNull('budget_month')->where('budget_month', '<>', '')
->distinct()->orderByDesc('budget_month')->pluck('budget_month')->all(),
'regions' => FundForecast::query()->whereNotNull('region')->where('region', '<>', '')
->distinct()->orderBy('region')->pluck('region')->all(),
'rows' => $rows,
'groups' => $groups,
'scopeCounts' => $scopeCounts,
'summary' => [
'company_count' => (clone $summaryQuery)->whereNotNull('company_name')->where('company_name', '<>', '')
->distinct()->count('company_name'),
'balance_total' => $this->sumColumns(clone $summaryQuery, FundForecast::BALANCE_FIELDS),
'income_total' => (float) (clone $summaryQuery)->sum('forecast_month_income'),
'gap_surplus' => (float) (clone $summaryQuery)->sum('gap_surplus'),
],
];
}
private function pendingData(Request $request, array $filters): array
{
$labels = FundForecast::columnLabels();
$groups = array_map(function (array $group) use ($labels): array {
$group['columns'] = array_map(
fn (string $field): array => ['field' => $field, 'label' => $labels[$field]],
$group['fields'],
);
return $group;
}, self::GROUPS);
return [
'ready' => false,
'filters' => $filters,
'months' => [],
'regions' => [],
'rows' => new LengthAwarePaginator([], 0, 50, max((int) $request->query('page', 1), 1), [
'path' => $request->url(),
'query' => $request->query(),
]),
'groups' => $groups,
'scopeCounts' => ['all' => 0, 'gap' => 0, 'unreported' => 0, 'pending_review' => 0],
'summary' => ['company_count' => 0, 'balance_total' => 0.0, 'income_total' => 0.0, 'gap_surplus' => 0.0],
];
}
private function filters(Request $request): array
{
$month = trim((string) $request->query('budget_month', ''));
$month = preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) === 1 ? $month : '';
$status = trim((string) $request->query('report_status', ''));
$status = in_array($status, ['待填报', '待审核', '已审核'], true) ? $status : '';
$view = trim((string) $request->query('view', 'all'));
$view = in_array($view, ['all', 'gap', 'unreported', 'pending_review'], true) ? $view : 'all';
return [
'budget_month' => $month,
'region' => mb_substr(trim((string) $request->query('region', '')), 0, 64),
'report_status' => $status,
'company_name' => mb_substr(trim((string) $request->query('company_name', '')), 0, 191),
'view' => $view,
];
}
private function applyFilters(Builder $query, array $filters): void
{
if ($filters['budget_month'] !== '') {
$query->where('budget_month', $filters['budget_month']);
}
if ($filters['region'] !== '') {
$query->where('region', $filters['region']);
}
if ($filters['report_status'] !== '') {
$query->where('report_status', $filters['report_status']);
}
if ($filters['company_name'] !== '') {
$query->where('company_name', 'like', '%' . addcslashes($filters['company_name'], '%_\\') . '%');
}
}
private function applyScope(Builder $query, string $scope): Builder
{
return match ($scope) {
'gap' => $query->where(function (Builder $nested): void {
$nested->where('has_gap', true)->orWhere('gap_surplus', '<', 0);
}),
'unreported' => $query->where(function (Builder $nested): void {
$nested->whereNull('report_status')->orWhere('report_status', '待填报');
}),
'pending_review' => $query->where('report_status', '待审核'),
default => $query,
};
}
private function sumColumns(Builder $query, array $columns): float
{
return array_reduce(
$columns,
fn (float $sum, string $column): float => $sum + (float) (clone $query)->sum($column),
0.0,
);
}
}

View File

@ -1,90 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\FundForecast;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Symfony\Component\HttpFoundation\StreamedResponse;
class FundForecastTemplate
{
private const MAX_ROWS = 5000;
public function download(): StreamedResponse
{
$spreadsheet = $this->makeSpreadsheet();
return response()->streamDownload(function () use ($spreadsheet): void {
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(false);
$writer->save('php://output');
$spreadsheet->disconnectWorksheets();
}, '资金预测表-导入模板.xlsx', [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Cache-Control' => 'no-store, no-cache, must-revalidate',
]);
}
private function makeSpreadsheet(): Spreadsheet
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setTitle('资金预测表导入模板')->setSubject('资金预测表批量导入');
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('资金预测表');
$sheet->setShowGridlines(false);
$sheet->freezePane('C3');
$sheet->getRowDimension(1)->setRowHeight(26);
$sheet->getRowDimension(2)->setRowHeight(24);
$sheet->setCellValueExplicit('A1', '预测月份', DataType::TYPE_STRING);
$sheet->setCellValueExplicit('B1', '公司名称', DataType::TYPE_STRING);
$sheet->mergeCells('A1:A2');
$sheet->mergeCells('B1:B2');
$labels = FundForecast::columnLabels();
$columnIndex = 3;
foreach (FundForecastPage::GROUPS as $group) {
$startColumn = Coordinate::stringFromColumnIndex($columnIndex);
$endColumn = Coordinate::stringFromColumnIndex($columnIndex + count($group['fields']) - 1);
$sheet->setCellValueExplicit("{$startColumn}1", $group['label'], DataType::TYPE_STRING);
$sheet->mergeCells("{$startColumn}1:{$endColumn}1");
foreach ($group['fields'] as $field) {
$column = Coordinate::stringFromColumnIndex($columnIndex++);
$sheet->setCellValueExplicit("{$column}2", $labels[$field], DataType::TYPE_STRING);
$sheet->getColumnDimension($column)->setWidth(16);
}
}
$lastColumn = Coordinate::stringFromColumnIndex($columnIndex - 1);
$sheet->getColumnDimension('A')->setWidth(14);
$sheet->getColumnDimension('B')->setWidth(28);
$sheet->getStyle("A1:{$lastColumn}2")->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
$sheet->getStyle("A1:{$lastColumn}2")->getFont()->setBold(true);
$sheet->getStyle("A1:{$lastColumn}1")->getFont()->getColor()->setARGB('FFFFFFFF');
$sheet->getStyle("A1:{$lastColumn}1")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF856632');
$sheet->getStyle("A2:{$lastColumn}2")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFF7F0DE');
$sheet->getStyle("A1:{$lastColumn}2")->getBorders()->getAllBorders()
->setBorderStyle(Border::BORDER_THIN)->getColor()->setARGB('FFD8D2C7');
$sheet->getStyle('A3:A' . (self::MAX_ROWS + 2))->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
$sheet->getStyle('C3:AD' . (self::MAX_ROWS + 2))->getNumberFormat()->setFormatCode('#,##0.00');
for ($row = 3; $row <= self::MAX_ROWS + 2; $row++) {
$sheet->setCellValue("AA{$row}", "=SUM(C{$row}:H{$row})");
$sheet->setCellValue("AB{$row}", "=SUM(I{$row}:N{$row})");
$sheet->setCellValue("AC{$row}", "=SUM(O{$row}:Z{$row})");
$sheet->setCellValue("AD{$row}", "=AA{$row}+AB{$row}-AC{$row}");
$sheet->setCellValue("AE{$row}", "=IF(AD{$row}<0,\"是\",\"否\")");
}
return $spreadsheet;
}
}

View File

@ -1,162 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\FundForecast;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
class FundForecastWorkbookImporter
{
private const HEADER_FIELDS = [
'预策月份' => 'budget_month',
'预测月份' => 'budget_month',
'公司名称' => 'company_name',
'余额/银行' => 'balance_bank',
'余额/京东' => 'balance_jd',
'余额/抖音' => 'balance_douyin',
'余额/得物' => 'balance_dewu',
'余额/淘系支付宝' => 'balance_taobao_alipay',
'余额/微信' => 'balance_wechat',
'收入/京东' => 'income_jd',
'收入/抖音' => 'income_douyin',
'收入/得物' => 'income_dewu',
'收入/淘系支付宝' => 'income_taobao_alipay',
'收入/货款' => 'income_goods_payment',
'收入/其他收入' => 'income_other',
'支出/供应商货款' => 'expense_supplier_goods',
'支出/快递款' => 'expense_courier',
'支出/纸厂压贴' => 'expense_paper_lamination',
'支出/封边条' => 'expense_edge_band',
'支出/日常报销' => 'expense_daily_reimbursement',
'支出/淘宝红包' => 'expense_taobao_red_packet',
'支出/板材' => 'expense_board',
'支出/店铺充值' => 'expense_store_top_up',
'支出/种菜' => 'expense_planting',
'支出/工资' => 'expense_salary',
'支出/税金' => 'expense_tax',
'支出/店铺花费暂估10%' => 'expense_store_spend',
];
public function import(UploadedFile $file, int $companyId): array
{
$spreadsheet = IOFactory::load($file->getRealPath());
$worksheet = $spreadsheet->getSheet(0);
$rows = $worksheet->toArray(null, true, false, false);
$columnMap = $this->columnMap($rows[0] ?? [], $rows[1] ?? []);
foreach (['budget_month', 'company_name'] as $required) {
if (! in_array($required, $columnMap, true)) {
throw ValidationException::withMessages([
'import' => '资金预测表缺少“预测月份”或“公司名称”表头。',
]);
}
}
$created = 0;
$updated = 0;
DB::transaction(function () use ($rows, $columnMap, $companyId, &$created, &$updated): void {
foreach (array_slice($rows, 2) as $offset => $row) {
if (collect($row)->every(fn ($value): bool => $value === null || trim((string) $value) === '')) {
continue;
}
$rowNumber = $offset + 3;
$data = [];
foreach ($columnMap as $columnIndex => $field) {
$data[$field] = $this->value($row[$columnIndex] ?? null, $field, $rowNumber);
}
if (($data['budget_month'] ?? '') === '' || ($data['company_name'] ?? '') === '') {
throw ValidationException::withMessages([
'import' => "第 {$rowNumber} 行必须填写预测月份和公司名称。",
]);
}
$identity = [
'company_id' => $companyId,
'budget_month' => $data['budget_month'],
'company_name' => $data['company_name'],
];
$record = FundForecast::query()->where($identity)->first();
$data['report_status'] = '待审核';
if ($record) {
$record->update($data);
$updated++;
} else {
FundForecast::create(array_merge($identity, $data));
$created++;
}
}
});
if ($created + $updated === 0) {
throw ValidationException::withMessages([
'import' => '表格中没有可导入的数据行。',
]);
}
return compact('created', 'updated');
}
private function columnMap(array $groups, array $headers): array
{
$map = [];
$group = '';
$count = max(count($groups), count($headers));
for ($index = 0; $index < $count; $index++) {
$candidate = trim((string) ($groups[$index] ?? ''));
if ($candidate !== '') {
$group = $candidate;
}
$header = trim((string) ($headers[$index] ?? ''));
$combined = $header === '' ? $group : ($group === '' ? $header : $group . '/' . $header);
$field = self::HEADER_FIELDS[$this->normalizeHeader($combined)] ?? null;
if ($field !== null) {
$map[$index] = $field;
}
}
return $map;
}
private function normalizeHeader(string $header): string
{
return preg_replace('/[\s_\-()()]+/u', '', trim($header));
}
private function value(mixed $value, string $field, int $rowNumber): mixed
{
if ($value === null || trim((string) $value) === '') {
return null;
}
if ($field === 'budget_month') {
if (is_numeric($value)) {
return ExcelDate::excelToDateTimeObject($value)->format('Y-m');
}
$text = trim((string) $value);
if (preg_match('/^(\d{4})[年\/.\-](\d{1,2})(?:月)?$/u', $text, $matches) === 1) {
$month = (int) $matches[2];
if ($month >= 1 && $month <= 12) {
return sprintf('%04d-%02d', (int) $matches[1], $month);
}
}
throw ValidationException::withMessages(['import' => "第 {$rowNumber} 行预测月份格式不正确。"]);
}
if ($field === 'company_name') {
return mb_substr(trim((string) $value), 0, 191);
}
$number = str_replace([',', ',', '¥', '¥'], '', trim((string) $value));
if (! is_numeric($number)) {
throw ValidationException::withMessages(['import' => "第 {$rowNumber} 行包含无效金额。"]);
}
return (float) $number;
}
}

View File

@ -1,237 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\InventoryWarehouseNameMapping;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
class InventoryInboundDetailImporter
{
private const TABLE = 'inventory_inbound_detail_rows';
/**
* Replace the imported inbound detail snapshot only after the workbook has
* been opened successfully. The delete and inserts share one transaction,
* so a malformed file cannot leave the page with a partially imported table.
*
* @return array{imported:int,mapped:int,skipped:int,total:int}
*/
public function import(string $file, string $forcedMonth = ''): array
{
$path = realpath($file);
if ($path === false || ! is_file($path) || ! is_readable($path)) {
throw new RuntimeException('入库明细文件不存在或不可读取。');
}
$forcedMonth = $this->normalizeForcedMonth($forcedMonth);
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$now = now();
$maps = $this->shortNameMap();
$reader = IOFactory::createReaderForFile($path);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($path);
$sheet = $spreadsheet->getSheet(0);
try {
return DB::connection($connection)->transaction(function () use (
$connection,
$sheet,
$maps,
$forcedMonth,
$now,
): array {
DB::connection($connection)->table(self::TABLE)->delete();
$batch = [];
$imported = 0;
$mapped = 0;
$skipped = 0;
foreach ($sheet->getRowIterator(2) as $row) {
$rowNumber = $row->getRowIndex();
$cells = [];
foreach ($row->getCellIterator('A', 'U') as $cell) {
$cells[] = $cell->getFormattedValue();
}
$warehouse = trim((string) ($cells[14] ?? ''));
$createdRaw = trim((string) ($cells[16] ?? ''));
if ($warehouse === '' && $createdRaw === '') {
$skipped++;
continue;
}
$month = $forcedMonth !== '' ? $forcedMonth : $this->monthOf($createdRaw);
if ($month === '') {
$skipped++;
continue;
}
// 代发仓按仓储方匹配;其它仓库按仓库名称做唯一匹配。
$shortName = '';
if ($warehouse !== '') {
$shortName = str_contains($warehouse, '代发仓')
? ($maps['provider'][$warehouse] ?? $maps['warehouse'][$warehouse] ?? '')
: ($maps['warehouse'][$warehouse] ?? '');
}
if ($shortName !== '') {
$mapped++;
}
$batch[] = [
'report_month' => $month,
'row_key' => sha1(substr($month, 0, 7) . '|' . $rowNumber),
'source_no' => $this->text($cells[0] ?? ''),
'document_no' => $this->text($cells[1] ?? ''),
'created_serial' => $this->text($cells[2] ?? ''),
'supplier' => $this->text($cells[3] ?? ''),
'item_no' => $this->text($cells[4] ?? ''),
'barcode' => $this->text($cells[5] ?? ''),
'spec_name' => $this->text($cells[6] ?? ''),
'quantity' => $this->number($cells[7] ?? ''),
'unit_price' => $this->number($cells[8] ?? ''),
'amount' => $this->number($cells[9] ?? ''),
'estimated_unit_price' => $this->number($cells[10] ?? ''),
'estimated_amount' => $this->number($cells[11] ?? ''),
'supplier_barcode' => $this->text($cells[12] ?? ''),
'remark' => $this->text($cells[13] ?? ''),
'warehouse' => $warehouse !== '' ? $warehouse : null,
'warehouse_short_name' => $shortName !== '' ? $shortName : null,
'created_at_raw' => $this->moment($createdRaw),
'express_name' => $this->text($cells[17] ?? ''),
'express_no' => $this->text($cells[18] ?? ''),
'not_sent' => $this->text($cells[19] ?? ''),
'owner_name' => $this->text($cells[20] ?? ''),
'imported_at' => $now,
];
$imported++;
if (count($batch) >= 1000) {
DB::connection($connection)->table(self::TABLE)->insertOrIgnore($batch);
$batch = [];
}
}
if ($batch !== []) {
DB::connection($connection)->table(self::TABLE)->insertOrIgnore($batch);
}
if ($imported === 0) {
throw new RuntimeException('入库明细文件中没有可导入的数据。');
}
return [
'imported' => $imported,
'mapped' => $mapped,
'skipped' => $skipped,
'total' => DB::connection($connection)->table(self::TABLE)->count(),
];
});
} finally {
$spreadsheet->disconnectWorksheets();
}
}
private function normalizeForcedMonth(string $month): string
{
$month = trim($month);
if ($month === '') {
return '';
}
if (preg_match('/^\d{4}-\d{2}$/', $month) === 1) {
return $month . '-01';
}
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $month) === 1) {
return $month;
}
throw new RuntimeException('指定月份格式应为 YYYY-MM。');
}
/** @return array{warehouse:array<string,string>,provider:array<string,string>} */
private function shortNameMap(): array
{
$rows = InventoryWarehouseNameMapping::withoutGlobalScopes()
->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']);
$grouped = [];
foreach ($rows as $row) {
$warehouse = trim((string) $row->warehouse);
if ($warehouse === '') {
continue;
}
$grouped[$warehouse][] = trim((string) $row->warehouse_short_name);
}
$byWarehouse = [];
foreach ($grouped as $warehouse => $names) {
$unique = array_values(array_unique($names));
if (count($unique) === 1 && $unique[0] !== '') {
$byWarehouse[$warehouse] = $unique[0];
}
}
$byProvider = [];
foreach ($rows as $row) {
$provider = trim((string) $row->warehouse_provider);
if ($provider !== '') {
$byProvider[$provider][] = trim((string) $row->warehouse_short_name);
}
}
foreach ($byProvider as $provider => $names) {
$unique = array_values(array_unique($names));
if (count($unique) === 1 && $unique[0] !== '') {
$byProvider[$provider] = $unique[0];
}
}
return ['warehouse' => $byWarehouse, 'provider' => $byProvider];
}
private function monthOf(string $value): string
{
$value = trim($value);
if ($value === '') {
return '';
}
foreach (['Y/m/d H:i:s', 'Y-m-d H:i:s', 'Y/m/d', 'Y-m-d'] as $format) {
$parsed = DateTimeImmutable::createFromFormat($format, $value);
if ($parsed instanceof DateTimeImmutable) {
return $parsed->format('Y-m') . '-01';
}
}
$timestamp = strtotime($value);
return $timestamp === false ? '' : date('Y-m-01', $timestamp);
}
private function moment(string $value): ?string
{
$value = trim($value);
if ($value === '') {
return null;
}
$timestamp = strtotime($value);
return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
}
private function text(mixed $value): ?string
{
$text = trim((string) $value);
return $text === '' ? null : $text;
}
private function number(mixed $value): ?float
{
$text = str_replace(',', '', trim((string) $value));
if ($text === '' || ! is_numeric($text)) {
return null;
}
return (float) $text;
}
}

View File

@ -1,213 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\InventoryWarehouseNameMapping;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
class InventoryWarehouseNameMappingWorkbookImporter
{
private const HEADERS = ['仓储方', '仓库', '仓库简称'];
/** @return array{rows:list<array>,sheet:string,headers:list<string>,summary:array} */
public function preview(UploadedFile $file): array
{
$spreadsheet = IOFactory::load($file->getRealPath());
$worksheet = $this->findWorksheet($spreadsheet);
if ($worksheet === null) {
throw ValidationException::withMessages([
'import' => '未找到包含“仓储方、仓库、仓库简称”三列的工作表。Sheet2 仅是辅助仓库清单,不能直接导入。',
]);
}
$rows = $worksheet->toArray(null, true, false, false);
$parsed = [];
$seen = [];
$created = 0;
$same = 0;
$conflicts = 0;
$invalid = 0;
foreach (array_slice($rows, 1) as $offset => $row) {
$rowNumber = $offset + 2;
$provider = trim((string) ($row[0] ?? ''));
$warehouse = trim((string) ($row[1] ?? ''));
$shortName = trim((string) ($row[2] ?? ''));
if ($provider === '' && $warehouse === '' && $shortName === '') {
continue;
}
$key = $this->key($provider, $warehouse);
$item = [
'row_number' => $rowNumber,
'warehouse_provider' => $provider,
'warehouse' => $warehouse,
'warehouse_short_name' => $shortName,
'status' => 'new',
'message' => '待新增',
];
if ($provider === '' || $warehouse === '' || $shortName === '') {
$item['status'] = 'invalid';
$item['message'] = '仓储方、仓库、仓库简称均为必填字段';
$invalid++;
} elseif (isset($seen[$key])) {
$item['status'] = $seen[$key]['warehouse_short_name'] === $shortName ? 'same' : 'conflict';
$item['message'] = $item['status'] === 'same'
? '与文件内前一行重复,将跳过'
: '与文件内前一行的仓库简称冲突';
$item['status'] === 'same' ? $same++ : $conflicts++;
} else {
$existing = InventoryWarehouseNameMapping::query()
->where('warehouse_provider', $provider)
->where('warehouse', $warehouse)
->first();
if ($existing) {
$item['status'] = $existing->warehouse_short_name === $shortName ? 'same' : 'conflict';
$item['message'] = $item['status'] === 'same'
? '数据库已有相同映射,将跳过'
: '数据库已有不同简称,禁止静默覆盖';
$item['status'] === 'same' ? $same++ : $conflicts++;
} else {
$created++;
}
}
$parsed[] = $item;
if ($provider !== '' && $warehouse !== '' && $shortName !== '' && ! isset($seen[$key])) {
$seen[$key] = $item;
}
}
return [
'rows' => $parsed,
'sheet' => $worksheet->getTitle(),
'headers' => self::HEADERS,
'summary' => compact('created', 'same', 'conflicts', 'invalid'),
];
}
/** @param array{rows:list<array>} $preview */
public function commit(array $preview): array
{
$rows = $preview['rows'] ?? [];
$invalid = collect($rows)->first(fn (array $row): bool => in_array($row['status'] ?? '', ['invalid', 'conflict'], true));
if ($invalid !== null) {
throw ValidationException::withMessages([
'import' => '导入预览存在必填字段错误或简称冲突,请先处理标记为失败的行。',
]);
}
$created = 0;
$skipped = 0;
DB::transaction(function () use ($rows, &$created, &$skipped): void {
foreach ($rows as $row) {
if (($row['status'] ?? '') === 'same') {
$skipped++;
continue;
}
$query = InventoryWarehouseNameMapping::query()
->where('warehouse_provider', $row['warehouse_provider'])
->where('warehouse', $row['warehouse']);
if ($query->exists()) {
throw ValidationException::withMessages([
'import' => "第 {$row['row_number']} 行在确认时已被其他操作占用,请重新预览。",
]);
}
InventoryWarehouseNameMapping::create([
'company_id' => company_id() ?: 1,
'warehouse_provider' => $row['warehouse_provider'],
'warehouse' => $row['warehouse'],
'warehouse_short_name' => $row['warehouse_short_name'],
'created_by' => auth()->id(),
'updated_by' => auth()->id(),
]);
$created++;
}
});
return compact('created', 'skipped');
}
public static function suggestion(string $provider, string $warehouse): string
{
$provider = trim($provider);
$warehouse = trim($warehouse);
$haystack = $provider . ' ' . $warehouse;
if (str_starts_with($provider, '奇门-')) {
return '不看';
}
foreach ([
'配件单仓' => '配件单仓-不看',
'POP仓' => '京东入仓-不看',
'自动发货仓' => '虚拟仓-不看',
'京东云仓' => '京东云仓-不看',
'京东京造' => '京东京造-不看',
'苏州福利品仓' => '苏州福利品仓-不看',
'信誉订单仓' => '信誉订单仓-不看',
'代发仓' => '代发仓',
'销退仓' => '销退仓-不看',
'客退' => '客退仓-不看',
'次品仓' => '退货报废-不看',
'数量校验仓' => '数量校验仓-不看',
] as $needle => $result) {
if (str_contains($haystack, $needle)) {
return $result;
}
}
foreach ([
'运营C崔桥工厂仓' => '崔桥工厂仓',
'运营C横林二仓' => '横林二仓',
'运营C睢宁' => '睢宁仓',
'运营C新苏北' => '新苏北仓',
'江西仓送货' => '南昌樵舍仓',
] as $needle => $result) {
if (str_contains($haystack, $needle)) {
return $result;
}
}
$short = preg_replace('/(主仓|进货仓)$/u', '', $warehouse) ?: $warehouse;
$short = preg_replace('/^(简尚-|京仓-|三方-|奇门-)/u', '', $short) ?: $short;
$providerBase = preg_replace('/^(简尚-|京仓-|三方-|奇门-)/u', '', $provider) ?: $provider;
if ($short === $providerBase || str_starts_with($short, $providerBase)) {
$short = $providerBase;
}
return $short !== '' ? $short : $warehouse;
}
private function findWorksheet($spreadsheet): ?object
{
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$row = $worksheet->toArray(null, true, false, false)[0] ?? [];
$headers = array_map(fn ($value): string => $this->normalize((string) $value), $row);
$expected = array_map(fn ($value): string => $this->normalize($value), self::HEADERS);
if (count(array_intersect($expected, $headers)) === count($expected)) {
return $worksheet;
}
}
return null;
}
private function normalize(string $value): string
{
return mb_strtolower(preg_replace('/[\s\x{FEFF}_\-()()]+/u', '', trim($value)));
}
private function key(string $provider, string $warehouse): string
{
return $provider . "\0" . $warehouse;
}
}

View File

@ -1,35 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\InventoryWarehouseNameMapping;
class InventoryWarehouseShortNames
{
/** @return array<string,string> */
public function forCompany(int $companyId): array
{
return InventoryWarehouseNameMapping::allCompanies()
->companyId($companyId)
->get(['warehouse_provider', 'warehouse', 'warehouse_short_name'])
->mapWithKeys(static fn (InventoryWarehouseNameMapping $mapping): array => [
self::key($mapping->warehouse_provider, $mapping->warehouse) => $mapping->warehouse_short_name,
])->all();
}
/** @param array<string,string> $names */
public function fill(object $row, array $names): object
{
$row->warehouse_short_name = $names[self::key(
(string) ($row->warehouse_provider ?? ''),
(string) ($row->warehouse ?? ''),
)] ?? '';
return $row;
}
private static function key(string $provider, string $warehouse): string
{
return $provider . "\0" . $warehouse;
}
}

View File

@ -1,367 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Database\DatabaseManager;
use InvalidArgumentException;
use RuntimeException;
/**
* 聚水潭订单标签明细导入(拆标签写入 jst_order_labels)。
*
* 一个标签一行:一单有 N 个标签就写 N 行;订单不去重、标签不汇总。
* 无标签的订单保留一行,标签记为「(无标签)」,方便与订单总数核对。
*
* 两个数据源:
* - 共享镜像 ops_jst_orders(常规,覆盖镜像有数据的区间);
* - 聚水潭「导出订单」Excel(镜像没有的历史区间,例如 2026-03,只能靠财务导出补)。
*/
class JstOrderLabelImporter
{
public const NO_LABEL = '(无标签)';
private const READ_CHUNK = 2000;
private const INSERT_CHUNK = 2000;
/** 聚水潭导出文件里用到的表头。 */
private const EXPORT_COLUMNS = ['线上订单号', '店铺名称', '下单时间', '标签'];
public function __construct(
private readonly DatabaseManager $databases,
private readonly ?XlsxSheetReader $exportReader = null,
private readonly ?JstOrderLabelItemCodes $itemCodes = null,
) {}
/**
* @return array{from:string,to:string,orders:int,rows:int,no_label_orders:int,labels:int,seconds:float}
*/
public function import(string $from, string $to, int $companyId = 1, bool $replace = false, string $source = 'jst-order-label-import'): array
{
$from = $this->normalizeDate($from, '起始日期');
$to = $this->normalizeDate($to, '结束日期');
if ($from > $to) {
throw new InvalidArgumentException('起始日期不能晚于结束日期。');
}
$start = $from . ' 00:00:00';
$end = date('Y-m-d', strtotime($to . ' +1 day')) . ' 00:00:00';
$mirror = $this->databases->connection(config('upstream_mirrors.connection', 'business_mirror'));
if (! $mirror->getSchemaBuilder()->hasTable('ops_jst_orders')) {
throw new RuntimeException('聚水潭订单镜像尚未建立(ops_jst_orders)。');
}
$target = $this->databases->connection();
$startedAt = microtime(true);
$itemCodes = $this->itemCodes ?? new JstOrderLabelItemCodes();
$hasItemTable = $mirror->getSchemaBuilder()->hasTable('ops_jst_order_item');
if ($replace) {
$target->table('jst_order_labels')
->where('company_id', $companyId)
->where('ordered_at', '>=', $start)
->where('ordered_at', '<', $end)
->delete();
app(PlantingOrderLabelLookup::class)->forget($companyId);
}
$now = now();
$orders = 0;
$rows = 0;
$noLabelOrders = 0;
$buffer = [];
$flush = function () use (&$buffer, &$rows, $target, $companyId): void {
foreach (array_chunk($buffer, self::INSERT_CHUNK) as $chunk) {
$target->table('jst_order_labels')->insert($chunk);
app(PlantingOrderLabelLookup::class)->forget($companyId);
$rows += count($chunk);
}
$buffer = [];
};
$mirror->table('ops_jst_orders')
->where('order_date', '>=', $start)
->where('order_date', '<', $end)
->orderBy('Id')
->chunkById(self::READ_CHUNK, function ($records) use (&$buffer, &$orders, &$noLabelOrders, $flush, $companyId, $source, $now, $itemCodes, $hasItemTable, $mirror): void {
// 货号:同批订单的商品编码(镜像商品明细,按 o_id 取),导入时一并写入
$orderCodes = $hasItemTable
? $itemCodes->forOrderIds($mirror, 'ops_jst_order_item', $records->pluck('o_id')->all())
: [];
foreach ($records as $record) {
$orders++;
$orderedAt = $record->order_date === null ? null : substr((string) $record->order_date, 0, 19);
if ($orderedAt === null || $orderedAt === '') {
continue;
}
$labels = $this->splitLabels((string) ($record->labels ?? ''));
if ($labels === []) {
$labels = [self::NO_LABEL];
$noLabelOrders++;
}
$itemCode = $orderCodes[(int) $record->o_id] ?? null;
foreach ($labels as $label) {
$buffer[] = [
'company_id' => $companyId,
'order_no' => mb_substr((string) $record->so_id, 0, 100),
'shop_name' => mb_substr((string) ($record->shop_name ?? ''), 0, 191),
'ordered_at' => $orderedAt,
'label' => $label,
'item_code' => $itemCode,
'created_from' => $source,
'created_at' => $now,
'updated_at' => $now,
];
}
if (count($buffer) >= self::INSERT_CHUNK * 2) {
$flush();
}
}
}, 'Id');
$flush();
$labels = $target->table('jst_order_labels')
->where('company_id', $companyId)
->where('ordered_at', '>=', $start)
->where('ordered_at', '<', $end)
->distinct()
->count('label');
// 导入会改变筛选选项,重新预热缓存,避免页面下次打开时做几秒的 distinct 扫描。
app(JstOrderLabelOptions::class)->forget($companyId);
app(JstOrderLabelOptions::class)->warm($companyId);
return [
'from' => $from,
'to' => $to,
'orders' => $orders,
'rows' => $rows,
'no_label_orders' => $noLabelOrders,
'labels' => (int) $labels,
'seconds' => round(microtime(true) - $startedAt, 1),
];
}
/**
* 从聚水潭「导出订单」Excel 导入。
*
* 导出文件是一单多行(商品明细),且同一单里可能只有部分明细行带标签:
* 第一遍先挑出真正有标签的订单号,第二遍再按「线上订单号 + 标签」去重拆行写入,
* 只对整单没标签的订单写「(无标签)」。同时兼容只勾 4 列导出的极简表头。
*
* 传 $from/$to 时会顺带按窗口过滤;带 $replace 时必须给窗口,
* 以便在写入前先清掉该区间,避免重复导入翻倍。
*
* @return array{file:string,company_id:int,from:?string,to:?string,orders:int,rows:int,no_label_orders:int,skipped:int,labels:int,seconds:float}
*/
public function importFromFile(
string $path,
?string $from = null,
?string $to = null,
int $companyId = 1,
bool $replace = false,
string $source = 'jst-order-label-file-import',
): array {
$from = $from === null || trim($from) === '' ? null : $this->normalizeDate(trim($from), '起始日期');
$to = $to === null || trim($to) === '' ? null : $this->normalizeDate(trim($to), '结束日期');
if ($from !== null && $to !== null && $from > $to) {
throw new InvalidArgumentException('起始日期不能晚于结束日期。');
}
if ($replace && ($from === null || $to === null)) {
throw new InvalidArgumentException('按文件导入并使用 --replace 时,必须同时给出 --from 与 --to,才能确定要清空的区间。');
}
$start = $from === null ? null : $from . ' 00:00:00';
$end = $to === null ? null : date('Y-m-d', strtotime($to . ' +1 day')) . ' 00:00:00';
$target = $this->databases->connection();
$startedAt = microtime(true);
// 清空区间推迟到第一次成功读到数据行之后:万一文件打不开或表头不对,
// 不能先把线上已有行删掉又导入失败。
$clearWindow = function () use ($target, $companyId, $start, $end): void {
$target->table('jst_order_labels')
->where('company_id', $companyId)
->where('ordered_at', '>=', $start)
->where('ordered_at', '<', $end)
->delete();
app(PlantingOrderLabelLookup::class)->forget($companyId);
};
$cleared = ! $replace;
$now = now();
$orders = 0;
$rows = 0;
$noLabelOrders = 0;
$skipped = 0;
$seen = [];
$orderSeen = [];
$buffer = [];
$flush = function () use (&$buffer, &$rows, $target, $companyId): void {
foreach (array_chunk($buffer, self::INSERT_CHUNK) as $chunk) {
$target->table('jst_order_labels')->insert($chunk);
app(PlantingOrderLabelLookup::class)->forget($companyId);
$rows += count($chunk);
}
$buffer = [];
};
$reader = $this->exportReader ?? app(XlsxSheetReader::class);
// 第一遍:挑出「有标签」的订单号。聚水潭导出是一单多行,同一单常常只有部分
// 明细行带标签;不按订单判断就会给本来有标签的订单多写一行「(无标签)」。
$labeledOrders = [];
$anyRow = false;
foreach ($reader->rows($path, self::EXPORT_COLUMNS) as $line) {
$anyRow = true;
if ($this->splitLabels((string) ($line['标签'] ?? '')) === []) {
continue;
}
$orderNo = trim((string) ($line['线上订单号'] ?? ''));
if ($orderNo !== '') {
$labeledOrders[$orderNo] = true;
}
}
if (! $anyRow) {
throw new RuntimeException('订单导出文件里没有数据行:' . basename($path));
}
if (! $cleared) {
$clearWindow();
$cleared = true;
}
// 第二遍:按「线上订单号 + 标签」去重后写入。
foreach ($reader->rows($path, self::EXPORT_COLUMNS) as $line) {
$orderNo = trim((string) ($line['线上订单号'] ?? ''));
$orderedAt = $this->normalizeOrderedAt((string) ($line['下单时间'] ?? ''));
if ($orderNo === '' || $orderedAt === null) {
$skipped++;
continue;
}
if ($start !== null && ($orderedAt < $start || $orderedAt >= $end)) {
$skipped++;
continue;
}
$labels = $this->splitLabels((string) ($line['标签'] ?? ''));
$withoutLabel = $labels === [];
if ($withoutLabel) {
if (isset($labeledOrders[$orderNo])) {
continue;
}
$labels = [self::NO_LABEL];
}
if (! isset($orderSeen[$orderNo])) {
$orderSeen[$orderNo] = true;
$orders++;
}
$shopName = mb_substr(trim((string) ($line['店铺名称'] ?? '')), 0, 191);
foreach ($labels as $label) {
$fingerprint = hash('xxh3', $orderNo . "\0" . $label);
if (isset($seen[$fingerprint])) {
continue;
}
$seen[$fingerprint] = true;
if ($withoutLabel) {
$noLabelOrders++;
}
$buffer[] = [
'company_id' => $companyId,
'order_no' => mb_substr($orderNo, 0, 100),
'shop_name' => $shopName,
'ordered_at' => $orderedAt,
'label' => $label,
'created_from' => $source,
'created_at' => $now,
'updated_at' => $now,
];
}
if (count($buffer) >= self::INSERT_CHUNK * 2) {
$flush();
}
}
$flush();
$labelQuery = $target->table('jst_order_labels')->where('company_id', $companyId);
if ($start !== null) {
$labelQuery->where('ordered_at', '>=', $start)->where('ordered_at', '<', $end);
}
$labels = $labelQuery->distinct()->count('label');
app(JstOrderLabelOptions::class)->forget($companyId);
app(JstOrderLabelOptions::class)->warm($companyId);
return [
'file' => basename($path),
'company_id' => $companyId,
'from' => $from,
'to' => $to,
'orders' => $orders,
'rows' => $rows,
'no_label_orders' => $noLabelOrders,
'skipped' => $skipped,
'labels' => (int) $labels,
'seconds' => round(microtime(true) - $startedAt, 1),
];
}
/** 下单时间归一成 Y-m-d H:i:s;解析不了就返回 null(该行跳过)。 */
private function normalizeOrderedAt(string $value): ?string
{
$value = trim($value);
if ($value === '') {
return null;
}
$timestamp = strtotime($value);
return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
}
/** @return list<string> */
private function splitLabels(string $labels): array
{
$out = [];
foreach (explode(',', $labels) as $label) {
$label = trim($label);
if ($label !== '') {
$out[] = mb_substr($label, 0, 191);
}
}
return array_values(array_unique($out));
}
private function normalizeDate(string $value, string $label): string
{
$value = trim($value);
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
throw new InvalidArgumentException($label . '必须是 YYYY-MM-DD。');
}
[$year, $month, $day] = array_map('intval', explode('-', $value));
if (! checkdate($month, $day, $year)) {
throw new InvalidArgumentException($label . '不是有效日期。');
}
return $value;
}
}

View File

@ -1,59 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Database\ConnectionInterface;
/**
* 订单「货号」查询:从聚水潭商品明细镜像按内部订单号取商品编码(sku_id)。
*
* 「被替换(Replaced)/取消(Cancelled、SentCancelled)」的明细行不算订单当前货号,
* 所以换过商品的订单(如信誉订单虚拟条码 X00006)只保留换入后的编码。
* 一单多个编码用英文逗号连接。
*/
class JstOrderLabelItemCodes
{
/** 商品明细状态:这些行不计入订单当前货号。 */
public const EXCLUDED_STATUSES = ['Replaced', 'Cancelled', 'SentCancelled'];
/**
* @param list<int|string> $orderIds 内部订单号(o_id)
* @return array<int,string> [内部订单号 => 货号]
*/
public function forOrderIds(ConnectionInterface $connection, string $itemsTable, array $orderIds): array
{
$orderIds = array_values(array_unique(array_filter(
array_map(static fn ($value): int => (int) $value, $orderIds),
static fn (int $value): bool => $value > 0,
)));
if ($orderIds === []) {
return [];
}
$rows = $connection->table($itemsTable)
->whereIn('o_id', $orderIds)
->where(function ($query): void {
$query->whereNull('item_status')
->orWhereNotIn('item_status', self::EXCLUDED_STATUSES);
})
->get(['o_id', 'sku_id']);
$skus = [];
foreach ($rows as $row) {
$sku = trim((string) $row->sku_id);
if ($sku === '') {
continue;
}
$skus[(int) $row->o_id][$sku] = true;
}
$codes = [];
foreach ($skus as $orderId => $list) {
$list = array_keys($list);
sort($list);
$codes[$orderId] = mb_substr(implode(',', $list), 0, 191);
}
return $codes;
}
}

View File

@ -1,99 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\JstOrderLabel;
use Illuminate\Support\Facades\Cache;
/**
* 聚水潭订单标签明细的筛选下拉选项。
*
* 表里有 200 万行以上,distinct 扫描一次要几秒;这里按公司缓存 24 小时,
* 导入命令结束时会主动预热,避免每次打开页面都慢。
*
* 上限只是防呆(选项过多会拖慢页面),要高于实际店铺数:2026-10 导入 4~7 月后
* 店铺已达 604 个,原来卡在 500 会让一部分店铺选不出来。
*/
class JstOrderLabelOptions
{
private const TTL_HOURS = 24;
private const TOTAL_TTL_MINUTES = 30;
private const LIMIT = 5000;
/** @return list<string> */
public function labels(int $companyId): array
{
return $this->remember($companyId, 'label');
}
/** @return list<string> */
public function shops(int $companyId): array
{
return $this->remember($companyId, 'shop_name');
}
public function warm(int $companyId): void
{
$this->labels($companyId);
$this->shops($companyId);
$this->total($companyId);
}
public function forget(int $companyId): void
{
Cache::forget($this->key($companyId, 'label'));
Cache::forget($this->key($companyId, 'shop_name'));
Cache::forget($this->totalKey($companyId));
}
/** 无筛选时的总行数:233 万行上 COUNT(*) 要 2 秒,缓存后翻页不再重复统计。 */
public function total(int $companyId): int
{
$key = $this->totalKey($companyId);
$cached = Cache::get($key);
if (is_numeric($cached)) {
return (int) $cached;
}
$count = (int) JstOrderLabel::query()->where('company_id', $companyId)->count();
Cache::put($key, $count, now()->addMinutes(self::TOTAL_TTL_MINUTES));
return $count;
}
/** @return list<string> */
private function remember(int $companyId, string $column): array
{
$key = $this->key($companyId, $column);
$cached = Cache::get($key);
if (is_array($cached)) {
return $cached;
}
$values = JstOrderLabel::query()
->where('company_id', $companyId)
->whereNotNull($column)
->where($column, '<>', '')
->distinct()
->orderBy($column)
->limit(self::LIMIT)
->pluck($column)
->all();
Cache::put($key, $values, now()->addHours(self::TTL_HOURS));
return $values;
}
private function key(int $companyId, string $column): string
{
return "jst-order-labels:options:v1:{$companyId}:{$column}";
}
private function totalKey(int $companyId): string
{
return "jst-order-labels:total:v1:{$companyId}";
}
}

View File

@ -1,92 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\JstOrderLabelPlantingRule;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* 聚水潭订单标签明细的「是否种菜订单」判断:
* - 按(公司 + 标签)匹配财务维护的映射表;
* - 订单货号含信誉订单虚拟条码(X00006)的直接判为「是」。
*
* 映射表由财务维护(判断种菜单.xlsx)并按公司缓存,页面与导出共用同一份结果;
* 映射表缺失或未导入时不报错,统一按「否」展示。
*/
class JstOrderLabelPlantingRules
{
private const TTL_HOURS = 24;
/** 该货号(信誉订单虚拟条码)的订单直接判为种菜订单。 */
public const PLANTING_ITEM_CODE = 'X00006';
/** @return array<string,string> [标签 => 是/否] */
public function map(int $companyId): array
{
return Cache::remember($this->key($companyId), now()->addHours(self::TTL_HOURS), function () use ($companyId): array {
try {
if (! Schema::hasTable('jst_order_label_planting_rules')) {
return [];
}
// 直接用表查询:避开基类的软删除/公司作用域与模型缓存,映射表由命令写入后立即失效重读
$map = [];
foreach (DB::table('jst_order_label_planting_rules')
->where('company_id', $companyId)
->get(['label', 'is_planting']) as $row) {
$label = trim((string) $row->label);
if ($label === '') {
continue;
}
$map[$label] = trim((string) $row->is_planting) === '否' ? '否' : '是';
}
return $map;
} catch (Throwable) {
return [];
}
});
}
/**
* 单条(标签 + 货号)的判断结果:标签命中映射表取其值;
* 货号含 X00006 的一律为「是」,其余未命中为「否」。
*/
public function flag(int $companyId, ?string $label, ?string $itemCode = null): string
{
$key = trim((string) $label);
$flag = $key === '' ? '否' : ($this->map($companyId)[$key] ?? '否');
if ($flag === '否' && $this->hasPlantingItemCode($itemCode)) {
return '是';
}
return $flag;
}
/** 货号(可能多个,逗号连接)里是否含信誉订单虚拟条码。 */
private function hasPlantingItemCode(?string $itemCode): bool
{
foreach (explode(',', (string) $itemCode) as $code) {
if (mb_strtoupper(trim($code)) === self::PLANTING_ITEM_CODE) {
return true;
}
}
return false;
}
public function forget(int $companyId): void
{
Cache::forget($this->key($companyId));
app(PlantingOrderLabelLookup::class)->forget($companyId);
}
private function key(int $companyId): string
{
return "jst-order-labels:planting-rules:v1:{$companyId}";
}
}

View File

@ -1,299 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\PlantingDetail;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use RuntimeException;
use Throwable;
/**
* 种菜明细表导入(xlsx / xls / csv)。
*
* 源表头与 planting_details 列一一对应;按表头名匹配,列顺序变化不影响。
* 日期兼容 Excel 序列号与常见字符串;金额按 4 位小数保存。
*/
class PlantingDetailImporter
{
/** 源表头 → 数据库列 */
private const COLUMNS = [
'日期' => 'bill_date',
'订单编号' => 'order_no',
'财务售价' => 'finance_selling_price',
'财务运费' => 'finance_freight',
'财务佣金' => 'finance_commission',
'京喜差价' => 'jingxi_price_diff',
'扣款' => 'deduction',
'财务空包费' => 'finance_empty_package_fee',
'财务打款金额' => 'finance_payment_amount',
'笔数' => 'pieces',
'备注' => 'remark',
'正确店铺' => 'store',
'负责人' => 'owner',
'账户' => 'account',
'类型' => 'type',
'创建人' => 'creator',
'标签' => 'tag',
'所属利润中心' => 'profit_center',
'负责平台' => 'responsible_platform',
'ID' => 'external_id',
];
private const MONEY_COLUMNS = [
'finance_selling_price', 'finance_freight', 'finance_commission',
'jingxi_price_diff', 'deduction', 'finance_empty_package_fee', 'finance_payment_amount',
];
private const CHUNK = 1000;
/**
* @return array{rows:int,inserted:int,skipped:int,selling_price:string,payment_amount:string,date_min:?string,date_max:?string}
*/
public function import(string $path, int $companyId = 1, bool $replace = false, ?int $userId = null, string $source = 'planting-detail-import'): array
{
if (! is_file($path)) {
throw new InvalidArgumentException('找不到要导入的文件:' . $path);
}
$grid = $this->read($path);
if ($grid === []) {
throw new InvalidArgumentException('文件里没有可读的数据行。');
}
$headerIndex = $this->locateHeader($grid);
if ($headerIndex === null) {
throw new InvalidArgumentException('没找到表头:至少要有「日期」「订单编号」「财务打款金额」。');
}
$map = $this->mapHeader($grid[$headerIndex]);
if (! isset($map['bill_date'], $map['order_no'], $map['finance_payment_amount'])) {
throw new InvalidArgumentException('表头缺少「日期」或「订单编号」或「财务打款金额」。');
}
$now = now();
$rows = [];
$skipped = 0;
$sellingPrice = 0.0;
$paymentAmount = 0.0;
$dateMin = null;
$dateMax = null;
$inserted = 0;
$connection = DB::connection();
if ($replace) {
PlantingDetail::query()->where('company_id', $companyId)->forceDelete();
}
$flush = function () use (&$rows, &$inserted, $connection): void {
if ($rows !== []) {
foreach (array_chunk($rows, self::CHUNK) as $chunk) {
$connection->table('planting_details')->insert($chunk);
$inserted += count($chunk);
}
$rows = [];
}
};
foreach (array_slice($grid, $headerIndex + 1) as $gridRow) {
if (! $this->hasContent($gridRow)) {
continue;
}
$date = $this->toDate($this->cell($gridRow, $map, 'bill_date'));
$orderNo = $this->toText($this->cell($gridRow, $map, 'order_no'));
if ($date === null || $orderNo === null) {
$skipped++;
continue;
}
$record = [
'company_id' => $companyId,
'bill_date' => $date,
'order_no' => mb_substr($orderNo, 0, 100),
'pieces' => (int) ($this->toNumber($this->cell($gridRow, $map, 'pieces')) ?? 0),
'remark' => $this->toText($this->cell($gridRow, $map, 'remark')),
'store' => $this->toText($this->cell($gridRow, $map, 'store')),
'owner' => $this->toText($this->cell($gridRow, $map, 'owner')),
'account' => $this->toText($this->cell($gridRow, $map, 'account')),
'type' => $this->toText($this->cell($gridRow, $map, 'type')),
'creator' => $this->toText($this->cell($gridRow, $map, 'creator')),
'tag' => $this->toText($this->cell($gridRow, $map, 'tag')),
'profit_center' => $this->toText($this->cell($gridRow, $map, 'profit_center')),
'responsible_platform' => $this->toText($this->cell($gridRow, $map, 'responsible_platform')),
// 源表存在一个单元格放多个 ID(换行分隔)的情况,这里保留到 500 字符。
'external_id' => $this->toText($this->cell($gridRow, $map, 'external_id'), 500),
'created_from' => $source,
'created_by' => $userId,
'created_at' => $now,
'updated_at' => $now,
];
foreach (self::MONEY_COLUMNS as $column) {
$value = $this->toNumber($this->cell($gridRow, $map, $column)) ?? 0.0;
$record[$column] = number_format($value, 4, '.', '');
}
$sellingPrice += (float) $record['finance_selling_price'];
$paymentAmount += (float) $record['finance_payment_amount'];
$dateMin = $dateMin === null || $date < $dateMin ? $date : $dateMin;
$dateMax = $dateMax === null || $date > $dateMax ? $date : $dateMax;
$rows[] = $record;
if (count($rows) >= self::CHUNK * 4) {
$flush();
}
}
$flush();
return [
'rows' => $inserted + $skipped,
'inserted' => $inserted,
'skipped' => $skipped,
'selling_price' => number_format($sellingPrice, 4, '.', ''),
'payment_amount' => number_format($paymentAmount, 4, '.', ''),
'date_min' => $dateMin,
'date_max' => $dateMax,
];
}
/** @return array<int,array<int,mixed>> */
private function read(string $path): array
{
$extension = mb_strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ($extension === 'csv') {
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('无法读取文件。');
}
$grid = [];
$first = true;
while (($cells = fgetcsv($handle)) !== false) {
if ($first && isset($cells[0])) {
$cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) $cells[0]);
$first = false;
}
$grid[] = $cells;
}
fclose($handle);
return $grid;
}
if (! in_array($extension, ['xlsx', 'xls'], true)) {
throw new InvalidArgumentException('只支持 xlsx、xls、csv。');
}
try {
$reader = IOFactory::createReader($extension === 'xlsx' ? 'Xlsx' : 'Xls');
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($path);
} catch (Throwable $exception) {
throw new InvalidArgumentException('读不出这个表格:' . $exception->getMessage());
}
try {
return $spreadsheet->getSheet(0)->toArray(null, true, false, false);
} finally {
$spreadsheet->disconnectWorksheets();
}
}
/** @param array<int,array<int,mixed>> $grid */
private function locateHeader(array $grid): ?int
{
foreach ($grid as $index => $row) {
$map = $this->mapHeader($row);
if (isset($map['bill_date'], $map['order_no'], $map['finance_payment_amount'])) {
return $index;
}
}
return null;
}
/** @param array<int,mixed> $row @return array<string,int> */
private function mapHeader(array $row): array
{
$map = [];
foreach ($row as $index => $value) {
$label = trim((string) (is_scalar($value) ? $value : ''));
if ($label === '') {
continue;
}
$column = self::COLUMNS[$label] ?? null;
if ($column !== null && ! isset($map[$column])) {
$map[$column] = (int) $index;
}
}
return $map;
}
/** @param array<int,mixed> $row @param array<string,int> $map */
private function cell(array $row, array $map, string $column): mixed
{
return isset($map[$column]) ? ($row[$map[$column]] ?? null) : null;
}
private function hasContent(array $row): bool
{
foreach ($row as $value) {
if ($value !== null && trim((string) (is_scalar($value) ? $value : '')) !== '') {
return true;
}
}
return false;
}
private function toDate(mixed $value): ?string
{
if ($value === null || $value === '') {
return null;
}
if (is_numeric($value) && (float) $value > 20000 && (float) $value < 60000) {
try {
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d');
} catch (Throwable) {
return null;
}
}
$text = trim((string) $value);
$timestamp = strtotime($text);
return $timestamp === false ? null : date('Y-m-d', $timestamp);
}
private function toText(mixed $value, int $limit = 191): ?string
{
if ($value === null) {
return null;
}
$text = trim((string) (is_scalar($value) ? $value : ''));
return $text === '' ? null : mb_substr($text, 0, $limit);
}
private function toNumber(mixed $value): ?float
{
if ($value === null || $value === '') {
return null;
}
if (is_numeric($value)) {
return (float) $value;
}
$text = str_replace([',', ' ', '¥', '¥'], '', (string) $value);
return is_numeric($text) ? (float) $text : null;
}
}

View File

@ -1,68 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/** Reuse label classification across monthly/platform jobs; writers invalidate it. */
class PlantingOrderLabelLookup
{
/** @param list<string> $positiveLabels @return list<string> */
public function orderNumbers(int $companyId, array $positiveLabels): array
{
sort($positiveLabels, SORT_STRING);
$rules = hash('sha256', json_encode($positiveLabels, JSON_THROW_ON_ERROR));
$key = $this->key($companyId);
$read = function () use ($key, $rules, $companyId): ?array {
$cached = Cache::get($key);
return is_array($cached) && ($cached['rules'] ?? null) === $rules
&& ($cached['revision'] ?? null) === $this->revision($companyId)
? $cached['orders'] : null;
};
if (($orders = $read()) !== null) {
return $orders;
}
return Cache::lock($key . ':build', 300)->block(305, function () use ($companyId, $positiveLabels, $key, $rules, $read): array {
if (($orders = $read()) !== null) {
return $orders;
}
$revision = $this->revision($companyId);
$orders = [];
foreach (DB::table('jst_order_labels')->where('company_id', $companyId)
->where(function ($query) use ($positiveLabels): void {
if ($positiveLabels !== []) {
$query->whereIn('label', $positiveLabels);
}
$query->orWhereRaw('FIND_IN_SET(?, item_code) > 0', [JstOrderLabelPlantingRules::PLANTING_ITEM_CODE]);
})->select('order_no')->distinct()->cursor() as $row) {
$orders[] = (string) $row->order_no;
}
// An import/rule change during the scan must not publish an old result.
if ($this->revision($companyId) === $revision) {
Cache::put($key, ['rules' => $rules, 'revision' => $revision, 'orders' => $orders], now()->addHours(24));
}
return $orders;
});
}
public function forget(int $companyId): void
{
$key = $this->key($companyId);
Cache::store('upstream_shared')->forever($key . ':revision', bin2hex(random_bytes(16)));
Cache::forget($key);
}
public function revision(int $companyId): ?string
{
return Cache::store('upstream_shared')->get($this->key($companyId) . ':revision');
}
private function key(int $companyId): string
{
return 'planting-order-labels:v1:' . $companyId;
}
}

View File

@ -1,396 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\PlantingDetail;
use Illuminate\Database\DatabaseManager;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
use RuntimeException;
/**
* 聚水潭「种菜报销」协同工单 → 种菜明细表(账单流水数据 › 种菜数据汇总 › 种菜明细表)月度同步。
*
* 口径(用 1~8 月已入库的 7 万多行反推、命中率 100%):
* - 只取「工单类型 = 种菜报销、工单状态 = 已完成」的工单;
* - 明细表「日期」= 工单完成日 − 1 天。所以某个月的数据 = 完成时间落在该月次日到下月次日的工单;
* - 一张工单一行,金额列与工单表单字段一一对应(见 FIELD_* 常量)。
*
* 排重:写入前先删掉「本月 + 本次订单号」的已有行,所以同一个月重复执行不会翻倍;
* 想整月覆盖(连没有对应工单的人工行一起清掉)用 --force-clear。
*
* 「所属利润中心」没有工单来源,按这个顺序取:
* 1. 表里已有的 店铺→利润中心 历史值(人工维护过的不覆盖);
* 2. 店铺维度报表的 ERP 系统店铺资料(ops_fys_shop_info.erpShopName → responsibleDepartment);
* 3. 两边都没有就留空,并在命令输出里列出来。
*/
class PlantingWorkOrderSynchronizer
{
/** 店铺维度报表用的店铺资料数据集(ERP系统店铺名称 → 店铺所属利润中心)。 */
public const SHOP_INFO_DATASET = 'operations_replica.rpt.fys_shopInfo';
/** 聚水潭协同工单镜像(jiansun.dbo.jst_workOrderInfo → js_jst_work_order_info)。 */
public const WORK_ORDER_DATASET = 'jiansun.dbo.jst_workOrderInfo';
/** 「种菜报销」这个工单类型的固定 id。 */
public const WORK_TYPE_ID = '6F03128403F2442CABCF283B59FAD88D';
/** 已完成的工单状态。 */
private const STATUS_CONFIRMED = 'CONFIRMED';
public const SOURCE = 'work-order-sync';
/** 工单表单字段(聚水潭只给 fieldId,不给字段名,这里的对应关系是拿历史数据逐列对撞出来的)。 */
private const FIELD_SELLING_PRICE = 'NUMBERField1413856620250924131615'; // 财务售价 = 任务付款金额
private const FIELD_FREIGHT = 'NUMBERField1413856620251113150537'; // 财务运费 = 任务快递费
private const FIELD_COMMISSION = 'NUMBERField1413856620251230154457'; // 财务佣金 = 任务佣金
private const FIELD_JINGXI_DIFF = 'NUMBERField1413856620250924131623'; // 京喜差价
private const FIELD_DEDUCTION = 'NUMBERField1413856620251113150612'; // 扣款 = 任务扣款费用
private const FIELD_EMPTY_PACKAGE = 'NUMBERField1413856620251113145620'; // 财务空包费 = 任务空包费
private const FIELD_PAYMENT = 'NUMBERField1413856620251117101250'; // 财务打款金额 = 最终报销金额
private const FIELD_OWNER = 'TEXTField1413856620251117180931'; // 负责人(收款人姓名)
private const FIELD_ACCOUNT = 'TEXTField1413856620251117113451'; // 账户(打款账号)
private const FIELD_TYPE = 'TEXTField1413856620251113150546'; // 类型(任务备注)
private const FIELD_TAG = 'businessRemarkField'; // 标签(业务备注)
private const FIELD_ORDER_NO = 'orderField'; // 订单编号(线上订单号)
private const FIELD_STORE = 'shopField'; // 正确店铺(店铺名称)
/** 金额列,统一按 4 位小数落库。 */
private const MONEY_COLUMNS = [
'finance_selling_price',
'finance_freight',
'finance_commission',
'jingxi_price_diff',
'deduction',
'finance_empty_package_fee',
'finance_payment_amount',
];
private const INSERT_CHUNK = 1000;
private const DELETE_CHUNK = 500;
public function __construct(
private readonly DatabaseManager $databases,
private readonly BusinessMirrorDatasetRegistry $datasets,
) {}
/**
* @return array{
* from:string,to:string,orders:int,inserted:int,deleted:int,
* selling_price:string,payment_amount:string,date_min:?string,date_max:?string,
* profit_center_from_erp:int,unmatched_stores:array<string,int>,dry_run:bool
* }
*/
public function sync(
string $from,
string $to,
int $companyId = 1,
bool $dryRun = false,
bool $forceClear = false,
): array {
$from = $this->normalizeDate($from, '起始日期');
$to = $this->normalizeDate($to, '结束日期');
if ($from > $to) {
throw new InvalidArgumentException('起始日期不能晚于结束日期。');
}
// 「日期」= 工单完成日 − 1,所以完成时间窗口整体后移一天。
$completeFrom = date('Y-m-d', strtotime($from . ' +1 day')) . ' 00:00:00';
$completeTo = date('Y-m-d', strtotime($to . ' +1 day')) . ' 00:00:00';
$target = $this->databases->connection();
$mirror = $this->databases->connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$table = $this->datasets->get(self::WORK_ORDER_DATASET)->targetTable();
if (! $mirror->getSchemaBuilder()->hasTable($table)) {
throw new RuntimeException('聚水潭协同工单镜像尚未建立(' . $table . ')。');
}
// 历史值优先(人工维护过的不覆盖),没有的再用 ERP 店铺资料补齐。
$storeToProfitCenter = $this->storeToProfitCenter($companyId);
$erpProfitCenters = $this->erpStoreToProfitCenter($mirror);
$now = now();
$rows = [];
$orders = 0;
$fromErp = 0;
$unmatchedStores = [];
$sellingPrice = 0.0;
$paymentAmount = 0.0;
$dateMin = null;
$dateMax = null;
$records = $mirror->table($table)
->where('woTypeId', self::WORK_TYPE_ID)
->where('status', self::STATUS_CONFIRMED)
->where('completeTime', '>=', $completeFrom)
->where('completeTime', '<', $completeTo)
->orderBy('completeTime')
->orderBy('woNo')
->get(['woNo', 'createby', 'completeTime', 'businessFieldList']);
foreach ($records as $record) {
$fields = $this->fields((string) $record->businessFieldList);
$orderNo = $this->text($fields[self::FIELD_ORDER_NO] ?? null);
if ($orderNo === null) {
continue;
}
$billDate = date('Y-m-d', strtotime((string) $record->completeTime . ' -1 day'));
if ($billDate < $from || $billDate > $to) {
continue;
}
$store = $this->text($fields[self::FIELD_STORE . '#label'] ?? null);
$profitCenter = null;
if ($store !== null) {
$profitCenter = $storeToProfitCenter[$store] ?? null;
if ($profitCenter === null && isset($erpProfitCenters[$store])) {
$profitCenter = $erpProfitCenters[$store];
$fromErp++;
}
}
if ($store !== null && $profitCenter === null) {
$unmatchedStores[$store] = ($unmatchedStores[$store] ?? 0) + 1;
}
$row = [
'company_id' => $companyId,
'bill_date' => $billDate,
'order_no' => mb_substr($orderNo, 0, 100),
'pieces' => 1,
'remark' => null,
'store' => $store,
'owner' => $this->text($fields[self::FIELD_OWNER] ?? null),
'account' => $this->text($fields[self::FIELD_ACCOUNT] ?? null),
'type' => $this->text($fields[self::FIELD_TYPE] ?? null),
'creator' => $this->text($record->createby),
'tag' => $this->text($fields[self::FIELD_TAG] ?? null),
'profit_center' => $profitCenter,
'responsible_platform' => null,
'external_id' => $this->text($this->platformItemId($fields), 100),
'created_from' => self::SOURCE,
'created_by' => null,
'created_at' => $now,
'updated_at' => $now,
];
foreach (self::MONEY_COLUMNS as $column) {
$row[$column] = number_format(0.0, 4, '.', '');
}
foreach ([
'finance_selling_price' => self::FIELD_SELLING_PRICE,
'finance_freight' => self::FIELD_FREIGHT,
'finance_commission' => self::FIELD_COMMISSION,
'jingxi_price_diff' => self::FIELD_JINGXI_DIFF,
'deduction' => self::FIELD_DEDUCTION,
'finance_empty_package_fee' => self::FIELD_EMPTY_PACKAGE,
'finance_payment_amount' => self::FIELD_PAYMENT,
] as $column => $field) {
$row[$column] = number_format($this->number($fields[$field] ?? null), 4, '.', '');
}
$orders++;
$sellingPrice += (float) $row['finance_selling_price'];
$paymentAmount += (float) $row['finance_payment_amount'];
$dateMin = $dateMin === null || $billDate < $dateMin ? $billDate : $dateMin;
$dateMax = $dateMax === null || $billDate > $dateMax ? $billDate : $dateMax;
$rows[] = $row;
}
$orderNumbers = array_values(array_unique(array_column($rows, 'order_no')));
$deleted = 0;
if (! $dryRun) {
$deleted = $this->clear($target, $companyId, $from, $to, $orderNumbers, $forceClear);
foreach (array_chunk($rows, self::INSERT_CHUNK) as $chunk) {
$target->table('planting_details')->insert($chunk);
}
}
arsort($unmatchedStores);
return [
'from' => $from,
'to' => $to,
'orders' => $orders,
'inserted' => $dryRun ? 0 : count($rows),
'deleted' => $deleted,
'selling_price' => number_format($sellingPrice, 4, '.', ''),
'payment_amount' => number_format($paymentAmount, 4, '.', ''),
'date_min' => $dateMin,
'date_max' => $dateMax,
'profit_center_from_erp' => $fromErp,
'unmatched_stores' => $unmatchedStores,
'dry_run' => $dryRun,
];
}
/**
* 排重:删掉本月内、这次要写入的那批订单号对应的已有行。
*
* @param list<string> $orderNumbers
*/
private function clear(
\Illuminate\Database\ConnectionInterface $target,
int $companyId,
string $from,
string $to,
array $orderNumbers,
bool $forceClear,
): int {
$base = static fn () => $target->table('planting_details')
->where('company_id', $companyId)
->where('bill_date', '>=', $from)
->where('bill_date', '<=', $to);
if ($forceClear) {
return (int) $base()->delete();
}
$deleted = 0;
foreach (array_chunk($orderNumbers, self::DELETE_CHUNK) as $chunk) {
$deleted += (int) $base()->whereIn('order_no', $chunk)->delete();
}
return $deleted;
}
/** @return array<string,string> 店铺 → 利润中心(同店铺多个取值时取出现次数最多的) */
private function storeToProfitCenter(int $companyId): array
{
$counts = [];
$rows = PlantingDetail::query()
->where('company_id', $companyId)
->whereNotNull('store')
->whereNotNull('profit_center')
->selectRaw('store, profit_center, COUNT(*) AS total')
->groupBy('store', 'profit_center')
->get();
foreach ($rows as $row) {
$store = (string) $row->store;
$counts[$store][(string) $row->profit_center] = (int) $row->total;
}
$map = [];
foreach ($counts as $store => $values) {
arsort($values);
$map[$store] = (string) array_key_first($values);
}
return $map;
}
/**
* 店铺维度报表的 ERP 系统店铺 → 店铺所属利润中心(ops_fys_shop_info.responsibleDepartment)。
*
* @return array<string,string>
*/
private function erpStoreToProfitCenter(\Illuminate\Database\ConnectionInterface $mirror): array
{
$table = $this->datasets->get(self::SHOP_INFO_DATASET)->targetTable();
if (! $mirror->getSchemaBuilder()->hasTable($table)) {
return [];
}
$map = [];
foreach ($mirror->table($table)
->whereNotNull('erpShopName')
->where('responsibleDepartment', '<>', '')
->get(['erpShopName', 'responsibleDepartment']) as $row) {
$name = trim((string) $row->erpShopName);
$department = trim((string) $row->responsibleDepartment);
if ($name !== '' && $department !== '' && ! isset($map[$name])) {
$map[$name] = mb_substr($department, 0, 191);
}
}
return $map;
}
/** @return array<string,mixed> fieldId → value(带 valueLabel 的另存为 fieldId#label) */
private function fields(string $businessFieldList): array
{
$fields = [];
$items = json_decode($businessFieldList, true);
if (! is_array($items)) {
return $fields;
}
foreach ($items as $item) {
if (! is_array($item) || ! isset($item['fieldId'])) {
continue;
}
if ($item['fieldId'] === 'itemInfo') {
// 商品明细是嵌套结构,原样留着给 platformItemId 取平台商品 ID。
$fields['itemInfo'] = $item;
continue;
}
$value = $item['value'] ?? null;
if (is_array($value)) {
$value = implode(',', array_map('strval', $value));
}
$fields[(string) $item['fieldId']] = $value;
if (($item['valueLabel'] ?? null) !== null) {
$fields[(string) $item['fieldId'] . '#label'] = $item['valueLabel'];
}
}
return $fields;
}
/** @param array<string,mixed> $fields */
private function platformItemId(array $fields): ?string
{
$itemInfo = $fields['itemInfo'] ?? null;
if (! is_array($itemInfo)) {
return null;
}
foreach ((array) ($itemInfo['childFieldList'] ?? []) as $childRow) {
foreach ((array) $childRow as $child) {
if (is_array($child) && ($child['fieldId'] ?? null) === 'platformItemId') {
return $this->text($child['value'] ?? null, 100);
}
}
}
return null;
}
private function text(mixed $value, int $limit = 191): ?string
{
if ($value === null) {
return null;
}
$text = trim((string) (is_scalar($value) ? $value : ''));
return $text === '' ? null : mb_substr($text, 0, $limit);
}
private function number(mixed $value): float
{
if ($value === null || $value === '') {
return 0.0;
}
return is_numeric($value) ? (float) $value : 0.0;
}
private function normalizeDate(string $value, string $label): string
{
$value = trim($value);
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
throw new InvalidArgumentException($label . '必须是 YYYY-MM-DD。');
}
[$year, $month, $day] = array_map('intval', explode('-', $value));
if (! checkdate($month, $day, $year)) {
throw new InvalidArgumentException($label . '不是有效日期。');
}
return $value;
}
}

View File

@ -1,261 +0,0 @@
<?php
namespace App\Business;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* 汇总商品月加权平均单价结果,并将入库明细差异按原因分类。
*/
class ProductMonthlyWeightedAverageReporter
{
// 异常阈值未由业务另行指定:取至少 100 行,且不超过总行数的 0.1%。
private const ANOMALY_THRESHOLD_MIN_ROWS = 100;
private const ANOMALY_THRESHOLD_RATE = 0.001;
private const ROW_TABLE = 'product_monthly_weighted_average_rows';
private const STATE_TABLE = 'product_monthly_weighted_average_states';
private const INBOUND_TABLE = 'inventory_inbound_detail_rows';
private const INVENTORY_MONTH_TABLE = 'inventory_report_authoritative_months';
private const INVENTORY_ROW_TABLE = 'inventory_report_authoritative_rows';
/** @return array<string,mixed> */
public function build(string $connection, CarbonImmutable $month): array
{
$month = $month->startOfMonth();
$db = DB::connection($connection);
$baseQuery = static fn () => $db->table(self::ROW_TABLE)
->where('report_month', $month->toDateString());
$totals = $baseQuery()
->selectRaw('count(*) as total_rows')
->selectRaw('coalesce(sum(opening_quantity), 0) as opening_quantity')
->selectRaw('coalesce(sum(opening_amount), 0) as opening_amount')
->selectRaw('coalesce(sum(purchase_quantity), 0) as purchase_quantity')
->selectRaw('coalesce(sum(purchase_amount), 0) as purchase_amount')
->selectRaw('sum(case when weighted_average_unit_price is not null then 1 else 0 end) as weighted_price_rows')
->selectRaw('sum(case when weighted_average_unit_price is null then 1 else 0 end) as missing_weighted_rows')
->selectRaw('sum(case when pricing_status = ? then 1 else 0 end) as manual_review_rows', ['待人工核查'])
->first();
if ($totals === null || (int) $totals->total_rows === 0) {
return [
'status' => 'missing',
'report_month' => $month->toDateString(),
'message' => '该月份尚未生成商品月加权平均单价。',
'generated_at' => now()->toDateTimeString(),
];
}
$weightedKeys = [];
foreach ($baseQuery()->select('product_code', 'warehouse_short_name')->cursor() as $row) {
$weightedKeys[$this->key($row->product_code, $row->warehouse_short_name)] = true;
}
$inbound = [
'source_rows' => 0,
'source_quantity' => 0.0,
'source_amount' => 0.0,
'matched_rows' => 0,
'matched_quantity' => 0.0,
'matched_amount' => 0.0,
'unmatched_rows' => 0,
'unmatched_quantity' => 0.0,
'unmatched_amount' => 0.0,
'unmatched_groups' => [],
];
foreach ($db->table(self::INBOUND_TABLE)
->where('report_month', $month->toDateString())
->selectRaw('upper(barcode) as code, warehouse_short_name, count(*) as rows_count')
->selectRaw('coalesce(sum(quantity), 0) as quantity')
->selectRaw('coalesce(sum(coalesce(amount, 0) + coalesce(estimated_amount, 0)), 0) as amount')
->groupByRaw('upper(barcode), warehouse_short_name')
->cursor() as $row) {
$rows = (int) $row->rows_count;
$quantity = (float) $row->quantity;
$amount = (float) $row->amount;
$inbound['source_rows'] += $rows;
$inbound['source_quantity'] += $quantity;
$inbound['source_amount'] += $amount;
if (isset($weightedKeys[$this->key($row->code, $row->warehouse_short_name)])) {
$inbound['matched_rows'] += $rows;
$inbound['matched_quantity'] += $quantity;
$inbound['matched_amount'] += $amount;
continue;
}
$inbound['unmatched_rows'] += $rows;
$inbound['unmatched_quantity'] += $quantity;
$inbound['unmatched_amount'] += $amount;
$inbound['unmatched_groups'][] = [
'product_code' => trim((string) $row->code),
'warehouse_short_name' => trim((string) $row->warehouse_short_name),
'source_rows' => $rows,
'quantity' => $this->number($quantity),
'amount' => $this->number($amount),
'reason' => '入库明细未匹配到商品编码 + 仓库简称行',
];
}
usort(
$inbound['unmatched_groups'],
static fn (array $left, array $right): int =>
abs((float) $right['amount']) <=> abs((float) $left['amount']),
);
$inbound = $this->roundNestedNumbers($inbound);
$monthState = $db->table(self::INVENTORY_MONTH_TABLE)
->where('dataset_key', 'jiansun.inventory-report.authoritative-month')
->where('source_month', $month->toDateString())
->first();
$generation = $monthState?->active_generation;
$actualSourceRows = $generation === null
? 0
: $db->table(self::INVENTORY_ROW_TABLE)
->where('generation', (string) $generation)
->count();
$expectedSourceRows = (int) ($monthState?->source_row_count ?? 0);
$weightedAnomalyRows = $baseQuery()
->where(function ($query): void {
$query->whereNull('weighted_average_unit_price')
->orWhere('pricing_status', '待人工核查');
})
->count();
$reasons = [];
if ((int) $totals->missing_weighted_rows > 0) {
$reasons[] = [
'code' => 'missing_weighted_price',
'label' => '加权平均单价为空',
'rows' => (int) $totals->missing_weighted_rows,
];
}
if ((int) $totals->manual_review_rows > 0) {
$reasons[] = [
'code' => 'manual_review',
'label' => '待人工核查',
'rows' => (int) $totals->manual_review_rows,
];
}
if ((int) $inbound['unmatched_rows'] > 0) {
$reasons[] = [
'code' => 'inbound_without_inventory_dimension',
'label' => '入库明细未匹配到商品编码 + 仓库简称行',
'rows' => (int) $inbound['unmatched_rows'],
'groups' => count($inbound['unmatched_groups']),
];
}
if ($actualSourceRows !== $expectedSourceRows) {
$reasons[] = [
'code' => 'upstream_source_row_mismatch',
'label' => '上游进销存源表行数与已激活明细不一致',
'rows' => abs($actualSourceRows - $expectedSourceRows),
];
}
$anomalyRows = $weightedAnomalyRows + (int) $inbound['unmatched_rows'];
$threshold = max(
self::ANOMALY_THRESHOLD_MIN_ROWS,
(int) ceil((int) $totals->total_rows * self::ANOMALY_THRESHOLD_RATE),
);
return [
'status' => $reasons === [] ? 'computed' : 'review_required',
'report_month' => $month->toDateString(),
'totals' => [
'rows' => (int) $totals->total_rows,
'opening_quantity' => $this->number((float) $totals->opening_quantity),
'opening_amount' => $this->number((float) $totals->opening_amount),
'purchase_quantity' => $this->number((float) $totals->purchase_quantity),
'purchase_amount' => $this->number((float) $totals->purchase_amount),
'weighted_price_rows' => (int) $totals->weighted_price_rows,
'missing_weighted_rows' => (int) $totals->missing_weighted_rows,
'manual_review_rows' => (int) $totals->manual_review_rows,
],
'inbound' => $inbound,
'source' => [
'expected_rows' => $expectedSourceRows,
'active_rows' => $actualSourceRows,
'row_difference' => $actualSourceRows - $expectedSourceRows,
'status' => (string) ($monthState?->status ?? 'missing'),
'active_generation' => $generation,
'source_filename' => $monthState?->source_filename,
],
'anomalies' => [
'affected_rows' => $anomalyRows,
'threshold_rows' => $threshold,
'threshold_exceeded' => $anomalyRows > $threshold,
'reasons' => $reasons,
],
'state' => $db->table(self::STATE_TABLE)
->where('report_month', $month->toDateString())
->first(),
'generated_at' => now()->toDateTimeString(),
];
}
/** @param array<string,mixed> $report */
public function brief(array $report): string
{
if (($report['status'] ?? null) === 'missing') {
return (string) ($report['message'] ?? '商品月加权平均单价尚未生成');
}
$totals = $report['totals'] ?? [];
$inbound = $report['inbound'] ?? [];
$anomalies = $report['anomalies'] ?? [];
$reasonLabels = array_map(
static fn (array $reason): string =>
(string) ($reason['label'] ?? $reason['code'] ?? '未知异常'),
$anomalies['reasons'] ?? [],
);
return sprintf(
'%s:总行数 %s;期初 %s 件 / %s;入库 %s 件 / %s;加权单价 %s 行;异常 %s 行%s',
substr((string) ($report['report_month'] ?? ''), 0, 7),
number_format((int) ($totals['rows'] ?? 0)),
number_format((float) ($totals['opening_quantity'] ?? 0), 2),
number_format((float) ($totals['opening_amount'] ?? 0), 2),
number_format((float) ($inbound['matched_quantity'] ?? 0), 2),
number_format((float) ($inbound['matched_amount'] ?? 0), 2),
number_format((int) ($totals['weighted_price_rows'] ?? 0)),
number_format((int) ($anomalies['affected_rows'] ?? 0)),
$reasonLabels === [] ? '' : '(' . implode('、', $reasonLabels) . ')',
);
}
private function key(mixed $productCode, mixed $warehouseShortName): string
{
return mb_strtoupper(trim((string) $productCode))
. "\0"
. trim((string) $warehouseShortName);
}
private function number(float $value): float
{
return round($value, 6);
}
/**
* @param array<string,mixed> $value
* @return array<string,mixed>
*/
private function roundNestedNumbers(array $value): array
{
foreach ($value as $key => $item) {
if (is_array($item)) {
$value[$key] = $this->roundNestedNumbers($item);
} elseif (is_float($item)) {
$value[$key] = round($item, 6);
}
}
return $value;
}
}

View File

@ -1,95 +0,0 @@
<?php
namespace App\Business;
use Carbon\CarbonInterface;
use Illuminate\Database\DatabaseManager;
use Modules\EcommerceFinance\Repositories\BusinessInformationMirrorRepository;
use RuntimeException;
class StoreInformationDailyArchive
{
public const TABLE = 'store_information_daily_archives';
public function __construct(
private readonly BusinessInformationMirrorRepository $mirror,
private readonly UpstreamBusinessInformation $information,
private readonly DatabaseManager $database,
) {}
/**
* 保存指定日期的完整店铺基础信息快照;同一天重跑时覆盖当天版本。
*/
public function capture(CarbonInterface $snapshotDate): int
{
if (! $this->mirror->ready('store-information.read')) {
throw new RuntimeException('店铺基础信息共享镜像尚未完成首次同步。');
}
$rows = $this->information->storesWithAccountOwnership(
$this->mirror->allStores(),
true,
);
if ($rows === []) {
throw new RuntimeException('店铺基础信息共享镜像没有可存档的数据。');
}
$snapshotDateValue = $snapshotDate->format('Y-m-d');
$capturedAt = now('Asia/Shanghai')->format('Y-m-d H:i:s.u');
$values = [];
foreach ($rows as $row) {
$recordId = trim((string) ($row['id'] ?? ''));
if ($recordId === '') {
continue;
}
$values[] = [
'snapshot_date' => $snapshotDateValue,
'store_record_id' => mb_substr($recordId, 0, 64),
'erp_store_name' => mb_substr(trim((string) ($row['erp_store_name'] ?? '')), 0, 191),
'store_name' => $this->nullable($row['store_name'] ?? null, 191),
'company_name' => $this->nullable($row['company_name'] ?? null, 255),
'store_manager' => $this->nullable($row['store_manager'] ?? null, 191),
'department_manager' => $this->nullable($row['department_manager'] ?? null, 191),
'profit_center' => $this->nullable($row['profit_center'] ?? null, 191),
'store_status' => $this->nullable($row['store_status'] ?? null, 64),
'payload' => json_encode(
$row,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
),
'captured_at' => $capturedAt,
'created_at' => $capturedAt,
'updated_at' => $capturedAt,
];
}
if ($values === []) {
throw new RuntimeException('店铺基础信息缺少可用的店铺记录 ID,未写入快照。');
}
$connection = $this->database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
$connection->transaction(function () use ($connection, $values): void {
foreach (array_chunk($values, 250) as $chunk) {
$connection->table(self::TABLE)->upsert(
$chunk,
['snapshot_date', 'store_record_id'],
[
'erp_store_name', 'store_name', 'company_name',
'store_manager', 'department_manager', 'profit_center',
'store_status', 'payload', 'captured_at', 'updated_at',
],
);
}
});
return count($values);
}
private function nullable(mixed $value, int $limit): ?string
{
$text = trim((string) $value);
return $text === '' ? null : mb_substr($text, 0, $limit);
}
}

View File

@ -1,84 +0,0 @@
<?php
namespace App\Business;
/**
* 平台数字 SKU → 历史已拆分内部商品编码。
*
* 平台 shop_sku_id 已包含平台规格维度;仅当同一 shop_sku_id + shop_i_id
* 的历史内部编码唯一时才允许替换,多候选保持待核验。
*/
class StoreReceiptPlatformSkuMapper
{
/** @var array<string,array<string,int>> */
private array $internalSkus = [];
/** @var array<string,array<string,int>> */
private array $internalProperties = [];
/** @var array<string,int> */
private array $historyRows = [];
/** @param iterable<object|array<string,mixed>> $historyRows */
public function __construct(iterable $historyRows)
{
foreach ($historyRows as $row) {
$shopSkuId = trim((string) $this->value($row, 'shop_sku_id'));
$shopItemId = trim((string) $this->value($row, 'shop_i_id'));
$skuId = trim((string) $this->value($row, 'sku_id'));
$itemId = trim((string) $this->value($row, 'i_id'));
if ($shopSkuId === '' || $shopItemId === '' || $skuId === '') {
continue;
}
// 平台原始行的 i_id 等于 shop_i_id;内部拆分行的 i_id 是内部款式编码。
if ($itemId === '' || $itemId === $shopItemId) {
continue;
}
$key = $this->key($shopSkuId, $shopItemId);
$this->internalSkus[$key][$skuId] = ($this->internalSkus[$key][$skuId] ?? 0) + 1;
$property = trim((string) $this->value($row, 'properties_value'));
if ($property !== '') {
$this->internalProperties[$key][$property] = ($this->internalProperties[$key][$property] ?? 0) + 1;
}
$this->historyRows[$key] = ($this->historyRows[$key] ?? 0) + 1;
}
}
/**
* @return array{
* status:string,
* internal_sku:?string,
* candidates:list<string>,
* history_rows:int,
* internal_properties:list<string>
* }
*/
public function resolve(string $shopSkuId, string $shopItemId): array
{
$key = $this->key(trim($shopSkuId), trim($shopItemId));
$skus = array_keys($this->internalSkus[$key] ?? []);
sort($skus);
$properties = array_keys($this->internalProperties[$key] ?? []);
sort($properties);
return [
'status' => count($skus) === 1 ? 'unique' : ($skus === [] ? 'missing' : 'ambiguous'),
'internal_sku' => count($skus) === 1 ? $skus[0] : null,
'candidates' => $skus,
'history_rows' => (int) ($this->historyRows[$key] ?? 0),
'internal_properties' => $properties,
];
}
private function key(string $shopSkuId, string $shopItemId): string
{
return $shopSkuId . "\0" . $shopItemId;
}
private function value(object|array $row, string $key): mixed
{
return is_array($row) ? ($row[$key] ?? null) : ($row->{$key} ?? null);
}
}

View File

@ -4,13 +4,11 @@ namespace App\Business;
use App\Models\Business\StoreReceivingAccount;
use Modules\EcommerceFinance\Repositories\BusinessInformationMirrorRepository;
use Modules\EcommerceFinance\Services\StoreReportPeriodBuilder;
class StoreReceivingAccountSynchronizer
{
public function __construct(
private readonly BusinessInformationMirrorRepository $mirror,
private readonly StoreReportPeriodBuilder $storeReportPeriods,
) {
}
@ -37,15 +35,6 @@ class StoreReceivingAccountSynchronizer
$byWallet = [];
$byPlatformAndName = [];
$byName = [];
$sourceStores = $this->mirror->receivingAccountStores();
// 店铺主体跟随店铺维度报表的“存续中”期间,不再直接取店铺档案当前主体。
$currentCompanies = $this->storeReportPeriods->currentCompanies(array_map(
static fn (array $row): array => [
'erp_store_name' => trim((string) ($row['erp_store_name'] ?? '')),
'system_company_name' => trim((string) ($row['company_name'] ?? '')),
],
$sourceStores,
));
foreach ($existing as $account) {
$platform = (string) $account->store_platform;
@ -60,7 +49,7 @@ class StoreReceivingAccountSynchronizer
}
}
foreach ($sourceStores as $row) {
foreach ($this->mirror->receivingAccountStores() as $row) {
$erpStoreName = trim((string) ($row['erp_store_name'] ?? ''));
$platform = $this->classify($erpStoreName, (string) ($row['source_platform'] ?? ''));
@ -86,8 +75,7 @@ class StoreReceivingAccountSynchronizer
'company_id' => $companyId,
'store_platform' => $platform,
'store_name' => $erpStoreName,
'store_entity_name' => $currentCompanies[$erpStoreName]
?? trim((string) ($row['company_name'] ?? '')),
'store_entity_name' => trim((string) ($row['company_name'] ?? '')),
'shop_name' => trim((string) ($row['shop_name'] ?? '')) ?: $erpStoreName,
'store_status' => $this->status($row['store_status'] ?? null),
'wallet_number' => $storeId,

View File

@ -1,274 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\StoreAccountMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreViolationRuleRepository;
use Throwable;
/**
* 店铺违规信息预警:预警级别、责任人、处理截止等派生字段的计算。
*
* - 级别/是否提醒:按「平台 + 违规类型」匹配违规字典;原文先去(…)括号处置说明,
* 再做 相等/前缀/关键词 匹配;匹配不到 = 不需要提醒(只入库不推送)。
* - 责任人:店铺账号镜像的运营负责人(与店铺维度报表同口径),
* 未命中时回退店铺档案(ops_fys_shop_info.shopHead)。
* - 处理截止:申诉截止日期非空→当天 23:59:59;否则按字典时效(小时)或
* 级别默认天数(P0+1 / P1+2 / P2+3 天)的当天 23:59:59。
*/
class StoreViolationAlertCalculator
{
/** @var list<array<string,mixed>>|null */
private ?array $rules = null;
/** @var array<string,array{operation_owner:string,operation_department_head:string,operation_director:string,profit_center:string}>|null */
private ?array $ownerMap = null;
/** @var array<string,?string> */
private array $ownerFallback = [];
public function __construct(
private readonly StoreViolationRuleRepository $ruleRepository,
private readonly StoreAccountMirrorRepository $storeAccounts,
) {
}
public function flush(): void
{
$this->rules = null;
$this->ownerMap = null;
$this->ownerFallback = [];
}
/** @return array<string,mixed> 预警相关字段(用于同步/导入写入) */
public function calculate(
string $platform,
?string $shopName,
?string $violationType,
?string $violationDate,
?string $appealDeadline,
): array {
$rule = self::matchRule($this->rules(), $platform, $violationType);
$needsAlert = $rule !== null && (bool) ($rule['needs_alert'] ?? true);
$level = null;
if ($needsAlert) {
$level = trim((string) ($rule['alert_level'] ?? ''));
if ($level === '' || ! array_key_exists($level, (array) config('store_violations.alert_levels', []))) {
$level = 'P2';
}
}
$hours = isset($rule['handling_hours']) && $rule['handling_hours'] !== null
? (int) $rule['handling_hours']
: null;
return [
'needs_alert' => $needsAlert,
'alert_level' => $level,
'alert_rule_id' => $needsAlert ? ($rule['id'] ?? null) : null,
'alert_action' => $needsAlert ? self::nullableText($rule['suggested_action'] ?? null, 500) : null,
'alert_channel' => $needsAlert ? self::nullableText($rule['remind_channel'] ?? null, 64) : null,
'handling_hours' => $needsAlert ? $hours : null,
'owner_name' => $this->ownerFor($shopName),
'handling_deadline' => self::deadlineFor($violationDate, $appealDeadline, $hours, $level),
];
}
/** @return list<array<string,mixed>> */
private function rules(): array
{
if ($this->rules === null) {
try {
$this->rules = $this->ruleRepository->activeRules();
} catch (Throwable) {
$this->rules = [];
}
}
return $this->rules;
}
/**
* 清理违规类型原文:反复去掉成对括号(含处置说明)并去除空白。
*/
public static function cleanViolationType(?string $text): string
{
$text = trim((string) $text);
if ($text === '') {
return '';
}
$previous = null;
while ($previous !== $text) {
$previous = $text;
$text = preg_replace('/[((【\[][^((【\[))】\]]*[))】\]]/u', '', $text) ?? $text;
}
return preg_replace('/[\s\x{3000}]+/u', '', $text) ?? $text;
}
private static function loose(string $text): string
{
return preg_replace('/[\/、,,。.;;::·\-—_]+/u', '', $text) ?? $text;
}
/**
* 按顺序匹配字典:相等 → 前缀 → 分词包含 → 宽松包含 → 关键词包含。
*
* @param list<array<string,mixed>> $rules 已按优先级排序
* @return array<string,mixed>|null
*/
public static function matchRule(array $rules, string $platform, ?string $violationType): ?array
{
$record = self::cleanViolationType($violationType);
if ($record === '') {
return null;
}
$looseRecord = self::loose($record);
foreach ($rules as $rule) {
if (trim((string) ($rule['platform'] ?? '')) !== $platform) {
continue;
}
$ruleType = self::cleanViolationType($rule['violation_type'] ?? null);
if ($ruleType !== '') {
if ($record === $ruleType || str_starts_with($record, $ruleType)) {
return $rule;
}
foreach (preg_split('/[\/、]/u', $ruleType) ?: [] as $part) {
$part = trim((string) $part);
if ($part !== '' && mb_strlen($part) >= 2 && mb_stripos($record, $part) !== false) {
return $rule;
}
}
$looseRule = self::loose($ruleType);
if ($looseRule !== '' && str_contains($looseRecord, $looseRule)) {
return $rule;
}
}
foreach (preg_split('/[|、,\/]/u', (string) ($rule['match_keywords'] ?? '')) ?: [] as $keyword) {
$keyword = self::loose(self::cleanViolationType($keyword));
if ($keyword !== '' && str_contains($looseRecord, $keyword)) {
return $rule;
}
}
}
return null;
}
/**
* 处理截止:申诉截止优先;否则字典时效(小时)或级别默认天数(当天 23:59:59)。
*/
public static function deadlineFor(
?string $violationDate,
?string $appealDeadline,
?int $handlingHours,
?string $alertLevel,
): ?string {
$appeal = trim((string) $appealDeadline);
if ($appeal !== '') {
try {
return Carbon::parse($appeal)->endOfDay()->toDateTimeString();
} catch (Throwable) {
// 解析失败时退回按级别计算
}
}
$date = trim((string) $violationDate);
if ($date === '') {
return null;
}
try {
$base = Carbon::parse($date)->startOfDay();
} catch (Throwable) {
return null;
}
if ($handlingHours !== null && $handlingHours > 0) {
return $base->addHours($handlingHours)->toDateTimeString();
}
$level = trim((string) $alertLevel);
if ($level === '') {
return null;
}
$days = (int) (config('store_violations.alert_default_days.' . $level) ?? 0);
return $days > 0 ? $base->addDays($days)->endOfDay()->toDateTimeString() : null;
}
/** 是否超时:处理状态不在终态且当前时间已过处理截止。 */
public static function isOverdue(mixed $handlingStatus, mixed $handlingDeadline, ?Carbon $now = null): bool
{
$status = trim((string) $handlingStatus);
if (in_array($status, ['处理完成', '已忽略', '已处理', '无需处理'], true)) {
return false;
}
$deadline = trim((string) $handlingDeadline);
if ($deadline === '') {
return false;
}
try {
return ($now ?? Carbon::now())->greaterThan(Carbon::parse($deadline));
} catch (Throwable) {
return false;
}
}
private function ownerFor(?string $shopName): ?string
{
$name = trim((string) $shopName);
if ($name === '') {
return null;
}
try {
if ($this->ownerMap === null) {
$this->ownerMap = $this->storeAccounts->ownershipByStoreName();
}
$key = StoreAccountMirrorRepository::storeNameKey($name);
$owner = trim((string) ($this->ownerMap[$key]['operation_owner'] ?? ''));
if ($owner !== '') {
return mb_substr($owner, 0, 64);
}
} catch (Throwable) {
$this->ownerMap ??= [];
}
// 兜底:店铺档案(经营分析副本库)的店铺运营负责人。
if (array_key_exists($name, $this->ownerFallback)) {
return $this->ownerFallback[$name];
}
$head = null;
try {
$row = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'))
->table('ops_fys_shop_info')
->where('shopName', $name)
->orderByDesc('id')
->first(['shopHead']);
$head = self::nullableText($row->shopHead ?? null, 64);
} catch (Throwable) {
$head = null;
}
return $this->ownerFallback[$name] = $head;
}
private static function nullableText(mixed $value, int $limit): ?string
{
$text = trim((string) $value);
return $text === '' ? null : mb_substr($text, 0, $limit);
}
}

View File

@ -1,151 +0,0 @@
<?php
namespace App\Business;
use DateTimeImmutable;
use DateTimeInterface;
use InvalidArgumentException;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
/**
* 店铺违规信息预警:上游抓取数据与导入文件到统一表头的映射。
*/
class StoreViolationMapper
{
public function platformForSourceValue(mixed $value): ?string
{
$normalized = mb_strtolower(trim((string) $value));
if ($normalized === '') {
return null;
}
foreach ((array) config('store_violations.platforms', []) as $slug => $platform) {
if ($normalized === $slug) {
return $slug;
}
foreach ($platform['source_values'] ?? [] as $sourceValue) {
if ($normalized === mb_strtolower(trim((string) $sourceValue))) {
return $slug;
}
}
}
return null;
}
public function categoryForContent(?string $content): string
{
$content = trim((string) $content);
if ($content === '') {
return (string) config('store_violations.default_category', '其他');
}
foreach ((array) config('store_violations.category_rules', []) as $category => $keywords) {
foreach ((array) $keywords as $keyword) {
if ($keyword !== '' && mb_stripos($content, (string) $keyword) !== false) {
return (string) $category;
}
}
}
return (string) config('store_violations.default_category', '其他');
}
/**
* 上游抓取行(rpt.crawl_shop_violation)→ 统一字段。
*
* @param array<string,mixed> $row
* @return array<string,mixed>|null 平台无法识别时返回 null
*/
public function mapCrawlRow(array $row): ?array
{
$platform = $this->platformForSourceValue($row['platform'] ?? null);
if ($platform === null) {
return null;
}
$content = trim((string) ($row['violation_content'] ?? ''));
return [
'platform' => $platform,
'shop_name' => mb_substr(trim((string) ($row['shop_name'] ?? '')), 0, 191),
'violation_type' => $content === '' ? null : mb_substr($content, 0, 500),
'violation_category' => $this->categoryForContent($content),
// 上游视图补齐这两列后由同步命令自动带出(见 SyncStoreViolations 的列探测)。
'violation_reason' => $this->normalizeLabel($row['violation_reason'] ?? null, 500),
'disposition' => $this->normalizeLabel($row['disposition'] ?? null, 500),
'violation_no' => mb_substr(trim((string) ($row['violation_no'] ?? '')), 0, 100),
'violation_date' => $this->normalizeDate($row['violation_date'] ?? null),
'status' => $this->normalizeLabel($row['status'] ?? null, 64),
'appeal_deadline' => $this->normalizeDate($row['deadline'] ?? null),
'window_name' => $this->normalizeLabel($row['window_name'] ?? null, 191),
'crawl_date' => $this->normalizeDate($row['crawl_date'] ?? null),
'source' => 'crawl',
];
}
public function normalizeDate(mixed $value): ?string
{
if ($value === null || $value === '') {
return null;
}
if ($value instanceof DateTimeInterface) {
return $value->format('Y-m-d');
}
if (is_numeric($value)) {
$number = (float) $value;
if ($number >= 20000 && $number <= 80000) {
return ExcelDate::excelToDateTimeObject($number)->format('Y-m-d');
}
}
$text = trim((string) $value);
if ($text === '' || in_array($text, ['-', '—', '无'], true)) {
return null;
}
$text = str_replace(['年', '月'], '-', str_replace('日', '', $text));
$text = str_replace(['/', '.'], '-', $text);
$text = trim(preg_replace('/\s+/', ' ', $text) ?? $text);
try {
return (new DateTimeImmutable($text))->format('Y-m-d');
} catch (\Throwable) {
throw new InvalidArgumentException('无法识别的日期:' . $value);
}
}
public function normalizePoints(mixed $value): ?float
{
if ($value === null || $value === '') {
return null;
}
if (is_numeric($value)) {
return (float) $value;
}
$text = trim((string) $value);
if ($text === '' || in_array($text, ['-', '—', '无', '不扣分'], true)) {
return null;
}
$text = preg_replace('/(分|点|个?扣|扣除)/u', '', $text) ?? $text;
$text = trim($text);
if ($text === '' || ! is_numeric($text)) {
throw new InvalidArgumentException('无法识别的扣分:' . $value);
}
return (float) $text;
}
private function normalizeLabel(mixed $value, int $limit): ?string
{
$text = trim((string) $value);
return $text === '' ? null : mb_substr($text, 0, $limit);
}
}

View File

@ -1,237 +0,0 @@
<?php
namespace App\Business;
use App\Models\Common\Company;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\URL;
use Modules\EcommerceFinance\Repositories\StoreViolationPushRepository;
use RuntimeException;
use Throwable;
/**
* 店铺违规信息预警:内部群机器人推送(先留接口,配置 Webhook 后启用)。
*
* - P0/P1 即时推送(每天 09:00 起由定时任务检查),消息含去认领签名链接;
* - P2 不即时推,每日 10:00 汇总成一条日报;
* - 以违规记录为唯一对象:已推送的不再重复推送(失败可显式重试)。
*/
class StoreViolationNotifier
{
public function __construct(private readonly StoreViolationPushRepository $pushes)
{
}
public function enabled(): bool
{
$config = (array) config('store_violations.push', []);
return (bool) ($config['enabled'] ?? false)
&& trim((string) ($config['webhook'] ?? '')) !== '';
}
/**
* @return array{attempted:int,succeeded:int,failed:int}
*/
public function pushInstant(int $limit = 200, bool $retryFailed = false): array
{
$levels = array_values(array_map('strval', (array) config('store_violations.push.instant_levels', ['P0', 'P1'])));
$candidates = $this->pushes->instantCandidates($levels, $retryFailed, $limit);
$summary = ['attempted' => $candidates->count(), 'succeeded' => 0, 'failed' => 0];
$ownerContacts = (array) config('store_violations.push.owner_contacts', []);
foreach ($candidates as $record) {
$owner = trim((string) ($record->owner_name ?? ''));
$atMobiles = [];
if ($owner !== '' && ! empty($ownerContacts[$owner])) {
$atMobiles[] = (string) $ownerContacts[$owner];
}
[$title, $text] = $this->instantMessage($record);
$pushNo = $this->pushNo();
$now = Carbon::now();
try {
$this->send($title, $text, $atMobiles);
$this->pushes->markPushed([(int) $record->id], $now);
$summary['succeeded']++;
$this->pushes->log([
'push_no' => $pushNo,
'pushed_at' => $now,
'channel' => (string) config('store_violations.push.channel', 'dingtalk_robot'),
'message_type' => 'instant',
'platform' => (string) ($record->platform ?? ''),
'violation_no' => (string) ($record->violation_no ?? ''),
'message_digest' => mb_substr($title, 0, 500),
'mentioned' => $owner,
'result' => 'success',
'error' => null,
]);
} catch (Throwable $exception) {
$summary['failed']++;
$this->pushes->markPushFailed((int) $record->id, $now);
$this->pushes->log([
'push_no' => $pushNo,
'pushed_at' => $now,
'channel' => (string) config('store_violations.push.channel', 'dingtalk_robot'),
'message_type' => 'instant',
'platform' => (string) ($record->platform ?? ''),
'violation_no' => (string) ($record->violation_no ?? ''),
'message_digest' => mb_substr($title, 0, 500),
'mentioned' => $owner,
'result' => 'failed',
'error' => mb_substr($exception->getMessage(), 0, 500),
]);
}
}
return $summary;
}
/**
* @return array{pending:array<string,int>,overdue:int,p2:int,sent:bool}
*/
public function pushDigest(): array
{
$data = $this->pushes->digestData();
$pending = $data['pending'];
$overdue = $data['overdue'];
$p2Ids = $data['p2_pending']->pluck('id')->map(static fn ($id): int => (int) $id)->all();
$lines = [
'### 店铺违规预警 · 每日汇总(' . Carbon::now()->format('m-d') . ')',
'- 待处理:P0 ' . (int) ($pending['P0'] ?? 0)
. ' 条 / P1 ' . (int) ($pending['P1'] ?? 0)
. ' 条 / P2 ' . (int) ($pending['P2'] ?? 0) . ' 条',
'- 已超时未认领:' . $overdue->count() . ' 条',
];
foreach ($overdue as $index => $record) {
$lines[] = sprintf(
' %d. [%s] %s(责任人:%s) · 截止 %s',
$index + 1,
(string) ($record->alert_level ?? ''),
(string) ($record->shop_name ?? ''),
trim((string) ($record->owner_name ?? '')) !== '' ? (string) $record->owner_name : '未分配',
(string) ($record->handling_deadline ?? ''),
);
}
$now = Carbon::now();
try {
$this->send('店铺违规预警 · 每日汇总', implode("\n", $lines), []);
} catch (Throwable $exception) {
$this->pushes->log([
'push_no' => $this->pushNo(),
'pushed_at' => $now,
'channel' => (string) config('store_violations.push.channel', 'dingtalk_robot'),
'message_type' => 'daily',
'platform' => null,
'violation_no' => null,
'message_digest' => mb_substr(implode(' ', array_slice($lines, 0, 3)), 0, 500),
'mentioned' => null,
'result' => 'failed',
'error' => mb_substr($exception->getMessage(), 0, 500),
]);
return ['pending' => $pending, 'overdue' => $overdue->count(), 'p2' => count($p2Ids), 'sent' => false];
}
// 汇总成功后把已点名的 P2 记录标记为已推送;未点名的明细汇总不重复提醒。
$this->pushes->markPushed($p2Ids, $now);
$this->pushes->log([
'push_no' => $this->pushNo(),
'pushed_at' => $now,
'channel' => (string) config('store_violations.push.channel', 'dingtalk_robot'),
'message_type' => 'daily',
'platform' => null,
'violation_no' => null,
'message_digest' => mb_substr(implode(' ', array_slice($lines, 0, 3)), 0, 500),
'mentioned' => null,
'result' => 'success',
'error' => null,
]);
return ['pending' => $pending, 'overdue' => $overdue->count(), 'p2' => count($p2Ids), 'sent' => true];
}
/** @return array{0:string,1:string} */
private function instantMessage(object $record): array
{
$level = (string) ($record->alert_level ?? '');
$levelLabel = (string) (config('store_violations.alert_levels.' . $level . '.label') ?? $level);
$platformLabel = (string) (config('store_violations.platforms.' . (string) ($record->platform ?? '') . '.label') ?? ($record->platform ?? ''));
$title = '店铺违规预警(' . $levelLabel . ')';
$lines = [
'### 【' . $levelLabel . '】店铺违规预警',
'- 平台/店铺:' . $platformLabel . ' / ' . (string) ($record->shop_name ?? ''),
'- 违规类型:' . mb_substr((string) ($record->violation_type ?? ''), 0, 200),
'- 处罚措施:' . (trim((string) ($record->disposition ?? '')) !== '' ? (string) $record->disposition : '—'),
'- 处理建议:' . (trim((string) ($record->alert_action ?? '')) !== '' ? (string) $record->alert_action : '按平台规则处理'),
'- 责任人:' . (trim((string) ($record->owner_name ?? '')) !== '' ? (string) $record->owner_name : '未分配'),
'- 处理截止:' . (string) ($record->handling_deadline ?? '—'),
];
$claimUrl = $this->claimUrl((int) $record->id);
if ($claimUrl !== null) {
$lines[] = '- [去认领](' . $claimUrl . ')(认领后处理状态自动变为「处理中」)';
}
return [$title, implode("\n", $lines)];
}
private function claimUrl(int $recordId): ?string
{
try {
$companyId = (int) (Company::query()->orderBy('id')->value('id') ?? 1);
return URL::signedRoute('business.store-violation-alert.claim', [
'record' => $recordId,
'company_id' => $companyId,
]);
} catch (Throwable) {
return null;
}
}
/** @param list<string> $atMobiles */
private function send(string $title, string $text, array $atMobiles): void
{
$config = (array) config('store_violations.push', []);
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
throw new RuntimeException('推送 Webhook 未配置。');
}
$url = $webhook;
$secret = trim((string) ($config['secret'] ?? ''));
if ($secret !== '') {
$timestamp = (string) (int) (microtime(true) * 1000);
$sign = urlencode(base64_encode(hash_hmac('sha256', $timestamp . "\n" . $secret, $secret, true)));
$url .= (str_contains($url, '?') ? '&' : '?') . 'timestamp=' . $timestamp . '&sign=' . $sign;
}
$response = Http::timeout(10)->post($url, [
'msgtype' => 'markdown',
'markdown' => ['title' => $title, 'text' => $text],
'at' => [
'atMobiles' => array_values($atMobiles),
'isAtAll' => (bool) ($config['at_all'] ?? false),
],
]);
if (! $response->successful()) {
throw new RuntimeException('推送接口返回 HTTP ' . $response->status());
}
$body = (array) $response->json();
if ((int) ($body['errcode'] ?? 0) !== 0) {
throw new RuntimeException('推送接口错误:' . (string) ($body['errcode'] ?? '?') . ' ' . (string) ($body['errmsg'] ?? ''));
}
}
private function pushNo(): string
{
return 'VP' . Carbon::now()->format('ymdHis') . strtoupper(substr(bin2hex(random_bytes(4)), 0, 6));
}
}

View File

@ -1,519 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Repositories\StoreViolationRecordRepository;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Throwable;
/**
* 店铺违规信息预警:导入文件按统一表头映射到 store_violation_records。
*
* preview() 只解析和校验,不写库;commit() 按 (platform, violation_no) 幂等写入。
*/
class StoreViolationWorkbookImporter
{
public function __construct(
private readonly StoreViolationMapper $mapper,
private readonly StoreViolationRecordRepository $repository,
private readonly StoreViolationAlertCalculator $alerts,
) {
}
/**
* @return array{platform:string,sheet:string,columns:list<array{key:string,label:string}>,unknown_headers:list<string>,rows:list<array>,summary:array,existing_checked:bool}
*/
public function preview(UploadedFile $file, string $platform): array
{
$platforms = (array) config('store_violations.platforms', []);
if (! array_key_exists($platform, $platforms)) {
throw ValidationException::withMessages(['import' => '未知平台,请刷新页面后重试。']);
}
if (! $this->repository->available()) {
throw ValidationException::withMessages(['import' => '导入功能尚未就绪:统一表尚未建立,请联系管理员完成迁移。']);
}
try {
$spreadsheet = IOFactory::load($file->getRealPath());
} catch (Throwable $exception) {
report($exception);
throw ValidationException::withMessages(['import' => '无法读取该文件,请上传 xlsx / xls / csv 格式的表格。']);
}
$worksheet = $spreadsheet->getActiveSheet();
$matrix = $worksheet->toArray(null, true, true, false);
[$headerIndex, $columnMap, $unknownHeaders] = $this->detectHeaders($matrix);
if ($headerIndex === null) {
throw ValidationException::withMessages([
'import' => '未找到可识别的表头行,请使用统一表头或下载导入模板。',
]);
}
$missing = [];
foreach (['shop_name', 'violation_no'] as $required) {
if (! in_array($required, $columnMap, true)) {
$missing[] = $this->labelFor($required);
}
}
if ($missing !== []) {
throw ValidationException::withMessages([
'import' => '缺少必填列:' . implode('、', $missing) . '。请使用统一表头或下载导入模板。',
]);
}
$maxRows = (int) config('store_violations.import.max_rows', 20000);
$dataRows = array_slice($matrix, $headerIndex + 1);
if (count($dataRows) > $maxRows) {
throw ValidationException::withMessages([
'import' => '单次最多导入 ' . number_format($maxRows) . ' 行,请拆分文件后重试。',
]);
}
$rows = [];
$seen = [];
$invalid = 0;
foreach ($dataRows as $offset => $row) {
$rowNumber = $headerIndex + 2 + $offset;
$raw = $this->rowToFields($row, $columnMap);
if ($this->isEmptyRow($raw)) {
continue;
}
$item = $this->normalizeRow($raw, $platform, $rowNumber, $columnMap);
if ($item['status'] === 'valid') {
$key = $platform . '|' . $item['data']['violation_no'];
if (isset($seen[$key])) {
$item = $seen[$key]['data'] === $item['data']
? $this->markRow($item, 'same', '与文件内前一行重复,将跳过')
: $this->markRow($item, 'invalid', '与文件内前一行的数据冲突,请先合并');
} else {
$seen[$key] = $item;
}
}
if ($item['status'] === 'invalid') {
$invalid++;
}
$rows[] = $item;
}
$summary = ['new' => 0, 'update' => 0, 'same' => 0, 'invalid' => $invalid];
$this->compareWithExisting($rows, $platform, $summary);
return [
'platform' => $platform,
'sheet' => $worksheet->getTitle(),
'columns' => collect((array) config('store_violations.columns', []))
->map(fn (array $column): array => ['key' => $column['key'], 'label' => $column['label']])
->all(),
'unknown_headers' => $unknownHeaders,
'provided_columns' => array_values($columnMap),
'rows' => $rows,
'summary' => $summary,
];
}
/** @param array{rows:list<array>} $preview */
public function commit(array $preview): array
{
$platform = (string) ($preview['platform'] ?? '');
$rows = $preview['rows'] ?? [];
$provided = array_values(array_unique((array) ($preview['provided_columns'] ?? [])));
$now = now();
$unifiedColumns = array_map(
static fn (array $column): string => (string) $column['key'],
(array) config('store_violations.columns', []),
);
$updateColumns = array_values(array_intersect($unifiedColumns, $provided));
if (! in_array('violation_category', $updateColumns, true) && in_array('violation_type', $provided, true)) {
$updateColumns[] = 'violation_category';
}
$updateColumns[] = 'source';
$updateColumns[] = 'updated_at';
// 预警派生字段(级别/责任人/处理截止等):导入时按当前字典自动计算写入。
$updateColumns = array_values(array_unique(array_merge(
$updateColumns,
StoreViolationRecordRepository::ALERT_DERIVED_COLUMNS,
)));
$payload = [];
$created = 0;
$updated = 0;
foreach ($rows as $row) {
$status = $row['status'] ?? '';
if (! in_array($status, ['new', 'update'], true)) {
continue;
}
$data = $row['data'] ?? [];
if (($data['platform'] ?? null) !== $platform || ($data['violation_no'] ?? '') === '') {
continue;
}
$matchType = trim((string) ($data['violation_type'] ?? '')) !== ''
? (string) $data['violation_type']
: ($data['violation_reason'] ?? null);
$data = array_merge($data, $this->alerts->calculate(
$platform,
(string) ($data['shop_name'] ?? ''),
$matchType,
$data['violation_date'] ?? null,
$data['appeal_deadline'] ?? null,
));
foreach (array_values(array_diff($updateColumns, ['source', 'updated_at'])) as $column) {
if (! array_key_exists($column, $data)) {
$data[$column] = null;
}
}
$payload[] = $data + [
'source' => 'import',
'created_at' => $now,
'updated_at' => $now,
];
$status === 'new' ? $created++ : $updated++;
}
$affected = $this->repository->upsertRows($payload, $updateColumns);
return ['created' => $created, 'updated' => $updated, 'affected' => $affected];
}
/**
* @param list<list<mixed>> $matrix
* @return array{0:?int,1:list<string>,2:list<string>}
*/
private function detectHeaders(array $matrix): array
{
$bestIndex = null;
$bestMap = [];
$bestUnknown = [];
$bestScore = 0;
foreach ($matrix as $index => $row) {
$map = [];
$unknown = [];
foreach ($row as $cell) {
$label = trim((string) $cell);
if ($label === '') {
continue;
}
$key = $this->matchHeader($label);
if ($key === null) {
$unknown[] = $label;
continue;
}
if (! in_array($key, $map, true)) {
$map[] = $key;
}
}
if (count($map) > $bestScore) {
$bestIndex = $index;
$bestMap = $map;
$bestUnknown = $unknown;
$bestScore = count($map);
}
// 命中 6 列以上视为表头,避免把数据行误判为表头
if ($bestScore >= 6) {
break;
}
}
if ($bestIndex === null || $bestScore < 2) {
return [null, [], []];
}
return [$bestIndex, $bestMap, array_values(array_unique($bestUnknown))];
}
private function matchHeader(string $label): ?string
{
$normalized = mb_strtolower(preg_replace('/[\s"* ]/u', '', $label) ?? $label);
foreach ((array) config('store_violations.header_aliases', []) as $key => $aliases) {
foreach ((array) $aliases as $alias) {
$alias = mb_strtolower(preg_replace('/[\s"* ]/u', '', (string) $alias) ?? (string) $alias);
if ($alias !== '' && $normalized === $alias) {
return (string) $key;
}
}
}
return null;
}
/**
* @param list<mixed> $row
* @param list<string> $columnMap
* @return array<string,mixed>
*/
private function rowToFields(array $row, array $columnMap): array
{
$fields = [];
foreach ($row as $index => $cell) {
$key = $columnMap[$index] ?? null;
if ($key !== null) {
$fields[$key] = $cell;
}
}
return $fields;
}
/** @param array<string,mixed> $fields */
private function isEmptyRow(array $fields): bool
{
foreach ($fields as $value) {
if (trim((string) $value) !== '') {
return false;
}
}
return true;
}
/**
* @param array<string,mixed> $raw
* @return array{row_number:int,status:string,message:string,data:array<string,mixed>}
*/
private function normalizeRow(array $raw, string $platform, int $rowNumber, array $provided): array
{
$errors = [];
$data = ['platform' => $platform];
$has = static fn (string $key): bool => in_array($key, $provided, true);
if ($has('shop_name')) {
$shopName = trim((string) ($raw['shop_name'] ?? ''));
if ($shopName === '') {
$errors[] = '店铺名不能为空';
} elseif (mb_strlen($shopName) > 191) {
$errors[] = '店铺名超过 191 字';
}
$data['shop_name'] = mb_substr($shopName, 0, 191);
}
if ($has('violation_no')) {
$violationNo = trim((string) ($raw['violation_no'] ?? ''));
if ($violationNo === '') {
$errors[] = '违规单号不能为空';
} elseif (mb_strlen($violationNo) > 100) {
$errors[] = '违规单号超过 100 字';
}
$data['violation_no'] = mb_substr($violationNo, 0, 100);
}
$type = $has('violation_type') ? trim((string) ($raw['violation_type'] ?? '')) : null;
if ($has('violation_type')) {
$data['violation_type'] = $type === '' ? null : mb_substr($type, 0, 500);
}
$reason = $has('violation_reason') ? trim((string) ($raw['violation_reason'] ?? '')) : null;
if ($has('violation_reason')) {
$data['violation_reason'] = $reason === '' ? null : mb_substr($reason, 0, 500);
}
if ($has('disposition')) {
$disposition = trim((string) ($raw['disposition'] ?? ''));
$data['disposition'] = $disposition === '' ? null : mb_substr($disposition, 0, 500);
}
if ($has('violation_category')) {
$categorySource = ($type !== null && $type !== '') ? $type : (string) $reason;
$category = trim((string) ($raw['violation_category'] ?? ''));
$data['violation_category'] = $category === ''
? $this->mapper->categoryForContent($categorySource)
: mb_substr($category, 0, 64);
} elseif ($has('violation_type') || $has('violation_reason')) {
$categorySource = ($type !== null && $type !== '') ? $type : (string) $reason;
$data['violation_category'] = $this->mapper->categoryForContent($categorySource);
}
if ($has('violation_date')) {
try {
$data['violation_date'] = $this->mapper->normalizeDate($raw['violation_date'] ?? null);
} catch (Throwable $exception) {
$errors[] = '违规日期:' . $exception->getMessage();
$data['violation_date'] = null;
}
}
if ($has('points_deducted')) {
try {
$data['points_deducted'] = $this->mapper->normalizePoints($raw['points_deducted'] ?? null);
} catch (Throwable $exception) {
$errors[] = '扣分:' . $exception->getMessage();
$data['points_deducted'] = null;
}
}
if ($has('status')) {
$status = trim((string) ($raw['status'] ?? ''));
$data['status'] = $status === '' ? null : mb_substr($status, 0, 64);
}
if ($has('penalty_date')) {
try {
$data['penalty_date'] = $this->mapper->normalizeDate($raw['penalty_date'] ?? null);
} catch (Throwable $exception) {
$errors[] = '处罚日期:' . $exception->getMessage();
$data['penalty_date'] = null;
}
}
if ($has('appeal_deadline')) {
try {
$data['appeal_deadline'] = $this->mapper->normalizeDate($raw['appeal_deadline'] ?? null);
} catch (Throwable $exception) {
$errors[] = '申诉截止日期:' . $exception->getMessage();
$data['appeal_deadline'] = null;
}
}
if ($has('handling_status')) {
$handling = trim((string) ($raw['handling_status'] ?? ''));
$legacyMap = (array) config('store_violations.handling_status_legacy', []);
$handling = (string) ($legacyMap[$handling] ?? $handling);
$options = (array) config('store_violations.handling_statuses', []);
if ($handling === '') {
$data['handling_status'] = (string) config('store_violations.default_handling_status', '未处理');
} elseif (! in_array($handling, $options, true)) {
$errors[] = '处理状态必须是:' . implode('、', $options);
$data['handling_status'] = $handling;
} else {
$data['handling_status'] = $handling;
}
}
if ($has('ignore_reason')) {
$ignoreReason = trim((string) ($raw['ignore_reason'] ?? ''));
$data['ignore_reason'] = $ignoreReason === '' ? null : mb_substr($ignoreReason, 0, 191);
}
if (($data['handling_status'] ?? null) === '已忽略' && trim((string) ($data['ignore_reason'] ?? '')) === '') {
$errors[] = '处理状态为“已忽略”时必须填写忽略原因';
}
return [
'row_number' => $rowNumber,
'status' => $errors === [] ? 'valid' : 'invalid',
'message' => $errors === [] ? '待导入' : implode(';', $errors),
'data' => $data,
];
}
private function markRow(array $row, string $status, string $message): array
{
$row['status'] = $status;
$row['message'] = $message;
return $row;
}
/**
* 与库内已有记录比对:无 → new,字段完全一致 → same,否则 → update。
*
* @param list<array> $rows
*/
private function compareWithExisting(array &$rows, string $platform, array &$summary): void
{
$keys = collect($rows)
->filter(fn (array $row): bool => $row['status'] === 'valid' && ($row['data']['violation_no'] ?? '') !== '')
->pluck('data.violation_no')
->unique()
->values();
if ($keys->isEmpty()) {
return;
}
$existing = collect();
foreach ($keys->chunk(500) as $chunk) {
$existing = $existing->merge(
DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'))
->table(StoreViolationRecordRepository::TABLE)
->where('platform', $platform)
->whereIn('violation_no', $chunk->all())
->get()
->keyBy('violation_no'),
);
}
foreach ($rows as $index => $row) {
if ($row['status'] !== 'valid') {
continue;
}
$record = $existing->get($row['data']['violation_no']);
if ($record === null) {
$summary['new']++;
$rows[$index] = $this->markRow($row, 'new', '新增记录');
continue;
}
$rows[$index] = $this->sameAsExisting($row['data'], $record)
? $this->markRow($row, 'same', '与库内记录一致,将跳过')
: $this->markRow($row, 'update', '库内已有该单号,将按文件内容更新');
$rows[$index]['status'] === 'same' ? $summary['same']++ : $summary['update']++;
}
}
private function sameAsExisting(array $data, object $record): bool
{
$normalizePoints = static function (mixed $value): string {
if ($value === null || $value === '') {
return '';
}
return number_format((float) $value, 2, '.', '');
};
foreach ($data as $key => $value) {
if ($key === 'platform') {
continue;
}
$current = $record->{$key} ?? null;
if ($key === 'points_deducted') {
if ($normalizePoints($value) !== $normalizePoints($current)) {
return false;
}
continue;
}
if (trim((string) $value) !== trim((string) $current)) {
return false;
}
}
return true;
}
private function labelFor(string $key): string
{
foreach ((array) config('store_violations.columns', []) as $column) {
if (($column['key'] ?? null) === $key) {
return (string) $column['label'];
}
}
return $key;
}
}

View File

@ -1,939 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\InventoryWarehouseNameMapping;
use DateTimeImmutable;
use DOMDocument;
use DOMXPath;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use RuntimeException;
use Throwable;
use XMLReader;
use ZipArchive;
/**
* 供应商汇总表月度增量导入。
*
* 仅追加目标月份的新行,不删除其他月份。内容相同的源明细按出现次序分配
* 稳定标识后全部保留;重复执行时只跳过已经写入的同一源行。
* 单行字段异常会进入失败清单,不阻断其他有效行。
*/
class SupplierSummaryInboundImporter
{
private const TABLE = 'inventory_inbound_detail_rows';
private const DETAIL_SHEET = '明细';
/** @var array<string,list<string>> */
private const REQUIRED_HEADERS = [
'source_no' => ['来源单号'],
'document_no' => ['单据编号(采购单号)', '单据编号(采购单号)', '单据编号'],
'supplier' => ['供应商'],
'item_no' => ['货号'],
'barcode' => ['条码'],
'spec_name' => ['规格名'],
'quantity' => ['库存变动量'],
'unit_price' => ['单价'],
'amount' => ['金额'],
'estimated_unit_price' => ['预估单价'],
'estimated_amount' => ['预估金额'],
'supplier_barcode' => ['供应商条码'],
'remark' => ['备注'],
'warehouse' => ['仓库'],
];
/** @var array<string,list<string>> */
private const OPTIONAL_HEADERS = [
'express_name' => ['快递名称'],
'express_no' => ['快递单号'],
'not_sent' => ['未发出'],
'owner_name' => ['负责人'],
];
/**
* @return array{
* status:string,
* report_month:string,
* source_filename:string,
* success:int,
* duplicates:int,
* failed:int,
* mapped:int,
* total_in_table:int,
* failure_reason_count:int,
* failure_reasons:list<array{row:int,reason:string}>
* }
*/
public function import(string $file, string $reportMonth): array
{
$path = realpath($file);
if ($path === false || ! is_file($path) || ! is_readable($path)) {
throw new RuntimeException('供应商汇总文件不存在或不可读取。');
}
$month = $this->normalizeMonth($reportMonth);
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$maps = $this->shortNameMap();
[$reader, $sharedStrings] = $this->streamDetailSheet($path);
try {
$success = 0;
$duplicates = 0;
$mapped = 0;
$failed = 0;
$reasons = [];
$occurrences = [];
$batch = [];
DB::connection($connection)->transaction(function () use (
$connection,
$reader,
$sharedStrings,
$maps,
$month,
&$success,
&$duplicates,
&$mapped,
&$failed,
&$reasons,
&$occurrences,
&$batch,
): void {
$flush = function () use (
$connection,
$month,
&$success,
&$duplicates,
&$batch,
): void {
if ($batch === []) {
return;
}
$keys = array_column($batch, 'row_key');
$existing = DB::connection($connection)
->table(self::TABLE)
->where('report_month', $month)
->whereIn('row_key', $keys)
->pluck('row_key')
->map(static fn (mixed $key): string => (string) $key)
->all();
$existing = array_fill_keys($existing, true);
$insertable = [];
foreach ($batch as $record) {
if (isset($existing[$record['row_key']])) {
$duplicates++;
continue;
}
$insertable[] = $record;
}
if ($insertable !== []) {
$inserted = DB::connection($connection)
->table(self::TABLE)
->insertOrIgnore($insertable);
$success += (int) $inserted;
$duplicates += count($insertable) - (int) $inserted;
}
$batch = [];
};
$headerRow = null;
$columns = [];
$headerCandidates = [];
while ($reader->read()) {
if (
$reader->nodeType !== XMLReader::ELEMENT
|| $reader->name !== 'row'
) {
continue;
}
$rowNumber = (int) $reader->getAttribute('r');
$values = $this->readRow($reader, $sharedStrings);
if ($headerRow === null) {
$headerCandidates[$rowNumber] = $values;
$header = $this->headerColumns($headerCandidates);
if ($header !== null) {
[$headerRow, $columns] = $header;
$headerCandidates = [];
continue;
}
if ($rowNumber >= 20) {
throw new RuntimeException(
'「明细」子表前 20 行未找到供应商汇总标准表头。',
);
}
continue;
}
if ($rowNumber <= $headerRow) {
continue;
}
if ($this->emptyRow($values)) {
continue;
}
try {
$record = $this->record(
$values,
$columns,
$maps,
$month,
$rowNumber,
);
} catch (Throwable $exception) {
$failed++;
$reasons[] = [
'row' => $rowNumber,
'reason' => $exception->getMessage(),
];
continue;
}
$baseKey = (string) $record['row_key'];
$occurrence = ($occurrences[$baseKey] ?? 0) + 1;
$occurrences[$baseKey] = $occurrence;
if ($occurrence > 1) {
$record['row_key'] = hash(
'sha256',
$baseKey . '|occurrence:' . $occurrence,
);
}
$mapped++;
$batch[] = $record;
if (count($batch) >= 500) {
$flush();
}
}
if ($headerRow === null) {
throw new RuntimeException(
'「明细」子表前 20 行未找到供应商汇总标准表头。',
);
}
$flush();
});
$status = $failed === 0
? 'success'
: ($success > 0 ? 'partial' : 'failed');
return [
'status' => $status,
'report_month' => $month,
'source_filename' => basename($path),
'success' => $success,
'duplicates' => $duplicates,
'failed' => $failed,
'mapped' => $mapped,
'total_in_table' => DB::connection($connection)
->table(self::TABLE)
->where('report_month', $month)
->count(),
'failure_reason_count' => count($reasons),
'failure_reasons' => $reasons,
];
} finally {
$reader->close();
}
}
private function normalizeMonth(string $month): string
{
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
throw new RuntimeException('月份格式应为 YYYY-MM。');
}
return $month . '-01';
}
/**
* @param array<int,array<int,mixed>> $rows
* @return array{0:int,1:array<string,int>}|null
*/
private function headerColumns(array $rows): ?array
{
ksort($rows);
foreach ($rows as $row => $values) {
$positions = [];
foreach ($values as $index => $value) {
$heading = $this->normalizeHeader(
(string) $this->plainValue($value),
);
if ($heading !== '') {
$positions[$heading][] = $index;
}
}
$columns = [];
foreach (self::REQUIRED_HEADERS as $field => $aliases) {
$position = $this->firstHeaderPosition($positions, $aliases);
if ($position !== null) {
$columns[$field] = $position;
}
}
$createdPositions = $positions[$this->normalizeHeader('创建时间')] ?? [];
if (count($createdPositions) >= 2) {
$columns['created_serial'] = $createdPositions[0];
$columns['created_at_raw'] = $createdPositions[1];
}
if (count($columns) < count(self::REQUIRED_HEADERS) + 2) {
continue;
}
foreach (self::OPTIONAL_HEADERS as $field => $aliases) {
$position = $this->firstHeaderPosition($positions, $aliases);
if ($position !== null) {
$columns[$field] = $position;
}
}
foreach (['created_serial', 'created_at_raw'] as $field) {
if (! isset($columns[$field])) {
throw new RuntimeException('「明细」表头缺少第二个「创建时间」列。');
}
}
return [$row, $columns];
}
return null;
}
/** @param array<string,list<int>> $positions @param list<string> $aliases */
private function firstHeaderPosition(array $positions, array $aliases): ?int
{
foreach ($aliases as $alias) {
$heading = $this->normalizeHeader($alias);
if (isset($positions[$heading][0])) {
return $positions[$heading][0];
}
}
return null;
}
private function normalizeHeader(string $heading): string
{
return preg_replace('/[\s\x{3000}]+/u', '', trim($heading)) ?? trim($heading);
}
/**
* @param array<int,mixed> $values
* @param array<string,int> $columns
* @param array{warehouse:array<string,string>,provider:array<string,string>} $maps
* @return array<string,mixed>
*/
private function record(
array $values,
array $columns,
array $maps,
string $month,
int $rowNumber,
): array {
$text = fn (string $field): ?string => $this->text(
$values[$columns[$field] ?? -1] ?? null,
);
$number = function (string $label, string $field) use (
$values,
$columns,
$rowNumber,
): ?float {
$value = $values[$columns[$field] ?? -1] ?? null;
if (is_array($value)) {
$formula = trim((string) ($value['__formula'] ?? ''));
if ($formula !== '') {
return $this->formulaValue(
$label,
$field,
$formula,
$rowNumber,
$values,
$columns,
);
}
$value = $value['__cached'] ?? null;
}
$text = str_replace(
[',', ','],
'',
trim((string) $this->plainValue($value)),
);
if ($text === '') {
return null;
}
if (! is_numeric($text)) {
throw new RuntimeException("字段「{$label}」不是有效数字:" . $text);
}
return (float) $text;
};
$barcode = $text('barcode');
$warehouse = $text('warehouse');
if ($barcode === null) {
throw new RuntimeException('商品编码(条码)为空');
}
if ($warehouse === null) {
throw new RuntimeException('仓库为空');
}
$shortName = $maps['warehouse'][$warehouse]
?? $maps['provider'][$warehouse]
?? null;
if ($shortName === null || trim($shortName) === '') {
throw new RuntimeException('仓库未匹配到唯一仓库简称:' . $warehouse);
}
$createdRaw = $this->moment($values[$columns['created_at_raw']] ?? null);
if ($createdRaw === null) {
throw new RuntimeException('第二个「创建时间」为空或格式无效');
}
$record = [
'report_month' => $month,
'source_no' => $text('source_no'),
'document_no' => $text('document_no'),
'created_serial' => $text('created_serial'),
'supplier' => $text('supplier'),
'item_no' => $text('item_no'),
'barcode' => mb_strtoupper($barcode),
'spec_name' => $text('spec_name'),
'quantity' => $number('库存变动量', 'quantity'),
'unit_price' => $number('单价', 'unit_price'),
'amount' => $number('金额', 'amount'),
'estimated_unit_price' => $number('预估单价', 'estimated_unit_price'),
'estimated_amount' => $number('预估金额', 'estimated_amount'),
'supplier_barcode' => $text('supplier_barcode'),
'remark' => $text('remark'),
'warehouse' => $warehouse,
'warehouse_short_name' => $shortName,
'created_at_raw' => $createdRaw,
'express_name' => $text('express_name'),
'express_no' => $text('express_no'),
'not_sent' => $text('not_sent'),
'owner_name' => $text('owner_name'),
];
unset($record['warehouse_short_name']);
$record['row_key'] = hash(
'sha256',
json_encode($record, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
);
$record['warehouse_short_name'] = $shortName;
$record['imported_at'] = now();
return $record;
}
/**
* 仅接受金额类字段当前行内的乘积公式,避免执行来源文件中的任意公式。
*
* @param array<int,mixed> $values
* @param array<string,int> $columns
*/
private function formulaValue(
string $label,
string $field,
string $formula,
int $rowNumber,
array $values,
array $columns,
): float {
$expectedFields = match ($field) {
'amount' => ['quantity', 'unit_price'],
'estimated_amount' => ['estimated_unit_price', 'quantity'],
default => [],
};
if ($expectedFields === []) {
throw new RuntimeException(
"字段「{$label}」不允许使用公式:" . $formula,
);
}
if (
preg_match(
'/^=?\s*\$?([A-Z]{1,3})\$?(\d+)\s*\*\s*\$?([A-Z]{1,3})\$?(\d+)\s*$/i',
$formula,
$matches,
) !== 1
) {
throw new RuntimeException(
"字段「{$label}」公式无法安全识别:" . $formula,
);
}
if ((int) $matches[2] !== $rowNumber || (int) $matches[4] !== $rowNumber) {
throw new RuntimeException(
"字段「{$label}」公式引用了其他行:" . $formula,
);
}
$actualColumns = [
$this->columnIndex($matches[1]),
$this->columnIndex($matches[3]),
];
$expectedColumns = [
$columns[$expectedFields[0]] + 1,
$columns[$expectedFields[1]] + 1,
];
sort($actualColumns);
sort($expectedColumns);
if ($actualColumns !== $expectedColumns) {
throw new RuntimeException(
"字段「{$label}」公式与取数口径不一致:" . $formula,
);
}
$left = $this->numericReference(
$values[$actualColumns[0] - 1] ?? null,
$label,
);
$right = $this->numericReference(
$values[$actualColumns[1] - 1] ?? null,
$label,
);
return $left * $right;
}
private function numericReference(mixed $value, string $label): float
{
if (is_array($value)) {
if (($value['__formula'] ?? '') !== '') {
throw new RuntimeException(
"字段「{$label}」的公式引用了另一个公式单元格",
);
}
$value = $value['__cached'] ?? null;
}
$text = str_replace(
[',', ','],
'',
trim((string) $this->plainValue($value)),
);
if (! is_numeric($text)) {
throw new RuntimeException(
"字段「{$label}」的公式引用值不是有效数字:" . $text,
);
}
return (float) $text;
}
/** @param array<int,mixed> $values */
private function emptyRow(array $values): bool
{
foreach ($values as $value) {
if (trim((string) $this->plainValue($value)) !== '') {
return false;
}
}
return true;
}
private function text(mixed $value): ?string
{
$text = trim((string) $this->plainValue($value));
return $text === '' ? null : $text;
}
private function plainValue(mixed $value): mixed
{
if (is_array($value)) {
return $value['__cached'] ?? null;
}
return $value;
}
private function moment(mixed $value): ?string
{
$value = $this->plainValue($value);
if ($value === null || trim((string) $value) === '') {
return null;
}
if (is_numeric($value)) {
try {
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d H:i:s');
} catch (Throwable) {
return null;
}
}
$value = trim((string) $value);
foreach (['Y/m/d H:i:s', 'Y-m-d H:i:s', 'Y/m/d', 'Y-m-d'] as $format) {
$date = DateTimeImmutable::createFromFormat($format, $value);
if ($date instanceof DateTimeImmutable) {
return $date->format('Y-m-d H:i:s');
}
}
$timestamp = strtotime($value);
return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
}
/** @return array{warehouse:array<string,string>,provider:array<string,string>} */
private function shortNameMap(): array
{
$rows = InventoryWarehouseNameMapping::withoutGlobalScopes()
->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']);
$grouped = [];
foreach ($rows as $row) {
$warehouse = trim((string) $row->warehouse);
if ($warehouse !== '') {
$grouped[$warehouse][] = trim((string) $row->warehouse_short_name);
}
}
$byWarehouse = [];
foreach ($grouped as $warehouse => $names) {
$unique = array_values(array_unique($names));
if (count($unique) === 1 && $unique[0] !== '') {
$byWarehouse[$warehouse] = $unique[0];
}
}
$providerGrouped = [];
foreach ($rows as $row) {
$provider = trim((string) $row->warehouse_provider);
if ($provider !== '') {
$providerGrouped[$provider][] = [
'warehouse' => trim((string) $row->warehouse),
'short_name' => trim((string) $row->warehouse_short_name),
];
}
}
$byProvider = [];
foreach ($providerGrouped as $provider => $providerRows) {
$unique = array_values(array_unique(array_column(
$providerRows,
'short_name',
)));
if (count($unique) === 1 && $unique[0] !== '') {
$byProvider[$provider] = $unique[0];
continue;
}
$mainShortNames = [];
foreach ($providerRows as $providerRow) {
if (str_contains($providerRow['warehouse'], '主仓')) {
$mainShortNames[] = $providerRow['short_name'];
}
}
$mainShortNames = array_values(array_unique($mainShortNames));
if (count($mainShortNames) === 1 && $mainShortNames[0] !== '') {
$byProvider[$provider] = $mainShortNames[0];
}
}
return ['warehouse' => $byWarehouse, 'provider' => $byProvider];
}
/** @return array{0:XMLReader,1:list<string>} */
private function streamDetailSheet(string $path): array
{
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
throw new RuntimeException('供应商汇总文件不是有效的 XLSX 工作簿。');
}
try {
$sheetPath = $this->detailSheetPath($zip);
$sharedStrings = $zip->locateName('xl/sharedStrings.xml') !== false
? $this->readSharedStrings($path)
: [];
} finally {
$zip->close();
}
return [
$this->openZipEntry($path, $sheetPath),
$sharedStrings,
];
}
private function detailSheetPath(ZipArchive $zip): string
{
$workbookXml = $zip->getFromName('xl/workbook.xml');
$relationshipsXml = $zip->getFromName('xl/_rels/workbook.xml.rels');
if ($workbookXml === false || $relationshipsXml === false) {
throw new RuntimeException('供应商汇总工作簿缺少工作簿结构文件。');
}
$workbook = new DOMDocument();
$relationships = new DOMDocument();
if (
! $workbook->loadXML($workbookXml, LIBXML_NONET)
|| ! $relationships->loadXML($relationshipsXml, LIBXML_NONET)
) {
throw new RuntimeException('供应商汇总工作簿结构无法读取。');
}
$relationshipId = null;
$xpath = new DOMXPath($workbook);
$xpath->registerNamespace(
'main',
'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
);
$xpath->registerNamespace(
'office',
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
);
foreach ($xpath->query('/main:workbook/main:sheets/main:sheet') ?: [] as $sheet) {
if ($sheet instanceof \DOMElement
&& $sheet->getAttribute('name') === self::DETAIL_SHEET
) {
$relationshipId = $sheet->getAttributeNS(
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'id',
);
break;
}
}
if ($relationshipId === null || $relationshipId === '') {
throw new RuntimeException('供应商汇总表缺少「明细」子表。');
}
$target = null;
foreach ($relationships->getElementsByTagName('Relationship') as $relationship) {
if ($relationship->getAttribute('Id') === $relationshipId) {
$target = $relationship->getAttribute('Target');
break;
}
}
if ($target === null || $target === '') {
throw new RuntimeException('「明细」子表的工作簿关系不存在。');
}
return $this->normalizeZipPath(
str_starts_with($target, '/') ? ltrim($target, '/') : 'xl/' . $target,
);
}
private function normalizeZipPath(string $path): string
{
$segments = [];
foreach (explode('/', str_replace('\\', '/', $path)) as $segment) {
if ($segment === '' || $segment === '.') {
continue;
}
if ($segment === '..') {
array_pop($segments);
continue;
}
$segments[] = $segment;
}
return implode('/', $segments);
}
/** @return list<string> */
private function readSharedStrings(string $path): array
{
$reader = $this->openZipEntry($path, 'xl/sharedStrings.xml');
$strings = [];
$current = null;
$stringDepth = null;
$phoneticDepth = null;
try {
while ($reader->read()) {
if (
$reader->nodeType === XMLReader::ELEMENT
&& $reader->name === 'si'
) {
$current = '';
$stringDepth = $reader->depth;
$phoneticDepth = null;
continue;
}
if ($current === null) {
continue;
}
if (
$reader->nodeType === XMLReader::ELEMENT
&& $reader->name === 'rPh'
) {
$phoneticDepth = $reader->depth;
continue;
}
if (
$reader->nodeType === XMLReader::END_ELEMENT
&& $reader->name === 'rPh'
&& $reader->depth === $phoneticDepth
) {
$phoneticDepth = null;
continue;
}
if (
$reader->nodeType === XMLReader::ELEMENT
&& $reader->name === 't'
&& $phoneticDepth === null
) {
$current .= $reader->readString();
continue;
}
if (
$reader->nodeType === XMLReader::END_ELEMENT
&& $reader->name === 'si'
&& $reader->depth === $stringDepth
) {
$strings[] = $current;
$current = null;
}
}
} finally {
$reader->close();
}
return $strings;
}
private function openZipEntry(string $path, string $entry): XMLReader
{
$reader = new XMLReader();
$flags = LIBXML_NONET | LIBXML_COMPACT;
if (! $reader->open("zip://{$path}#{$entry}", null, $flags)) {
throw new RuntimeException("无法读取工作簿内容:{$entry}");
}
return $reader;
}
/**
* @param list<string> $sharedStrings
* @return array<int,mixed>
*/
private function readRow(XMLReader $reader, array $sharedStrings): array
{
$values = [];
$rowDepth = $reader->depth;
while ($reader->read()) {
if (
$reader->nodeType === XMLReader::END_ELEMENT
&& $reader->name === 'row'
&& $reader->depth === $rowDepth
) {
break;
}
if (
$reader->nodeType !== XMLReader::ELEMENT
|| $reader->name !== 'c'
) {
continue;
}
$reference = $reader->getAttribute('r') ?? '';
if (
preg_match('/^([A-Z]{1,3})\d+$/i', $reference, $matches) !== 1
) {
continue;
}
$values[$this->columnIndex($matches[1]) - 1] = $this->readCell(
$reader,
$sharedStrings,
);
}
return $values;
}
/** @param list<string> $sharedStrings */
private function readCell(XMLReader $reader, array $sharedStrings): mixed
{
if ($reader->isEmptyElement) {
return null;
}
$type = $reader->getAttribute('t') ?? '';
$cellDepth = $reader->depth;
$cached = null;
$formula = null;
$hasFormula = false;
$inlineParts = [];
$phoneticDepth = null;
while ($reader->read()) {
if (
$reader->nodeType === XMLReader::END_ELEMENT
&& $reader->name === 'c'
&& $reader->depth === $cellDepth
) {
break;
}
if ($reader->nodeType === XMLReader::ELEMENT) {
if ($reader->name === 'f') {
$hasFormula = true;
$formula = $reader->readString();
continue;
}
if ($reader->name === 'v') {
$cached = $reader->readString();
continue;
}
if ($reader->name === 'rPh') {
$phoneticDepth = $reader->depth;
continue;
}
if (
$reader->name === 't'
&& $phoneticDepth === null
) {
$inlineParts[] = $reader->readString();
}
}
if (
$reader->nodeType === XMLReader::END_ELEMENT
&& $reader->name === 'rPh'
&& $reader->depth === $phoneticDepth
) {
$phoneticDepth = null;
}
}
$value = match ($type) {
's' => is_numeric($cached)
? ($sharedStrings[(int) $cached] ?? null)
: null,
'inlineStr' => implode('', $inlineParts),
'b' => $cached === null ? null : ($cached === '1' ? '1' : '0'),
default => $cached ?? implode('', $inlineParts),
};
if ($hasFormula) {
return [
'__formula' => (string) $formula,
'__cached' => $value,
];
}
return $value;
}
private function columnIndex(string $column): int
{
$index = 0;
foreach (str_split(strtoupper($column)) as $letter) {
$index = ($index * 26) + (ord($letter) - 64);
}
return $index;
}
}

View File

@ -1,693 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\SystemizationTodo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Services\PayablesWorkbookStreamReader;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use RuntimeException;
class SystemizationTodoWorkbookImporter
{
private const REQUIRED_HEADERS = [
'category' => '类型',
'section' => '内容',
'title' => '待办事项',
'owner' => '总负责人',
'assignee' => '责任人',
'start' => '开始时间',
'finish' => '完成时间',
'progress' => '完成情况',
'notes' => '备注',
];
/**
* 导入财务系统化待办。只新增系统中不存在的来源行,不覆盖日常维护后的状态与截图。
*
* @return array{created:int,skipped:int,sheet:string}
*/
public function import(string $path, int $companyId, ?int $userId = null): array
{
if (! is_file($path)) {
throw new RuntimeException('找不到待办 Excel 文件。');
}
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ($extension !== 'xlsx') {
throw new RuntimeException('系统化待办仅支持 .xlsx 文件。');
}
$reader = PayablesWorkbookStreamReader::forFile($path, $extension);
foreach ($reader->sheetNames() as $sheetIndex => $sheetName) {
$headerInfo = $this->headerMap($reader, $sheetIndex);
if ($headerInfo === null) {
continue;
}
$header = $headerInfo['columns'];
$headerRow = $headerInfo['row'];
$rows = $this->workbookRows(
$reader,
$sheetIndex,
$sheetName,
$header,
$headerRow,
$companyId,
);
$created = 0;
$skipped = 0;
DB::transaction(function () use ($rows, $companyId, $userId, &$created, &$skipped): void {
foreach ($rows as $row) {
$exists = SystemizationTodo::withoutGlobalScopes()
->where('company_id', $companyId)
->where('source_key', $row['data']['source_key'])
->exists();
if ($exists) {
$skipped++;
continue;
}
SystemizationTodo::withoutGlobalScopes()->create([
...$row['data'],
'company_id' => $companyId,
'imported_at' => now(),
'created_by' => $userId,
'updated_by' => $userId,
]);
$created++;
}
});
return ['created' => $created, 'skipped' => $skipped, 'sheet' => $sheetName];
}
throw new RuntimeException(
'未找到待办表头。请确认工作表包含:类型、内容、待办事项、总负责人、责任人、开始时间、完成时间、完成情况、备注。'
);
}
/**
* 将新版工作簿同步到已有来源记录。保留截图和来源中已不在工作簿的事项,只新增和更新。
*
* @return array{created:int,updated:int,retained:int,sheet:string}
*/
public function sync(string $path, int $companyId, ?int $userId = null, bool $dryRun = false): array
{
if (! is_file($path)) {
throw new RuntimeException('找不到待办 Excel 文件。');
}
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ($extension !== 'xlsx') {
throw new RuntimeException('系统化待办仅支持 .xlsx 文件。');
}
$reader = PayablesWorkbookStreamReader::forFile($path, $extension);
foreach ($reader->sheetNames() as $sheetIndex => $sheetName) {
$headerInfo = $this->headerMap($reader, $sheetIndex);
if ($headerInfo === null) {
continue;
}
$rows = $this->workbookRows(
$reader,
$sheetIndex,
$sheetName,
$headerInfo['columns'],
$headerInfo['row'],
$companyId,
);
$existing = SystemizationTodo::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
->whereNotNull('imported_at')
->orderBy('sort_order')
->orderBy('id')
->get();
[$matches, $newIndexes] = $this->matchRows($rows, $existing);
$matchedIds = array_values($matches);
$retained = $existing
->filter(static fn (SystemizationTodo $todo): bool => ! in_array($todo->id, $matchedIds, true))
->sortBy(static fn (SystemizationTodo $todo): string =>
sprintf('%010d-%010d', (int) $todo->sort_order, (int) $todo->id)
)
->values();
$retainedSortOrder = max(
(int) $existing->max('sort_order'),
...array_map(
static fn (array $row): int => (int) $row['data']['sort_order'],
$rows,
),
) + 1;
$oldSourceKeys = $existing->pluck('source_key', 'id')->all();
$updated = 0;
foreach ($matches as $rowIndex => $todoId) {
$todo = $existing->firstWhere('id', $todoId);
if ($todo && $this->contentDiffers($todo, $rows[$rowIndex]['data'])) {
$updated++;
}
}
if ($dryRun) {
return [
'created' => count($newIndexes),
'updated' => $updated,
'retained' => $retained->count(),
'sheet' => $sheetName,
];
}
$created = 0;
$updated = 0;
DB::transaction(function () use (
$rows,
$matches,
$newIndexes,
$existing,
$retained,
$oldSourceKeys,
$retainedSortOrder,
$companyId,
$userId,
&$created,
&$updated,
): void {
SystemizationTodo::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
->whereNotNull('imported_at')
->update(['source_key' => null]);
foreach ($matches as $rowIndex => $todoId) {
$todo = $existing->firstWhere('id', $todoId);
if (! $todo) {
continue;
}
$todo->source_key = null;
$todo->syncOriginalAttribute('source_key');
$todo->fill($rows[$rowIndex]['data']);
$contentChanged = $todo->isDirty([
'category',
'section',
'title',
'owner',
'assignee',
'start_date',
'start_note',
'due_date',
'due_note',
'status',
'completed_at',
'progress',
'notes',
]);
$todo->updated_by = $userId;
$todo->save();
if ($contentChanged) {
$updated++;
}
}
foreach ($newIndexes as $rowIndex) {
SystemizationTodo::withoutGlobalScopes()->create([
...$rows[$rowIndex]['data'],
'company_id' => $companyId,
'imported_at' => now(),
'created_by' => $userId,
'updated_by' => $userId,
]);
$created++;
}
foreach ($retained as $todo) {
SystemizationTodo::withoutGlobalScopes()
->whereKey($todo->id)
->update([
'sort_order' => $retainedSortOrder++,
'source_key' => $oldSourceKeys[$todo->id] ?? null,
]);
}
});
return [
'created' => $created,
'updated' => $updated,
'retained' => $retained->count(),
'sheet' => $sheetName,
];
}
throw new RuntimeException(
'未找到待办表头。请确认工作表包含:类型、内容、待办事项、总负责人、责任人、开始时间、完成时间、完成情况、备注。'
);
}
/**
* @param array<int,int> $columns
* @return array<int,array{
* row:int,
* title_index:int,
* title_count:int,
* source_title:string,
* category:string,
* section:string,
* title:string,
* data:array<string,mixed>
* }>
*/
private function workbookRows(
PayablesWorkbookStreamReader $reader,
int $sheetIndex,
string $sheetName,
array $columns,
int $headerRow,
int $companyId,
): array {
$rows = [];
$category = '';
$section = '';
foreach ($reader->rows($sheetIndex) as $rowNumber => $cells) {
if ($rowNumber <= $headerRow) {
continue;
}
$categoryValue = $this->cell($cells, $columns['category'] ?? null);
if ($categoryValue !== '') {
$category = $categoryValue;
}
$sectionValue = $this->cell($cells, $columns['section'] ?? null);
if ($sectionValue !== '') {
$section = $sectionValue;
}
$sourceTitle = $this->cell($cells, $columns['title'] ?? null);
if ($sourceTitle === '') {
continue;
}
$titles = $this->titleSegments($sourceTitle);
$titleCount = count($titles);
$owner = $this->cell($cells, $columns['owner'] ?? null);
$assignee = $this->cell($cells, $columns['assignee'] ?? null);
$startText = $this->cell($cells, $columns['start'] ?? null);
$finishText = $this->cell($cells, $columns['finish'] ?? null);
[$startDate, $startNote] = $this->dateParts($startText);
[$finishDate, $finishNote] = $this->dateParts($finishText);
$progress = $this->cell($cells, $columns['progress'] ?? null);
$notes = $this->cell($cells, $columns['notes'] ?? null);
$status = $this->status($progress, $startText, $finishText);
foreach ($titles as $offset => $title) {
$titleIndex = $offset + 1;
$sortOrder = ($rowNumber * 100) + $titleIndex;
$rows[] = [
'row' => $rowNumber,
'title_index' => $titleIndex,
'title_count' => $titleCount,
'source_title' => $sourceTitle,
'category' => $category,
'section' => $section,
'title' => $title,
'data' => [
'category' => $category !== '' ? $category : null,
'section' => $section !== '' ? $section : null,
'title' => $title,
'owner' => $owner !== '' ? $owner : null,
'assignee' => $assignee !== '' ? $assignee : null,
'start_date' => $startDate,
'start_note' => $startNote !== '' ? $startNote : null,
'due_date' => $finishDate,
'due_note' => $finishNote !== '' ? $finishNote : null,
'status' => $status,
'completed_at' => $status === SystemizationTodo::STATUS_COMPLETED
? ($finishDate ?? now()->toDateString())
: null,
'progress' => $progress !== '' ? $progress : null,
'notes' => $notes !== '' ? $notes : null,
'sort_order' => $sortOrder,
'source_key' => hash(
'sha256',
implode('|', [
$companyId,
$sheetName,
$rowNumber,
$titleIndex,
$category,
$section,
$title,
$owner,
$assignee,
])
),
],
];
}
}
return $rows;
}
/**
* Split a cell into separate tasks only when it contains multiple numbered lines.
*
* @return array<int,string>
*/
private function titleSegments(string $value): array
{
$value = trim(str_replace(["\r\n", "\r"], "\n", $value));
$marker = '/^\s*(?:\d+|[一二三四五六七八九十百]+)\s*[、,,..::;;)]\s*/u';
$lines = preg_split('/\n/u', $value) ?: [];
$numberedLines = array_filter(
$lines,
static fn (string $line): bool => preg_match($marker, trim($line)) === 1,
);
if (count($numberedLines) < 2) {
return [$value];
}
$segments = [];
$current = '';
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
if (preg_match($marker, $line) === 1) {
if ($current !== '') {
$segments[] = trim($current);
}
$current = trim((string) preg_replace($marker, '', $line));
continue;
}
$current = $current === '' ? $line : $current . "\n" . $line;
}
if ($current !== '') {
$segments[] = trim($current);
}
return $segments !== [] ? $segments : [$value];
}
/**
* @param array<int,array{
* row:int,
* title_index:int,
* title_count:int,
* source_title:string,
* category:string,
* section:string,
* title:string,
* data:array<string,mixed>
* }> $rows
* @return array{0:array<int,int>,1:array<int,int>}
*/
private function matchRows(array $rows, \Illuminate\Support\Collection $existing): array
{
$matches = [];
$usedIds = [];
$candidates = [];
foreach ($existing as $todo) {
$candidates[$this->matchTitleKey($todo->title)][] = $todo;
}
foreach ($rows as $rowIndex => $row) {
if ($row['title_count'] < 2 || $row['title_index'] !== 1) {
continue;
}
$sourceKey = $this->matchTitleKey($row['source_title']);
$available = array_values(array_filter(
$candidates[$sourceKey] ?? [],
fn (SystemizationTodo $todo): bool =>
! in_array($todo->id, $usedIds, true)
&& $this->matchText($todo->category) === $this->matchText($row['category'])
&& $this->matchText($todo->section) === $this->matchText($row['section']),
));
if ($available === []) {
continue;
}
usort($available, static fn (SystemizationTodo $a, SystemizationTodo $b): int =>
abs($a->sort_order - $row['data']['sort_order'])
<=> abs($b->sort_order - $row['data']['sort_order'])
);
$matches[$rowIndex] = $available[0]->id;
$usedIds[] = $available[0]->id;
}
foreach ($rows as $rowIndex => $row) {
if (isset($matches[$rowIndex])) {
continue;
}
$key = $this->matchTitleKey($row['title']);
$available = array_values(array_filter(
$candidates[$key] ?? [],
static fn (SystemizationTodo $todo): bool => ! in_array($todo->id, $usedIds, true),
));
if ($available === []) {
continue;
}
usort($available, static fn (SystemizationTodo $a, SystemizationTodo $b): int =>
abs($a->sort_order - $row['data']['sort_order'])
<=> abs($b->sort_order - $row['data']['sort_order'])
);
$todo = $available[0];
$matches[$rowIndex] = $todo->id;
$usedIds[] = $todo->id;
}
$remainingIds = $existing
->pluck('id')
->reject(static fn (int $id): bool => in_array($id, $usedIds, true))
->values();
$todoById = $existing->keyBy('id');
$pairs = [];
foreach ($rows as $rowIndex => $row) {
if (isset($matches[$rowIndex])) {
continue;
}
foreach ($remainingIds as $todoId) {
$todo = $todoById->get($todoId);
if (! $todo
|| $this->matchText($todo->category) !== $this->matchText($row['category'])
|| $this->matchText($todo->section) !== $this->matchText($row['section'])) {
continue;
}
$similarity = $this->titleSimilarity((string) $todo->title, $row['title']);
if ($similarity >= 0.55) {
$pairs[] = [
'rowIndex' => $rowIndex,
'todoId' => $todoId,
'score' => $similarity - abs($todo->sort_order - $row['data']['sort_order']) / 1000,
];
}
}
}
usort($pairs, static fn (array $a, array $b): int => $b['score'] <=> $a['score']);
foreach ($pairs as $pair) {
if (isset($matches[$pair['rowIndex']]) || in_array($pair['todoId'], $usedIds, true)) {
continue;
}
$matches[$pair['rowIndex']] = $pair['todoId'];
$usedIds[] = $pair['todoId'];
}
return [
$matches,
array_values(array_filter(
array_keys($rows),
static fn (int $rowIndex): bool => ! isset($matches[$rowIndex]),
)),
];
}
private function matchTitleKey(?string $value): string
{
$value = preg_replace(
'/^\s*(?:\d+|[一二三四五六七八九十百]+)\s*[、,,..::;;)]\s*/u',
'',
(string) $value,
) ?? '';
return $this->matchText($value);
}
private function matchText(?string $value): string
{
return mb_strtolower(
preg_replace('/[\s “”"\',。;、,.!?::;()()【】\[\]—-]+/u', '', (string) $value) ?? '',
'UTF-8',
);
}
/**
* @param array<string,mixed> $data
*/
private function contentDiffers(SystemizationTodo $todo, array $data): bool
{
foreach ([
'category',
'section',
'title',
'owner',
'assignee',
'start_date',
'start_note',
'due_date',
'due_note',
'status',
'completed_at',
'progress',
'notes',
] as $field) {
$current = $todo->{$field};
$incoming = $data[$field] ?? null;
if ($current instanceof \DateTimeInterface && $incoming !== null) {
$current = $current->format('Y-m-d');
}
if ((string) ($current ?? '') !== (string) ($incoming ?? '')) {
return true;
}
}
return false;
}
private function titleSimilarity(string $left, string $right): float
{
$left = $this->matchTitleKey($left);
$right = $this->matchTitleKey($right);
if ($left === '' || $right === '') {
return 0.0;
}
if ($left === $right) {
return 1.0;
}
$leftChars = mb_str_split($left);
$rightChars = mb_str_split($right);
$leftPairs = [];
$rightPairs = [];
for ($index = 0; $index < count($leftChars) - 1; $index++) {
$leftPairs[$leftChars[$index] . $leftChars[$index + 1]] = true;
}
for ($index = 0; $index < count($rightChars) - 1; $index++) {
$rightPairs[$rightChars[$index] . $rightChars[$index + 1]] = true;
}
$leftPairs = array_keys($leftPairs);
$rightPairs = array_keys($rightPairs);
$containment = str_contains($left, $right) || str_contains($right, $left) ? 0.95 : 0.0;
$dice = ($leftPairs === [] || $rightPairs === [])
? 0.0
: 2 * count(array_intersect($leftPairs, $rightPairs)) / (count($leftPairs) + count($rightPairs));
return max($containment, $dice);
}
/**
* @return array{row:int,columns:array<string,int>}|null
*/
private function headerMap(PayablesWorkbookStreamReader $reader, int $sheetIndex): ?array
{
foreach ($reader->rows($sheetIndex, null, 12) as $rowNumber => $cells) {
$normalized = [];
foreach ($cells as $column => $value) {
$value = $this->normalizeHeader($this->text($value));
if ($value !== '') {
$normalized[$value] = $column;
}
}
$mapped = [];
foreach (self::REQUIRED_HEADERS as $field => $label) {
$needle = $this->normalizeHeader($label);
foreach ($normalized as $header => $column) {
if ($header === $needle || str_starts_with($header, $needle)) {
$mapped[$field] = $column;
break;
}
}
}
if (isset($mapped['title'])
&& isset($mapped['owner'])
&& isset($mapped['assignee'])) {
return ['row' => $rowNumber, 'columns' => $mapped];
}
}
return null;
}
private function normalizeHeader(string $value): string
{
return preg_replace('/[\s ()()]+/u', '', $value) ?? '';
}
/**
* @param array<int,mixed> $cells
*/
private function cell(array $cells, ?int $column): string
{
return $column === null ? '' : $this->text($cells[$column] ?? null);
}
private function text(mixed $value): string
{
if ($value === null) {
return '';
}
if (is_bool($value)) {
return $value ? '1' : '0';
}
return trim(str_replace("\u{00A0}", ' ', (string) $value));
}
/**
* @return array{0:string|null,1:string}
*/
private function dateParts(string $value): array
{
$value = trim($value);
if ($value === '' || $value === '已完成') {
return [null, ''];
}
if (is_numeric($value)) {
$serial = (float) $value;
if ($serial >= 20000 && $serial <= 80000) {
return [ExcelDate::excelToDateTimeObject($serial)->format('Y-m-d'), ''];
}
}
foreach (['Y-m-d', 'Y/m/d', 'Y.m.d', 'Y年n月j日'] as $format) {
try {
$date = Carbon::createFromFormat($format, $value);
if ($date !== false) {
return [$date->format('Y-m-d'), ''];
}
} catch (\Throwable) {
// 不是标准日期,保留原值作为时间备注。
}
}
return [null, mb_substr($value, 0, 100)];
}
private function status(string $progress, string $startNote, string $finishNote): string
{
if (str_contains($progress, '已完成')) {
return SystemizationTodo::STATUS_COMPLETED;
}
if ($progress !== '') {
return str_contains($progress, '延期')
? SystemizationTodo::STATUS_DELAYED
: SystemizationTodo::STATUS_IN_PROGRESS;
}
if (str_contains($startNote, '延期') || str_contains($finishNote, '延期')) {
return SystemizationTodo::STATUS_DELAYED;
}
return SystemizationTodo::STATUS_PENDING;
}
}

View File

@ -17,7 +17,6 @@ use App\Models\Business\StoreChange;
use App\Models\Business\StoreChangeLog;
use App\Models\Business\StoreClosing;
use App\Models\Business\StoreInformation;
use App\Models\Business\ShopInfoFlow;
use App\Models\Business\StoreInvoice;
use App\Models\Business\StoreOpening;
use App\Models\Business\StoreReceivingAccount;
@ -172,7 +171,6 @@ class TableRegistry
'fund-management/shared-company-accounts' => BankAccount::class, // 重用 BankAccount,仅类型过滤
'billing-transactions/store-receiving-balance' => StoreReceivingAccount::class,
'financial-operations/installation-details' => InstallationDetail::class,
'financial-risk-control/process-statistics' => ShopInfoFlow::class,
];
}
@ -262,7 +260,6 @@ class TableRegistry
'store-management/store-report',
'trademark-management/information',
'financial-operations/installation-details',
'financial-risk-control/process-statistics',
], true);
}

View File

@ -35,7 +35,7 @@ class TaobaoAlipayBillSpreadsheetImporter
'counterparty_account', 'account_order_no', 'business_serial_no', 'goods_name',
];
public function import(string $path, int $companyId, bool $replace = false): array
public function import(string $path, int $companyId): array
{
if (! is_file($path) || ! is_readable($path)) {
throw new InvalidArgumentException('导入文件不存在或不可读取。');
@ -55,27 +55,21 @@ class TaobaoAlipayBillSpreadsheetImporter
throw new InvalidArgumentException('表头与淘系支付宝账户模板不一致。');
}
$rows = [];
$skipped = 0;
for ($rowNumber = 2; $rowNumber <= $sheet->getHighestDataRow(); $rowNumber++) {
$values = $sheet->rangeToArray("A{$rowNumber}:Y{$rowNumber}", null, false, false)[0];
if (collect($values)->every(fn ($value) => $value === null || trim((string) $value) === '')) {
$skipped++;
continue;
}
$rows[] = $this->normalizeRow(array_combine(self::FIELDS, $values), $rowNumber);
}
$inserted = 0;
$updated = 0;
$replaced = 0;
$skipped = 0;
DB::transaction(function () use ($rows, $companyId, $replace, &$inserted, &$updated, &$replaced) {
if ($replace) {
$replaced = DB::table('ec_alipay_bills')->where('company_id', $companyId)->delete();
}
DB::transaction(function () use ($sheet, $companyId, &$inserted, &$updated, &$skipped) {
for ($rowNumber = 2; $rowNumber <= $sheet->getHighestDataRow(); $rowNumber++) {
$values = $sheet->rangeToArray("A{$rowNumber}:Y{$rowNumber}", null, false, false)[0];
foreach ($rows as $data) {
if (collect($values)->every(fn ($value) => $value === null || trim((string) $value) === '')) {
$skipped++;
continue;
}
$data = array_combine(self::FIELDS, $values);
$data = $this->normalizeRow($data, $rowNumber);
$record = AlipayBill::query()
->where('company_id', $companyId)
->where('record_code', $data['record_code'])
@ -99,7 +93,7 @@ class TaobaoAlipayBillSpreadsheetImporter
$spreadsheet->disconnectWorksheets();
return compact('inserted', 'updated', 'skipped', 'replaced');
return compact('inserted', 'updated', 'skipped');
}
private function normalizeRow(array $data, int $rowNumber): array

View File

@ -1,89 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Business;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* 三方仓核算的商品重量来源。
*
* 重量取【普通商品资料】主档「重量(kg)」,即业务镜像表 ops_jst_sku 的
* weight 列,按商品编码(sku_id)关联。字段与表定义与
* Modules\EcommerceFinance\Repositories\ProductCatalogMirrorRepository 一致
* (dataset operations_replica.rpt.jst_sku → ops_jst_sku,见 config/upstream_mirrors.php)。
* 同一编码可能有多条历史行,取最新 autoid 的重量。
*/
class ThirdPartyWarehouseProductWeightRepository
{
/** 普通商品资料主档在业务镜像中的落地表。 */
private const PRODUCT_TABLE = 'ops_jst_sku';
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $databases)
{
$this->connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* 按商品编码批量取重量(kg)。
*
* @param list<string> $skuCodes
* @return array<string,float> 商品编码 => 重量(kg)
*/
public function weightsBySkuCodes(array $skuCodes): array
{
$codes = [];
foreach ($skuCodes as $code) {
$code = trim((string) $code);
if ($code !== '') {
$codes[$code] = $code;
}
}
$codes = array_values($codes);
if ($codes === [] || ! $this->available()) {
return [];
}
try {
$latest = $this->connection->table(self::PRODUCT_TABLE)
->where('sku_type', 'normal')
->whereIn('sku_id', $codes)
->groupBy('sku_id')
->select('sku_id')
->selectRaw('MAX(autoid) AS autoid');
return $this->connection->table(self::PRODUCT_TABLE . ' as s')
->joinSub($latest, 'latest', function ($join): void {
$join->on('latest.sku_id', '=', 's.sku_id')
->on('latest.autoid', '=', 's.autoid');
})
->pluck('s.weight', 's.sku_id')
->map(static fn (mixed $weight): float => (float) $weight)
->all();
} catch (Throwable) {
return [];
}
}
private function available(): bool
{
try {
$schema = Schema::connection($this->connection->getName());
return $schema->hasTable(self::PRODUCT_TABLE)
&& $schema->hasColumn(self::PRODUCT_TABLE, 'weight')
&& $schema->hasColumn(self::PRODUCT_TABLE, 'sku_id');
} catch (Throwable) {
return false;
}
}
}

View File

@ -1,144 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\ThirdPartyWarehouseQuote;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
/**
* 三方仓仓储报价的唯一读写入口。
*
* 结算只需按仓库和结算期查找生效日不晚于该期间的最新启用记录,
* 因此每次价格变化都新增版本,不覆盖旧报价。
*/
class ThirdPartyWarehouseQuoteRepository
{
public function ready(): bool
{
try {
return Schema::hasTable((new ThirdPartyWarehouseQuote())->getTable());
} catch (QueryException) {
return false;
}
}
/** @return array{ready:bool,rows:Collection,summary:array<string,int>} */
public function pageData(): array
{
if (! $this->ready()) {
return $this->emptyPageData();
}
try {
$quotes = ThirdPartyWarehouseQuote::query()
->with('owner')
->orderByDesc('effective_at')
->orderByDesc('id')
->get();
} catch (QueryException) {
return $this->emptyPageData();
}
return [
'ready' => true,
'rows' => $quotes->map(fn (ThirdPartyWarehouseQuote $quote): array => $this->present($quote)),
'summary' => [
'total' => $quotes->count(),
'active' => $quotes->where('status', ThirdPartyWarehouseQuote::STATUS_ACTIVE)->count(),
'warehouses' => $quotes->pluck('warehouse_name')->filter()->unique()->count(),
],
];
}
/**
* 取某仓库在结算月生效的最新启用报价:生效日 ≤ 结算月月末,按生效日、id 倒序取一条。
*/
public function effectiveFor(string $warehouseName, string $period): ?ThirdPartyWarehouseQuote
{
if (! $this->ready()) {
return null;
}
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
return null;
}
$monthEnd = Carbon::createFromFormat('Y-m-d', $period . '-01')->endOfMonth()->toDateString();
try {
return ThirdPartyWarehouseQuote::query()
->where('warehouse_name', trim($warehouseName))
->where('status', ThirdPartyWarehouseQuote::STATUS_ACTIVE)
->whereDate('effective_at', '<=', $monthEnd)
->orderByDesc('effective_at')
->orderByDesc('id')
->first();
} catch (QueryException) {
return null;
}
}
/** @param array<string,mixed> $data */
public function create(array $data, int $userId): ThirdPartyWarehouseQuote
{
return ThirdPartyWarehouseQuote::query()->create([
'company_id' => company_id(),
'warehouse_name' => trim((string) $data['warehouse_name']),
'inbound_rate_per_ton' => $data['inbound_rate_per_ton'],
'outbound_rate_per_order' => $data['outbound_rate_per_order'],
'pieces_per_pallet' => $data['pieces_per_pallet'],
'pallet_area_sqm' => $data['pallet_area_sqm'],
'storage_rate_per_sqm_month' => $data['storage_rate_per_sqm_month'],
'effective_at' => $data['effective_at'],
'status' => ThirdPartyWarehouseQuote::STATUS_ACTIVE,
'remark' => trim((string) ($data['remark'] ?? '')) ?: null,
'created_by' => $userId,
'updated_by' => $userId,
]);
}
public function setStatus(ThirdPartyWarehouseQuote $quote, string $status, int $userId): ThirdPartyWarehouseQuote
{
abort_unless(in_array($status, [
ThirdPartyWarehouseQuote::STATUS_ACTIVE,
ThirdPartyWarehouseQuote::STATUS_INACTIVE,
], true), 422, '报价状态不合法。');
$quote->forceFill(['status' => $status, 'updated_by' => $userId])->save();
return $quote->fresh();
}
/** @return array<string,mixed> */
private function present(ThirdPartyWarehouseQuote $quote): array
{
return [
'id' => 'WHQ-' . str_pad((string) $quote->id, 4, '0', STR_PAD_LEFT),
'db_id' => $quote->id,
'warehouse_name' => $quote->warehouse_name,
'inbound_rate_per_ton' => (float) $quote->inbound_rate_per_ton,
'outbound_rate_per_order' => (float) $quote->outbound_rate_per_order,
'pieces_per_pallet' => (float) $quote->pieces_per_pallet,
'pallet_area_sqm' => (float) $quote->pallet_area_sqm,
'storage_rate_per_sqm_month' => (float) $quote->storage_rate_per_sqm_month,
'effective_at' => optional($quote->effective_at)->format('Y-m-d'),
'status_code' => $quote->status,
'status' => $quote->statusLabel(),
'remark' => $quote->remark,
'creator' => optional($quote->owner)->name ?: '-',
];
}
/** @return array{ready:false,rows:Collection,summary:array<string,int>} */
private function emptyPageData(): array
{
return [
'ready' => false,
'rows' => collect(),
'summary' => ['total' => 0, 'active' => 0, 'warehouses' => 0],
];
}
}

View File

@ -1,222 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Business;
use Carbon\Carbon;
use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorRepository;
/**
* 三方仓月度仓储费核算引擎。
*
* 口径(与「第三方仓储报价」页公式一致;各移动列按数量/绝对值计入):
* - 入库管理费 = Σ( 普通商品资料重量kg ÷ 1000 ×
* (加工进仓+加工出仓+采购进仓+采购退货+其它退货+销售退货+盘点+调拨入) ) × 入库单价
* - 出库费用 = Σ( 销售出仓 + 其它出库 + 调拨出 ) × 出库单价
* - 每日仓储费 = Σ_日( 当日库存结余 ÷ 每托件数 × 每托面积 × 面积单价 ÷ 当月天数 )
* - 合计 = 入库 + 出库 + 仓储 + 记账 + 盘亏扣款 + 赔偿
* 系统数据为唯一核算来源,不读取仓库提供/核对/差异列。
*/
class ThirdPartyWarehouseStorageFeeCalculator
{
/** 入库计费口径涉及的移动列(取绝对数量求和)。 */
private const INBOUND_COLUMNS = [
'processing_in', 'processing_out', 'purchase_in', 'purchase_return',
'other_return', 'sales_return', 'stocktake', 'transfer_in',
];
/** 出库计费口径涉及的移动列(取绝对数量求和)。 */
private const OUTBOUND_COLUMNS = ['sales_out', 'other_out', 'transfer_out'];
public function __construct(
private readonly ThirdPartyWarehouseStorageMirrorRepository $mirror,
private readonly ThirdPartyWarehouseQuoteRepository $quotes,
private readonly ThirdPartyWarehouseProductWeightRepository $weights,
) {
}
/**
* @return array{summary:array<string,mixed>,daily:list<array<string,mixed>>,per_sku:list<array<string,mixed>>,daily_sku:list<array<string,mixed>>}
*/
public function calculate(int $warehouseId, string $warehouseName, string $period): array
{
abort_unless(
preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1,
422,
'结算月份格式应为 YYYY-MM。',
);
$quote = $this->quotes->effectiveFor($warehouseName, $period);
abort_if($quote === null, 422, '请先在「第三方仓储报价」录入该仓库在 ' . $period . ' 生效的报价。');
$monthStart = Carbon::createFromFormat('Y-m-d', $period . '-01')->startOfMonth();
$days = (int) $monthStart->daysInMonth;
$inboundRate = (float) $quote->inbound_rate_per_ton;
$outboundRate = (float) $quote->outbound_rate_per_order;
$piecesPerPallet = (float) $quote->pieces_per_pallet;
$palletArea = (float) $quote->pallet_area_sqm;
$sqmRate = (float) $quote->storage_rate_per_sqm_month;
/** @var array<string,array{closing:float,inbound_qty:float,outbound_qty:float}> $daily */
$daily = [];
/** @var array<string,array<string,mixed>> $skus */
$skus = [];
$dailySku = [];
$storagePerPiecePerDay = $days > 0 && $piecesPerPallet > 0
? $palletArea * $sqmRate / $piecesPerPallet / $days
: 0.0;
foreach ($this->mirror->exportRows(['dimension' => 'month', 'period' => $period], 5000) as $row) {
$date = trim((string) ($row['date'] ?? ''));
$code = trim((string) ($row['sku_code'] ?? ''));
if ($date === '' || $code === '') {
continue;
}
$opening = (float) ($row['opening_qty'] ?? 0);
$closing = (float) ($row['closing_qty'] ?? 0);
$inboundQty = 0.0;
foreach (self::INBOUND_COLUMNS as $column) {
$inboundQty += abs((float) ($row[$column] ?? 0));
}
$outboundQty = 0.0;
foreach (self::OUTBOUND_COLUMNS as $column) {
$outboundQty += abs((float) ($row[$column] ?? 0));
}
if (! isset($daily[$date])) {
$daily[$date] = ['closing' => 0.0, 'inbound_qty' => 0.0, 'outbound_qty' => 0.0];
}
$daily[$date]['closing'] += $closing;
$daily[$date]['inbound_qty'] += $inboundQty;
$daily[$date]['outbound_qty'] += $outboundQty;
$dailySku[] = [
'date' => $date,
'owner' => (string) ($row['owner'] ?? ''),
'sku_code' => $code,
'product_name' => (string) ($row['product_name'] ?? ''),
'supplier' => (string) ($row['supplier'] ?? ''),
'category' => (string) ($row['category'] ?? ''),
'unit' => (string) ($row['unit'] ?? ''),
'opening' => round($opening, 2),
'net_movement' => round($closing - $opening, 2),
'closing' => round($closing, 2),
'storage_fee' => round($closing * $storagePerPiecePerDay, 6),
];
if (! isset($skus[$code])) {
$skus[$code] = [
'owner' => (string) ($row['owner'] ?? ''),
'sku_code' => $code,
'product_name' => (string) ($row['product_name'] ?? ''),
'supplier' => (string) ($row['supplier'] ?? ''),
'category' => (string) ($row['category'] ?? ''),
'unit' => (string) ($row['unit'] ?? ''),
'first_date' => $date,
'last_date' => $date,
'opening' => $opening,
'closing' => $closing,
'inbound_qty' => 0.0,
'outbound_qty' => 0.0,
];
}
$sku = &$skus[$code];
if ($date <= $sku['first_date']) {
$sku['first_date'] = $date;
$sku['opening'] = $opening;
}
if ($date >= $sku['last_date']) {
$sku['last_date'] = $date;
$sku['closing'] = $closing;
}
$sku['inbound_qty'] += $inboundQty;
$sku['outbound_qty'] += $outboundQty;
unset($sku);
}
$weightMap = $this->weights->weightsBySkuCodes(array_keys($skus));
$inboundTons = 0.0;
$outboundQtyTotal = 0.0;
$perSku = [];
foreach ($skus as $code => $sku) {
$weight = (float) ($weightMap[$code] ?? 0.0);
$perTon = $weight / 1000;
$totalTon = $perTon * $sku['inbound_qty'];
$inboundTons += $totalTon;
$outboundQtyTotal += $sku['outbound_qty'];
$perSku[] = [
'owner' => $sku['owner'],
'sku_code' => $code,
'product_name' => $sku['product_name'],
'supplier' => $sku['supplier'],
'category' => $sku['category'],
'unit' => $sku['unit'],
'weight' => round($weight, 4),
'per_ton' => round($perTon, 6),
'inbound_qty' => round($sku['inbound_qty'], 2),
'total_ton' => round($totalTon, 4),
'outbound_qty' => round($sku['outbound_qty'], 2),
'opening' => round($sku['opening'], 2),
'closing' => round($sku['closing'], 2),
];
}
$inboundFee = round($inboundTons * $inboundRate, 2);
$outboundFee = round($outboundQtyTotal * $outboundRate, 2);
ksort($daily);
$dailyRows = [];
$storageFee = 0.0;
foreach ($daily as $date => $agg) {
$dayStorage = $days > 0 && $piecesPerPallet > 0
? $agg['closing'] / $piecesPerPallet * $palletArea * $sqmRate / $days
: 0.0;
$storageFee += $dayStorage;
$dailyRows[] = [
'date' => $date,
'inbound_qty' => round($agg['inbound_qty'], 2),
'outbound_qty' => round($agg['outbound_qty'], 2),
'closing' => round($agg['closing'], 2),
'storage_fee' => round($dayStorage, 4),
'outbound_fee' => round($agg['outbound_qty'] * $outboundRate, 2),
'total' => round($dayStorage + $agg['outbound_qty'] * $outboundRate, 2),
];
}
$storageFee = round($storageFee, 2);
$totalFee = round($inboundFee + $outboundFee + $storageFee, 2);
return [
'summary' => [
'period' => $period,
'warehouse_id' => $warehouseId,
'warehouse_name' => $warehouseName,
'quote_id' => (int) $quote->id,
'days_in_month' => $days,
'inbound_rate_per_ton' => $inboundRate,
'outbound_rate_per_order' => $outboundRate,
'pieces_per_pallet' => $piecesPerPallet,
'pallet_area_sqm' => $palletArea,
'storage_rate_per_sqm_month' => $sqmRate,
'inbound_tons' => round($inboundTons, 4),
'inbound_fee' => $inboundFee,
'outbound_qty' => round($outboundQtyTotal, 2),
'outbound_fee' => $outboundFee,
'storage_fee' => $storageFee,
'memo_fee' => 0.0,
'loss_fee' => 0.0,
'compensation_fee' => 0.0,
'total_fee' => $totalFee,
],
'daily' => $dailyRows,
'per_sku' => $perSku,
'daily_sku' => $dailySku,
];
}
}

View File

@ -20,10 +20,10 @@ class UpstreamBusinessInformation
public function __construct(
private readonly UpstreamQueryCacheFactory $caches,
private readonly BusinessInformationMirrorRepository $mirror,
private readonly InstallationDetailMirrorRepository $installationMirror,
// 兼容仍按旧构造方式调用的代码;容器解析时会正常注入仓储。
private readonly ?StoreReportRepository $storeReports = null,
private readonly ?StoreAccountMirrorRepository $storeAccounts = null,
private readonly ?InstallationDetailMirrorRepository $installationMirror = null,
) {}
public function paginate(string $section, string $page, int $perPage = 50): LengthAwarePaginator
@ -40,13 +40,8 @@ class UpstreamBusinessInformation
'company-management/subject-operating-report' => $this->subjectOperatingReportPage($currentPage, $perPage),
'trademark-management/information' => $this->trademarkPage($currentPage, $perPage),
'financial-operations/installation-details' => $this->installationPage($currentPage, $perPage),
'financial-risk-control/process-statistics' => $this->shopInfoFlowPage($currentPage, $perPage),
default => ['data' => [], 'total' => 0],
};
request()->attributes->set(
'business-page-summary-cards',
app(BusinessSummaryCards::class)->forPage($key, $payload['summary'] ?? []),
);
return new LengthAwarePaginator(
array_map(static fn (array $row) => (object) $row, $payload['data']),
@ -60,30 +55,9 @@ class UpstreamBusinessInformation
);
}
/**
* 财务经营风险管控 › 流程统计:店铺申请流程(开店 / 变更 / 关店)只读镜像。
*
* @return array{data:list<array<string,mixed>>,total:int}
*/
private function shopInfoFlowPage(int $page, int $perPage): array
{
try {
return app(\Modules\EcommerceFinance\Repositories\ShopInfoFlowMirrorRepository::class)->paginate(
$page,
$perPage,
$this->pageFilters('financial-risk-control', 'process-statistics'),
);
} catch (\RuntimeException $exception) {
report($exception);
throw new ServiceUnavailableHttpException(null, '店铺申请流程共享镜像尚未完成首次同步。');
}
}
private function installationPage(int $page, int $perPage): array
{
$mirror = $this->installationMirror ?? app(InstallationDetailMirrorRepository::class);
$payload = $mirror->paginate($page, $perPage, InstallationDetailMirrorRepository::requestFilters());
$payload = $this->installationMirror->paginate($page, $perPage, InstallationDetailMirrorRepository::requestFilters());
if (! $payload['ready']) {
throw new ServiceUnavailableHttpException(null, '安装明细镜像尚未完成首次同步');
}
@ -162,230 +136,25 @@ SQL);
private function storePage(int $page, int $perPage): array
{
$filters = $this->pageFilters('store-management', 'basic-information');
if ($this->mirror->ready('store-information.read')) {
$storeFilters = array_diff_key(
$filters,
array_flip(['store_manager', 'department_manager', '_sort', '_direction']),
);
return $this->pageStoreInformation(
$page,
$perPage,
$filters,
$this->storesWithAccountOwnership(array_map(
fn (array $row): array => $this->mapStore($row),
$this->mirror->allStores($storeFilters),
)),
);
}
$payload = $this->page(
return $this->page(
'store-information.read',
$page,
$perPage,
array_diff_key($filters, array_flip(['store_manager', 'department_manager'])),
$filters,
fn () => $this->snapshot('store-information.read', [
'page' => $page,
'perPage' => $perPage,
]),
false,
);
$rows = $this->storesWithAccountOwnership($payload['data']);
$rows = array_values(array_filter(
$rows,
fn (array $row): bool => $this->storeOwnershipMatchesFilters($row, $filters),
));
return ['data' => $rows, 'total' => count($rows)];
}
/**
* 店铺基础信息页每次读取时把负责人字段覆盖为店铺账号镜像中的值。
* 账号店铺名与 ERP 店铺名只差下划线/空格,因此统一归一后关联。
*
* @param list<array<string,mixed>> $rows
* @return list<array<string,mixed>>
*/
public function storesWithAccountOwnership(array $rows, bool $requireAccountOwnership = false): array
{
$ownership = $this->storeOwnership($requireAccountOwnership);
foreach ($rows as &$row) {
$key = StoreAccountMirrorRepository::storeNameKey($row['erp_store_name'] ?? '');
$match = $ownership[$key] ?? null;
if ($match === null) {
continue;
}
foreach ([
'store_manager' => $match['operation_owner'],
'department_manager' => $match['operation_department_head'],
] as $field => $value) {
if ($value !== '') {
$row[$field] = $value;
}
}
}
unset($row);
return $rows;
}
/** @param array<string,string|list<string>> $filters */
private function pageStoreInformation(int $page, int $perPage, array $filters, array $rows): array
{
$rows = array_values(array_filter(
$rows,
fn (array $row): bool => $this->storeOwnershipMatchesFilters($row, $filters),
));
$summary = $this->storeInformationSummary($rows);
$this->sortStoreInformation($rows, $filters);
$total = count($rows);
$offset = ($page - 1) * $perPage;
return [
'data' => array_slice($rows, $offset, $perPage),
'total' => $total,
'summary' => $summary,
];
}
/** @param list<array<string,mixed>> $rows */
private function storeInformationSummary(array $rows): array
{
$stores = [];
$platforms = [];
foreach ($rows as $row) {
$key = trim((string) ($row['id'] ?? $row['erp_store_name'] ?? $row['store_name'] ?? ''));
if ($key === '') {
continue;
}
$stores[$key] = match ((string) ($row['store_status'] ?? '')) {
'0', '正常' => '正常',
'3', '关闭中' => '关闭中',
'6', '已关闭', '关店' => '已关闭',
default => (string) ($row['store_status'] ?? ''),
};
$platform = trim((string) ($row['platform'] ?? ''));
if ($platform !== '') {
$platforms[$platform] = true;
}
}
$statusCounts = array_count_values($stores);
return [
'total' => count($stores),
'normal' => (int) ($statusCounts['正常'] ?? 0),
'closing' => (int) ($statusCounts['关闭中'] ?? 0),
'closed' => (int) ($statusCounts['已关闭'] ?? 0),
'platforms' => count($platforms),
];
}
/** @param array<string,string|list<string>> $filters */
private function storeOwnershipMatchesFilters(array $row, array $filters): bool
{
foreach (['store_manager', 'department_manager'] as $key) {
$expected = trim((string) ($filters[$key] ?? ''));
if ($expected !== ''
&& mb_stripos((string) ($row[$key] ?? ''), $expected) === false) {
return false;
}
}
return true;
}
/** @param list<array<string,mixed>> $rows @param array<string,string|list<string>> $filters */
private function sortStoreInformation(array &$rows, array $filters): void
{
$key = (string) ($filters['_sort'] ?? '');
if ($key === '') {
return;
}
$direction = ($filters['_direction'] ?? 'asc') === 'desc' ? -1 : 1;
usort($rows, static function (array $left, array $right) use ($key, $direction): int {
$comparison = strnatcasecmp(
(string) ($left[$key] ?? ''),
(string) ($right[$key] ?? ''),
) * $direction;
return $comparison !== 0
? $comparison
: ((int) ($right['id'] ?? 0) <=> (int) ($left['id'] ?? 0));
});
}
private function storeReportPage(int $page, int $perPage): array
{
$filters = StoreReportRepository::requestFilters();
$rows = $this->storeReportRows($filters);
// 整列为 0 的月份视为没有销量,默认隐藏;仍可从「筛选字段」手动打开。
request()->attributes->set(
'store-report.default_hidden_columns',
$this->columnsWithoutData($rows, 'sales_', zeroCountsAsData: false),
);
$offset = ($page - 1) * $perPage;
return [
'data' => array_slice($rows, $offset, $perPage),
'total' => count($rows),
'summary' => $this->storeReportSummary($rows),
];
}
/** @param list<array<string,mixed>> $rows */
private function storeReportSummary(array $rows): array
{
$normalStores = [];
$previousMonth = now()->startOfMonth()->subMonthNoOverflow();
$currentMonth = now()->startOfMonth();
$previousMonthKey = 'sales_' . $previousMonth->format('m');
$currentMonthKey = 'sales_' . $currentMonth->format('m');
$previousSales = 0.0;
$currentSales = 0.0;
$previousStores = [];
$currentStores = [];
foreach ($rows as $row) {
if (trim((string) ($row['status'] ?? '')) !== '开店中') {
continue;
}
$key = trim((string) ($row['erp_store_name'] ?? ''));
if ($key === '') {
$key = trim((string) ($row['store_id'] ?? $row['id'] ?? ''));
}
if ($key === '') {
continue;
}
$normalStores[$key] = true;
$previousValue = (float) ($row[$previousMonthKey] ?? 0);
$currentValue = (float) ($row[$currentMonthKey] ?? 0);
$previousSales += $previousValue;
$currentSales += $currentValue;
if ($previousValue > 0) {
$previousStores[$key] = true;
}
if ($currentValue > 0) {
$currentStores[$key] = true;
}
}
return [
'normal_stores' => count($normalStores),
'previous_month_sales' => round($previousSales, 2),
'current_month_sales' => round($currentSales, 2),
'previous_month_stores' => count($previousStores),
'current_month_stores' => count($currentStores),
'previous_month_key' => $previousMonthKey,
'current_month_key' => $currentMonthKey,
'previous_month_label' => $previousMonth->isSameYear($currentMonth)
? '上月(' . $previousMonth->format('n月') . ')'
: '上月(' . $previousMonth->format('Y年n月') . ')',
'current_month_label' => '当月(' . $currentMonth->format('n月') . ')',
];
return ['data' => array_slice($rows, $offset, $perPage), 'total' => count($rows)];
}
/** @return array{data:array<int,array<string,mixed>>,total:int} */
@ -428,13 +197,16 @@ SQL);
*/
private function storeMatchesFilters(array $row, array $filters): bool
{
foreach (['erp_store_name', 'store_name', 'store_id', 'profit_center', 'store_manager', 'department_manager'] as $key) {
foreach (['erp_store_name', 'store_id', 'profit_center', 'store_manager', 'department_manager'] as $key) {
$expected = trim((string) ($filters[$key] ?? ''));
if ($expected === '') {
continue;
}
$actual = trim((string) ($row[$key] ?? ''));
if (! str_contains(mb_strtolower($actual), mb_strtolower($expected))) {
// 页面“店铺ID(唯一值)”展示 ERP 店铺名称,筛选按同一列匹配。
$actual = $key === 'store_id'
? trim((string) ($row['erp_store_name'] ?? ''))
: trim((string) ($row[$key] ?? ''));
if ($expected !== '' && ! str_contains(mb_strtolower($actual), mb_strtolower($expected))) {
return false;
}
}
@ -471,7 +243,7 @@ SQL);
{
$rows = $query->select(<<<SQL
SELECT s.Id AS id, s.sotreId AS store_id, s.openTime AS opened_at, s.renewalTime AS renewed_at,
s.erpShopName AS erp_store_name, s.shopName AS store_name, s.unifiedSocialCreditCode AS unified_social_credit_code,
s.erpShopName AS erp_store_name, s.unifiedSocialCreditCode AS unified_social_credit_code,
c.businessLicenseName AS company_name, c.businessLicenseType AS company_type,
s.trademarkNumber AS trademark_number, t.trademarkName AS trademark_name, s.platform AS platform,
s.responsibleDepartment AS profit_center, NULL AS store_manager, NULL AS department_manager,
@ -488,11 +260,6 @@ SQL);
private function subjectOperatingReportPage(int $page, int $perPage): array
{
$filters = $this->pageFilters('company-management', 'subject-operating-report');
$companyStatusReady = $this->mirror->ready('company-information.read');
$companyStatus = trim((string) request('company_status', ''));
if (in_array($companyStatus, ['正常', '已注销'], true)) {
$filters['company_status'] = $companyStatus;
}
$rows = $this->storeReportRows(array_intersect_key($filters, array_flip(['company_type'])));
$entities = [];
@ -526,191 +293,34 @@ SQL);
$rows = array_values($entities);
$details = $this->companyDetails(array_column($rows, 'entity'));
try {
$classifications = $this->mirror->companyClassificationsByNames(array_column($rows, 'entity'));
} catch (Throwable) {
$classifications = [];
}
foreach ($rows as &$row) {
$row['company_details'] = $details[$row['entity']] ?? [];
$row['city'] = $this->cityFromDetails($row['company_details']);
$row['company_status'] = $row['company_details'][0]['company_status'] ?? null;
$classification = $classifications[$row['entity']] ?? [];
$taxType = $classification['tax_type']
?? $row['company_details'][0]['taxpayer_category']
?? null;
$businessType = $classification['business_registration_type']
?? $row['company_details'][0]['business_registration_type']
?? null;
$classificationStatus = trim((string) ($classification['status'] ?? ''));
$retained = $classificationStatus !== ''
? $classificationStatus === '保留'
: $row['company_status'] === '正常';
$row['company_status'] = $retained ? '正常' : '已注销';
// Excel 台账明确有税务类型时始终展示;没有时再回退到上游公司资料。
$row['tax_type'] = $this->normalizeTaxType($taxType) ?? '/';
$businessType = trim((string) $businessType);
$row['business_registration_type'] = $retained
&& in_array($businessType, ['核定', '个人独资企业'], true)
? $businessType
: '/';
}
unset($row);
// 整列为空的月份默认隐藏;金额 0 仍视为有账单,不隐藏。
request()->attributes->set(
'subject-operating-report.default_hidden_columns',
$this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true),
);
$rows = array_values(array_filter($rows, fn (array $row): bool => $this->subjectMatchesFilters($row, $filters)));
$summary = $this->subjectSummary($rows, $companyStatusReady);
$this->sortSubjectRows($rows, $filters);
$offset = ($page - 1) * $perPage;
$pageRows = array_slice($rows, $offset, $perPage);
return ['data' => $pageRows, 'total' => count($rows), 'summary' => $summary];
}
/** @param list<array<string,mixed>> $rows */
private function subjectSummary(array $rows, bool $companyStatusReady): array
{
$normal = 0;
$deregistered = 0;
$smallTaxpayers = 0;
$generalTaxpayers = 0;
$previousMonth = now()->startOfMonth()->subMonthNoOverflow();
$currentMonth = now()->startOfMonth();
$previousMonthKey = 'income_' . $previousMonth->format('m');
$currentMonthKey = 'income_' . $currentMonth->format('m');
$previousIncome = 0.0;
$currentMonthIncome = 0.0;
$previousIncomeEntities = 0;
$currentIncomeEntities = 0;
foreach ($rows as $row) {
$status = trim((string) ($row['company_status'] ?? ''));
if ($status === '正常') {
$normal++;
} elseif ($status === '已注销') {
$deregistered++;
}
if ($status !== '正常') {
continue;
}
$taxType = (string) ($row['tax_type'] ?? '');
if (str_contains($taxType, '小规模')) {
$smallTaxpayers++;
}
if (str_contains($taxType, '一般纳税人')) {
$generalTaxpayers++;
}
$previousValue = (float) ($row[$previousMonthKey] ?? 0);
$currentValue = (float) ($row[$currentMonthKey] ?? 0);
$previousIncome += $previousValue;
$currentMonthIncome += $currentValue;
if ($previousValue > 0) {
$previousIncomeEntities++;
}
if ($currentValue > 0) {
$currentIncomeEntities++;
}
}
return [
'total' => count($rows),
'normal' => $normal,
'deregistered' => $deregistered,
'small_taxpayer' => $smallTaxpayers,
'general_taxpayer' => $generalTaxpayers,
'previous_income' => round($previousIncome, 2),
'current_month_income' => round($currentMonthIncome, 2),
'previous_income_entities' => $previousIncomeEntities,
'current_income_entities' => $currentIncomeEntities,
'previous_month_key' => $previousMonthKey,
'current_month_key' => $currentMonthKey,
'previous_month_label' => $previousMonth->isSameYear($currentMonth)
? '上月(' . $previousMonth->format('n月') . ')'
: '上月(' . $previousMonth->format('Y年n月') . ')',
'current_month_label' => '当月(' . $currentMonth->format('n月') . ')',
'company_status_ready' => $companyStatusReady,
];
}
private function normalizeTaxType(mixed $value): ?string
{
$taxType = trim((string) $value);
if ($taxType === '') {
return null;
}
return match ($taxType) {
'小规模' => '小规模纳税人',
'一般纳税人', '小规模纳税人', '个体工商户', '无税务登记' => $taxType,
default => $taxType,
};
}
/**
* 返回整列都没有数据的月份列;这类列只默认隐藏,字段和数据不会被删除。
*
* @param list<array<string,mixed>> $rows
* @return list<string>
*/
private function columnsWithoutData(array $rows, string $prefix, bool $zeroCountsAsData): array
{
$columns = [];
for ($month = 1; $month <= 12; $month++) {
$key = sprintf('%s%02d', $prefix, $month);
foreach ($rows as $row) {
$value = $row[$key] ?? null;
if ($value === null || $value === '') {
continue;
}
if (! $zeroCountsAsData && (float) $value === 0.0) {
continue;
}
continue 2;
}
$columns[] = $key;
}
return $columns;
return ['data' => $pageRows, 'total' => count($rows)];
}
/** @param array<string,mixed> $row @param array<string,string> $filters */
private function subjectMatchesFilters(array $row, array $filters): bool
{
$companyStatus = trim((string) ($filters['company_status'] ?? ''));
if ($companyStatus !== '' && (string) ($row['company_status'] ?? '') !== $companyStatus) {
return false;
}
if (($filters['company_type'] ?? '') !== '' && (string) ($row['company_type'] ?? '') !== (string) $filters['company_type']) {
return false;
}
foreach (['city', 'entity', 'tax_type', 'business_registration_type', 'plan', 'new_entity'] as $key) {
foreach (['city', 'entity', 'plan', 'new_entity'] as $key) {
$needle = trim((string) ($filters[$key] ?? ''));
if ($needle !== '' && mb_stripos((string) ($row[$key] ?? ''), $needle) === false) {
return false;
}
}
foreach (['rolling_12m_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
$needle = str_replace(',', '', trim((string) ($filters[$key] ?? '')));
if ($needle !== '' && (! is_numeric($needle) || ! is_numeric($row[$key] ?? null)
|| abs((float) $row[$key] - (float) $needle) > 0.000001)) {
return false;
}
}
$canChange = trim((string) ($filters['can_change_entity'] ?? ''));
return $canChange === '' || (string) ($row['can_change_entity'] ?? '') === $canChange;
}
@ -718,9 +328,9 @@ SQL);
/** @param array<int,array<string,mixed>> $rows @param array<string,string> $filters */
private function sortSubjectRows(array &$rows, array $filters): void
{
$key = (string) ($filters['_sort'] ?? 'entity');
$key = (string) ($filters['_sort'] ?? '');
$allowed = [
'city', 'entity', 'company_type', 'tax_type', 'business_registration_type', 'rolling_12m_income',
'city', 'entity', 'company_type', 'rolling_12m_income',
...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12)),
'can_change_entity', 'plan', 'new_entity',
];
@ -733,12 +343,10 @@ SQL);
$leftValue = $left[$key] ?? null;
$rightValue = $right[$key] ?? null;
if (is_numeric($leftValue) && is_numeric($rightValue)) {
$comparison = ((float) $leftValue <=> (float) $rightValue) * $direction;
} else {
$comparison = strcmp((string) ($leftValue ?? ''), (string) ($rightValue ?? '')) * $direction;
return ((float) $leftValue <=> (float) $rightValue) * $direction;
}
return $comparison !== 0 ? $comparison : strcmp((string) ($left['entity'] ?? ''), (string) ($right['entity'] ?? ''));
return strnatcasecmp((string) ($leftValue ?? ''), (string) ($rightValue ?? '')) * $direction;
});
}
@ -821,8 +429,7 @@ SQL);
'company_status' => $row['companyStatus'] ?? $row['company_status'] ?? null,
'financial_officer' => $row['financialManager'] ?? $row['financial_officer'] ?? null,
'supervisor' => $row['supervisor'] ?? null,
'taxpayer_category' => $row['finance_tax_type'] ?? $row['taxCategoryAndType'] ?? $row['taxpayer_category'] ?? null,
'business_registration_type' => $row['business_registration_type'] ?? null,
'taxpayer_category' => $row['taxCategoryAndType'] ?? $row['taxpayer_category'] ?? null,
'shareholders' => $row['shareholders'] ?? null,
]);
}
@ -836,15 +443,14 @@ SQL);
$storeFilters = array_diff_key($filters, array_flip(['store_manager', 'department_manager', 'profit_center']));
$stores = $this->allStores($storeFilters);
foreach ($stores['data'] as &$store) {
$key = StoreAccountMirrorRepository::storeNameKey($store['erp_store_name'] ?? '');
$match = $ownership[$key] ?? null;
$match = $ownership[trim((string) ($store['erp_store_name'] ?? ''))] ?? null;
if ($match === null) {
continue;
}
// 未匹配到账号或字段为空时保留经营分析副本库原值。
foreach ([
'store_manager' => $match['operation_owner'],
'department_manager' => $match['operation_department_head'],
'department_manager' => $match['operation_director'],
'profit_center' => $match['profit_center'],
] as $field => $value) {
if ($value !== '') {
@ -862,15 +468,12 @@ SQL);
}
}
/** @return array<string,array{operation_owner:string,operation_department_head:string,operation_director:string,profit_center:string}> */
private function storeOwnership(bool $requireAccountOwnership = false): array
/** @return array<string,array{operation_owner:string,operation_director:string,profit_center:string}> */
private function storeOwnership(): array
{
try {
return ($this->storeAccounts ?? app(StoreAccountMirrorRepository::class))->ownershipByStoreName();
} catch (\RuntimeException | \InvalidArgumentException $exception) {
if ($requireAccountOwnership) {
throw new \RuntimeException('店铺账号密码共享镜像尚未就绪,无法关联负责人。', 0, $exception);
}
// 账号镜像未登记或未就绪时保留经营分析副本库原值,不阻断店铺报表。
return [];
}
@ -886,7 +489,6 @@ SELECT
s.openTime AS opened_at,
s.renewalTime AS renewed_at,
s.erpShopName AS erp_store_name,
s.shopName AS store_name,
s.unifiedSocialCreditCode AS unified_social_credit_code,
c.businessLicenseName AS company_name,
c.businessLicenseType AS company_type,
@ -968,16 +570,9 @@ SQL);
];
}
private function page(
string $scope,
int $page,
int $perPage,
array $filters,
callable $resolver,
?bool $mirrorReady = null,
): array
private function page(string $scope, int $page, int $perPage, array $filters, callable $resolver): array
{
if ($mirrorReady ?? $this->mirror->ready($scope)) {
if ($this->mirror->ready($scope)) {
return $this->normalize($scope, $this->mirror->paginate($scope, $page, $perPage, $filters));
}
@ -997,7 +592,7 @@ SQL);
});
}
/** @return array<string,string|list<string>> */
/** @return array<string,string> */
private function pageFilters(string $section, string $page): array
{
$fields = collect(config('business_navigation'))
@ -1012,20 +607,7 @@ SQL);
$filters = [];
foreach ($allowed as $name) {
foreach ([$name, $name . '_from', $name . '_to'] as $key) {
$raw = request($key, '');
// 多选筛选(xxx[])传进来是数组:去重后原样带下去,由各自的仓库取并集。
if (is_array($raw)) {
$values = [];
foreach ($raw as $item) {
if (! is_scalar($item)) continue;
$item = mb_substr(trim((string) $item), 0, 191);
if ($item !== '') $values[$item] = true;
if (count($values) >= 50) break;
}
if ($values !== []) $filters[$key] = array_keys($values);
continue;
}
$value = trim((string) $raw);
$value = trim((string) request($key, ''));
if ($value !== '') $filters[$key] = mb_substr($value, 0, 191);
}
}
@ -1051,7 +633,6 @@ SQL);
return [
'data' => array_map($mapper, $payload['data']),
'total' => (int) $payload['total'],
'summary' => (array) ($payload['summary'] ?? []),
];
}
@ -1066,10 +647,6 @@ SQL);
'1' => '已注销',
default => $row['company_status'] ?? null,
};
$businessType = trim((string) ($row['business_registration_type'] ?? ''));
$row['business_registration_type'] = in_array($businessType, ['核定', '个人独资企业'], true)
? $businessType
: '/';
return $row;
}

View File

@ -1,238 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\StoreReceivingAccount;
use App\Models\Business\Todo;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
class WithdrawalBalanceAlertSynchronizer
{
public const CATEGORY = '提现余额预警';
public const TODO_STATUS = '待处理';
public function __construct(
private readonly JushuitanShopBalanceRepository $shopBalances,
) {
}
/**
* Evaluate the latest balance date for a company and persist one open todo
* per store that has exceeded its reserve standard without any change for
* three consecutive calendar days.
*
* @return array{balance_date:string,dates:list<string>,alerts:array<int,array<string,mixed>>,created:int,updated:int}
*/
public function syncLatest(int $companyId): array
{
$latest = $this->shopBalances->latestBalanceDate(now());
if ($latest === null) {
return [
'balance_date' => '',
'dates' => [],
'alerts' => [],
'created' => 0,
'updated' => 0,
];
}
return $this->syncForDate($companyId, $latest);
}
/**
* @return array{balance_date:string,dates:list<string>,alerts:array<int,array<string,mixed>>,created:int,updated:int}
*/
public function syncForDate(int $companyId, string $balanceDate): array
{
$dates = self::datesEndingAt($balanceDate);
$stores = StoreReceivingAccount::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
->orderBy('id')
->get();
if ($stores->isEmpty()) {
return [
'balance_date' => $balanceDate,
'dates' => $dates,
'alerts' => [],
'created' => 0,
'updated' => 0,
];
}
$balancesByDate = $this->shopBalances->matchesForStoresOnDates($stores, $dates);
$reserveStandards = $stores->mapWithKeys(
static fn (StoreReceivingAccount $store): array => [
(int) $store->id => WithdrawalReserveStandard::amountFor(
$store->store_platform,
$store->erp_store_name,
),
],
)->all();
$alerts = self::detect($stores, $balancesByDate, $reserveStandards, $dates);
[$created, $updated] = DB::transaction(function () use ($companyId, $stores, &$alerts): array {
$created = 0;
$updated = 0;
foreach ($stores as $store) {
$alert = $alerts[(int) $store->id] ?? null;
if ($alert === null) {
continue;
}
$title = $this->todoTitle($store);
$description = $this->description($store, $alert);
$todo = Todo::withoutGlobalScopes()
->where('company_id', $companyId)
->where('category', self::CATEGORY)
->where('title', $title)
->whereNull('deleted_at')
->whereNotIn('status', ['已完成', '已关闭'])
->orderByDesc('id')
->lockForUpdate()
->first();
if ($todo === null) {
$todo = Todo::withoutGlobalScopes()->create([
'company_id' => $companyId,
'title' => $title,
'category' => self::CATEGORY,
'priority' => '高',
'status' => self::TODO_STATUS,
'description' => $description,
]);
$created++;
} else {
$attributes = [
'priority' => '高',
'description' => $description,
];
if ($todo->status !== self::TODO_STATUS) {
$attributes['status'] = self::TODO_STATUS;
}
if ($todo->fill($attributes)->isDirty()) {
$todo->save();
$updated++;
}
}
$alerts[(int) $store->id]['todo_id'] = (int) $todo->id;
}
return [$created, $updated];
});
return [
'balance_date' => $balanceDate,
'dates' => $dates,
'alerts' => $alerts,
'created' => $created,
'updated' => $updated,
];
}
/**
* @param iterable<StoreReceivingAccount> $stores
* @param array<int,array<string,array{status:string,balance:?float,source_store_name:?string,source_platform:?string}>> $balancesByDate
* @param array<int,int|null> $reserveStandards
* @param list<string> $dates
* @return array<int,array{balance:float,start_date:string,end_date:string,message:string}>
*/
public static function detect(
iterable $stores,
array $balancesByDate,
array $reserveStandards,
array $dates,
): array {
if (count($dates) !== 3) {
return [];
}
$alerts = [];
foreach ($stores as $store) {
$reserve = $reserveStandards[(int) $store->id] ?? null;
if ($reserve === null) {
continue;
}
$balanceCents = null;
$unchanged = true;
foreach ($dates as $date) {
$match = $balancesByDate[(int) $store->id][$date]
?? ['status' => 'not_ready', 'balance' => null];
if (($match['status'] ?? '') !== 'matched' || ($match['balance'] ?? null) === null) {
$unchanged = false;
break;
}
$cents = (int) round((float) $match['balance'] * 100);
if ($balanceCents === null) {
$balanceCents = $cents;
} elseif ($balanceCents !== $cents) {
$unchanged = false;
break;
}
}
if (! $unchanged || $balanceCents === null || $balanceCents <= $reserve * 100) {
continue;
}
$balance = $balanceCents / 100;
$alerts[(int) $store->id] = [
'balance' => $balance,
'start_date' => $dates[0],
'end_date' => $dates[2],
'message' => sprintf(
'余额连续 3 天保持 %s 元,高于预留标准 %s 元。',
number_format($balance, 2),
number_format($reserve, 2),
),
];
}
return $alerts;
}
/** @return list<string> */
public static function datesEndingAt(string $balanceDate): array
{
$end = CarbonImmutable::createFromFormat('!Y-m-d', $balanceDate);
if (! $end instanceof CarbonImmutable || $end->format('Y-m-d') !== $balanceDate) {
return [];
}
return [
$end->subDays(2)->toDateString(),
$end->subDay()->toDateString(),
$end->toDateString(),
];
}
private function todoTitle(StoreReceivingAccount $store): string
{
return mb_substr(
'提现余额连续3天未变动|' . (string) $store->store_platform . '|' . (string) $store->erp_store_name,
0,
255,
);
}
/** @param array{balance:float,start_date:string,end_date:string,message:string} $alert */
private function description(StoreReceivingAccount $store, array $alert): string
{
return implode("\n", array_filter([
$alert['message'],
'统计期间:' . $alert['start_date'] . ' 至 ' . $alert['end_date'],
'店铺平台:' . ($store->store_platform ?: '未配置'),
'ERP店铺名称:' . ($store->erp_store_name ?: '未配置'),
'店铺主体:' . ($store->store_entity_name ?: '未配置'),
'平台店铺ID:' . ($store->store_id ?: '未配置'),
'处理建议:核实店铺余额是否真实停滞,并检查是否应执行提现。',
], static fn (string $line): bool => $line !== ''));
}
}

View File

@ -1,384 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\StoreReceivingAccount;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
class WithdrawalManagementReport
{
private const SORT_FIELDS = [
'platform',
'erp_store_name',
'store_id',
'store_entity',
'withdrawal_path',
'withdrawal_account',
'bank_card',
'balance_two_days_ago',
'balance_yesterday',
'balance',
'balance_alert',
'reserve_standard',
'withdrawal_amount',
'compliance',
];
public function __construct(
private readonly JushuitanShopBalanceRepository $shopBalances,
) {
}
/**
* @return array{
* filters:array{platform:string,withdrawalPath:string,storeEntity:string,keyword:string,balanceStatus:string,balanceDate:string},
* platforms:list<string>,paths:list<string>,storeEntities:list<string>,rows:Collection<int,StoreReceivingAccount>,
* balances:array<int,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}>,
* balancesByDate:array<int,array<string,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}>>,
* balanceDays:list<array{key:string,date:string,label:string}>,
* alerts:array<int,array{balance:float,start_date:string,end_date:string,message:string}>,
* reserveStandards:array<int,int|null>,withdrawalAmounts:array<int,float|null>,compliance:array<int,string|null>,
* summary:array{source:int,matched:int,finance:int,ambiguous:int,unmatched:int,not_ready:int},
* balanceColumnLabel:string,balanceDate:string,latestBalanceDate:?string,balanceDates:list<string>,sort:array{field:string,direction:string}
* }
*/
public function results(Request $request): array
{
$filters = $this->filters($request);
$sort = $this->sorting($request);
$platforms = $this->options('store_platform');
$paths = $this->options('receiving_method');
$storeEntities = $this->options('store_entity_name');
$query = StoreReceivingAccount::query();
if ($filters['platform'] !== '') {
$query->where('store_platform', $filters['platform']);
}
if ($filters['withdrawalPath'] !== '') {
$query->where('receiving_method', $filters['withdrawalPath']);
}
if ($filters['storeEntity'] !== '') {
$query->where('store_entity_name', $filters['storeEntity']);
}
if ($filters['keyword'] !== '') {
$query->where('store_name', 'like', '%' . addcslashes($filters['keyword'], '%_\\') . '%');
}
$today = now()->startOfDay();
// 余额快照按日期长期保留:默认显示最新余额日期,也可指定历史日期回看。
$latestBalanceDate = $this->shopBalances->latestBalanceDate($today);
$balanceDate = $filters['balanceDate'] !== ''
? $filters['balanceDate']
: ($latestBalanceDate ?? $today->copy()->subDay()->toDateString());
$labelDate = $filters['balanceDate'] !== ''
? CarbonImmutable::parse($balanceDate)
: $today;
$rows = $query->orderByDesc('id')->get();
$historyDates = WithdrawalBalanceAlertSynchronizer::datesEndingAt($balanceDate);
$balancesByDate = $this->shopBalances->matchesForStoresOnDates($rows, $historyDates);
$balances = array_map(
static fn (array $dates): array => $dates[$balanceDate] ?? [
'status' => 'not_ready',
'balance' => null,
'source_store_name' => null,
'source_platform' => null,
],
$balancesByDate,
);
$balanceCounts = collect($balances)->countBy(
static fn (array $match): string => $match['status'],
);
$financeCount = collect($balances)->filter(
static fn (array $match): bool => ($match['data_source'] ?? null)
=== JushuitanShopBalanceRepository::DATA_SOURCE_FINANCE,
)->count();
if ($filters['balanceStatus'] !== '') {
$rows = $rows->filter(
static fn (StoreReceivingAccount $row): bool => ($balances[(int) $row->id]['status'] ?? 'not_ready') === $filters['balanceStatus'],
);
}
$reserveStandards = $rows->mapWithKeys(
static fn (StoreReceivingAccount $row): array => [
(int) $row->id => WithdrawalReserveStandard::amountFor(
$row->store_platform,
$row->erp_store_name,
),
],
)->all();
$balanceDays = collect($historyDates)->map(
static fn (string $date, int $index): array => [
'key' => $index === 0 ? 'balance_two_days_ago' : ($index === 1 ? 'balance_yesterday' : 'balance'),
'date' => $date,
'label' => CarbonImmutable::parse($date)->format('n月j日') . '店铺余额',
],
)->values()->all();
$alerts = WithdrawalBalanceAlertSynchronizer::detect(
$rows,
$balancesByDate,
$reserveStandards,
$historyDates,
);
$withdrawalAmounts = $rows->mapWithKeys(
fn (StoreReceivingAccount $row): array => [
(int) $row->id => $this->withdrawalAmountFor($row, $balanceDate),
],
)->all();
$compliance = $rows->mapWithKeys(
fn (StoreReceivingAccount $row): array => [
(int) $row->id => self::complianceFor(
$balances[(int) $row->id] ?? ['status' => 'not_ready', 'balance' => null],
$reserveStandards[(int) $row->id] ?? null,
$withdrawalAmounts[(int) $row->id] ?? null,
),
],
)->all();
$rows = $sort['field'] === ''
? $this->sortByBalanceStatus($rows, $balances)
: $this->sortRows(
$rows,
$sort,
$balancesByDate,
$balanceDays,
$alerts,
$reserveStandards,
$withdrawalAmounts,
$compliance,
);
return [
'filters' => $filters,
'platforms' => $platforms,
'paths' => $paths,
'storeEntities' => $storeEntities,
'rows' => $rows,
'balances' => $balances,
'balancesByDate' => $balancesByDate,
'balanceDays' => $balanceDays,
'alerts' => $alerts,
'reserveStandards' => $reserveStandards,
'withdrawalAmounts' => $withdrawalAmounts,
'compliance' => $compliance,
'summary' => [
'source' => $this->shopBalances->countForDate($balanceDate),
'matched' => (int) $balanceCounts->get('matched', 0),
'finance' => $financeCount,
'ambiguous' => (int) $balanceCounts->get('ambiguous', 0),
'unmatched' => (int) $balanceCounts->get('unmatched', 0),
'not_ready' => (int) $balanceCounts->get('not_ready', 0),
],
'balanceColumnLabel' => $labelDate->format('n月j日') . '店铺余额',
'balanceDate' => $balanceDate,
'latestBalanceDate' => $latestBalanceDate,
'balanceDates' => $this->shopBalances->availableDates($today),
'sort' => $sort,
];
}
/** @return array{platform:string,withdrawalPath:string,storeEntity:string,keyword:string,balanceStatus:string,balanceDate:string} */
public function filters(Request $request): array
{
$clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length);
$balanceStatus = $clean($request->query('balance_status'));
$balanceDate = $clean($request->query('balance_date'), 10);
if (! in_array($balanceStatus, ['matched', 'unmatched', 'ambiguous', 'not_ready'], true)) {
$balanceStatus = '';
}
$validDate = preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $balanceDate, $parts) === 1
&& checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1]);
if (! $validDate || $balanceDate > now()->toDateString()) {
$balanceDate = '';
}
return [
'platform' => $clean($request->query('platform')),
'withdrawalPath' => $clean($request->query('withdrawal_path')),
'storeEntity' => $clean($request->query('store_entity'), 191),
'keyword' => $clean($request->query('keyword'), 191),
'balanceStatus' => $balanceStatus,
'balanceDate' => $balanceDate,
];
}
/** @return list<string> */
private function options(string $column): array
{
return StoreReceivingAccount::query()
->whereNotNull($column)
->where($column, '<>', '')
->distinct()
->orderBy($column)
->pluck($column)
->filter()
->values()
->all();
}
/** @return array{field:string,direction:string} */
private function sorting(Request $request): array
{
$field = trim((string) $request->query('sort'));
$direction = strtolower(trim((string) $request->query('direction')));
return [
'field' => in_array($field, self::SORT_FIELDS, true) ? $field : '',
'direction' => in_array($direction, ['asc', 'desc'], true) ? $direction : 'asc',
];
}
/**
* @param Collection<int,StoreReceivingAccount> $rows
* @param array<int,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}> $balances
* @return Collection<int,StoreReceivingAccount>
*/
private function sortByBalanceStatus(Collection $rows, array $balances): Collection
{
$statusOrder = ['matched' => 0, 'ambiguous' => 1, 'unmatched' => 2, 'not_ready' => 3];
return $rows->sort(
static function (StoreReceivingAccount $left, StoreReceivingAccount $right) use ($balances, $statusOrder): int {
$leftStatus = $balances[(int) $left->id]['status'] ?? 'not_ready';
$rightStatus = $balances[(int) $right->id]['status'] ?? 'not_ready';
$statusComparison = ($statusOrder[$leftStatus] ?? 99) <=> ($statusOrder[$rightStatus] ?? 99);
return $statusComparison !== 0
? $statusComparison
: ((int) $right->id <=> (int) $left->id);
},
)->values();
}
/**
* @param Collection<int,StoreReceivingAccount> $rows
* @param array{field:string,direction:string} $sort
* @param array<int,array<string,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}>> $balancesByDate
* @param list<array{key:string,date:string,label:string}> $balanceDays
* @param array<int,array{balance:float,start_date:string,end_date:string,message:string}> $alerts
* @param array<int,int|null> $reserveStandards
* @param array<int,float|null> $withdrawalAmounts
* @param array<int,string|null> $compliance
* @return Collection<int,StoreReceivingAccount>
*/
private function sortRows(
Collection $rows,
array $sort,
array $balancesByDate,
array $balanceDays,
array $alerts,
array $reserveStandards,
array $withdrawalAmounts,
array $compliance,
): Collection {
return $rows->sort(function (StoreReceivingAccount $left, StoreReceivingAccount $right) use (
$sort,
$balancesByDate,
$balanceDays,
$alerts,
$reserveStandards,
$withdrawalAmounts,
$compliance,
): int {
$leftValue = $this->sortValue($left, $sort['field'], $balancesByDate, $balanceDays, $alerts, $reserveStandards, $withdrawalAmounts, $compliance);
$rightValue = $this->sortValue($right, $sort['field'], $balancesByDate, $balanceDays, $alerts, $reserveStandards, $withdrawalAmounts, $compliance);
$comparison = $this->compareSortValues($leftValue, $rightValue, $sort['direction']);
return $comparison !== 0
? $comparison
: ((int) $right->id <=> (int) $left->id);
})->values();
}
/**
* @param array<int,array<string,array{status:string,balance:?float,source_store_name:?string,source_platform:?string}>> $balancesByDate
* @param list<array{key:string,date:string,label:string}> $balanceDays
* @param array<int,array{balance:float,start_date:string,end_date:string,message:string}> $alerts
* @param array<int,int|null> $reserveStandards
* @param array<int,float|null> $withdrawalAmounts
* @param array<int,string|null> $compliance
*/
private function sortValue(
StoreReceivingAccount $row,
string $field,
array $balancesByDate,
array $balanceDays,
array $alerts,
array $reserveStandards,
array $withdrawalAmounts,
array $compliance,
): mixed {
$balanceFor = static function (string $dayKey) use ($row, $balancesByDate, $balanceDays): ?float {
$date = null;
foreach ($balanceDays as $day) {
if ($day['key'] === $dayKey) {
$date = $day['date'];
break;
}
}
$match = $date === null
? null
: ($balancesByDate[(int) $row->id][$date] ?? null);
return ($match['status'] ?? null) === 'matched' ? (float) $match['balance'] : null;
};
return match ($field) {
'platform' => $row->store_platform,
'erp_store_name' => $row->erp_store_name,
'store_id' => $row->store_id,
'store_entity' => $row->store_entity_name,
'withdrawal_path' => $row->withdrawal_path,
'withdrawal_account' => $row->withdrawal_account_name,
'bank_card' => $row->bank_card_last_four,
'balance_two_days_ago' => $balanceFor('balance_two_days_ago'),
'balance_yesterday' => $balanceFor('balance_yesterday'),
'balance' => $balanceFor('balance'),
'balance_alert' => isset($alerts[(int) $row->id]) ? 1 : 0,
'reserve_standard' => $reserveStandards[(int) $row->id] ?? null,
'withdrawal_amount' => $withdrawalAmounts[(int) $row->id] ?? null,
'compliance' => $compliance[(int) $row->id] ?? null,
default => null,
};
}
private function withdrawalAmountFor(StoreReceivingAccount $row, string $balanceDate): ?float
{
if ($row->withdrawal_balance_date !== $balanceDate || $row->withdrawal_amount === null) {
return null;
}
return is_numeric($row->withdrawal_amount) ? (float) $row->withdrawal_amount : null;
}
/** @param array{status:string,balance:?float} $balance */
public static function complianceFor(array $balance, ?int $reserve, ?float $withdrawalAmount): ?string
{
if (($balance['status'] ?? '') !== 'matched' || $balance['balance'] === null || $reserve === null || $withdrawalAmount === null) {
return null;
}
$remainingCents = (int) round((float) $balance['balance'] * 100)
- (int) round($withdrawalAmount * 100);
return $remainingCents <= $reserve * 100 ? 'yes' : 'no';
}
private function compareSortValues(mixed $left, mixed $right, string $direction): int
{
$leftEmpty = $left === null || $left === '';
$rightEmpty = $right === null || $right === '';
if ($leftEmpty || $rightEmpty) {
return $leftEmpty === $rightEmpty ? 0 : ($leftEmpty ? 1 : -1);
}
$comparison = is_numeric($left) && is_numeric($right)
? ((float) $left <=> (float) $right)
: strnatcasecmp((string) $left, (string) $right);
return $direction === 'desc' ? -$comparison : $comparison;
}
}

View File

@ -1,718 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\StoreReceivingAccount;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
class WithdrawalManagementSpreadsheet
{
private const CONFIG_HEADERS = [
'店铺平台',
'ERP店铺名称',
'平台店铺ID',
'店铺主体',
'提现路径',
'提现账户名称',
'银行卡号(后四位)',
];
private const CLEAR_VALUE = '[清空]';
private const WITHDRAWAL_TEMPLATE_HEADERS = [
'店铺平台',
'ERP店铺名称',
'平台店铺ID',
'余额日期',
'店铺余额',
'预留标准',
'提现金额',
'提现后余额',
'是否达标',
];
public function __construct(
private readonly JushuitanShopBalanceRepository $shopBalances,
) {
}
/**
* @param array{
* rows:\Illuminate\Support\Collection<int,StoreReceivingAccount>,
* balances:array<int,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}>,
* balancesByDate:array<int,array<string,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}>>,
* balanceDays:list<array{key:string,date:string,label:string}>,
* alerts:array<int,array{balance:float,start_date:string,end_date:string,message:string}>,
* reserveStandards:array<int,int|null>,withdrawalAmounts:array<int,float|null>,compliance:array<int,string|null>,
* balanceColumnLabel:string,balanceDate:string
* } $report
*/
public function export(array $report): StreamedResponse
{
$spreadsheet = $this->workbook($report);
return $this->download(
$spreadsheet,
'withdrawal_management_' . str_replace('-', '', $report['balanceDate']) . '_' . now()->format('His') . '.xlsx',
);
}
public function template(): StreamedResponse
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('提现管理');
$this->writeHeader($sheet, [...self::CONFIG_HEADERS, '提现金额']);
$this->sizeColumns($sheet, [14, 30, 20, 32, 16, 24, 22, 18]);
$instructions = $spreadsheet->createSheet();
$instructions->setTitle('填写说明');
$instructions->fromArray([
['提现管理导入说明'],
['1. 店铺平台、ERP店铺名称用于定位店铺;有平台店铺ID时优先按平台和ID匹配。'],
['2. 店铺主体、提现路径、提现账户名称、银行卡号后四位和提现金额为可更新字段。'],
['3. 可更新字段留空表示保持原值,填写“' . self::CLEAR_VALUE . '”表示清空原值。'],
['4. 提现金额须为非负数,最多两位小数,只用于当前页面显示的余额数据日期(最近 5 天内最新可用日期);上传后先预览再确认。'],
], null, 'A1');
$instructions->getStyle('A1')->getFont()->setBold(true)->setSize(14);
$instructions->getColumnDimension('A')->setWidth(88);
$instructions->getStyle('A1:A5')->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
foreach (range(1, 5) as $row) {
$instructions->getRowDimension($row)->setRowHeight($row === 1 ? 26 : 34);
}
$spreadsheet->setActiveSheetIndex(0);
return $this->download($spreadsheet, 'withdrawal_management_import_template.xlsx');
}
/**
* 按当前筛选预填店铺和余额参考值,同事只需填写提现金额。
*
* @param array<string,mixed> $report
*/
public function withdrawalTemplate(array $report): StreamedResponse
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('提现金额');
$this->writeHeader($sheet, self::WITHDRAWAL_TEMPLATE_HEADERS);
$this->sizeColumns($sheet, [14, 30, 20, 14, 18, 18, 18, 18, 14]);
$rowNumber = 2;
foreach ($report['rows'] as $row) {
$storeId = (int) $row->id;
$balanceMatch = $report['balances'][$storeId] ?? [
'status' => 'not_ready',
'balance' => null,
];
$hasBalance = ($balanceMatch['status'] ?? '') === 'matched'
&& ($balanceMatch['balance'] ?? null) !== null;
$reserve = $report['reserveStandards'][$storeId] ?? null;
$amount = $report['withdrawalAmounts'][$storeId] ?? null;
foreach ([
'A' => (string) ($row->store_platform ?? ''),
'B' => (string) ($row->erp_store_name ?? ''),
'C' => (string) ($row->store_id ?? ''),
'D' => (string) $report['balanceDate'],
] as $column => $value) {
$sheet->setCellValueExplicit("{$column}{$rowNumber}", $value, DataType::TYPE_STRING);
}
if ($hasBalance) {
$sheet->setCellValue("E{$rowNumber}", (float) $balanceMatch['balance']);
} else {
$sheet->setCellValueExplicit("E{$rowNumber}", $this->balanceStatus((string) ($balanceMatch['status'] ?? 'not_ready')), DataType::TYPE_STRING);
}
if ($reserve !== null) {
$sheet->setCellValue("F{$rowNumber}", $reserve);
} else {
$sheet->setCellValueExplicit("F{$rowNumber}", '待配置', DataType::TYPE_STRING);
}
if ($amount !== null) {
$sheet->setCellValue("G{$rowNumber}", $amount);
}
$sheet->setCellValue(
"H{$rowNumber}",
"=IF(OR(NOT(ISNUMBER(E{$rowNumber})),G{$rowNumber}=\"\"),\"\",E{$rowNumber}-G{$rowNumber})",
);
$sheet->setCellValue(
"I{$rowNumber}",
"=IF(OR(H{$rowNumber}=\"\",NOT(ISNUMBER(F{$rowNumber}))),\"\",IF(H{$rowNumber}<=F{$rowNumber},\"是\",\"否\"))",
);
$rowNumber++;
}
$lastDataRow = max(2, $rowNumber - 1);
$sheet->getStyle("E2:I{$lastDataRow}")->getNumberFormat()->setFormatCode('#,##0.00');
$sheet->getStyle("E2:I{$lastDataRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$sheet->getStyle("G2:G{$lastDataRow}")->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FFF7F0DE');
$sheet->getStyle('G1')->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FFB9954F');
$validation = new DataValidation();
$validation->setType(DataValidation::TYPE_DECIMAL)
->setOperator(DataValidation::OPERATOR_GREATERTHANOREQUAL)
->setFormula1('0')
->setAllowBlank(true)
->setShowErrorMessage(true)
->setErrorTitle('提现金额格式错误')
->setError('请填写非负金额,最多两位小数。');
$sheet->setDataValidation("G2:G{$lastDataRow}", $validation);
$instructions = $spreadsheet->createSheet();
$instructions->setTitle('填写说明');
$instructions->fromArray([
['提现金额导入说明'],
['1. 本模板按下载时的页面筛选生成,已预填店铺标识、余额日期、店铺余额和预留标准。'],
['2. 只需填写黄色“提现金额”列;未填写金额的店铺不会提交。填写“' . self::CLEAR_VALUE . '”可清空该店铺提现金额。'],
['3. 店铺余额、预留标准、提现后余额和是否达标仅用于下载时预览,系统会在上传后按最新余额日期重新计算。'],
['4. 判定规则:店铺余额 - 提现金额 ≤ 预留标准时,“是否达标”为“是”,即该笔提现按大笔提现处理。'],
['5. 模板余额日期为 ' . $report['balanceDate'] . ';日期滚动后请重新下载模板,避免上传过期金额。'],
], null, 'A1');
$instructions->getStyle('A1')->getFont()->setBold(true)->setSize(14);
$instructions->getColumnDimension('A')->setWidth(96);
$instructions->getStyle('A1:A6')->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
foreach (range(1, 6) as $row) {
$instructions->getRowDimension($row)->setRowHeight($row === 1 ? 26 : 36);
}
$spreadsheet->setActiveSheetIndex(0);
return $this->download(
$spreadsheet,
'withdrawal_amount_import_' . str_replace('-', '', (string) $report['balanceDate']) . '.xlsx',
);
}
/**
* @return array{
* total:int,changed:int,unchanged:int,
* preview:list<array{platform:string,erp_store_name:string,store_id:string,changes:string,withdrawal_amount:?float,post_withdrawal_balance:?float,reserve_standard:?int,compliance:?string}>,
* plan:list<array{id:int,updated_at:string,changes:array<string,string|null>}>
* }
*/
public function preview(UploadedFile $file, int $companyId): array
{
try {
$spreadsheet = IOFactory::load($file->getRealPath());
$sheet = $spreadsheet->getSheetByName('提现管理') ?? $spreadsheet->getActiveSheet();
$matrix = $sheet->toArray(null, false, true, false);
$spreadsheet->disconnectWorksheets();
} catch (Throwable) {
throw ValidationException::withMessages([
'import' => 'Excel 文件无法读取,请确认文件未损坏并使用最新模板。',
]);
}
[$headerIndex, $headers, $headerMode] = $this->headers($matrix);
$indexes = array_flip($headers);
$balanceDate = $this->currentBalanceDate();
$accounts = StoreReceivingAccount::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
->get();
[$byId, $byName] = $this->indexes($accounts);
$balances = $this->shopBalances->matchesForStores($accounts, $balanceDate);
$withdrawalOnlyMode = $headerMode === 'withdrawal';
$errors = [];
$plan = [];
$preview = [];
$seen = [];
$total = 0;
$unchanged = 0;
foreach (array_slice($matrix, $headerIndex + 1, null, true) as $matrixIndex => $row) {
$values = [];
foreach ([...self::CONFIG_HEADERS, '提现金额', '余额日期'] as $header) {
$values[$header] = isset($indexes[$header])
? trim((string) ($row[$indexes[$header]] ?? ''))
: '';
}
// 专用模板会预填所有店铺,只把填写了提现金额的行视为提交数据。
if ($withdrawalOnlyMode && $values['提现金额'] === '') {
continue;
}
if (count(array_filter($values, static fn (string $value): bool => $value !== '')) === 0) {
continue;
}
$total++;
if ($total > 5000) {
throw ValidationException::withMessages(['import' => '单次最多导入 5000 行,请拆分文件后重试。']);
}
$line = $matrixIndex + 1;
$platform = mb_substr($values['店铺平台'], 0, 80);
$erpStoreName = mb_substr($values['ERP店铺名称'], 0, 191);
$storeId = mb_substr(ltrim($values['平台店铺ID'], "'"), 0, 191);
if ($platform === '' || ($storeId === '' && $erpStoreName === '')) {
$errors[] = "第 {$line} 行缺少店铺平台或店铺标识";
continue;
}
if ($withdrawalOnlyMode && $values['余额日期'] !== '' && $values['余额日期'] !== $balanceDate) {
$errors[] = "第 {$line} 行余额日期 {$values['余额日期']} 已过期,请按最新余额日期 {$balanceDate} 重新下载模板";
continue;
}
$matches = $storeId !== ''
? ($byId[$this->key($platform, $storeId)] ?? [])
: ($byName[$this->key($platform, $erpStoreName)] ?? []);
if (count($matches) === 0) {
$identity = $storeId !== '' ? "平台店铺ID {$storeId}" : "ERP 店铺名称 {$erpStoreName}";
$errors[] = "第 {$line} 行未找到 {$platform} / {$identity}";
continue;
}
if (count($matches) > 1) {
$errors[] = "第 {$line} 行匹配到多家店铺,请补充或核对平台店铺ID";
continue;
}
/** @var StoreReceivingAccount $account */
$account = $matches[0];
if (isset($seen[(int) $account->id])) {
$errors[] = "第 {$line} 行与第 {$seen[(int) $account->id]} 行重复指向同一家店铺";
continue;
}
$seen[(int) $account->id] = $line;
try {
$changes = $this->changes($account, $values, $balanceDate);
} catch (\InvalidArgumentException $exception) {
$errors[] = "第 {$line} 行" . $exception->getMessage();
continue;
}
if ($changes === []) {
$unchanged++;
continue;
}
$labels = [
'store_entity_name' => '店铺主体',
'receiving_method' => '提现路径',
'receiving_account_name' => '提现账户名称',
'bank_card_last_four' => '银行卡号后四位',
'withdrawal_amount' => '提现金额',
'withdrawal_balance_date' => '提现金额',
];
$changedLabels = array_unique(array_map(
static fn (string $field): string => $labels[$field],
array_keys($changes),
));
$plan[] = [
'id' => (int) $account->id,
'updated_at' => (string) $account->getRawOriginal('updated_at'),
'changes' => $changes,
];
if (count($preview) < 20) {
$amount = array_key_exists('withdrawal_amount', $changes)
? ($changes['withdrawal_amount'] === null ? null : (float) $changes['withdrawal_amount'])
: (
$account->withdrawal_balance_date === $balanceDate
&& $account->withdrawal_amount !== null
&& is_numeric($account->withdrawal_amount)
? (float) $account->withdrawal_amount
: null
);
$balance = ($balances[(int) $account->id]['status'] ?? '') === 'matched'
? (float) $balances[(int) $account->id]['balance']
: null;
$reserve = WithdrawalReserveStandard::amountFor(
$account->store_platform,
$account->erp_store_name,
);
$preview[] = [
'platform' => $platform,
'erp_store_name' => $erpStoreName,
'store_id' => $storeId,
'changes' => implode('、', $changedLabels),
'withdrawal_amount' => $amount,
'post_withdrawal_balance' => $balance !== null && $amount !== null
? round($balance - $amount, 2)
: null,
'reserve_standard' => $reserve,
'compliance' => WithdrawalManagementReport::complianceFor(
[
'status' => $balance === null ? 'not_ready' : 'matched',
'balance' => $balance,
],
$reserve,
$amount,
),
];
}
}
if ($total === 0) {
throw ValidationException::withMessages(['import' => '导入文件中没有可识别的数据行。']);
}
if ($errors !== []) {
$visible = array_slice($errors, 0, 10);
if (count($errors) > count($visible)) {
$visible[] = '另有 ' . (count($errors) - count($visible)) . ' 项错误';
}
throw ValidationException::withMessages(['import' => implode(';', $visible) . '。']);
}
return [
'total' => $total,
'changed' => count($plan),
'unchanged' => $unchanged,
'preview' => $preview,
'plan' => $plan,
];
}
/** @param list<array{id:int,updated_at:string,changes:array<string,string|null>}> $plan */
public function commit(array $plan, int $companyId): int
{
return DB::transaction(function () use ($plan, $companyId): int {
$updated = 0;
$currentBalanceDate = null;
foreach ($plan as $item) {
/** @var StoreReceivingAccount|null $account */
$account = StoreReceivingAccount::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
->whereKey((int) $item['id'])
->lockForUpdate()
->first();
if ($account === null || (string) $account->getRawOriginal('updated_at') !== (string) $item['updated_at']) {
throw ValidationException::withMessages([
'import' => '预览后店铺配置发生变化,请重新上传并预览。',
]);
}
if (isset($item['changes']['withdrawal_balance_date'])
&& $item['changes']['withdrawal_balance_date'] !== null) {
$currentBalanceDate ??= $this->currentBalanceDate();
if ($item['changes']['withdrawal_balance_date'] !== $currentBalanceDate) {
throw ValidationException::withMessages([
'import' => '余额日期已滚动,请重新上传并预览提现金额。',
]);
}
}
foreach ($item['changes'] as $field => $value) {
if ($field === 'bank_card_last_four') {
$account->bank_card_last_four = $value;
} else {
$account->setAttribute($field, $value);
}
}
$account->save();
$updated++;
}
return $updated;
});
}
private function workbook(array $report): Spreadsheet
{
$balanceHeaders = array_map(
static fn (array $day): string => (string) $day['label'],
$report['balanceDays'],
);
$headers = [
...self::CONFIG_HEADERS,
...$balanceHeaders,
'余额来源',
'余额预警',
'预留标准',
'提现金额',
'是否达标',
];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('提现管理');
$this->writeHeader($sheet, $headers);
$this->sizeColumns($sheet, [14, 32, 20, 32, 16, 24, 22, 20, 20, 20, 32, 18, 18, 18, 14]);
$rowNumber = 2;
foreach ($report['rows'] as $row) {
$reserve = $report['reserveStandards'][(int) $row->id] ?? null;
$withdrawalAmount = $report['withdrawalAmounts'][(int) $row->id] ?? null;
$compliance = $report['compliance'][(int) $row->id] ?? null;
$alert = $report['alerts'][(int) $row->id] ?? null;
$hasCompleteAlertSeries = collect($report['balanceDays'])->every(
fn (array $day): bool => (
$report['balancesByDate'][(int) $row->id][(string) $day['date']]['status'] ?? ''
) === 'matched',
);
$textValues = [
1 => (string) ($row->store_platform ?? ''),
2 => (string) ($row->erp_store_name ?? ''),
3 => (string) ($row->store_id ?? ''),
4 => (string) ($row->store_entity_name ?? ''),
5 => (string) ($row->withdrawal_path ?? ''),
6 => (string) ($row->withdrawal_account_name ?? ''),
7 => (string) ($row->bank_card_last_four ?? ''),
];
foreach ($textValues as $column => $value) {
$sheet->setCellValueExplicit([$column, $rowNumber], $value, DataType::TYPE_STRING);
}
foreach ($report['balanceDays'] as $dayIndex => $day) {
$column = 8 + $dayIndex;
$match = $report['balancesByDate'][(int) $row->id][$day['date']]
?? ['status' => 'not_ready', 'balance' => null];
if ($match['status'] === 'matched') {
$sheet->setCellValue([$column, $rowNumber], (float) $match['balance']);
} else {
$sheet->setCellValueExplicit([$column, $rowNumber], $this->balanceStatus($match['status']), DataType::TYPE_STRING);
}
}
$sourceParts = [];
foreach ($report['balanceDays'] as $day) {
$match = $report['balancesByDate'][(int) $row->id][$day['date']]
?? ['status' => 'not_ready'];
$sourceParts[] = str_replace('店铺余额', '', (string) $day['label']) . ':' . match ($match['status']) {
'matched' => ($match['data_source'] ?? null) === 'finance' ? '财务系统' : '聚水潭',
'ambiguous' => '多条匹配',
'unmatched' => '未匹配',
default => '待同步',
};
}
$sheet->setCellValueExplicit([11, $rowNumber], implode(';', $sourceParts), DataType::TYPE_STRING);
$sheet->setCellValueExplicit(
[12, $rowNumber],
$alert !== null ? '连续3天未变动' : ($hasCompleteAlertSeries ? '未触发' : '数据不足'),
DataType::TYPE_STRING,
);
if ($reserve === null) {
$sheet->setCellValueExplicit([13, $rowNumber], '待配置', DataType::TYPE_STRING);
} else {
$sheet->setCellValue([13, $rowNumber], $reserve);
}
if ($withdrawalAmount === null) {
$sheet->setCellValueExplicit([14, $rowNumber], '待接入', DataType::TYPE_STRING);
} else {
$sheet->setCellValue([14, $rowNumber], $withdrawalAmount);
}
$sheet->setCellValueExplicit([15, $rowNumber], match ($compliance) {
'yes' => '是',
'no' => '否',
default => '待核验',
}, DataType::TYPE_STRING);
$rowNumber++;
}
if ($rowNumber > 2) {
$sheet->getStyle('H2:J' . ($rowNumber - 1))->getNumberFormat()->setFormatCode('#,##0.00');
$sheet->getStyle('M2:N' . ($rowNumber - 1))->getNumberFormat()->setFormatCode('#,##0.00');
$sheet->getStyle('H2:J' . ($rowNumber - 1))->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$sheet->getStyle('M2:N' . ($rowNumber - 1))->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
}
$sheet->getStyle('C2:C' . max(2, $rowNumber - 1))->getNumberFormat()->setFormatCode('@');
$sheet->getStyle('G2:G' . max(2, $rowNumber - 1))->getNumberFormat()->setFormatCode('@');
$spreadsheet->getProperties()->setTitle('提现管理')->setDescription('余额数据日期:' . $report['balanceDate']);
return $spreadsheet;
}
/** @return array{0:int,1:list<string>,2:'config'|'withdrawal'} */
private function headers(array $matrix): array
{
foreach (array_slice($matrix, 0, 10, true) as $index => $row) {
$headers = array_map(static fn (mixed $value): string => trim((string) $value), $row);
if (! in_array('店铺平台', $headers, true) || ! in_array('提现金额', $headers, true)) {
continue;
}
$this->requireUniqueHeader($headers, '店铺平台');
$this->requireUniqueHeader($headers, '提现金额');
$fullConfigurationTemplate = collect(self::CONFIG_HEADERS)->every(
static fn (string $header): bool => in_array($header, $headers, true),
);
if ($fullConfigurationTemplate) {
foreach (self::CONFIG_HEADERS as $required) {
$this->requireUniqueHeader($headers, $required);
}
return [(int) $index, $headers, 'config'];
}
if (! in_array('ERP店铺名称', $headers, true) && ! in_array('平台店铺ID', $headers, true)) {
throw ValidationException::withMessages([
'import' => '提现金额模板必须包含“ERP店铺名称”或“平台店铺ID”用于定位店铺,请下载最新模板。',
]);
}
foreach ([
'ERP店铺名称', '平台店铺ID', '余额日期', '店铺余额', '预留标准',
'提现后余额', '是否达标',
] as $optional) {
if (count(array_keys($headers, $optional, true)) > 1) {
throw ValidationException::withMessages([
'import' => "导入表头只能包含一个“{$optional}”列。",
]);
}
}
return [(int) $index, $headers, 'withdrawal'];
}
throw ValidationException::withMessages([
'import' => '未找到提现管理导入表头,请下载最新模板。',
]);
}
/** @param list<string> $headers */
private function requireUniqueHeader(array $headers, string $header): void
{
if (count(array_keys($headers, $header, true)) !== 1) {
throw ValidationException::withMessages([
'import' => "导入表头必须且只能包含一个“{$header}”列,请下载最新模板。",
]);
}
}
/** @return array{0:array<string,list<StoreReceivingAccount>>,1:array<string,list<StoreReceivingAccount>>} */
private function indexes($accounts): array
{
$byId = [];
$byName = [];
foreach ($accounts as $account) {
$platform = trim((string) $account->store_platform);
$storeId = trim((string) ($account->store_id ?: $account->wallet_number));
$erpStoreName = trim((string) $account->erp_store_name);
if ($platform !== '' && $storeId !== '') {
$byId[$this->key($platform, $storeId)][] = $account;
}
if ($platform !== '' && $erpStoreName !== '') {
$byName[$this->key($platform, $erpStoreName)][] = $account;
}
}
return [$byId, $byName];
}
/** @param array<string,string> $values @return array<string,string|null> */
private function changes(StoreReceivingAccount $account, array $values, string $balanceDate): array
{
$fields = [
'店铺主体' => ['field' => 'store_entity_name', 'current' => $account->store_entity_name, 'max' => 191, 'clear' => ''],
'提现路径' => ['field' => 'receiving_method', 'current' => $account->withdrawal_path, 'max' => 191, 'clear' => ''],
'提现账户名称' => ['field' => 'receiving_account_name', 'current' => $account->withdrawal_account_name, 'max' => 191, 'clear' => null],
'银行卡号(后四位)' => ['field' => 'bank_card_last_four', 'current' => $account->bank_card_last_four, 'max' => 4, 'clear' => null],
];
$changes = [];
foreach ($fields as $header => $definition) {
$raw = trim((string) ($values[$header] ?? ''));
if ($raw === '') {
continue;
}
$value = $raw === self::CLEAR_VALUE ? $definition['clear'] : $raw;
if ($header === '银行卡号(后四位)' && $value !== null) {
if (preg_match('/^\d{4}$/', $value) !== 1) {
throw new \InvalidArgumentException('的银行卡号必须填写后四位数字');
}
}
if ($value !== null && mb_strlen($value) > $definition['max']) {
throw new \InvalidArgumentException("的{$header}超过 {$definition['max']} 个字符");
}
$current = trim((string) ($definition['current'] ?? '')) ?: null;
$comparisonValue = $value === '' ? null : $value;
if ($current !== $comparisonValue) {
$changes[$definition['field']] = $value;
}
}
$amount = $values['提现金额'] ?? '';
if ($amount !== '' && $amount !== '待接入') {
if ($amount === self::CLEAR_VALUE) {
if ($account->withdrawal_amount !== null || $account->withdrawal_balance_date !== null) {
$changes['withdrawal_amount'] = null;
$changes['withdrawal_balance_date'] = null;
}
} else {
if (preg_match('/^\d{1,10}(?:\.\d{1,2})?$/', $amount) !== 1) {
throw new \InvalidArgumentException('的提现金额须为非负数,最多两位小数');
}
$normalized = number_format((float) $amount, 2, '.', '');
if ($account->withdrawal_amount !== $normalized || $account->withdrawal_balance_date !== $balanceDate) {
$changes['withdrawal_amount'] = $normalized;
$changes['withdrawal_balance_date'] = $balanceDate;
}
}
}
return $changes;
}
private function currentBalanceDate(): string
{
$today = now()->startOfDay();
return $this->shopBalances->latestBalanceDate($today)
?? $today->copy()->subDay()->toDateString();
}
private function key(string $platform, string $identity): string
{
return trim($platform) . "\0" . trim($identity);
}
private function balanceStatus(string $status): string
{
return match ($status) {
'ambiguous' => '多条匹配',
'unmatched' => '未匹配',
default => '待同步',
};
}
private function writeHeader($sheet, array $headers): void
{
$lastColumn = Coordinate::stringFromColumnIndex(count($headers));
$sheet->fromArray($headers, null, 'A1');
$sheet->freezePane('A2');
$sheet->setAutoFilter("A1:{$lastColumn}1");
$sheet->getRowDimension(1)->setRowHeight(26);
$sheet->getStyle("A1:{$lastColumn}1")->getFont()->setBold(true)->getColor()->setARGB('FFFFFFFF');
$sheet->getStyle("A1:{$lastColumn}1")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF856632');
$sheet->getStyle("A1:{$lastColumn}1")->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
}
private function sizeColumns($sheet, array $widths): void
{
foreach ($widths as $index => $width) {
$sheet->getColumnDimension(Coordinate::stringFromColumnIndex($index + 1))->setWidth($width);
}
}
private function download(Spreadsheet $spreadsheet, string $filename): StreamedResponse
{
return response()->streamDownload(function () use ($spreadsheet): void {
(new Xlsx($spreadsheet))->save('php://output');
$spreadsheet->disconnectWorksheets();
}, $filename, [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Cache-Control' => 'private, no-store',
]);
}
}

View File

@ -1,35 +0,0 @@
<?php
namespace App\Business;
final class WithdrawalReserveStandard
{
private const TMALL_HIGH_RESERVE_STORES = [
'天猫-亿家达旗舰店',
'天猫-欧意朗旗舰店',
'天猫-卓禾家具旗舰店',
];
private const PLATFORM_DEFAULTS = [
'天猫' => 20000,
'淘宝' => 10000,
'淘宝分销' => 10000,
'阿里巴巴' => 10000,
'京东' => 5000,
'京喜' => 5000,
'抖音' => 5000,
'拼多多' => 5000,
];
public static function amountFor(?string $platform, ?string $erpStoreName): ?int
{
$platform = trim((string) $platform);
$erpStoreName = trim((string) $erpStoreName);
if ($platform === '天猫' && in_array($erpStoreName, self::TMALL_HIGH_RESERVE_STORES, true)) {
return 50000;
}
return self::PLATFORM_DEFAULTS[$platform] ?? null;
}
}

View File

@ -1,339 +0,0 @@
<?php
namespace App\Business;
use Generator;
use RuntimeException;
use ZipArchive;
/**
* xlsx 工作表流式读取器(按表头取列)。
*
* 主要给几十万行的大表用(聚水潭导出订单、快递运费明细等),直接套常规 Excel 读法会踩坑:
* - 字符串用 inlineStr 内联存储(sharedStrings 里是空的);
* - worksheet 的 <dimension> 只写一个 A1,靠它判断行数会把整表读成空;
* - 一行订单一个商品明细,单文件常见上万行 × 上百列,解压后几十 MB。
*
* 所以这里用 ZipArchive 取压缩流 + expat 增量解析,只保留调用方点名的列,
* 内存占用与文件大小无关(导出 20 万行也不会整表进内存)。
*/
class XlsxSheetReader
{
private const READ_CHUNK = 262144;
/**
* 逐行读取导出文件(跳过表头行)。
*
* @param list<string|list<string>> $columns 需要取出的列(缺列会报错)。给字符串就是精确匹配表头;
* 给数组表示同一列有多个可选表头(取第一个命中的,
* 返回键用数组里的第一个名字)。
* @param list<string|list<string>> $optionalColumns 可选列:文件里有就取,没有就跳过(不报错)。
* @return Generator<int, array<string, string>>
*/
public function rows(string $path, array $columns, array $optionalColumns = []): Generator
{
if (! is_file($path)) {
throw new RuntimeException('订单导出文件不存在:' . $path);
}
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
throw new RuntimeException('无法打开订单导出文件(不是有效的 xlsx):' . $path);
}
$stream = $zip->getStream($this->worksheetPath($zip));
if ($stream === false) {
$zip->close();
throw new RuntimeException('订单导出文件里没有可读的工作表。');
}
try {
yield from $this->parseSheet($stream, $this->sharedStrings($zip), $columns, $optionalColumns);
} finally {
fclose($stream);
$zip->close();
}
}
/**
* @param resource $stream
* @param list<string> $shared
* @param list<string|list<string>> $columns
* @param list<string|list<string>> $optionalColumns
* @return Generator<int, array<string, string>>
*/
private function parseSheet($stream, array $shared, array $columns, array $optionalColumns): Generator
{
$state = [
'row' => [],
'column' => -1,
'type' => null,
'value' => '',
'inValue' => false,
'rowNumber' => 0,
'wanted' => [],
'pending' => [],
];
$parser = xml_parser_create('UTF-8');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_set_element_handler(
$parser,
static function ($parser, string $name, array $attributes) use (&$state): void {
$name = self::localName($name);
switch ($name) {
case 'row':
$state['row'] = [];
$state['column'] = -1;
break;
case 'c':
$state['column'] = self::columnIndex($attributes['r'] ?? null, $state['column'] + 1);
$state['type'] = $attributes['t'] ?? null;
$state['value'] = '';
break;
case 'v':
case 't':
$state['inValue'] = true;
break;
}
},
static function ($parser, string $name) use (&$state, $shared, $columns, $optionalColumns): void {
$name = self::localName($name);
switch ($name) {
case 'v':
case 't':
$state['inValue'] = false;
break;
case 'c':
$state['row'][$state['column']] = self::cellValue($state['type'], $state['value'], $shared);
break;
case 'row':
$state['rowNumber']++;
if ($state['rowNumber'] === 1) {
$state['wanted'] = self::wantedColumns($state['row'], $columns, $optionalColumns);
break;
}
$values = [];
foreach ($state['wanted'] as $index => $column) {
$values[$column] = $state['row'][$index] ?? '';
}
$state['pending'][] = $values;
break;
}
}
);
xml_set_character_data_handler($parser, static function ($parser, string $data) use (&$state): void {
if ($state['inValue']) {
$state['value'] .= $data;
}
});
$first = true;
try {
while (! feof($stream)) {
$chunk = fread($stream, self::READ_CHUNK);
if ($chunk === false || $chunk === '') {
break;
}
if ($first) {
// 聚水潭导出的 XML 带 UTF-8 BOM,expat 会当成非法前缀。
$chunk = preg_replace('/^\xEF\xBB\xBF/', '', $chunk, 1);
$first = false;
}
if (xml_parse($parser, $chunk, false) === 0) {
throw new RuntimeException('订单导出文件解析失败:' . xml_error_string(xml_get_error_code($parser)));
}
while ($state['pending'] !== []) {
yield array_shift($state['pending']);
}
}
if (xml_parse($parser, '', true) === 0) {
throw new RuntimeException('订单导出文件解析失败:' . xml_error_string(xml_get_error_code($parser)));
}
} finally {
xml_parser_free($parser);
}
while ($state['pending'] !== []) {
yield array_shift($state['pending']);
}
}
/**
* 表头行 -> [列下标 => 列名],并校验需要的列都在;可选列缺了不算错。
*
* @param array<int, string> $header
* @param list<string|list<string>> $columns
* @param list<string|list<string>> $optionalColumns
* @return array<int, string>
*/
private static function wantedColumns(array $header, array $columns, array $optionalColumns = []): array
{
$byName = [];
foreach ($header as $index => $name) {
$name = trim($name);
if ($name !== '' && ! isset($byName[$name])) {
$byName[$name] = $index;
}
}
$wanted = [];
foreach ($columns as $column) {
$names = is_array($column) ? array_values($column) : [$column];
$matched = null;
foreach ($names as $name) {
if (isset($byName[$name])) {
$matched = $name;
break;
}
}
if ($matched === null) {
throw new RuntimeException('文件缺少列:' . implode(' / ', $names));
}
$wanted[$byName[$matched]] = $names[0];
}
foreach ($optionalColumns as $column) {
$names = is_array($column) ? array_values($column) : [$column];
$matched = null;
foreach ($names as $name) {
if (isset($byName[$name])) {
$matched = $name;
break;
}
}
if ($matched !== null && ! isset($wanted[$byName[$matched]])) {
$wanted[$byName[$matched]] = $names[0];
}
}
return $wanted;
}
/**
* @param list<string> $shared
*/
private static function cellValue(?string $type, string $value, array $shared): string
{
if ($type === 's') {
return $shared[(int) $value] ?? '';
}
return trim($value);
}
/** 单元格引用(如 AV12)-> 0 基列下标。 */
private static function columnIndex(?string $reference, int $fallback): int
{
if ($reference === null || preg_match('/^([A-Z]+)/i', $reference, $matches) !== 1) {
return $fallback;
}
$letters = strtoupper($matches[1]);
$index = 0;
for ($i = 0, $length = strlen($letters); $i < $length; $i++) {
$index = $index * 26 + (ord($letters[$i]) - 64);
}
return $index - 1;
}
private function worksheetPath(ZipArchive $zip): string
{
$workbook = $zip->getFromName('xl/workbook.xml');
$relationships = $zip->getFromName('xl/_rels/workbook.xml.rels');
if (is_string($workbook) && is_string($relationships)
&& preg_match('/<sheet[^>]*r:id="([^"]+)"/', $workbook, $sheet) === 1
&& preg_match('/Id="' . preg_quote($sheet[1], '/') . '"[^>]*Target="([^"]+)"/', $relationships, $target) === 1) {
$path = ltrim($target[1], '/');
return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path;
}
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = (string) $zip->getNameIndex($i);
if (preg_match('#^xl/worksheets/[^/]+\.xml$#', $name) === 1) {
return $name;
}
}
return 'xl/worksheets/sheet1.xml';
}
/**
* 读取共享字符串表;聚水潭导出通常为空,但标准 xlsx 会用到。
*
* @return list<string>
*/
private function sharedStrings(ZipArchive $zip): array
{
$xml = $zip->getFromName('xl/sharedStrings.xml');
if (! is_string($xml) || $xml === '') {
return [];
}
$out = [];
$index = -1;
$buffer = '';
$inside = false;
$parser = xml_parser_create('UTF-8');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_set_element_handler(
$parser,
static function ($parser, string $name) use (&$inside, &$buffer, &$index): void {
$name = self::localName($name);
if ($name === 'si') {
$index++;
$buffer = '';
} elseif ($name === 't') {
$inside = true;
}
},
static function ($parser, string $name) use (&$inside, &$buffer, &$out): void {
$name = self::localName($name);
if ($name === 't') {
$inside = false;
} elseif ($name === 'si') {
$out[] = $buffer;
}
}
);
xml_set_character_data_handler($parser, static function ($parser, string $data) use (&$inside, &$buffer): void {
if ($inside) {
$buffer .= $data;
}
});
try {
xml_parse($parser, preg_replace('/^\xEF\xBB\xBF/', '', $xml, 1), true);
} finally {
xml_parser_free($parser);
}
return $out;
}
private static function localName(string $name): string
{
$separator = strrpos($name, ':');
return $separator === false ? $name : substr($name, $separator + 1);
}
}

View File

@ -1,50 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\StoreInformationDailyArchive;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Throwable;
class ArchiveStoreInformationDaily extends Command
{
protected $signature = 'business-mirror:archive-store-information
{--date= : 快照日期,格式 YYYY-MM-DD;默认今天}';
protected $description = '每日保存一份店铺基础信息完整快照,便于后续复查';
public function handle(StoreInformationDailyArchive $archive): int
{
$date = trim((string) ($this->option('date') ?: now('Asia/Shanghai')->format('Y-m-d')));
if (! preg_match('/^\d{4}-\d{2}-\d{2}$/D', $date)) {
$this->error('快照日期格式应为 YYYY-MM-DD。');
return self::FAILURE;
}
try {
$snapshotDate = CarbonImmutable::createFromFormat('!Y-m-d', $date, 'Asia/Shanghai');
} catch (Throwable) {
$snapshotDate = null;
}
if ($snapshotDate === null || $snapshotDate->format('Y-m-d') !== $date) {
$this->error('快照日期不是有效日期。');
return self::FAILURE;
}
try {
$count = $archive->capture($snapshotDate);
} catch (Throwable $exception) {
report($exception);
$this->error('店铺基础信息存档失败:' . $exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf('已保存 %s 店铺基础信息快照,共 %d 条。', $date, $count));
return self::SUCCESS;
}
}

View File

@ -1,246 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\ProductMonthlyWeightedAverageReporter;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
/**
* 检查上游完整性后,自动生成尚未计算的最新月份商品月加权平均单价。
*/
class AutoComputeProductMonthlyWeightedAverage extends Command
{
protected $signature = 'product:monthly-weighted-average:auto
{--month= : 指定月份;默认取最新已成功的进销存月份}
{--result-json= : 将执行结果写入指定 JSON 文件}';
protected $description = '上游完整后自动计算商品月加权平均单价,并保护已计算历史月份';
public function handle(ProductMonthlyWeightedAverageReporter $reporter): int
{
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$month = $this->targetMonth($connection);
if ($month === null) {
return $this->finish('blocked', null, [
'message' => '未找到已成功导入的进销存月份。',
]);
}
$lock = Cache::lock('product-monthly-weighted-average-auto:' . $month->format('Y-m'), 7200);
if (! $lock->get()) {
return $this->finish('blocked', $month, [
'message' => '同月自动计算任务正在执行。',
]);
}
try {
$state = DB::connection($connection)->table('product_monthly_weighted_average_states')
->where('report_month', $month->toDateString())
->first();
if (($state?->status ?? null) === 'computed') {
$report = $reporter->build($connection, $month);
$report['calculation_status'] = $report['status'];
$report['status'] = 'already_computed';
return $this->finish('already_computed', $month, $report, $reporter);
}
$checks = $this->checks($connection, $month);
if (in_array(false, array_column($checks, 'passed'), true)) {
DB::connection($connection)->table('product_monthly_weighted_average_states')->updateOrInsert(
['report_month' => $month->toDateString()],
[
'status' => 'blocked',
'last_error' => '上游数据未通过完整性检查',
'updated_at' => now(),
'created_at' => now(),
],
);
return $this->finish('blocked', $month, [
'message' => '上游数据未更新或不完整,未执行计算。',
'checks' => $checks,
]);
}
$baseExit = $this->call('product:monthly-weighted-average:base', [
'month' => $month->format('Y-m'),
'--from-previous' => true,
// 自动任务只会在尚未 computed 的月份走到这里,可安全清理失败重试留下
// 的同月基表;已 computed 的历史月份在前面的门禁直接跳过。
'--force' => true,
]);
if ($baseExit !== self::SUCCESS) {
return $this->finish('failed', $month, [
'message' => '生成期初基数失败。',
]);
}
$computeExit = $this->call('product:monthly-weighted-average:compute', [
'month' => $month->format('Y-m'),
]);
if ($computeExit !== self::SUCCESS) {
return $this->finish('failed', $month, [
'message' => '加权平均单价计算失败。',
]);
}
$report = $reporter->build($connection, $month);
$report['checks'] = $checks;
return $this->finish(
($report['status'] ?? null) === 'review_required' ? 'review_required' : 'success',
$month,
$report,
$reporter,
);
} finally {
$lock->release();
}
}
private function targetMonth(string $connection): ?CarbonImmutable
{
$requested = trim((string) $this->option('month'));
if ($requested !== '') {
return CarbonImmutable::parse($requested)->startOfMonth();
}
$latest = DB::connection($connection)->table('inventory_report_authoritative_months')
->where('dataset_key', 'jiansun.inventory-report.authoritative-month')
->where('status', 'succeeded')
->whereNotNull('active_generation')
->orderByDesc('source_month')
->value('source_month');
return $latest === null ? null : CarbonImmutable::parse((string) $latest)->startOfMonth();
}
/** @return list<array{name:string,passed:bool,actual:mixed,expected:mixed}> */
private function checks(string $connection, CarbonImmutable $month): array
{
$db = DB::connection($connection);
$monthState = $db->table('inventory_report_authoritative_months')
->where('dataset_key', 'jiansun.inventory-report.authoritative-month')
->where('source_month', $month->toDateString())
->first();
$generation = $monthState?->active_generation;
$activeRows = $generation === null
? 0
: $db->table('inventory_report_authoritative_rows')
->where('generation', (string) $generation)
->count();
$expectedRows = (int) ($monthState?->source_row_count ?? 0);
$previous = $month->subMonthNoOverflow();
$previousState = $db->table('product_monthly_weighted_average_states')
->where('report_month', $previous->toDateString())
->value('status');
$previousRows = $db->table('product_monthly_weighted_average_rows')
->where('report_month', $previous->toDateString())
->count();
$inboundRows = $db->table('inventory_inbound_detail_rows')
->where('report_month', $month->toDateString())
->count();
$inboundMissingDimensions = $db->table('inventory_inbound_detail_rows')
->where('report_month', $month->toDateString())
->where(function ($query): void {
$query->whereNull('barcode')->orWhere('barcode', '')
->orWhereNull('warehouse_short_name')->orWhere('warehouse_short_name', '');
})
->count();
$inboundMissingAmounts = $db->table('inventory_inbound_detail_rows')
->where('report_month', $month->toDateString())
->whereNull('amount')
->whereNull('estimated_amount')
->count();
$productCatalogRows = $db->table('ops_jst_sku')->whereNotNull('sku_id')->count();
return [
[
'name' => '进销存月份状态成功',
'passed' => ($monthState?->status ?? null) === 'succeeded',
'actual' => $monthState?->status,
'expected' => 'succeeded',
],
[
'name' => '进销存激活明细行数完整',
'passed' => $expectedRows > 0 && $activeRows === $expectedRows,
'actual' => $activeRows,
'expected' => $expectedRows,
],
[
'name' => '上月加权平均结果已完成',
'passed' => $previousState === 'computed' && $previousRows > 0,
'actual' => ['status' => $previousState, 'rows' => $previousRows],
'expected' => ['status' => 'computed', 'rows' => '> 0'],
],
[
'name' => '入库明细已更新',
'passed' => $inboundRows > 0,
'actual' => $inboundRows,
'expected' => '> 0',
],
[
'name' => '入库商品编码与仓库简称无缺失',
'passed' => $inboundMissingDimensions === 0,
'actual' => $inboundMissingDimensions,
'expected' => 0,
],
[
'name' => '入库金额至少取金额或预估金额',
'passed' => $inboundMissingAmounts === 0,
'actual' => $inboundMissingAmounts,
'expected' => 0,
],
[
'name' => '普通商品资料已更新',
'passed' => $productCatalogRows > 0,
'actual' => $productCatalogRows,
'expected' => '> 0',
],
];
}
/**
* @param array<string,mixed> $payload
*/
private function finish(
string $status,
?CarbonImmutable $month,
array $payload,
?ProductMonthlyWeightedAverageReporter $reporter = null,
): int {
$result = ['status' => $status] + $payload;
if (! isset($result['report_month']) && $month !== null) {
$result['report_month'] = $month->toDateString();
}
$path = trim((string) $this->option('result-json'));
if ($path !== '') {
File::ensureDirectoryExists(dirname($path));
File::put(
$path,
json_encode(
$result,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT,
) . PHP_EOL,
);
}
if ($reporter !== null && isset($result['totals'])) {
$this->line($reporter->brief($result));
} elseif (isset($result['message'])) {
$this->error((string) $result['message']);
}
return in_array($status, ['blocked', 'failed'], true)
? self::FAILURE
: self::SUCCESS;
}
}

View File

@ -1,133 +0,0 @@
<?php
namespace App\Console\Commands;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
/**
* 固定月度顺序:先生成商品月加权平均单价,再同步商品成本表。
*/
class AutoMonthlyWeightedAverageAndProductCost extends Command
{
protected $signature = 'finance:monthly-weighted-product-cost:auto
{--month= : 指定月份;默认取最新已成功的进销存月份}
{--result-json= : 将两阶段结果写入指定 JSON 文件}';
protected $description = '先计算商品月加权平均单价,再自动同步商品成本表';
public function handle(): int
{
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$month = $this->targetMonth($connection);
if ($month === null) {
return $this->writeResult([
'status' => 'blocked',
'message' => '未找到已成功导入的进销存月份。',
]);
}
$weightedPath = tempnam(sys_get_temp_dir(), 'weighted-result-') . '.json';
$costPath = tempnam(sys_get_temp_dir(), 'product-cost-result-') . '.json';
try {
$weightedExit = $this->call('product:monthly-weighted-average:auto', [
'--month' => $month->format('Y-m'),
'--result-json' => $weightedPath,
]);
$weighted = $this->readJson($weightedPath);
if (
$weightedExit !== self::SUCCESS
|| in_array($weighted['status'] ?? 'failed', ['blocked', 'failed'], true)
) {
return $this->writeResult([
'status' => 'failed',
'report_month' => $month->toDateString(),
'message' => '商品月加权平均单价未完成,商品成本未执行。',
'weighted_average' => $weighted,
'product_cost' => null,
]);
}
$costExit = $this->call('store-receipt:product-cost:sync', [
'month' => $month->format('Y-m'),
'--result-json' => $costPath,
]);
$cost = $this->readJson($costPath);
$status = $costExit !== self::SUCCESS
? 'failed'
: ((int) ($cost['pending_cost_rows'] ?? 0) > 0 ? 'review_required' : 'success');
return $this->writeResult([
'status' => $status,
'report_month' => $month->toDateString(),
'message' => match ($status) {
'success' => '月加权平均单价与商品成本已按顺序完成。',
'review_required' => '月加权平均单价与商品成本已完成,存在待核验成本。',
default => '商品成本同步失败。',
},
'weighted_average' => $weighted,
'product_cost' => $cost,
]);
} finally {
@unlink($weightedPath);
@unlink($costPath);
}
}
private function targetMonth(string $connection): ?CarbonImmutable
{
$requested = trim((string) $this->option('month'));
if ($requested !== '') {
return CarbonImmutable::parse($requested)->startOfMonth();
}
$latest = DB::connection($connection)->table('inventory_report_authoritative_months')
->where('dataset_key', 'jiansun.inventory-report.authoritative-month')
->where('status', 'succeeded')
->whereNotNull('active_generation')
->orderByDesc('source_month')
->value('source_month');
return $latest === null ? null : CarbonImmutable::parse((string) $latest)->startOfMonth();
}
/** @return array<string,mixed> */
private function readJson(string $path): array
{
if (! is_file($path)) {
return ['status' => 'failed', 'message' => '子任务未生成结果文件。'];
}
$decoded = json_decode((string) file_get_contents($path), true);
return is_array($decoded)
? $decoded
: ['status' => 'failed', 'message' => '子任务结果文件无法解析。'];
}
/** @param array<string,mixed> $result */
private function writeResult(array $result): int
{
$path = trim((string) $this->option('result-json'));
if ($path !== '') {
File::ensureDirectoryExists(dirname($path));
File::put(
$path,
json_encode(
$result,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT,
) . PHP_EOL,
);
}
if (isset($result['message'])) {
$this->line((string) $result['message']);
}
return in_array($result['status'] ?? 'failed', ['success', 'review_required'], true)
? self::SUCCESS
: self::FAILURE;
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\WorkOrderWaybillLookup;
class BackfillWorkOrderWaybillLookup extends Command
{
protected $signature = 'business-mirror:index-work-order-waybills {--batch=500} {--max-batches=2} {--pause-ms=50}';
protected $description = '按稳定游标建立查件运单小索引;生产须使用 run-finance-batch.sh 执行';
public function handle(WorkOrderWaybillLookup $lookup): int
{
$lock = Cache::store('upstream_shared')->lock('work-order-waybill-lookup:backfill', 3600);
if (! $lock->get()) {
$this->info('已有运单索引任务运行,本轮跳过。');
return self::SUCCESS;
}
try {
$result = $lookup->backfill((int) $this->option('batch'), max(0, (int) $this->option('max-batches')), max(0, (int) $this->option('pause-ms')));
$this->info(json_encode($result));
return self::SUCCESS;
} finally {
$lock->release();
}
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\CrawlerDataGuard;
use Modules\EcommerceFinance\Services\DataLogicSettings;
use Throwable;
class CheckCrawlerWarnings extends Command
{
protected $signature = 'crawler:warnings:check {--quiet-summary : 只输出汇总}';
protected $description = '检查店铺主体、商标爬虫数据的更新和一致性,生成预警记录';
public function handle(CrawlerDataGuard $guard): int
{
DataLogicSettings::bootCompanyContext();
try {
$summary = $guard->check();
} catch (Throwable $exception) {
$this->error('预警检查失败:' . $exception->getMessage());
return self::FAILURE;
}
if ($summary === []) {
$this->info('预警检查完成:没有发现需要处理的记录。');
return self::SUCCESS;
}
$this->table(
['预警类型', '本次检查命中'],
collect($summary)->map(fn (int $count, string $type): array => [$type, $count])->values()->all(),
);
return self::SUCCESS;
}
}

View File

@ -1,334 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\ProductMonthlyWeightedAverageReporter;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
/**
* 按取数逻辑计算某个月的更改价格、定价状态、采购单价、期初金额、入库金额和加权平均单价。
*/
class ComputeProductMonthlyWeightedAverage extends Command
{
protected $signature = 'product:monthly-weighted-average:compute
{month : 报表月份,例如 2026-07}
{--force : 覆盖已经计算完成的同月结果}
{--result-json= : 将结果简报写入指定 JSON 文件}';
protected $description = '按取数逻辑计算商品月加权平均单价';
public function handle(ProductMonthlyWeightedAverageReporter $reporter): int
{
$month = CarbonImmutable::parse($this->argument('month'))->startOfMonth();
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$table = 'product_monthly_weighted_average_rows';
$deadline = $month->addMonthNoOverflow()->day(2)->startOfDay();
$stateStatus = DB::connection($connection)
->table('product_monthly_weighted_average_states')
->where('report_month', $month->toDateString())
->value('status');
$computedRows = DB::connection($connection)->table($table)
->where('report_month', $month->toDateString())
->whereNotNull('computed_at')
->count();
if (! $this->option('force') && ($stateStatus === 'computed' || $computedRows > 0)) {
$this->error($month->format('Y-m') . ' 已经计算完成,历史月份不自动覆盖;如需人工纠正请显式使用 --force。');
return self::FAILURE;
}
$query = DB::connection($connection)->table($table)->where('report_month', $month->toDateString());
$codes = (clone $query)->distinct()->pluck('product_code')->map(fn ($code) => trim((string) $code))->unique()->values()->all();
$this->info('待计算 SKU:' . count($codes));
$cost = $this->costPrices($connection, $codes);
$work = $this->workPlatformPrices($connection, $codes);
$change = $this->priceChanges($connection, $codes);
$inbound = $this->inboundAggregate($connection, $month);
$costRecordSkus = $this->costPriceRecordSkus($connection, $codes);
$total = (clone $query)->count();
$computed = 0;
$now = now();
for ($offset = 0; $offset < $total; $offset += 1000) {
$rows = (clone $query)->orderBy('row_key')->offset($offset)->limit(1000)
->get([
'row_key', 'barcode_warehouse', 'warehouse_short_name', 'product_code', 'base_source', 'imported_at',
'opening_quantity', 'opening_unit_price', 'previous_pricing_status', 'purchase_quantity',
]);
$updates = [];
foreach ($rows as $row) {
// 普通商品资料与进销存的商品编码大小写不一致,统一按大写匹配。
$code = mb_strtoupper(trim((string) $row->product_code));
$costPrice = is_array($cost) ? ($cost[$code] ?? null) : null;
$workPrice = is_array($work) ? ($work[$code] ?? null) : null;
$changePrice = is_array($change) ? ($change[$code] ?? null) : null;
$inboundKey = $code . "\0" . trim((string) $row->warehouse_short_name);
$payload = $this->calculate(
$row,
$costPrice,
$workPrice,
$changePrice,
$deadline,
$inbound[$inboundKey] ?? null,
isset($costRecordSkus[$code]),
);
$updates[] = array_merge([
'report_month' => $month->toDateString(),
'row_key' => $row->row_key,
'barcode_warehouse' => $row->barcode_warehouse,
'warehouse_short_name' => $row->warehouse_short_name,
'product_code' => $row->product_code,
'base_source' => $row->base_source,
'imported_at' => $row->imported_at,
'computed_at' => $now,
], $payload);
$computed++;
}
if ($updates !== []) {
DB::connection($connection)->table($table)->upsert(
$updates,
['report_month', 'row_key'],
['adjusted_unit_price', 'opening_amount', 'purchase_quantity', 'purchase_unit_price', 'purchase_amount', 'weighted_average_unit_price', 'pricing_status', 'computed_at'],
);
}
}
DB::connection($connection)->table('product_monthly_weighted_average_states')->updateOrInsert(
['report_month' => $month->toDateString()],
['status' => 'computed', 'computed_rows' => $computed, 'last_computed_at' => $now, 'updated_at' => $now, 'created_at' => $now],
);
$report = $reporter->build($connection, $month);
$json = json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if (is_string($json)) {
$resultPath = trim((string) $this->option('result-json'));
if ($resultPath !== '') {
File::ensureDirectoryExists(dirname($resultPath));
File::put($resultPath, $json . PHP_EOL);
}
}
$this->info($month->format('Y-m') . " 计算完成:{$computed} 行");
$this->line($reporter->brief($report));
if (($report['status'] ?? null) === 'review_required') {
$this->warn('存在待复核差异;结果已生成,但不会视为完全无异常。');
}
return self::SUCCESS;
}
/**
* @return array<string,float>
*/
private function costPrices(string $connection, array $codes): array
{
$map = [];
foreach (array_chunk($codes, 2000) as $chunk) {
foreach (DB::connection($connection)->table('ops_jst_sku')
->whereIn('sku_id', $chunk)->whereNotNull('cost_price')->get(['sku_id', 'cost_price']) as $row) {
$map[mb_strtoupper(trim((string) $row->sku_id))] = (float) $row->cost_price;
}
}
return $map;
}
/**
* @return array<string,array{price:float,effect:?string}>
*/
private function workPlatformPrices(string $connection, array $codes): array
{
$map = [];
$now = now();
foreach (array_chunk($codes, 2000) as $chunk) {
$rows = DB::connection($connection)->table('js_pm_price_adjustment')
->whereIn('skuCode', $chunk)
->whereNotNull('purchasePrice')
->where(function ($query) use ($now): void {
$query->whereNull('effectTime')->orWhere('effectTime', '<=', $now);
})
->orderBy('effectTime')
->get(['skuCode', 'purchasePrice', 'effectTime']);
foreach ($rows as $row) {
$map[mb_strtoupper(trim((string) $row->skuCode))] = [
'price' => (float) $row->purchasePrice,
'effect' => $row->effectTime === null ? null : (string) $row->effectTime,
];
}
}
return $map;
}
/**
* @return array<string,array{price:float,time:?string}>
*/
/**
* 入库明细汇总:按「大写条码 + 仓库简称」汇总库存变动量与总计(金额 + 预估金额)。
*
* @return array<string,array{quantity:float,total:float}>
*/
private function inboundAggregate(string $connection, CarbonImmutable $month): array
{
$map = [];
if (! \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('inventory_inbound_detail_rows')) {
return $map;
}
foreach (DB::connection($connection)->table('inventory_inbound_detail_rows')
->where('report_month', $month->toDateString())
->selectRaw('warehouse_short_name, upper(barcode) as code, sum(quantity) as quantity, sum(coalesce(amount, 0) + coalesce(estimated_amount, 0)) as total')
->groupBy('warehouse_short_name')
->groupByRaw('upper(barcode)')
->get() as $row) {
$key = mb_strtoupper(trim((string) $row->code)) . "\0" . trim((string) $row->warehouse_short_name);
$map[$key] = ['quantity' => (float) $row->quantity, 'total' => (float) $row->total];
}
return $map;
}
/**
* 有"聚水潭成本价记录"(operated_at 非空)的商品编码集合。
*
* @return array<string,bool>
*/
private function costPriceRecordSkus(string $connection, array $codes): array
{
$map = [];
if (! \Illuminate\Support\Facades\Schema::connection($connection)->hasTable('jushuitan_cost_price_history_rows')) {
return $map;
}
foreach (array_chunk($codes, 2000) as $chunk) {
$rows = DB::connection($connection)->table('jushuitan_cost_price_history_rows')
->whereNotNull('operated_at')
->where(function ($query) use ($chunk): void {
$query->whereIn('sku_id', $chunk)->orWhereIn('sku_id_normalized', $chunk);
})
->get(['sku_id', 'sku_id_normalized']);
foreach ($rows as $row) {
foreach ([$row->sku_id, $row->sku_id_normalized] as $value) {
$key = mb_strtoupper(trim((string) $value));
if ($key !== '') {
$map[$key] = true;
}
}
}
}
return $map;
}
private function priceChanges(string $connection, array $codes): array
{
$map = [];
foreach (array_chunk($codes, 2000) as $chunk) {
$rows = DB::connection($connection)->table('js_pm_price_adjustment_log')
->whereIn('skucode', $chunk)
->whereNotNull('afterPrice')
->orderBy('effectStartTime')
->get(['skucode', 'afterPrice', 'originalPrice', 'effectStartTime', 'createTime']);
foreach ($rows as $row) {
$map[mb_strtoupper(trim((string) $row->skucode))] = [
'price' => (float) $row->afterPrice,
'before' => $row->originalPrice === null ? null : (float) $row->originalPrice,
'time' => $row->effectStartTime === null ? null : (string) $row->effectStartTime,
'created' => $row->createTime === null ? null : (string) $row->createTime,
];
}
}
return $map;
}
/**
* @param array{price:float,effect:?string}|null $work
* @param array{price:float,time:?string}|null $change
* @return array<string,mixed>
*/
private function calculate(object $row, ?float $cost, ?array $work, ?array $change, CarbonImmutable $deadline, ?array $inbound = null, bool $hasCostRecord = false): array
{
$openingQuantity = $row->opening_quantity === null ? 0.0 : (float) $row->opening_quantity;
$purchaseQuantity = $row->purchase_quantity === null ? 0.0 : (float) $row->purchase_quantity;
$openingUnitPrice = $row->opening_unit_price === null ? null : (float) $row->opening_unit_price;
$previousStatus = trim((string) ($row->previous_pricing_status ?? ''));
$changePrice = $change['price'] ?? null;
$workPrice = $work['price'] ?? null;
// 最终规则:生效开始日期为空 → 未匹配到工作平台价格;
// 生效开始日期 > 本月,或记录时间 > 次月2号(记录时间为空视为 ≤ 次月2号)→ 新价当月未生效,取变价前价格。
$changeTime = $change['time'] ?? null;
$changeCreated = $change['created'] ?? null;
$monthStart = $deadline->startOfMonth();
$hasWorkPlatformRecord = $changePrice !== null && $changeTime !== null;
$newPricePending = false;
if ($hasWorkPlatformRecord) {
$newPricePending = CarbonImmutable::parse($changeTime)->greaterThanOrEqualTo($monthStart)
|| ($changeCreated !== null && CarbonImmutable::parse($changeCreated)->greaterThan($deadline));
$changePrice = $newPricePending ? ($change['before'] ?? $changePrice) : $changePrice;
}
$previousStatus = in_array($previousStatus, ['预估价', '未定价'], true) ? '未定价' : $previousStatus;
// 更改价格 + 定价状态(表2 第10条)
if ($openingUnitPrice !== null) {
if ($previousStatus !== '未定价') {
$adjusted = $openingUnitPrice;
$status = $previousStatus !== '' ? $previousStatus : '已定价';
} elseif ($hasWorkPlatformRecord) {
$adjusted = $changePrice;
$status = $newPricePending ? '未定价' : '已定价';
} else {
$adjusted = $openingUnitPrice;
$status = '未定价';
}
} elseif ($hasWorkPlatformRecord) {
$adjusted = $changePrice;
$status = $newPricePending ? '未定价' : '已定价';
} elseif ($cost !== null) {
// 方案②:只有"聚水潭成本价记录"里有生效记录(operated_at 非空)才算有生效日期 → 已定价。
$adjusted = $cost;
$status = $hasCostRecord ? '已定价' : '未定价';
} else {
$adjusted = null;
$status = '待人工核查';
}
// 采购数量/入库金额来自入库明细(大写条码 + 仓库简称汇总),采购单价 = 入库金额 ÷ 采购数量
$purchaseQuantity = (float) ($inbound['quantity'] ?? 0);
// 加权平均单价按“先除再舍入”计算,因此这里保留未舍入的金额参与除法。
$purchaseAmountRaw = $inbound === null ? 0.0 : (float) ($inbound['total'] ?? 0);
$purchaseAmount = $inbound === null ? null : round($purchaseAmountRaw, 2);
$purchaseUnitPrice = ($inbound === null || $purchaseQuantity == 0.0)
? null
: round((float) ($inbound['total'] ?? 0) / $purchaseQuantity, 2);
$openingAmountRaw = $adjusted === null ? 0.0 : $openingQuantity * $adjusted;
$openingAmount = $adjusted === null ? null : round($openingAmountRaw, 2);
$denominator = $openingQuantity + $purchaseQuantity;
if ($denominator === 0.0) {
// 四项全 0:加权平均单价取"更改价格"(按两位舍入后的值)。
$weighted = $adjusted === null ? null : round($adjusted, 2);
} else {
// 先除再舍入:用未舍入的期初金额与入库金额相除,最后统一保留两位。
$weighted = round(($openingAmountRaw + $purchaseAmountRaw) / $denominator, 4);
}
return [
'purchase_quantity' => $purchaseQuantity,
'adjusted_unit_price' => $adjusted === null ? null : round($adjusted, 2),
'opening_amount' => $openingAmount,
'purchase_unit_price' => $purchaseUnitPrice === null ? null : round($purchaseUnitPrice, 2),
'purchase_amount' => $purchaseAmount,
'weighted_average_unit_price' => $weighted,
'pricing_status' => $status,
];
}
}

View File

@ -1,27 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\Jushuitan\ShippingReplicaSynchronizer;
/**
* 一次性:全表扫描,仅删除同订单、同发货日有干净单号对应的 @ 包裹。
* php artisan jst:dedup-at
*/
class DedupAt extends Command
{
protected $signature = 'jst:dedup-at';
protected $description = '去除同订单、同发货日且有干净单号对应的 @ 包裹';
public function handle(): int
{
@ini_set('memory_limit', '1024M');
@set_time_limit(0);
$removed = ShippingReplicaSynchronizer::make()->dedupAtPrefix();
$this->info('去除@重复单号:' . $removed . ' 条');
return self::SUCCESS;
}
}

View File

@ -1,164 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
use Modules\EcommerceFinance\Services\BusinessMirrorSchemaManager;
use Throwable;
/**
* 让登记过的数据集自动跟随上游新增字段。
*
* 上游视图/表新增列时,数据字典(upstream_schema_columns)会先刷新出来,这里再把新列
* 补进数据集定义、建好镜像列;下一次常规同步就会把数据带进来,页面也会自动多出这一列。
* 只做"新增":不删除、不改写已有字段,敏感字段名一律跳过。
*/
class FollowUpstreamColumns extends Command
{
protected $signature = 'business-mirror:follow-upstream-columns
{--dataset= : 只处理指定数据集}';
protected $description = '把上游新增字段补进登记过的镜像数据集(页面字段自动跟随)';
private const DENIED_KEYWORDS = ['password', 'passwd', 'secret', 'token', 'cipher', 'credential', 'private'];
public function handle(
BusinessMirrorDatasetRegistry $datasets,
BusinessMirrorSchemaManager $schemas,
): int {
$keys = array_values(array_filter(array_map(
static fn (mixed $key): string => trim((string) $key),
(array) ($this->option('dataset') ?: array_values((array) config('upstream_mirrors.auto_follow_columns', []))),
), static fn (string $key): bool => $key !== ''));
if ($keys === []) {
$this->info('没有登记需要自动跟随上游字段的数据集。');
return self::SUCCESS;
}
// 先刷新数据字典,否则新字段根本不在目录里。该命令自带 24 小时新鲜度判断,
// 已经同步过会直接跳过。
foreach (array_unique($this->sourcesOf($keys)) as $source) {
try {
// --due:数据字典新鲜(24 小时内同步过)就不再重复扫上游。
Artisan::call('upstream:schema:sync', ['source' => $source, '--due' => true]);
} catch (Throwable $exception) {
report($exception);
$this->warn($source .':数据字典刷新失败,本轮跳过新字段检测。');
}
}
$followed = 0;
foreach ($keys as $key) {
try {
$added = $this->follow($key, $datasets, $schemas);
if ($added !== []) {
$followed += count($added);
$this->info($key . ':新增 ' . implode('、', $added) . ' 并已建列,下次同步即带回数据。');
Log::info('业务镜像自动跟随上游新增字段。', ['dataset' => $key, 'columns' => $added]);
}
} catch (Throwable $exception) {
report($exception);
$this->error($key . ':跟随失败 —— ' . $exception->getMessage());
}
}
$this->info($followed > 0 ? sprintf('共补入 %d 个新字段。', $followed) : '没有发现上游新增字段。');
return self::SUCCESS;
}
/** @param list<string> $keys @return list<string> */
private function sourcesOf(array $keys): array
{
$sources = [];
foreach (DB::table('business_mirror_datasets')->whereIn('dataset_key', $keys)->get() as $row) {
$definition = json_decode((string) $row->definition, true) ?: [];
$source = trim((string) ($definition['source_key'] ?? ''));
if ($source !== '') {
$sources[] = $source;
}
}
return $sources;
}
/**
* @return list<string> 本次补入的字段
*/
private function follow(string $key, BusinessMirrorDatasetRegistry $datasets, BusinessMirrorSchemaManager $schemas): array
{
$row = DB::table('business_mirror_datasets')->where('dataset_key', $key)->first();
if ($row === null) {
return [];
}
$definition = json_decode((string) $row->definition, true) ?: [];
$source = trim((string) ($definition['source_key'] ?? ''));
$schema = trim((string) ($definition['schema'] ?? ''));
$object = trim((string) ($definition['object'] ?? ''));
$current = array_values(array_filter(array_map(
static fn (mixed $column): string => trim((string) $column),
(array) ($definition['columns'] ?? []),
), static fn (string $column): bool => $column !== ''));
if ($source === '' || $schema === '' || $object === '' || $current === []) {
return [];
}
$upstream = DB::table('upstream_schema_columns')
->where('source_key', $source)
->whereRaw('LOWER(schema_name) = ?', [strtolower($schema)])
->whereRaw('LOWER(object_name) = ?', [strtolower($object)])
->orderBy('ordinal_position')
->pluck('column_name')
->map(static fn (mixed $name): string => (string) $name)
->all();
$added = [];
foreach ($upstream as $column) {
if (in_array($column, $current, true) || str_starts_with($column, '_mirror') || $this->isSensitive($column)) {
continue;
}
$added[] = $column;
}
if ($added === []) {
return [];
}
$definition['columns'] = array_values(array_merge($current, $added));
// 记下"跟随进来的字段":页面据此自动补列,不会把历史上刻意没展示的字段带出来。
$definition['followed_columns'] = array_values(array_unique(array_merge(
(array) ($definition['followed_columns'] ?? []),
$added,
)));
DB::table('business_mirror_datasets')->where('dataset_key', $key)->update([
'definition' => json_encode($definition, JSON_THROW_ON_ERROR),
'updated_at' => now(),
]);
// 立刻建列,下一次同步就能写入;页面在数据到达前显示为空即可。
$schemas->ensure($datasets->get($key));
return $added;
}
private function isSensitive(string $column): bool
{
$name = strtolower($column);
foreach (self::DENIED_KEYWORDS as $keyword) {
if (str_contains($name, $keyword)) {
return true;
}
}
return false;
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\AccessoryReshipCourierImporter;
use Modules\EcommerceFinance\Services\AccessoryReshipCourierStore;
class ImportAccessoryReshipCourierConfigs extends Command
{
protected $signature = 'accessory-reship:import-courier-configs {file} {--company= : 导入所属公司ID} {--dry-run : 仅检查文件及输出条数,不写入}';
protected $description = '导入用户提供的存量快递补发扣款比例配置(重复项跳过、冲突整批回滚)';
public function handle(AccessoryReshipCourierImporter $importer, AccessoryReshipCourierStore $store): int
{
$companyId = (int) $this->option('company');
if ($companyId <= 0 || !Company::query()->where('id', $companyId)->exists()) {
$this->error('请指定有效的 --company,公司配置不会跨公司写入。');
return self::FAILURE;
}
$path = $this->argument('file');
$rows = $importer->read($path);
if ($this->option('dry-run')) {
$this->info('文件校验通过,共' . count($rows) . '条;未写入。');
return self::SUCCESS;
}
$result = $store->import($companyId, $rows, '用户授权存量配置导入', hash_file('sha256', $path));
$this->info('导入完成:新增' . $result['added'] . '条,重复跳过' . $result['skipped'] . '条。');
return self::SUCCESS;
}
}

View File

@ -1,139 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Services\AccountLedgerRemarkMap;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Throwable;
/**
* 导入「平台 | 账单项目 | 总账备注」映射表,供店铺收款账户账单的「总账备注」列使用。
*/
class ImportAccountLedgerRemarks extends Command
{
protected $signature = 'account-ledger-remarks:import {path : xlsx/csv 文件} {--sheet=1 : 工作表序号(从 1 开始)或名称} {--replace : 先清空再导入(默认按平台+账单项目覆盖)}';
protected $description = '导入账单项目对应的总账备注映射表';
public function handle(AccountLedgerRemarkMap $map): int
{
$path = (string) $this->argument('path');
if (! is_file($path)) {
$this->error('文件不存在:' . $path);
return self::FAILURE;
}
try {
$rows = $this->readRows($path);
} catch (Throwable $e) {
$this->error('读取失败:' . $e->getMessage());
return self::FAILURE;
}
if ($rows === []) {
$this->error('没有解析到有效数据(需要表头:平台 / 账单项目 / 总账备注)。');
return self::FAILURE;
}
$now = now();
DB::transaction(function () use ($rows, $now): void {
if ($this->option('replace')) {
DB::table('ec_account_ledger_remarks')->delete();
}
foreach (array_chunk($rows, 500) as $chunk) {
DB::table('ec_account_ledger_remarks')->upsert(
array_map(static fn (array $row): array => $row + ['created_at' => $now, 'updated_at' => $now], $chunk),
['platform', 'bill_item'],
['ledger_remark', 'updated_at'],
);
}
});
$map->forget();
$platforms = [];
foreach ($rows as $row) {
$platforms[$row['platform']] = ($platforms[$row['platform']] ?? 0) + 1;
}
ksort($platforms);
$this->info(sprintf('已导入 %d 条总账备注映射。', count($rows)));
foreach ($platforms as $platform => $count) {
$this->line(sprintf(' %s:%d 条', $platform, $count));
}
return self::SUCCESS;
}
/**
* @return list<array{platform:string,bill_item:string,ledger_remark:string}>
*/
private function readRows(string $path): array
{
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$readerType = match ($extension) {
'xlsx' => 'Xlsx',
'xls' => 'Xls',
'csv' => 'Csv',
default => throw new \InvalidArgumentException('只支持 xlsx / xls / csv 文件。'),
};
$reader = IOFactory::createReader($readerType);
$reader->setReadDataOnly(true);
if ($readerType === 'Csv') {
$reader->setInputEncoding('UTF-8');
}
$book = $reader->load($path);
$sheetOption = trim((string) $this->option('sheet'));
if ($sheetOption !== '' && ctype_digit($sheetOption)) {
$index = (int) $sheetOption - 1;
if ($index < 0 || $index >= $book->getSheetCount()) {
throw new \InvalidArgumentException('工作表序号超出范围:' . $sheetOption);
}
$sheet = $book->getSheet($index);
} else {
$sheet = $sheetOption === '' ? $book->getActiveSheet() : $book->getSheetByName($sheetOption);
if ($sheet === null) {
throw new \InvalidArgumentException('找不到工作表:' . $sheetOption);
}
}
$rows = [];
$header = null;
foreach ($sheet->getRowIterator() as $row) {
$cells = [];
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$cells[] = trim((string) $cell->getValue());
}
if ($header === null) {
$cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', $cells[0] ?? '');
$header = $cells;
continue;
}
$platform = trim($cells[0] ?? '');
$item = trim($cells[1] ?? '');
$remark = trim($cells[2] ?? '');
if ($platform === '' || $item === '') {
continue;
}
$rows[] = [
'platform' => mb_substr($platform, 0, 32),
'bill_item' => mb_substr($item, 0, 191),
'ledger_remark' => mb_substr($remark, 0, 191),
];
}
return $rows;
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\AccountMappingStore;
/**
* 把科目映射表的旧文件存储(storage/app/account-mapping/rules.json / events.json)
* 导入共享系统数据库(ec_account_mapping_rules / ec_account_mapping_events)。
*
* 幂等:以文件为准覆盖数据库内容,可重复执行。
*/
class ImportAccountMappingFiles extends Command
{
protected $signature = 'account-mapping:import-files {--events : 一并导入操作记录}';
protected $description = '把科目映射表的旧文件存储导入共享数据库';
public function handle(AccountMappingStore $store): int
{
$result = $store->syncFromFiles((bool) $this->option('events'));
$this->info(
'已导入规则 ' . $result['rules'] . ' 条'
. ($result['events'] > 0 ? ',操作记录 ' . $result['events'] . ' 条' : '')
. '。'
);
return self::SUCCESS;
}
}

View File

@ -1,205 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\XlsxSheetReader;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\AfterSalesCostRowRepository;
/**
* 导入聚水潭「商品利润 → 导出明细数据 → 订单售后费用数据」Excel。
*
* 该报表已按商品编码(组合装拆成组件)给出每行和成本,导入后订单售后费用明细页面
* 在覆盖的店铺/月份范围内直接按这些明细行展示。
*/
class ImportAfterSalesCostRows extends Command
{
protected $signature = 'order-data:import-after-sales-cost
{file : Excel 文件路径}
{--period= : 数据月份,格式 YYYY-MM}
{--chunk=500 : 每批写入行数}
{--dry-run : 只解析不入库}';
protected $description = '导入聚水潭「订单售后费用数据」Excel 到订单售后费用明细';
public function handle(XlsxSheetReader $reader): int
{
$path = (string) $this->argument('file');
$period = trim((string) $this->option('period'));
if (! is_file($path)) {
$this->error('文件不存在:' . $path);
return self::FAILURE;
}
if ($period !== '' && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
$this->error('数据月份格式必须是 YYYY-MM:' . $period);
return self::FAILURE;
}
$headers = (array) config('order_after_sales_cost.headers', []);
$numberKeys = array_flip((array) config('order_after_sales_cost.number_keys', []));
if ($headers === []) {
$this->error('缺少表头映射:config/order_after_sales_cost.php');
return self::FAILURE;
}
$this->info('流式读取文件:' . $path);
$chunkSize = max((int) $this->option('chunk'), 100);
$dryRun = (bool) $this->option('dry-run');
$buffer = [];
$total = 0;
$written = 0;
$skipped = 0;
$shops = [];
$mappedRows = 0;
$minDate = null;
$maxDate = null;
$importedAt = now()->toDateTimeString();
try {
foreach ($reader->rows($path, [], array_keys($headers)) as $row) {
$total++;
$payload = [];
foreach ($headers as $header => $key) {
if (! array_key_exists($header, $row)) {
continue;
}
$value = trim((string) $row[$header]);
if ($value === '') {
continue;
}
if (isset($numberKeys[$key])) {
$value = is_numeric($value) ? (float) $value : 0.0;
} elseif (self::isDateKey($key)) {
$value = self::dateValue($value);
}
$payload[$key] = $value;
}
if ($payload !== []) {
$mappedRows++;
}
$shop = trim((string) ($payload['shop_name'] ?? ''));
$productCode = trim((string) ($payload['product_code'] ?? ''));
if ($shop === '' || $productCode === '') {
$skipped++;
continue;
}
$buffer[] = AfterSalesCostRowRepository::toRecord(
$payload,
$importedAt,
$period !== '' ? $period : null,
);
$shops[$shop] = true;
$orderTime = $payload['order_time'] ?? null;
if (is_string($orderTime) && $orderTime !== '') {
$minDate = $minDate === null || $orderTime < $minDate ? $orderTime : $minDate;
$maxDate = $maxDate === null || $orderTime > $maxDate ? $orderTime : $maxDate;
}
if (! $dryRun && count($buffer) >= $chunkSize) {
$written += $this->flush($buffer);
$buffer = [];
$this->output->write("\r写入 " . $written . ' 行');
}
if ($dryRun && $buffer !== []) {
$buffer = [];
}
}
} catch (\Throwable $exception) {
if (! $dryRun) {
Cache::forget('order-data.after-sales.imported-shop-options');
}
$this->error('读取失败:' . $exception->getMessage());
return self::FAILURE;
}
if ($mappedRows === 0) {
$this->error('表头和配置的映射对不上,请检查文件或 config/order_after_sales_cost.php');
return self::FAILURE;
}
if (! $dryRun && $buffer !== []) {
$written += $this->flush($buffer);
}
if (! $dryRun) {
Cache::forget('order-data.after-sales.imported-shop-options');
}
$this->newLine(2);
$this->info(sprintf(
'完成:读取 %d 行,写入 %d 行,跳过 %d 行;店铺 %d 个;数据月份 %s;订单时间 %s ~ %s;峰值内存 %.1f MB',
$total,
$written,
$skipped,
count($shops),
$period !== '' ? $period : '-',
$minDate ?? '-',
$maxDate ?? '-',
memory_get_peak_usage(true) / 1048576,
));
return self::SUCCESS;
}
/** @param list<array<string,mixed>> $rows */
private function flush(array $rows): int
{
DB::table('ops_after_sales_cost_rows')->upsert(
$rows,
['row_key'],
[
'shop_name', 'shop_code', 'online_order_no', 'internal_order_no', 'product_code',
'style_code', 'shop_product_code', 'shop_style_code',
'order_time', 'source_period', 'product_quantity', 'product_amount', 'product_cost', 'cost_source',
'combine_type', 'payload', 'imported_at', 'updated_at',
],
);
return count($rows);
}
private static function isDateKey(string $key): bool
{
return in_array($key, [
'pay_time', 'order_complete_time', 'send_time', 'order_time', 'registration_time',
'confirmation_time', 'warehouse_entry_time',
], true);
}
private static function dateValue(mixed $value): ?string
{
if ($value instanceof \DateTimeInterface) {
return $value->format('Y-m-d H:i:s');
}
if (is_numeric($value) && (float) $value > 20000 && (float) $value < 80000) {
$timestamp = ((float) $value - 25569) * 86400;
return gmdate('Y-m-d H:i:s', (int) $timestamp);
}
$timestamp = strtotime((string) $value);
return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
}
}

View File

@ -1,46 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\AlibabaAccountBalanceWorkbookImporter;
use Throwable;
class ImportAlibabaAccountBalances extends Command
{
protected $signature = 'business:import-alibaba-account-balances
{path : 阿里巴巴账户余额 Excel 文件路径}
{--source-name= : 原始文件名,用于导入来源追溯}
{--dry-run : 只校验和统计,不写入共享业务库}';
protected $description = '校验并导入阿里巴巴账户月末余额快照';
public function handle(AlibabaAccountBalanceWorkbookImporter $importer): int
{
$path = (string) $this->argument('path');
try {
$sourceName = trim((string) $this->option('source-name'));
$result = $importer->import(
$path,
$sourceName !== '' ? $sourceName : basename($path),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$action = $this->option('dry-run') ? '校验完成' : '导入完成';
$this->info(sprintf(
'%s:共 %d 条,新增 %d 条,更新 %d 条。',
$action,
$result['total'],
$result['created'],
$result['updated'],
));
return self::SUCCESS;
}
}

View File

@ -1,41 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\CourierFreightImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportCourierFreight extends Command
{
protected $signature = 'courier-freight:import
{file : xlsx / csv 文件路径}
{--company=1 : 公司 ID}
{--replace : 先清空该公司已有的快递运费明细}';
protected $description = '导入「快递运费」数据(财务经营报表 › 快递运费)';
public function handle(CourierFreightImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('file'),
(int) $this->option('company'),
(bool) $this->option('replace'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$sources = $result['sources'];
$result['sources'] = count($sources);
$this->info(json_encode($result, JSON_UNESCAPED_UNICODE));
foreach ($sources as $name => $count) {
$this->line(sprintf(' %s:%d 行', $name === '' ? '(空来源)' : $name, $count));
}
return self::SUCCESS;
}
}

View File

@ -1,280 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Business\CourierQuoteVersion;
use App\Models\Common\Company;
use App\Support\CourierQuoteStructure;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use RuntimeException;
/**
* 把整理好的结构化计费规则(标准计费规则_导入用.json)写入现有报价版本,供运费核算使用。
* 只写 billing_structure / billing_rows 两列,原始报价单元格、执行日期、状态都不动。
*/
class ImportCourierQuoteBillingRules extends Command
{
protected $signature = 'courier-quotes:import-billing-rules {file : 标准计费规则 JSON}
{--company= : 报价所属公司ID}
{--dry-run : 只校验并输出结果,不写入}
{--force : 覆盖已有且内容不同的计费规则}';
protected $description = '把存量报价的结构化计费规则批量写入报价版本(按版本号匹配,整批事务)';
private const MODES = ['waybill_rate', 'first_additional', 'flat_bands', 'flat_then', CourierQuoteStructure::SEGMENTS];
public function handle(): int
{
$companyId = (int) $this->option('company');
if ($companyId <= 0 || ! Company::query()->where('id', $companyId)->exists()) {
$this->error('请指定有效的 --company。');
return self::FAILURE;
}
$payload = json_decode((string) @file_get_contents((string) $this->argument('file')), true);
$items = is_array($payload) ? ($payload['versions'] ?? null) : null;
if (! is_array($items) || $items === []) {
$this->error('文件不是有效的计费规则 JSON(缺少 versions)。');
return self::FAILURE;
}
$plan = [];
$report = [];
$seen = [];
foreach ($items as $item) {
if (! is_array($item)) {
$report[] = ['', '', '错误', '版本条目必须是对象'];
continue;
}
$code = (string) ($item['version_id'] ?? '');
if (isset($seen[$code])) {
$report[] = [$code, '', '错误', '同一文件中的版本号不能重复'];
continue;
}
$seen[$code] = true;
[$status, $note, $data] = $this->prepare($companyId, $item);
$report[] = [$code, (string) ($item['company_name'] ?? ''), $status, $note];
if ($data !== null) {
$plan[] = $data;
}
}
$this->table(['版本', '快递公司', '结果', '说明'], $report);
$counts = array_count_values(array_column($report, 2));
$summary = collect($counts)->map(fn ($n, $k) => "{$k} {$n}")->implode(',');
if (isset($counts['错误'])) {
$this->error('存在错误,整批未写入:' . $summary);
return self::FAILURE;
}
if ($this->option('dry-run')) {
$this->info('校验通过,未写入(dry-run):' . $summary);
return self::SUCCESS;
}
try {
DB::transaction(function () use ($plan): void {
foreach ($plan as [$version, $structure, $rows]) {
$current = DB::table($version->getTable())->where('id', $version->id)->lockForUpdate()->first();
if (! $current || $current->company_name !== $version->company_name
|| json_decode($current->billing_structure ?? 'null', true) != $version->billing_structure
|| json_decode($current->billing_rows ?? 'null', true) != $version->billing_rows) {
throw new RuntimeException('报价在校验后被其他操作修改,整批未写入,请重新校验。');
}
$version->forceFill(['billing_structure' => $structure, 'billing_rows' => $rows])->save();
}
});
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info('导入完成:' . $summary);
return self::SUCCESS;
}
/**
* @param array<string,mixed> $item
* @return array{0:string,1:string,2:?array}
*/
private function prepare(int $companyId, array $item): array
{
$code = (string) ($item['version_id'] ?? '');
$version = CourierQuoteVersion::query()->allCompanies()->where('company_id', $companyId)->where('version_code', $code)->first();
if ($version === null) {
return ['错误', '系统中找不到该版本号', null];
}
if (trim((string) $version->company_name) !== trim((string) ($item['company_name'] ?? ''))) {
return ['错误', '快递名称不一致:系统为「' . $version->company_name . '」', null];
}
if (($item['conversion'] ?? '') === 'manual') {
return ['跳过', '特殊计费(' . ($item['manual_reason'] ?? '按体积/条码') . '),需人工核算', null];
}
if (($error = $this->inputError($item)) !== null) {
return ['错误', $error, null];
}
$source = (array) ($item['structure'] ?? []);
$segments = ($item['conversion'] ?? '') === 'needs_segment_mode';
$mode = $segments ? CourierQuoteStructure::SEGMENTS : (string) ($source['mode'] ?? '');
if (! in_array($mode, self::MODES, true)) {
return ['错误', '不支持的计费方式:' . $mode, null];
}
$params = (array) ($item['params'] ?? []);
$perTicket = 0.0;
foreach ((array) ($params['surcharges'] ?? []) as $surcharge) {
if (($surcharge['condition'] ?? '') === '每票' && is_numeric($surcharge['amount'] ?? null)) {
$perTicket += (float) $surcharge['amount'];
}
}
$structure = [
'mode' => $mode,
'flat_bands' => $segments ? [] : $this->numbers($source['flat_bands'] ?? []),
'then_mode' => $segments ? '' : (string) ($source['then_mode'] ?? ''),
'first_weight' => ! $segments && is_numeric($source['first_weight'] ?? null) ? (float) $source['first_weight'] : null,
'rate_tiers' => $segments ? [] : $this->numbers($source['rate_tiers'] ?? []),
'rounding' => in_array($source['rounding'] ?? 'none', array_keys(CourierQuoteStructure::ROUNDING), true) ? (string) ($source['rounding'] ?? 'none') : 'none',
'volumetric_divisor' => is_numeric($params['volumetric_divisor'] ?? null) ? (int) $params['volumetric_divisor'] : null,
'weight_limit' => is_numeric($params['weight_limit_kg'] ?? null) ? (float) $params['weight_limit_kg'] : null,
'min_weight' => is_numeric($source['min_weight'] ?? $params['min_weight_kg'] ?? null) ? (float) ($source['min_weight'] ?? $params['min_weight_kg']) : null,
'per_ticket_surcharge' => $perTicket > 0 ? $perTicket : null,
'notes' => array_values(array_map('strval', (array) ($params['notes'] ?? []))),
'imported_from' => 'stock-quote-billing-import',
];
$rows = [];
foreach ((array) ($segments ? ($item['segments_rows'] ?? []) : ($item['rows'] ?? [])) as $row) {
$region = trim((string) ($row['region'] ?? ''));
if ($region === '') {
return ['错误', '存在没有地区名的行', null];
}
if ($segments) {
$list = [];
foreach ((array) ($row['segments'] ?? []) as $s) {
$list[] = array_filter([
'lo' => (float) ($s['lo'] ?? 0),
'hi' => is_numeric($s['hi'] ?? null) ? (float) $s['hi'] : null,
'type' => (string) ($s['type'] ?? ''),
'price' => $this->number($s['price'] ?? null),
'base' => $this->number($s['base'] ?? null),
'rate' => $this->number($s['rate'] ?? null),
'fw' => $this->number($s['fw'] ?? null),
], static fn ($v, $k) => $v !== null || $k === 'hi', ARRAY_FILTER_USE_BOTH);
}
$rows[] = ['region' => $region, 'segments' => $list];
} else {
$rows[] = [
'region' => $region,
'flat' => array_map(fn ($v) => $this->number($v), array_values((array) ($row['flat'] ?? []))),
'base' => $this->number($row['base'] ?? null),
'rates' => array_map(fn ($v) => $this->number($v), array_values((array) ($row['rates'] ?? []))),
];
}
}
if ($rows === []) {
return ['错误', '没有任何地区价格', null];
}
$existing = $version->billing_structure;
$note = CourierQuoteStructure::describe($structure) . ',' . count($rows) . ' 个地区';
if (is_array($existing) && $existing !== []) {
if ($existing == $structure && $version->billing_rows == $rows) {
return ['跳过', '已导入且内容相同', null];
}
if (! $this->option('force')) {
return ['错误', '已有不同的计费规则,如需覆盖请加 --force', null];
}
return ['覆盖', $note, [$version, $structure, $rows]];
}
return ['写入', $note, [$version, $structure, $rows]];
}
private function number(mixed $value): ?float
{
return is_numeric($value) ? round((float) $value, 4) : null;
}
/** 金额导入拒绝负数、歧义分段和不支持的附加条件,不静默改写计费含义。 */
private function inputError(array $item): ?string
{
$structure = $item['structure'] ?? null;
$params = $item['params'] ?? [];
if (! is_array($structure) || ! is_array($params)) {
return 'structure 和 params 必须是对象';
}
if (! array_key_exists($structure['rounding'] ?? 'none', CourierQuoteStructure::ROUNDING)) {
return '不支持的重量取整方式';
}
$valid = static fn ($v): bool => is_numeric($v) && is_finite((float) $v) && (float) $v >= 0;
foreach ([$params['volumetric_divisor'] ?? null, $params['weight_limit_kg'] ?? null,
$structure['min_weight'] ?? $params['min_weight_kg'] ?? null, $structure['first_weight'] ?? null] as $v) {
if ($v !== null && ! $valid($v)) return '重量、体积系数必须是非负有限数字';
}
if (isset($params['volumetric_divisor']) && (float) $params['volumetric_divisor'] <= 0) return '体积系数必须大于0';
$minimum = (float) ($structure['min_weight'] ?? $params['min_weight_kg'] ?? 0);
if (($params['weight_limit_kg'] ?? 0) > 0 && $minimum > $params['weight_limit_kg']) return '起算重量不能大于限重';
foreach (['flat_bands', 'rate_tiers'] as $field) {
$previous = 0;
if (! is_array($structure[$field] ?? [])) return '重量分段必须是数组';
foreach ($structure[$field] ?? [] as $edge) {
if (! $valid($edge) || (float) $edge <= $previous) return '重量节点必须为严格递增的正数';
$previous = (float) $edge;
}
}
$mode = ($item['conversion'] ?? '') === 'needs_segment_mode' ? CourierQuoteStructure::SEGMENTS : ($structure['mode'] ?? '');
if (in_array($mode, ['flat_bands', 'flat_then'], true) && empty($structure['flat_bands'])) return '缺少一口价重量节点';
if ($mode === 'flat_then' && ! in_array($structure['then_mode'] ?? '', ['waybill_rate', 'first_additional'], true)) return '不支持的超重计费方式';
if (CourierQuoteStructure::usesFirstWeight($mode, $structure['then_mode'] ?? '') && ! (($structure['first_weight'] ?? 0) > 0)) return '首重必须大于0';
if ($mode === 'flat_then' && ! empty($structure['rate_tiers']) && min($structure['rate_tiers']) <= max($structure['flat_bands'])) return '超重费率节点必须大于一口价最后节点';
if (! is_array($params['surcharges'] ?? [])) return '附加费必须是数组';
foreach ($params['surcharges'] ?? [] as $fee) {
if (! is_array($fee) || ($fee['condition'] ?? '') !== '每票' || ! $valid($fee['amount'] ?? null)) return '附加费条件不支持自动核算,需人工核对';
}
$rows = $item[$mode === CourierQuoteStructure::SEGMENTS ? 'segments_rows' : 'rows'] ?? null;
if (! is_array($rows) || $rows === []) return '没有任何地区价格';
$regions = [];
foreach ($rows as $row) {
if (! is_array($row) || ! is_string($row['region'] ?? null) || trim($row['region']) === '') return '地区行格式不正确';
$region = mb_strtolower(preg_replace('/\s+/u', '', $row['region']));
if (isset($regions[$region])) return '存在重复地区行';
$regions[$region] = true;
if ($mode === CourierQuoteStructure::SEGMENTS) {
if (! is_array($row['segments'] ?? null) || $row['segments'] === []) return '缺少地区计费分段';
$previous = 0.0;
foreach ($row['segments'] as $segment) {
if (! is_array($segment) || ! $valid($segment['lo'] ?? null)
|| (float) $segment['lo'] < $previous || ! in_array($segment['type'] ?? '', ['flat', 'waybill', 'first_add'], true)) return '分段类型不支持或存在重叠';
$hi = $segment['hi'] ?? null;
if ($hi !== null && (! $valid($hi) || (float) $hi <= (float) $segment['lo'])) return '分段上限必须大于下限';
$previous = $hi === null ? INF : (float) $hi;
foreach (['price', 'base', 'rate', 'fw'] as $key) {
if (isset($segment[$key]) && ! $valid($segment[$key])) return '分段金额和重量必须是非负有限数字';
}
if ($segment['type'] === 'first_add' && ! $valid($segment['fw'] ?? null)) return '分段首重缺失';
}
} else {
if (! is_array($row['flat'] ?? []) || ! is_array($row['rates'] ?? [])) return '价格必须是数组';
if (count($row['flat'] ?? []) !== count($structure['flat_bands'] ?? [])
|| (CourierQuoteStructure::usesRates($mode) && count($row['rates'] ?? []) !== count($structure['rate_tiers'] ?? []) + 1)) return '价格列数与重量节点不匹配';
foreach (array_merge($row['flat'] ?? [], $row['rates'] ?? [], [$row['base'] ?? null]) as $v) {
if ($v !== null && ! $valid($v)) return '价格必须是非负有限数字或null(不发)';
}
}
}
return null;
}
/** @return list<float> */
private function numbers(mixed $values): array
{
return array_values(array_map('floatval', array_filter((array) $values, 'is_numeric')));
}
}

View File

@ -1,72 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DewuSettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportDewuSettlementBills extends Command
{
protected $signature = 'dewu-bills:import-authoritative
{path : 聚胜算导出的得物完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
{--to= : 账期结束日期,格式 YYYY-MM-DD}
{--expected-count= : 完整账单权威笔数}
{--expected-income= : 完整账单权威收入}
{--expected-expense= : 完整账单权威支出}
{--batch=1000 : 分批写入行数}';
protected $description = '导入并核验聚胜算得物完整账单(保留全部渠道)';
public function handle(DewuSettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
$this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。");
return self::FAILURE;
}
}
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('from'),
(string) $this->option('to'),
(int) $this->option('expected-count'),
(string) $this->option('expected-income'),
(string) $this->option('expected-expense'),
(int) $this->option('batch'),
);
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('得物完整账单导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['状态', '账单行数', '跳过行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[
$result['status'],
$result['row_count'],
$result['excluded_rows'],
$result['store_count'],
$result['bill_item_count'],
$result['income_total'],
$result['expense_total'],
$result['net_total'],
$result['period_start'] . ' 至 ' . $result['period_end'],
]]);
$this->line('渠道:' . collect($result['channel_counts'])
->map(fn (int $count, string $channel): string => "{$channel} {$count}")
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
return self::SUCCESS;
}
}

View File

@ -1,43 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorImporter;
use Throwable;
class ImportDingProcessDetails extends Command
{
protected $signature = 'ding:import-process-details
{file : 15 列流程明细 CSV 文件路径}
{--scope=personal_permission : 数据权限范围标识}
{--replace : 导入前清空同一范围的数据}';
protected $description = '导入钉钉流程明细到共享业务镜像';
public function handle(DingProcessDetailMirrorImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('file'),
(string) $this->option('scope'),
(bool) $this->option('replace'),
);
} catch (Throwable $exception) {
$this->error('导入失败:' . $exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'导入完成:%d 行,跳过占位 %d 行,跳过无效 %d 行,重复 %d 行,范围 %s。',
$result['rows'],
$result['placeholders'],
$result['invalid'],
$result['duplicates'],
$result['scope'],
));
return self::SUCCESS;
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DouyinAuthoritativeBillImporter;
use Throwable;
class ImportDouyinAuthoritativeBills extends Command
{
protected $signature = 'business-mirror:import-douyin-authoritative
{path : 胜算原始明细 UTF-8 CSV} {month : 所属月份 YYYY-MM}
{--count= : 核对笔数} {--income= : 核对收入合计} {--expense= : 核对支出合计}
{--through= : 月初至此日期的完整数据 YYYY-MM-DD,省略时为整月}';
protected $description = '校验并原子启用指定月份或月初至截止日的胜算抖音明细,保留旧版本用于回滚';
public function handle(DouyinAuthoritativeBillImporter $importer): int
{
try {
$result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'),
(int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense'), $this->option('through'));
} catch (Throwable $e) {
$this->error('胜算抖音明细未启用,保留上一版数据。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件和镜像连接。'));
return self::FAILURE;
}
$this->info('胜算抖音明细已启用,范围:[' . $result['period_start'] . ', ' . $result['period_end'] . '),笔数:' . $result['row_count']);
return self::SUCCESS;
}
}

View File

@ -1,49 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\FinanceLedgerBaseImporter;
use Throwable;
class ImportFinanceLedgerBase extends Command
{
protected $signature = 'finance-ledger:import-base
{path : 《银行当前余额-*.xlsx》路径}
{--opening-date= : 期初日期,默认读取配置}
{--recalculate : 导入后立即重算每日流水}';
protected $description = '导入财务台账的账户、店铺、公司、期初余额(全量覆盖)';
public function handle(FinanceLedgerBaseImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
$this->option('opening-date') ?: null,
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '数量/金额'], [
['账户', $result['accounts']],
['店铺', $result['shops']],
['公司', $result['companies']],
['期初账户', $result['opening_rows']],
['期初合计', number_format($result['opening_sum'], 2)],
['账户余额合计', number_format($result['account_balance_sum'], 2)],
['期初日期', $result['opening_date']],
]);
if ($this->option('recalculate')) {
$this->call('finance-ledger:recalculate');
}
$this->info('财务台账基础数据导入完成。');
return self::SUCCESS;
}
}

View File

@ -1,42 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\FinanceLedgerSnapshotImporter;
use Throwable;
class ImportFinanceLedgerSnapshot extends Command
{
protected $signature = 'finance-ledger:import-snapshot
{path : 已核对的 ledger_raw.json 路径}
{--no-recalculate : 只导入明细,不重算流水}';
protected $description = '导入财务台账动账明细快照(本地开发或首次建账使用)';
public function handle(FinanceLedgerSnapshotImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
! $this->option('no-recalculate'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '值'], [
['明细行数', $result['rows']],
['收入合计', number_format($result['income'], 2)],
['支出合计', number_format($result['expense'], 2)],
['日期范围', $result['from'] . ' ~ ' . $result['to']],
['每日流水行数', $result['recalculated']['flows'] ?? '-'],
['期末余额合计', isset($result['recalculated']) ? number_format($result['recalculated']['balance_sum'], 2) : '-'],
]);
$this->info('财务台账动账明细导入完成。');
return self::SUCCESS;
}
}

View File

@ -1,42 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\InventoryInboundDetailImporter;
use Illuminate\Console\Command;
use Throwable;
/**
* 进销存报表 → 入库明细数据:按原始 Excel 原样导入,仓库简称用仓库名称映射表按「仓库」唯一匹配。
*/
class ImportInventoryInboundDetail extends Command
{
protected $signature = 'inventory:inbound-detail:import {file : 入库明细表 Excel} {--month= : 统一指定月份(不传则按创建时间判断)}';
protected $description = '导入进销存报表的入库明细数据';
public function handle(InventoryInboundDetailImporter $importer): int
{
$file = (string) $this->argument('file');
$forcedMonth = trim((string) ($this->option('month') ?? ''));
try {
$result = $importer->import($file, $forcedMonth);
$this->info(sprintf(
'导入完成:%d 行,仓库简称匹配上 %d 行,跳过 %d 行;库中该表共 %d 行',
$result['imported'],
$result['mapped'],
$result['skipped'],
$result['total'],
));
return self::SUCCESS;
} catch (Throwable $exception) {
report($exception);
$this->error('入库明细导入失败:' . $exception->getMessage());
$this->warn('已保留上一版有效数据。');
return self::FAILURE;
}
}
}

View File

@ -1,36 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\InventoryReportAuthoritativeImporter;
use Throwable;
class ImportInventoryReportAuthoritativeMonth extends Command
{
protected $signature = 'business-mirror:import-inventory-report-month
{path : 聚水潭按商品、按仓库、按月多维分析完整 XLSX 导出文件}';
protected $description = '导入进销存报表权威月明细,保留仓储方和子仓维度';
public function handle(InventoryReportAuthoritativeImporter $importer): int
{
try {
$result = $importer->import((string) $this->argument('path'));
} catch (Throwable $exception) {
report($exception);
$this->error('进销存权威月报导入失败:' . $exception->getMessage());
$this->warn('已保留上一版有效数据。');
return self::FAILURE;
}
$this->info(sprintf(
'进销存权威月报导入完成:月份 %s,明细 %d 行。',
$result['source_month'],
$result['source_rows'],
));
return self::SUCCESS;
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\JdDailyBillImporter;
use Throwable;
class ImportJdDailyBills extends Command
{
protected $signature = 'business-mirror:import-jd-daily
{path : 胜算京东日账单指定月份月初至截止日期 UTF-8 CSV} {month : YYYY-MM}
{--through= : 截止日期 YYYY-MM-DD,默认月末} {--count= : 核对笔数} {--income= : 核对收入} {--expense= : 核对支出}';
protected $description = '核对并启用胜算京东日账单月份镜像,保留旧版本';
public function handle(JdDailyBillImporter $importer): int
{
$lock = Cache::lock('jd-daily-bill-import', 21600);
if (! $lock->get()) {
$this->error('京东日账单正在导入,请稍后重试。');
return self::FAILURE;
}
try {
$result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'),
(int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense'), $this->option('through'));
$this->info('京东日账单已启用,笔数:' . $result['row_count']);
return self::SUCCESS;
} catch (Throwable $e) {
$this->error('京东日账单未启用,保留上一版本。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件、重复记录及镜像连接。'));
return self::FAILURE;
} finally {
$lock->release();
}
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\JdWalletBillImporter;
use Throwable;
class ImportJdWalletBills extends Command
{
protected $signature = 'business-mirror:import-jd-wallet
{path : 胜算京东钱包指定月份月初至截止日期 UTF-8 CSV} {month : YYYY-MM}
{--through= : 截止日期 YYYY-MM-DD,默认月末} {--count= : 核对笔数} {--income= : 核对收入} {--expense= : 核对支出}';
protected $description = '核对并启用胜算京东钱包月份镜像,保留旧版本';
public function handle(JdWalletBillImporter $importer): int
{
$lock = Cache::lock('jd-wallet-bill-import', 21600);
if (! $lock->get()) {
$this->error('京东钱包正在导入,请稍后重试。');
return self::FAILURE;
}
try {
$result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'),
(int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense'), $this->option('through'));
$this->info('京东钱包已启用,笔数:' . $result['row_count']);
return self::SUCCESS;
} catch (Throwable $e) {
$this->error('京东钱包未启用,保留上一版本。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件、重复记录及镜像连接。'));
return self::FAILURE;
} finally {
$lock->release();
}
}
}

View File

@ -1,146 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\JstOrderLabelPlantingRules;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Throwable;
/**
* 导入「标签 | 是否种菜订单」映射表,供聚水潭订单标签明细的「是否种菜订单」列使用。
*/
class ImportJstOrderLabelPlantingRules extends Command
{
protected $signature = 'jst-order-labels:import-planting-rules
{path : xlsx/csv 文件}
{--company= : 公司ID(默认使用当前公司或 1)}
{--sheet=1 : 工作表序号(从 1 开始)或名称}
{--replace : 先清空该公司已有映射再导入(默认按标签覆盖)}';
protected $description = '导入聚水潭订单标签明细的「是否种菜订单」映射表';
public function handle(JstOrderLabelPlantingRules $rules): int
{
$path = (string) $this->argument('path');
if (! is_file($path)) {
$this->error('文件不存在:' . $path);
return self::FAILURE;
}
$companyId = (int) ($this->option('company') ?: (function_exists('company_id') && company_id() ? company_id() : 1));
if ($companyId <= 0) {
$this->error('公司ID无效,请用 --company 指定。');
return self::FAILURE;
}
try {
$rows = $this->readRows($path);
} catch (Throwable $e) {
$this->error('读取失败:' . $e->getMessage());
return self::FAILURE;
}
if ($rows === []) {
$this->error('没有解析到有效数据(需要表头:标签 / 是否种菜订单)。');
return self::FAILURE;
}
$now = now();
DB::transaction(function () use ($rows, $now, $companyId): void {
if ($this->option('replace')) {
DB::table('jst_order_label_planting_rules')->where('company_id', $companyId)->delete();
}
foreach (array_chunk($rows, 500) as $chunk) {
DB::table('jst_order_label_planting_rules')->upsert(
array_map(static fn (array $row): array => $row + [
'company_id' => $companyId,
'created_at' => $now,
'updated_at' => $now,
], $chunk),
['company_id', 'label'],
['is_planting', 'updated_at'],
);
}
});
$rules->forget($companyId);
$planting = count(array_filter($rows, static fn (array $row): bool => $row['is_planting'] === '是'));
$this->info(sprintf('已导入 %d 条「是否种菜订单」映射(公司 %d):种菜 %d 条,非种菜 %d 条。', count($rows), $companyId, $planting, count($rows) - $planting));
return self::SUCCESS;
}
/**
* @return list<array{label:string,is_planting:string}>
*/
private function readRows(string $path): array
{
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$readerType = match ($extension) {
'xlsx' => 'Xlsx',
'xls' => 'Xls',
'csv' => 'Csv',
default => throw new \InvalidArgumentException('只支持 xlsx / xls / csv 文件。'),
};
$reader = IOFactory::createReader($readerType);
$reader->setReadDataOnly(true);
if ($readerType === 'Csv') {
$reader->setInputEncoding('UTF-8');
}
$book = $reader->load($path);
$sheetOption = trim((string) $this->option('sheet'));
if ($sheetOption !== '' && ctype_digit($sheetOption)) {
$index = (int) $sheetOption - 1;
if ($index < 0 || $index >= $book->getSheetCount()) {
throw new \InvalidArgumentException('工作表序号超出范围:' . $sheetOption);
}
$sheet = $book->getSheet($index);
} else {
$sheet = $sheetOption === '' ? $book->getActiveSheet() : $book->getSheetByName($sheetOption);
if ($sheet === null) {
throw new \InvalidArgumentException('找不到工作表:' . $sheetOption);
}
}
$rows = [];
$header = null;
foreach ($sheet->getRowIterator() as $row) {
$cells = [];
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$cells[] = trim((string) $cell->getValue());
}
if ($header === null) {
$cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', $cells[0] ?? '');
$header = $cells;
continue;
}
$label = trim($cells[0] ?? '');
$flag = trim($cells[1] ?? '');
if ($label === '') {
continue;
}
$rows[] = [
'label' => mb_substr($label, 0, 191),
'is_planting' => in_array(mb_strtolower($flag), ['否', 'n', 'no', '0', 'false'], true) ? '否' : '是',
];
}
return $rows;
}
}

View File

@ -1,43 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\JstOrderLabelImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportJstOrderLabels extends Command
{
protected $signature = 'jst-order-labels:import
{--from= : 起始下单日期 YYYY-MM-DD}
{--to= : 结束下单日期 YYYY-MM-DD}
{--file= : 聚水潭「导出订单」Excel 路径;给了它就从文件导入(镜像没有的历史区间用)}
{--company=1 : 公司 ID}
{--replace : 先清空该区间已有行}';
protected $description = '把聚水潭订单按标签拆行导入「聚水潭订单标签明细」:默认读共享镜像,给 --file 则读聚水潭导出的订单 Excel';
public function handle(JstOrderLabelImporter $importer): int
{
$from = (string) $this->option('from');
$to = (string) $this->option('to');
$file = trim((string) $this->option('file'));
try {
$companyId = (int) $this->option('company');
$replace = (bool) $this->option('replace');
$result = $file === ''
? $importer->import($from, $to, $companyId, $replace, 'jst-order-label-import')
: $importer->importFromFile($file, $from ?: null, $to ?: null, $companyId, $replace);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(json_encode($result, JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
}
}

View File

@ -1,106 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\WithdrawalBalanceAlertSynchronizer;
use App\Models\Business\StoreReceivingAccount;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\FinanceBillShopBalanceFallback;
use Modules\EcommerceFinance\Services\JushuitanShopBalanceImporter;
use Throwable;
class ImportJushuitanShopBalances extends Command
{
protected $signature = 'business:import-jushuitan-shop-balances
{path : 聚水潭店铺余额接口 JSON 或 XLSX/XLS 导出文件}
{--balance-date= : 导入日期,格式 YYYY-MM-DD;多日期导出必须指定}
{--scope=all : 来源范围,同一日期同一范围会被原子替换}
{--dry-run : 只校验和统计,不写入共享业务库}';
protected $description = '导入聚水潭店铺余额,并用财务账单补录缺失店铺';
public function handle(
JushuitanShopBalanceImporter $importer,
WithdrawalBalanceAlertSynchronizer $alertSynchronizer,
FinanceBillShopBalanceFallback $financeFallback,
): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
$this->option('balance-date') === null ? null : (string) $this->option('balance-date'),
(string) $this->option('scope'),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'%s:%s 共 %d 条,替换原有 %d 条。',
$result['dry_run'] ? '校验完成' : '导入完成',
$result['balance_date'],
$result['total'],
$result['replaced'],
));
$financeFallbackFailed = false;
try {
$fallback = $financeFallback->fillMissing(
$result['balance_date'],
(string) $this->option('scope'),
(bool) $result['dry_run'],
);
if (! $fallback['supported']) {
$this->warn('账单余额回填:当前来源的店铺收款账户账单没有累计账户余额字段,跳过回填。');
} elseif ($fallback['missing'] === 0) {
$this->info('账单余额回填:聚水潭余额没有缺失店铺。');
} else {
$this->info(sprintf(
'账单余额回填:缺失 %d 家,匹配 %d 家,写入 %d 条,仍有 %d 家待补。',
$fallback['missing'],
$fallback['resolved'],
$fallback['filled'],
$fallback['unresolved'],
));
}
} catch (Throwable $exception) {
report($exception);
$this->error('财务系统店铺收款账户账单余额回填失败,聚水潭余额已保留,财务回填未覆盖。');
$financeFallbackFailed = true;
}
if (! $result['dry_run']) {
$companyIds = StoreReceivingAccount::withoutGlobalScopes()
->whereNull('deleted_at')
->distinct()
->pluck('company_id')
->filter()
->map(static fn (mixed $id): int => (int) $id)
->unique()
->values();
foreach ($companyIds as $companyId) {
try {
$alerts = $alertSynchronizer->syncLatest($companyId);
if ($alerts['created'] > 0 || $alerts['updated'] > 0) {
$this->info(sprintf(
'余额预警待办:公司 %d 新增 %d 条、更新 %d 条。',
$companyId,
$alerts['created'],
$alerts['updated'],
));
}
} catch (Throwable $exception) {
report($exception);
$this->warn("余额预警待办生成失败(公司 {$companyId}),余额快照已保留。");
}
}
}
return $financeFallbackFailed ? self::FAILURE : self::SUCCESS;
}
}

View File

@ -1,72 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\PinduoduoSettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportPinduoduoSettlementBills extends Command
{
protected $signature = 'pinduoduo-bills:import-authoritative
{path : 聚胜算导出的拼多多完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
{--to= : 账期结束日期,格式 YYYY-MM-DD}
{--expected-count= : 完整账单权威笔数}
{--expected-income= : 完整账单权威收入}
{--expected-expense= : 完整账单权威支出}
{--batch=1000 : 分批写入行数}';
protected $description = '导入并核验聚胜算拼多多完整账单(保留全部账户类型)';
public function handle(PinduoduoSettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
$this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。");
return self::FAILURE;
}
}
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('from'),
(string) $this->option('to'),
(int) $this->option('expected-count'),
(string) $this->option('expected-income'),
(string) $this->option('expected-expense'),
(int) $this->option('batch'),
);
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('拼多多完整货款账单导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['状态', '账单行数', '跳过行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[
$result['status'],
$result['row_count'],
$result['excluded_account_rows'],
$result['store_count'],
$result['bill_item_count'],
$result['income_total'],
$result['expense_total'],
$result['net_total'],
$result['period_start'] . ' 至 ' . $result['period_end'],
]]);
$this->line('账户类型:' . collect($result['account_type_counts'])
->map(fn (int $count, string $account): string => "{$account} {$count}")
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
return self::SUCCESS;
}
}

View File

@ -1,38 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\PlantingDetailImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportPlantingDetails extends Command
{
protected $signature = 'planting-details:import
{file : xlsx / xls / csv 文件路径}
{--company=1 : 公司 ID}
{--replace : 先清空该公司已有的种菜明细}';
protected $description = '导入「种菜明细表」数据(账单流水数据 › 种菜明细表)';
public function handle(PlantingDetailImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('file'),
(int) $this->option('company'),
(bool) $this->option('replace'),
null,
'planting-detail-import',
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(json_encode($result, JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
}
}

View File

@ -1,350 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Business\InventoryWarehouseNameMapping;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
* 商品月加权平均单价:导入某个月的期初基数。
*
* 基数来源两类:
* 1) 首个可用月份(7月)来自财务提供的《商品月末加权平均单价》表1,包含仓库简称、商品编码和上月加权平均单价;
* 2) 其余月份由上月算出的加权平均单价滚动生成(--from-previous)。
* 无论哪一类,都会并入进销存总表里"代发仓"的商品(代发仓没有库存,采购数量取销售出库)。
*/
class ImportProductMonthlyWeightedAverageBase extends Command
{
protected $signature = 'product:monthly-weighted-average:base
{month : 报表月份,例如 2026-07}
{--file= : 期初基数 Excel(表1),首月使用}
{--from-previous : 用上月的加权平均单价作为本月原始价格}
{--force : 覆盖已经存在的同月基数}';
protected $description = '导入/生成商品月加权平均单价的期初基数';
public function handle(): int
{
$month = CarbonImmutable::parse($this->argument('month'))->startOfMonth();
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$rowsTable = 'product_monthly_weighted_average_rows';
$now = now();
$existingRows = DB::connection($connection)->table($rowsTable)
->where('report_month', $month->toDateString())
->count();
$existingState = DB::connection($connection)->table('product_monthly_weighted_average_states')
->where('report_month', $month->toDateString())
->value('status');
if (! $this->option('force') && ($existingRows > 0 || $existingState !== null)) {
$this->error($month->format('Y-m') . ' 已存在基数或计算状态,不自动覆盖;如需人工纠正请显式使用 --force。');
return self::FAILURE;
}
$inventory = $this->inventoryAggregate($connection, $month);
$jiangxiPurchase = $this->jiangxiDeliveryPurchase($connection, $month);
$nanchangOpening = $this->nanchangOpeningQuantity($connection, $month);
$this->info('进销存(排除不看)合计 ' . count($inventory) . ' 个 仓库简称+商品编码');
DB::connection($connection)->table($rowsTable)->where('report_month', $month->toDateString())->delete();
$payload = [];
$baseRows = 0;
$deliveryRows = 0;
$mirrorRows = 0;
$file = (string) ($this->option('file') ?? '');
if ($file !== '') {
foreach ($this->readBaseFile($file) as $row) {
$payload[$this->rowKey($month, $row['warehouse_short_name'], $row['product_code'])] = [
'report_month' => $month->toDateString(),
'row_key' => $this->rowKey($month, $row['warehouse_short_name'], $row['product_code']),
'barcode_warehouse' => $row['barcode_warehouse'],
'warehouse_short_name' => $row['warehouse_short_name'],
'product_code' => $row['product_code'],
'opening_unit_price' => $row['opening_unit_price'],
'previous_pricing_status' => $row['previous_pricing_status'],
'base_source' => 'base',
'imported_at' => $now,
];
$baseRows++;
}
} elseif ($this->option('from-previous')) {
$previous = $month->subMonthNoOverflow();
foreach (DB::connection($connection)->table($rowsTable)
->where('report_month', $previous->toDateString())
->get(['barcode_warehouse', 'warehouse_short_name', 'product_code', 'pricing_status', 'weighted_average_unit_price']) as $row) {
$key = $this->rowKey($month, $row->warehouse_short_name, $row->product_code);
$payload[$key] = [
'report_month' => $month->toDateString(),
'row_key' => $key,
'barcode_warehouse' => $row->barcode_warehouse,
'warehouse_short_name' => $row->warehouse_short_name,
'product_code' => $row->product_code,
'opening_unit_price' => $row->weighted_average_unit_price,
'previous_pricing_status' => $row->pricing_status,
'base_source' => 'base',
'imported_at' => $now,
];
$baseRows++;
}
} else {
$this->error('请给出 --file=表1.xlsx(首月)或 --from-previous(滚动月份)。');
return self::FAILURE;
}
// 代发仓:没有库存,但必须出现在这张表里,采购数量取销售出库。
foreach ($inventory as $key => $item) {
$rowKey = $this->rowKey($month, $item['warehouse_short_name'], $item['product_code']);
if (isset($payload[$rowKey])) {
continue;
}
$isDelivery = $this->isDeliveryWarehouse($item['warehouse_short_name']);
$payload[$rowKey] = [
'report_month' => $month->toDateString(),
'row_key' => $rowKey,
// 条码+仓库 = 商品编码 + 仓库简称
'barcode_warehouse' => $item['product_code'] . $item['warehouse_short_name'],
'warehouse_short_name' => $item['warehouse_short_name'],
'product_code' => $item['product_code'],
'opening_unit_price' => null,
'previous_pricing_status' => null,
'base_source' => $isDelivery ? 'delivery' : 'mirror',
'imported_at' => $now,
];
$isDelivery ? $deliveryRows++ : $mirrorRows++;
}
// 南昌樵舍仓的采购数量取自"简尚-江西仓送货主仓",这些条码也要一并纳入行维度,
// 否则只存在于江西仓送货的单据会因为表里没有对应行而丢掉采购数量。
foreach (array_keys($jiangxiPurchase) as $code) {
$rowKey = $this->rowKey($month, '南昌樵舍仓', $code);
if (isset($payload[$rowKey])) {
continue;
}
$payload[$rowKey] = [
'report_month' => $month->toDateString(),
'row_key' => $rowKey,
'barcode_warehouse' => $code . '南昌樵舍仓',
'warehouse_short_name' => '南昌樵舍仓',
'product_code' => $code,
'opening_unit_price' => null,
'previous_pricing_status' => null,
'base_source' => 'mirror',
'imported_at' => $now,
];
$mirrorRows++;
}
$matched = 0;
foreach ($payload as $key => $row) {
$item = $inventory[$row['warehouse_short_name'] . "\0" . $row['product_code']] ?? null;
// 代发仓判定不能只看 base_source(滚动月份会丢标记),按仓库简称再兜一层。
$isDelivery = $row['base_source'] === 'delivery'
|| str_contains((string) $row['warehouse_short_name'], '代发仓');
$isNanchang = $row['warehouse_short_name'] === '南昌樵舍仓';
// 原始数量只取"主仓"的期初数量(仓库名称含主仓字样)。
$openingQuantity = $isDelivery ? 0.0 : (float) ($item['opening_quantity'] ?? 0);
if ($isNanchang) {
// 南昌樵舍仓是特殊仓库:期初数量取"三方-南昌樵舍仓主仓"对应商品的期初数量。
$openingQuantity = (float) ($nanchangOpening[$row['product_code']] ?? 0);
}
$purchaseQuantity = $isDelivery
? abs((float) ($item['sales_out'] ?? 0))
: ($isNanchang
// 南昌樵舍仓是特殊仓库:采购数量取"简尚-江西仓送货主仓"对应商品的采购进仓数量。
? (float) ($jiangxiPurchase[$row['product_code']] ?? 0)
: (float) ($item['purchase_in'] ?? 0));
if ($item !== null) {
$matched++;
}
$payload[$key]['product_name'] = $item['category'] ?? null;
$payload[$key]['opening_quantity'] = $openingQuantity;
$payload[$key]['purchase_quantity'] = $purchaseQuantity;
$payload[$key]['opening_original_amount'] = $row['opening_unit_price'] === null
? null
: round($openingQuantity * (float) $row['opening_unit_price'], 2);
}
foreach (array_chunk($payload, 1000, true) as $chunk) {
DB::connection($connection)->table($rowsTable)->insert(array_values($chunk));
}
DB::connection($connection)->table('product_monthly_weighted_average_states')->updateOrInsert(
['report_month' => $month->toDateString()],
[
'status' => 'base_imported',
'base_filename' => $file !== '' ? basename($file) : null,
'base_rows' => $baseRows,
'delivery_rows' => $deliveryRows,
'matched_rows' => $matched,
'last_error' => null,
'updated_at' => $now,
'created_at' => $now,
],
);
$this->info(sprintf(
'%s 基数导入完成:基表 %d 行 + 代发仓 %d 行,合计 %d 行,其中 %d 行在进销存总表匹配到数据。',
$month->format('Y-m'),
$baseRows,
$deliveryRows,
count($payload),
$matched,
));
return self::SUCCESS;
}
/** @return array<string,array{warehouse_short_name:string,product_code:string,opening_quantity:string,purchase_in:string,sales_out:string,category:string}> */
private function inventoryAggregate(string $connection, CarbonImmutable $month): array
{
$generation = DB::connection($connection)->table('inventory_report_authoritative_months')
->where('source_month', $month->toDateString())
->value('active_generation');
if (! $generation) {
throw new \RuntimeException($month->format('Y-m') . ' 的进销存总表尚未导入。');
}
$mappingModel = new InventoryWarehouseNameMapping();
$mappingConnection = DB::connection($mappingModel->getConnectionName());
$mappingTable = $mappingConnection->getDriverName() === 'sqlite'
? $mappingModel->getTable()
: $mappingModel->getConnection()->getDatabaseName()
. '.' . $mappingConnection->getTablePrefix()
. $mappingModel->getTable();
$sql = "select m.warehouse_short_name as short_name, r.product_code as product_code,
sum(case when r.warehouse like '%主仓%' then r.opening_quantity else 0 end) as opening_quantity,
sum(r.purchase_in) as purchase_in,
sum(r.sales_out) as sales_out, max(r.category) as category
from inventory_report_authoritative_rows r
join {$mappingTable} m
on m.warehouse_provider = r.warehouse_provider
and m.warehouse = r.warehouse
and m.company_id = 1
and m.deleted_at is null
where r.generation = ?
and m.warehouse_short_name not like '%不看%'
and r.warehouse like '%主仓%'
and m.warehouse_short_name <> '南昌樵舍仓'
group by m.warehouse_short_name, r.product_code";
$aggregate = [];
foreach (DB::connection($connection)->select($sql, [$generation]) as $row) {
$aggregate[$row->short_name . "\0" . mb_strtoupper(trim((string) $row->product_code))] = [
'warehouse_short_name' => (string) $row->short_name,
// 商品编码统一按大写建索引,避免与表1/普通商品资料大小写不一致导致匹配不上。
'product_code' => mb_strtoupper(trim((string) $row->product_code)),
'opening_quantity' => (string) $row->opening_quantity,
'purchase_in' => (string) $row->purchase_in,
'sales_out' => (string) $row->sales_out,
'category' => (string) ($row->category ?? ''),
];
}
return $aggregate;
}
/** @return \Generator<int,array{barcode_warehouse:string,warehouse_short_name:string,product_code:string,opening_unit_price:?float}> */
private function readBaseFile(string $file): \Generator
{
$reader = IOFactory::createReaderForFile($file);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file);
$sheet = $spreadsheet->getSheetByName('7月份期初基数') ?? $spreadsheet->getSheet(0);
foreach ($sheet->getRowIterator(3) as $row) {
$cells = [];
foreach ($row->getCellIterator('A', 'P') as $cell) {
$cells[] = $cell->getFormattedValue();
}
$shortName = trim((string) ($cells[2] ?? ''));
$productCode = trim((string) ($cells[4] ?? ''));
if ($shortName === '' || $productCode === '') {
continue;
}
$price = trim((string) ($cells[7] ?? ''));
$previousStatus = trim((string) ($cells[15] ?? ''));
yield [
// 条码+仓库统一为「仓库简称 + 商品编码」,不再沿用表1 里的单元格写法。
'barcode_warehouse' => $shortName . $productCode,
'warehouse_short_name' => $shortName,
'product_code' => mb_strtoupper($productCode),
// 原始价格保留源表精度(不提前舍入),保证加权平均单价与手工表一致;页面展示仍按两位。
'opening_unit_price' => $price === '' ? null : (float) str_replace(',', '', $price),
'previous_pricing_status' => $previousStatus === '' ? null : $previousStatus,
];
}
}
private function isDeliveryWarehouse(string $shortName): bool
{
return str_contains($shortName, '代发');
}
/**
* 南昌樵舍仓的采购数量取"简尚-江西仓送货主仓"对应商品的采购进仓数量。
*
* @return array<string,string>
*/
private function jiangxiDeliveryPurchase(string $connection, CarbonImmutable $month): array
{
$generation = DB::connection($connection)->table('inventory_report_authoritative_months')
->where('source_month', $month->toDateString())
->value('active_generation');
if (! $generation) {
return [];
}
$map = [];
foreach (DB::connection($connection)->table('inventory_report_authoritative_rows')
->where('generation', $generation)
->where('warehouse', '简尚-江西仓送货主仓')
->selectRaw('product_code, sum(purchase_in) as quantity')
->groupBy('product_code')
->get() as $row) {
$map[mb_strtoupper(trim((string) $row->product_code))] = (string) $row->quantity;
}
return $map;
}
/**
* 南昌樵舍仓的期初数量取"三方-南昌樵舍仓主仓"对应商品的期初数量。
*
* @return array<string,string>
*/
private function nanchangOpeningQuantity(string $connection, CarbonImmutable $month): array
{
$generation = DB::connection($connection)->table('inventory_report_authoritative_months')
->where('source_month', $month->toDateString())
->value('active_generation');
if (! $generation) {
return [];
}
$map = [];
foreach (DB::connection($connection)->table('inventory_report_authoritative_rows')
->where('generation', $generation)
->where('warehouse', '三方-南昌樵舍仓主仓')
->selectRaw('product_code, sum(opening_quantity) as quantity')
->groupBy('product_code')
->get() as $row) {
$map[mb_strtoupper(trim((string) $row->product_code))] = (string) $row->quantity;
}
return $map;
}
private function rowKey(CarbonImmutable $month, string $shortName, string $productCode): string
{
return sha1($month->format('Y-m') . '|' . $shortName . '|' . $productCode);
}
}

View File

@ -1,140 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\XlsxSheetReader;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\PromotionCostRowRepository;
class ImportPromotionCostRows extends Command
{
protected $signature = 'order-data:import-promotion-cost
{file : Excel 文件路径}
{--period= : 数据月份,格式 YYYY-MM}
{--chunk=500 : 每批写入行数}
{--dry-run : 只解析不入库}';
protected $description = '导入聚水潭商品推广费用明细 Excel';
public function handle(XlsxSheetReader $reader): int
{
$path = (string) $this->argument('file');
$period = trim((string) $this->option('period'));
if (! is_file($path)) {
$this->error('文件不存在:' . $path);
return self::FAILURE;
}
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
$this->error('数据月份格式必须是 YYYY-MM:' . ($period !== '' ? $period : '(空)'));
return self::FAILURE;
}
$headers = (array) config('order_promotion_cost.headers', []);
if ($headers === []) {
$this->error('缺少表头映射:config/order_promotion_cost.php');
return self::FAILURE;
}
$this->info('流式读取文件:' . $path);
$chunkSize = max((int) $this->option('chunk'), 100);
$dryRun = (bool) $this->option('dry-run');
$importedAt = now()->toDateTimeString();
$buffer = [];
$total = 0;
$written = 0;
$skipped = 0;
$promotionFee = 0.0;
$shops = [];
try {
foreach ($reader->rows($path, array_keys($headers)) as $row) {
$total++;
$payload = [];
foreach ($headers as $header => $key) {
$value = trim((string) ($row[$header] ?? ''));
if ($value === '') {
continue;
}
$payload[$key] = $key === 'promotion_fee'
? (is_numeric($value) ? (float) $value : 0.0)
: $value;
}
$shop = trim((string) ($payload['shop_name'] ?? ''));
$product = trim((string) ($payload['product_code'] ?? ''));
if ($shop === '' || $product === '') {
$skipped++;
continue;
}
$shops[$shop] = true;
$promotionFee += (float) ($payload['promotion_fee'] ?? 0);
$buffer[] = PromotionCostRowRepository::toRecord($payload, $period, $importedAt);
if (! $dryRun && count($buffer) >= $chunkSize) {
$written += $this->flush($buffer);
$buffer = [];
$this->output->write("\r写入 " . $written . ' 行');
}
if ($dryRun && $buffer !== []) {
$buffer = [];
}
}
} catch (\Throwable $exception) {
if (! $dryRun) {
Cache::forget('order-data.promotion.imported-shop-options:' . $period);
}
$this->error('读取失败:' . $exception->getMessage());
return self::FAILURE;
}
if (! $dryRun && $buffer !== []) {
$written += $this->flush($buffer);
}
if (! $dryRun) {
Cache::forget('order-data.promotion.imported-shop-options:' . $period);
}
$this->newLine(2);
$this->info(sprintf(
'完成:读取 %d 行,写入 %d 行,跳过 %d 行;店铺 %d 个;数据月份 %s;推广费合计 %.2f;峰值内存 %.1f MB',
$total,
$written,
$skipped,
count($shops),
$period,
$promotionFee,
memory_get_peak_usage(true) / 1048576,
));
return self::SUCCESS;
}
/** @param list<array<string,mixed>> $rows */
private function flush(array $rows): int
{
DB::table('ops_promotion_cost_rows')->upsert(
$rows,
['row_key'],
[
'source_period', 'shop_name', 'product_code', 'style_code',
'shop_product_code', 'shop_style_code', 'online_color_spec',
'promotion_fee', 'payload', 'imported_at', 'updated_at',
],
);
return count($rows);
}
}

View File

@ -1,187 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\StoreViolationRuleRepository;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Throwable;
/**
* 店铺违规信息预警:违规字典维护(Excel 导入 / 更新,按 平台+违规类型 幂等)。
*
* 表头(顺序不限):平台、违规分类、违规类型、匹配关键词、预警级别、是否需要提醒、
* 建议处理动作、处理时效、提醒方式、排序、启用、备注。
* 导入后按需执行 store-violations:recalc-alerts 让存量记录套用新字典。
*/
class ImportStoreViolationRules extends Command
{
protected $signature = 'store-violations:import-rules
{file : xlsx / xls / csv 文件路径}
{--dry-run : 只解析并统计,不写库}';
protected $description = '导入违规字典(预警级别、提醒规则等)';
private const HEADERS = [
'platform' => ['平台', 'platform'],
'violation_category' => ['违规分类', '分类', 'violation_category'],
'violation_type' => ['违规类型', '类型', 'violation_type'],
'match_keywords' => ['匹配关键词', '关键词', 'match_keywords'],
'alert_level' => ['预警级别', '级别', '预警等级', 'alert_level'],
'needs_alert' => ['是否需要提醒', '需提醒', '需要提醒', 'needs_alert'],
'suggested_action' => ['建议处理动作', '处理建议', '建议动作', 'suggested_action'],
'handling_hours' => ['处理时效', '时效', 'handling_hours'],
'remind_channel' => ['提醒方式', 'remind_channel'],
'sort' => ['排序', 'sort'],
'enabled' => ['启用', 'enabled'],
'remark' => ['备注', 'remark'],
];
private const PLATFORM_MAP = [
'淘系' => 'taobao', '淘宝' => 'taobao', '天猫' => 'taobao',
'京东' => 'jd', '京喜' => 'jingxi', '抖音' => 'douyin',
'拼多多' => 'pinduoduo', '阿里巴巴' => 'alibaba',
];
public function handle(): int
{
$file = (string) $this->argument('file');
if (! is_file($file)) {
$this->error('文件不存在:' . $file);
return self::FAILURE;
}
try {
$reader = IOFactory::createReaderForFile($file);
if (method_exists($reader, 'setReadDataOnly')) {
$reader->setReadDataOnly(true);
}
if (method_exists($reader, 'setReadFilter')) {
// 字典文件通常只有几十行;部分导出文件带巨大空白维度,限制读取范围。
$reader->setReadFilter(new class implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
public function readCell($columnAddress, $row, $worksheetName = ''): bool
{
return $row <= 5000;
}
});
}
$matrix = $reader->load($file)->getActiveSheet()->toArray(null, true, true, false);
} catch (Throwable $exception) {
$this->error('无法读取文件:' . $exception->getMessage());
return self::FAILURE;
}
if ($matrix === []) {
$this->error('文件为空。');
return self::FAILURE;
}
$map = [];
foreach ($matrix[0] as $index => $cell) {
$label = mb_strtolower(trim((string) $cell));
foreach (self::HEADERS as $key => $aliases) {
foreach ($aliases as $alias) {
if ($label === mb_strtolower($alias)) {
$map[$key] = $index;
break 2;
}
}
}
}
if (! isset($map['platform'], $map['violation_type'])) {
$this->error('缺少必需表头:平台、违规类型。');
return self::FAILURE;
}
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
if (! app(StoreViolationRuleRepository::class)->available()) {
$this->error('违规字典表尚未建立,请先执行数据库迁移。');
return self::FAILURE;
}
$created = 0;
$updated = 0;
$skipped = 0;
$sort = 0;
foreach (array_slice($matrix, 1) as $row) {
$value = static fn (string $key): string => isset($map[$key]) ? trim((string) ($row[$map[$key]] ?? '')) : '';
$platform = $value('platform');
$platform = self::PLATFORM_MAP[$platform] ?? mb_strtolower($platform);
$type = $value('violation_type');
if ($platform === '' || $type === '') {
$skipped++;
continue;
}
$sort += 10;
$levelRaw = strtoupper($value('alert_level'));
$level = in_array($levelRaw, ['P0', 'P1', 'P2'], true) ? $levelRaw : null;
$needsAlertRaw = mb_strtolower($value('needs_alert'));
$needsAlert = ! in_array($needsAlertRaw, ['否', 'no', '0', 'false'], true);
$hoursRaw = $value('handling_hours');
$hours = is_numeric($hoursRaw) ? max((int) $hoursRaw, 0) : null;
$payload = [
'platform' => $platform,
'violation_category' => $value('violation_category') !== '' ? mb_substr($value('violation_category'), 0, 64) : null,
'violation_type' => mb_substr($type, 0, 500),
'match_keywords' => $value('match_keywords') !== '' ? mb_substr($value('match_keywords'), 0, 500) : null,
'alert_level' => $needsAlert ? $level : null,
'needs_alert' => $needsAlert ? 1 : 0,
'suggested_action' => $value('suggested_action') !== '' ? mb_substr($value('suggested_action'), 0, 500) : null,
'handling_hours' => $hours,
'remind_channel' => $value('remind_channel') !== '' ? mb_substr($value('remind_channel'), 0, 191) : null,
'sort' => is_numeric($value('sort')) ? (int) $value('sort') : $sort,
'enabled' => ! in_array(mb_strtolower($value('enabled')), ['否', 'no', '0', 'false'], true) ? 1 : 0,
'remark' => $value('remark') !== '' ? mb_substr($value('remark'), 0, 191) : null,
'updated_at' => now(),
];
$exists = $connection->table(StoreViolationRuleRepository::TABLE)
->where('platform', $platform)
->where('violation_type', $payload['violation_type'])
->exists();
if ($this->option('dry-run')) {
$exists ? $updated++ : $created++;
continue;
}
if ($exists) {
$connection->table(StoreViolationRuleRepository::TABLE)
->where('platform', $platform)
->where('violation_type', $payload['violation_type'])
->update($payload);
$updated++;
} else {
$connection->table(StoreViolationRuleRepository::TABLE)->insert($payload + [
'created_at' => now(),
]);
$created++;
}
}
$this->info(sprintf(
'字典导入%s:新增 %d 条,更新 %d 条,跳过 %d 条。',
$this->option('dry-run') ? '(试运行,未写库)' : '完成',
$created,
$updated,
$skipped,
));
$this->line('提示:需要让存量记录套用新字典时,执行 store-violations:recalc-alerts。');
return self::SUCCESS;
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\SupplierBookkeepingConfigImporter;
use Modules\EcommerceFinance\Services\SupplierBookkeepingConfigStore;
class ImportSupplierBookkeepingConfigs extends Command
{
protected $signature = 'supplier-bookkeeping:import-configs {file} {--dry-run : 仅检查文件并输出条数,不写入}';
protected $description = '导入财务提供的厂家记账配置 Excel(供应商、厂家是否记账);新增/更新/跳过,任一行无法识别整批不写入';
public function handle(SupplierBookkeepingConfigImporter $importer, SupplierBookkeepingConfigStore $store): int
{
$path = (string) $this->argument('file');
$rows = $importer->read($path);
if ($this->option('dry-run')) {
$this->info('文件校验通过,共' . count($rows) . '条;未写入。');
return self::SUCCESS;
}
$result = $store->import($rows, '命令行导入', hash_file('sha256', $path));
$this->info("导入完成:新增{$result['added']}条,更新{$result['updated']}条,未变化{$result['skipped']}条。");
return self::SUCCESS;
}
}

View File

@ -1,121 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\SupplierSummaryInboundImporter;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Throwable;
/**
* 供应商汇总表月度增量导入:读取已解密工作簿的「明细」子表,仅追加目标月份数据。
*/
class ImportSupplierSummaryInbound extends Command
{
protected $signature = 'inventory:supplier-summary:import
{file : 已解密的供应商汇总 XLSX 文件}
{--month= : 目标月份 YYYY-MM,默认上一个月}
{--result-json= : 将执行结果写入指定 JSON 文件}';
protected $description = '将供应商汇总表「明细」增量导入入库明细数据';
public function handle(SupplierSummaryInboundImporter $importer): int
{
$month = trim((string) $this->option('month'));
if ($month === '') {
$month = now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m');
}
$lock = Cache::lock('inventory-supplier-summary-inbound-import', 21600);
if (! $lock->get()) {
return $this->finish([
'status' => 'failed',
'report_month' => $month,
'source_filename' => basename((string) $this->argument('file')),
'success' => 0,
'duplicates' => 0,
'failed' => 1,
'mapped' => 0,
'total_in_table' => 0,
'failure_reason_count' => 1,
'failure_reasons' => [[
'row' => 0,
'reason' => '已有供应商汇总导入任务正在执行',
]],
]);
}
try {
$result = $importer->import((string) $this->argument('file'), $month);
} catch (Throwable $exception) {
report($exception);
$result = [
'status' => 'failed',
'report_month' => $month,
'source_filename' => basename((string) $this->argument('file')),
'success' => 0,
'duplicates' => 0,
'failed' => 1,
'mapped' => 0,
'total_in_table' => 0,
'failure_reason_count' => 1,
'failure_reasons' => [[
'row' => 0,
'reason' => $exception->getMessage(),
]],
];
} finally {
$lock->release();
}
return $this->finish($result);
}
/** @param array<string,mixed> $result */
private function finish(array $result): int
{
$reasons = is_array($result['failure_reasons'] ?? null)
? $result['failure_reasons']
: [];
$result['failure_reason_count'] = count($reasons);
$json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (! is_string($json)) {
$json = '{"status":"failed","failure_reasons":[{"row":0,"reason":"结果 JSON 编码失败"}]}';
}
$resultPath = trim((string) $this->option('result-json'));
if ($resultPath !== '') {
File::ensureDirectoryExists(dirname($resultPath));
File::put($resultPath, $json . PHP_EOL);
}
$this->line(sprintf(
'%s 导入状态=%s,成功=%s,重复=%s,失败=%s,目标月份总行数=%s',
(string) ($result['report_month'] ?? ''),
(string) ($result['status'] ?? 'failed'),
number_format((int) ($result['success'] ?? 0)),
number_format((int) ($result['duplicates'] ?? 0)),
number_format((int) ($result['failed'] ?? 0)),
number_format((int) ($result['total_in_table'] ?? 0)),
));
foreach (array_slice($reasons, 0, 10) as $reason) {
$this->warn(sprintf(
'第 %s 行:%s',
(string) ($reason['row'] ?? ''),
(string) ($reason['reason'] ?? '未知错误'),
));
}
if (count($reasons) > 10) {
$this->line(sprintf(
'另有 %s 条失败原因,完整清单见结果 JSON。',
number_format(count($reasons) - 10),
));
}
return ($result['status'] ?? 'failed') === 'success'
? self::SUCCESS
: self::FAILURE;
}
}

View File

@ -1,57 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\SystemizationTodoWorkbookImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportSystemizationTodos extends Command
{
protected $signature = 'systemization-todos:import
{file : 待办 Excel 文件路径}
{--company=1 : 写入的 company_id}
{--user= : 操作人用户 ID}
{--sync : 新增并更新现有来源事项,保留截图}
{--dry-run : 只预览同步结果,不写入数据库}';
protected $description = '导入或同步财务系统化待办清单';
public function handle(SystemizationTodoWorkbookImporter $importer): int
{
try {
$file = (string) $this->argument('file');
$companyId = max((int) $this->option('company'), 1);
$userId = $this->option('user') !== null ? (int) $this->option('user') : null;
if ($this->option('sync')) {
$result = $importer->sync($file, $companyId, $userId, (bool) $this->option('dry-run'));
} else {
$result = $importer->import($file, $companyId, $userId);
}
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
if ($this->option('sync')) {
$this->info(sprintf(
'%s工作表 %s:新增 %d 条,更新 %d 条,保留工作簿外事项 %d 条。',
$this->option('dry-run') ? '同步预检:' : '同步完成:',
$result['sheet'],
$result['created'],
$result['updated'],
$result['retained'],
));
} else {
$this->info(sprintf(
'工作表 %s:新增 %d 条,跳过已存在 %d 条。',
$result['sheet'],
$result['created'],
$result['skipped'],
));
}
return self::SUCCESS;
}
}

View File

@ -10,8 +10,7 @@ class ImportTaobaoAlipayBills extends Command
{
protected $signature = 'business:import-taobao-alipay-bills
{file : 淘系支付宝账户 Excel 文件路径}
{--company=1 : 数据所属公司 ID}
{--replace : 校验通过后替换该公司的全部淘系支付宝账单}';
{--company=1 : 数据所属公司 ID}';
protected $description = '从标准附件导入店铺收款账户账单的淘系支付宝账户数据';
@ -21,7 +20,6 @@ class ImportTaobaoAlipayBills extends Command
$result = $importer->import(
(string) $this->argument('file'),
max(1, (int) $this->option('company')),
(bool) $this->option('replace'),
);
} catch (Throwable $e) {
$this->components->error($e->getMessage());
@ -30,7 +28,7 @@ class ImportTaobaoAlipayBills extends Command
}
$this->components->info(
"导入完成:新增 {$result['inserted']} 条,更新 {$result['updated']} 条,替换旧数据 {$result['replaced']} 条,跳过 {$result['skipped']} 条。"
"导入完成:新增 {$result['inserted']} 条,更新 {$result['updated']} 条,跳过 {$result['skipped']} 条。"
);
return self::SUCCESS;

View File

@ -1,71 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\TaobaoAlipaySettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportTaobaoAlipaySettlementBills extends Command
{
protected $signature = 'taobao-alipay-bills:import-authoritative
{path : 聚胜算导出的淘系支付宝完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
{--to= : 账期结束日期,格式 YYYY-MM-DD}
{--expected-count= : 完整账单权威笔数}
{--expected-income= : 完整账单权威收入}
{--expected-expense= : 完整账单权威支出}
{--batch=1000 : 分批写入行数}';
protected $description = '导入并核验聚胜算淘系支付宝完整账单';
public function handle(TaobaoAlipaySettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
$this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。");
return self::FAILURE;
}
}
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('from'),
(string) $this->option('to'),
(int) $this->option('expected-count'),
(string) $this->option('expected-income'),
(string) $this->option('expected-expense'),
(int) $this->option('batch'),
);
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('淘系支付宝完整账单导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['状态', '账单行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[
$result['status'],
$result['row_count'],
$result['store_count'],
$result['bill_item_count'],
$result['income_total'],
$result['expense_total'],
$result['net_total'],
$result['period_start'] . ' 至 ' . $result['period_end'],
]]);
$this->line('业务类型:' . collect($result['business_type_counts'])
->map(fn (int $count, string $type): string => "{$type} {$count}")
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
return self::SUCCESS;
}
}

View File

@ -1,72 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\TaobaoWechatSettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportTaobaoWechatSettlementBills extends Command
{
protected $signature = 'taobao-wechat-bills:import-authoritative
{path : 聚胜算导出的淘系微信完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
{--to= : 账期结束日期,格式 YYYY-MM-DD}
{--expected-count= : 完整账单权威笔数}
{--expected-income= : 完整账单权威收入}
{--expected-expense= : 完整账单权威支出}
{--batch=1000 : 分批写入行数}';
protected $description = '导入并核验聚胜算淘系微信完整账单';
public function handle(TaobaoWechatSettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
$this->error("缺少 --{$option},完整账单导入必须提供账期和三项权威控制数。");
return self::FAILURE;
}
}
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('from'),
(string) $this->option('to'),
(int) $this->option('expected-count'),
(string) $this->option('expected-income'),
(string) $this->option('expected-expense'),
(int) $this->option('batch'),
);
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('淘系微信完整账单导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['状态', '账单行数', '跳过行数', '店铺数', '账单项目数', '收入', '支出', '净额', '账期'], [[
$result['status'],
$result['row_count'],
$result['excluded_rows'],
$result['store_count'],
$result['bill_item_count'],
$result['income_total'],
$result['expense_total'],
$result['net_total'],
$result['period_start'] . ' 至 ' . $result['period_end'],
]]);
$this->line('入账类型:' . collect($result['entry_type_counts'])
->map(fn (int $count, string $type): string => "{$type} {$count}")
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
return self::SUCCESS;
}
}

View File

@ -1,36 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\ThirdPartyWarehouseStorageAuthoritativeAnchorImporter;
use Throwable;
class ImportThirdPartyWarehouseStorageAuthoritativeAnchor extends Command
{
protected $signature = 'business-mirror:import-third-party-warehouse-anchor
{path : 聚水潭三方仓按商品加按天多维分析完整 XLSX 导出文件}';
protected $description = '导入三方仓权威日进销存明细及月末库存锚点,用于稳定历史余额';
public function handle(ThirdPartyWarehouseStorageAuthoritativeAnchorImporter $importer): int
{
try {
$result = $importer->import((string) $this->argument('path'));
} catch (Throwable $exception) {
report($exception);
$this->error('三方仓权威进销存导入失败,已保留上一版有效数据。');
return self::FAILURE;
}
$this->info(sprintf(
'三方仓权威日明细导入完成:校验 %s 条明细,生成 %s 个商品锚点,锚点时刻 %s。',
number_format($result['source_rows']),
number_format($result['anchor_skus']),
$result['anchor_at'],
));
return self::SUCCESS;
}
}

View File

@ -1,39 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class JstCount extends Command
{
protected $signature = 'jst:count';
protected $description = '发货数据本地表统计';
public function handle(): int
{
$c = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
$t = fn () => $c->table('jst_oms_shipping');
$this->line('明细行数 total='.$t()->count());
$this->line('包裹数(distinct source_id)='.$t()->distinct()->count('source_id'));
$this->line('自动发货仓行(source>=1e9)='.$t()->where('source_id', '>=', 1000000000)->count());
$this->line('补差残留='.$t()->where('product_name', 'like', '%补收差价%')->count());
$this->line('快递单号非空='.$t()->whereNotNull('express_no')->where('express_no', '<>', '')->count());
$this->line('件数pkg_count非空='.$t()->whereNotNull('pkg_count')->where('pkg_count', '<>', '')->count());
// 多件包裹数(pkg_count 不是 1/1)
$multi = $t()->where('pkg_count', 'not like', '1/1')->where('pkg_count', 'like', '1/%')->distinct()->count('source_id');
$this->line('多件包裹数(件数≠1/1)='.$multi);
// 一个多件包裹样例
$sample = $t()->where('pkg_count', 'like', '1/%')->where('pkg_count', '<>', '1/1')->orderByDesc('source_id')->first();
if ($sample) {
$rows = $t()->where('source_id', $sample->source_id)->get(['barcode', 'product_name', 'qty', 'pkg_count', 'actual_weight', 'freight', 'volume_cm3']);
$this->line('--- 样例多件包裹 source_id='.$sample->source_id.' 快递单号='.$sample->express_no.' ---');
foreach ($rows as $r) {
$this->line(sprintf(' 条码=%s 名称=%s 数量=%s 件数=%s 实称=%s 运费=%s 体积=%s',
$r->barcode, mb_substr((string) $r->product_name, 0, 12), $r->qty, $r->pkg_count, $r->actual_weight, $r->freight, $r->volume_cm3));
}
}
return self::SUCCESS;
}
}

View File

@ -1,45 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Repositories\ShippingOrderRepository;
class JstDump extends Command
{
protected $signature = 'jst:dump {--mode=merged} {--from=} {--to=}';
protected $description = '把 caiwu 发货数据(合并/明细)以 CSV 输出到 STDOUT,供比对';
public function handle(ShippingOrderRepository $repo): int
{
@ini_set('memory_limit', '1024M');
@set_time_limit(0);
$mode = $this->option('mode') === 'detail' ? 'detail' : 'merged';
$filters = [
'ship_from' => (string) $this->option('from'),
'ship_to' => (string) $this->option('to'),
];
$cols = [
['express_no', '快递单号'], ['trade_no', '交易单号'], ['item_id', '商品ID'], ['barcode', '条形码'],
['product_name', '商品名称'], ['qty', '数量'], ['pkg_count', '件数'], ['warehouse_name', '仓库'],
['supplier_name', '供应商'], ['platform', '平台'], ['shop_name', '店铺名称'],
['volume_cm3', '体积'], ['length_cm', '长'], ['width_cm', '宽'], ['height_cm', '高'],
['actual_weight', '实称重量'], ['online_weight', '线上重量'], ['freight', '运费'],
['ship_time', '发货时间'], ['pay_time', '付款时间'], ['product_code', '货号'],
['receiver_state', '省'], ['receiver_city', '市'], ['receiver_district', '区'],
['package_no', '配货单号'], ['amount', '金额'], ['express_name1', '快递名称'],
];
$fh = fopen('php://output', 'w');
fwrite($fh, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($fh, array_map(fn ($c) => $c[1], $cols));
$n = 0;
foreach ($repo->exportRows($filters, 2000, $mode) as $row) {
fputcsv($fh, array_map(fn ($c) => (string) ($row[$c[0]] ?? ''), $cols));
$n++;
}
fflush($fh);
fwrite(STDERR, 'wrote '.$n.' rows ('.$mode.')'.PHP_EOL);
return self::SUCCESS;
}
}

View File

@ -1,20 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class JstRow extends Command
{
protected $signature = 'jst:row {--trade=}';
protected $description = '看本地表某交易单号的行';
public function handle(): int
{
$c = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
$rows = $c->table('jst_oms_shipping')->where('trade_no', (string) $this->option('trade'))
->get(['express_no', 'barcode', 'product_name', 'qty', 'pkg_count', 'supplier_name', 'length_cm', 'volume_cm3']);
$this->line('行数='.count($rows));
foreach ($rows as $r) {
$this->line(' '.json_encode($r, JSON_UNESCAPED_UNICODE));
}
return self::SUCCESS;
}
}

View File

@ -1,62 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\StoreReceiptDefaultCompensationSnapshotBuilder;
use Throwable;
class PreviewStoreReceiptDefaultCompensation extends Command
{
protected $signature = 'store-receipt:default-compensation:preview
{month : 账期 YYYY-MM}
{mapping : 最新科目映射表 xlsx 路径}
{--output= : 输出 JSON 路径;默认写入 storage/app/local/performance-details/default-compensation}';
protected $description = '人工核对:按指定科目映射表生成「违约赔付(冲减收入)」金额快照,不写数据库';
public function handle(StoreReceiptDefaultCompensationSnapshotBuilder $builder): int
{
$startedAt = hrtime(true);
$month = trim((string) $this->argument('month'));
$mapping = (string) $this->argument('mapping');
try {
$snapshot = $builder->build($month, $mapping);
$path = (string) ($this->option('output') ?: storage_path(
'app/local/performance-details/default-compensation/' . $month . '.json'
));
$directory = dirname($path);
if (! is_dir($directory) && ! mkdir($directory, 0775, true) && ! is_dir($directory)) {
throw new \RuntimeException('无法创建快照目录:' . $directory);
}
$temporary = $path . '.tmp';
$json = json_encode($snapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if ($json === false || file_put_contents($temporary, $json, LOCK_EX) === false) {
throw new \RuntimeException('无法写入本地快照。');
}
rename($temporary, $path);
$this->info('本地预览快照已生成:' . $path);
$this->line('映射条数:' . $snapshot['mapping_rows']);
$this->line('关联行数:' . count($snapshot['amounts']));
$this->line('金额合计:' . number_format((float) $snapshot['total'], 2, '.', ''));
$this->line('耗时:' . number_format((hrtime(true) - $startedAt) / 1e6, 0) . ' ms');
$this->line('PHP 峰值内存:' . number_format(memory_get_peak_usage(true) / 1024 / 1024, 1) . ' MB');
foreach ($snapshot['source_stats'] as $platform => $stats) {
$this->line(sprintf(
' %s:账单行 %d,金额 %s',
$platform,
$stats['rows'],
number_format((float) $stats['amount'], 2, '.', ''),
));
}
return self::SUCCESS;
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
}

Some files were not shown because too many files have changed in this diff Show More