Compare commits

..

97 Commits

Author SHA1 Message Date
bddfffecec feat(顾家过账): 支持整月金额自动分配过账标签
PR #1796
2026-12-06 22:48:32 +08:00
2a3787f400 修复历史已结算附加费重复计入 (#1795) 2026-12-06 18:18:14 +08:00
05edc5f4a3 fix(补记账): 保持数字运单索引查询为文本 (#1794) 2026-12-06 17:50:14 +08:00
8e95325e21 fix(物流对账): 校准换单信息并锁定已确认结果 (#1793) 2026-12-06 17:38:03 +08:00
d2c7f0e355 修复退回附加费跨月匹配与补记账自动更新 (#1792) 2026-12-06 17:27:11 +08:00
7a584439a6 fix(未发出明细): 排除外部仓占位单号 (#1791) 2026-12-06 17:08:30 +08:00
d26532dee4 fix(运费对账): 结算重量紧跟核算运费 (#1790) 2026-12-06 17:01:19 +08:00
aa7ec7aece 配件运费扣除明细:支持财务确认单号免扣 (#1789) 2026-12-06 16:53:48 +08:00
10410f2792 fix(运费对账): 按分比较结算差额消除小数尾差 (#1788) 2026-12-06 16:47:26 +08:00
24b71caca4 feat(未发出明细): 展示并导出换单前后单号及快递名称 (#1787) 2026-12-06 16:44:25 +08:00
15558bc874 fix(运费对账): 按最终结算值计算运费差和重量差 (#1786) 2026-12-06 16:38:30 +08:00
9175804957 fix(未发出明细): 修正日期控件撑高筛选行 (#1785) 2026-12-06 16:24:31 +08:00
d30b9f6deb style(未发出明细): 整理同步状态与筛选列表布局 (#1784) 2026-12-06 16:18:21 +08:00
8ae0e54fbc feat(代发运费): 增加按厂家月份重新匹配 (#1783) 2026-12-06 16:15:02 +08:00
7b175036e1 fix(代发运费): 增加与页面一致的厂家汇总导出 (#1782) 2026-12-06 15:35:01 +08:00
95f2633005 fix(退回件): 合并普通与淘系重复售后商品 (#1781) 2026-12-06 15:32:09 +08:00
cccfe8acbd fix(同步): 补齐淘系退回件并恢复未发出明细刷新 (#1780) 2026-12-06 15:09:30 +08:00
85f8eda9ff fix(快递对账): 中铁物流和武进安能按核算运费结算 (#1779) 2026-12-06 15:01:33 +08:00
ff0a450e67 快递应付汇总:允许手工修改自动带出的实付金额 (#1778) 2026-12-06 14:52:55 +08:00
31bd498aea fix(代发运费): 补齐重量差并优化仓库查询 (#1777) 2026-12-06 14:41:52 +08:00
882447989d 快递应付汇总:自动实付、合同日期与对账状态筛选 (#1776) 2026-12-06 14:33:50 +08:00
cccca2815b fix(供应商对账): 支持推送未定价并快速筛选条码 (#1775)
未定价差异可发送给厂家,并支持从汇总卡直接筛选未定价条码。
2026-12-06 14:23:19 +08:00
84370c60be feat(快递对账): 按较低金额结算并补武进韵达重量差 (#1774) 2026-12-06 14:21:50 +08:00
2c4062d9e2 fix(逆向附加费): 支持超长超重按公斤计费 (#1773) 2026-12-06 12:08:08 +08:00
fc8415421a fix(快递对账): 移除空白附加费占位类目 (#1772) 2026-12-06 11:15:34 +08:00
1abeedb96a fix(附加费): 支持明确配置多个改地址原因 (#1771) 2026-12-06 11:03:43 +08:00
77b1044565 fix(附加费): 支持配置的查件原因和单边长度条件 (#1770) 2026-12-06 10:48:54 +08:00
fd55a7736b fix(配件扣款): 自有快递优先扣款并按代发配置识别 (#1769) 2026-12-06 10:12:53 +08:00
0e4fc0a510 fix(发货运费): 取消五家曹县德邦超长加收 (#1768) 2026-12-06 10:05:08 +08:00
474fc97a61 feat(代发对账): 明细上方显示账单小汇总 (#1767) 2026-12-06 09:40:38 +08:00
17bffa50d0 fix(配件运费): 按代发厂家配置免扣同名代发快递 (#1766) 2026-12-06 09:31:11 +08:00
8b56efb66f fix(厂家记账): 按财务确认恢复缺文件核价与免扣判定
厂家记账对已确认未发出的单据仍显示待确认;缺月度发货文件时无法继续成本核价;同一快递号的其他发货来源会干扰工单对应商品的运费替代。

本次调整:全部未发出的工单明确不扣款;缺文件且无原单匹配的补偿/全款,保留原小额免记账顺序,按完整工单逐商品数量与当前成本、20%替代运费核价,再和原金额取小值;成本核价排除同号无关商品来源;增加公司级单工单免扣设置,应用财务确认的特例而不扩大到所有缺供应商工单。原单部分匹配、数量含糊、缺成本及运费损耗无记录等情况继续待确认。

修改范围:核价Repository、核价服务、商品组合解析、扣款规则、页面数据服务、对应单元/页面回归及规则文档。无数据库迁移;不改权限、上游、发货重量或发货运费计算。上线仅保存已获财务明确授权的一个工单免扣设置,并备份旧设置,不改原始工单。

验证:Docker 中以 www-data、禁用网络、内存 SQLite 运行相关核价、商品解析、规则、Repository 与页面回归,68 tests / 649 assertions 全通过(96.69秒,PHPUnit峰值121MB)。覆盖50元/40%边界、两轮实付、未发出、同号不同来源、多商品数量、缺项、页面筛选与CSV一致性。生产399条工单只读试算0.51秒、峰值52.5MiB,确认只有预期范围变化,敏感明细未放入Git或PR。
2026-12-06 09:26:54 +08:00
2f74eeab39 fix(供应商对账): 允许推送厂家少算差异 (#1764)
厂家多、厂家少和数量金额不一致均可进入差异推送范围。
2026-12-05 17:43:33 +08:00
59e0e46b8a fix(供应商对账): 限制钉钉差异消息正文大小 (#1763)
按实际请求体字节动态分批,并限制单条差异展开明细数量。
2026-12-05 17:27:20 +08:00
e2572c9a4c feat(供应商对账): 锁定已确认厂家账单上传
每月15日12:00后锁定已确认厂家的本期对账单上传,锁定前仍允许上传更正。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-05 17:20:33 +08:00
f94f40c218 修复淘系订单镜像视图超时
将淘系 qmcust 订单及明细镜像源从报表库无索引视图切换到 jiansun 实体表,保留既有数据集键、状态和目标表。
2026-12-05 17:02:56 +08:00
f809de684a fix(供应商对账): 有差异仅统计厂家需改单行
未定价和厂家少算不再进入有差异,也不推送厂家改单。相关页面与钉钉测试通过。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-05 16:16:59 +08:00
19688075d8 feat(供应商对账): 同页查看厂家原始账单 (#1759)
财务端比对页同页查看厂家原始账单,支持分页、搜索和按差异定位。
2026-12-05 15:56:58 +08:00
d334392c33 fix(供应商对账): 精简差异通知分类计数
钉钉差异通知只显示差异总条数,避免厂家混淆。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-05 13:41:44 +08:00
f876c793af fix(厂家记账): 缺月度文件时按同步原包裹恢复核价 (#1757) 2026-12-05 12:32:25 +08:00
e6cb7c098f fix(附加费对账): 统一拦截费用名称匹配 (#1756) 2026-12-05 12:05:04 +08:00
9114b3727b 种菜通知:测试期间暂停取消工单逐单推送 (#1755) 2026-12-05 12:01:25 +08:00
97dc21cc50 feat(运费对账): 分版确认与异议处理 (#1754) 2026-12-05 11:53:58 +08:00
b93aef72d1 fix(附加费对账): 支持彩艺买家原因及破损固定单价 (#1753) 2026-12-05 11:34:52 +08:00
5937d0cc0b 取消常州德邦发货超长费 (#1751) 2026-12-05 11:22:13 +08:00
875e8c3700 种菜报销:允许蔡明君作为报销收款人 (#1750) 2026-12-05 11:21:40 +08:00
04f9e25ba5 fix(附加费对账): 保留指定账期自动匹配结果 (#1749) 2026-12-05 10:40:12 +08:00
abacecfd1e feat(附加费对账): 按报价固定单价自动核算 (#1748) 2026-12-05 10:28:47 +08:00
773681773f fix(科目映射): 淘宝天猫按同一平台处理 (#1747) 2026-12-05 09:53:10 +08:00
46825fc165 fix(供应商对账): 补充三家现结免上传厂家
帝富尼、沐野竹木、沭阳简华家具有限公司纳入现结免上传范围。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-05 09:39:53 +08:00
43cf75734d 退件单号索引兼容生产字段长度 (#1744) 2026-12-04 19:07:53 +08:00
6952d6c3b7 修复逆向账单纯数字实退单号比较 (#1743) 2026-12-04 18:25:31 +08:00
303972e90a fix(发货核算): 三家专线读取工作平台逐包运费 (#1742) 2026-12-04 18:19:43 +08:00
7f8afd290d 逆向快递账单按退件资料匹配并核算运费 (#1741) 2026-12-04 18:14:14 +08:00
43bd01493b feat(供应商对账): 分离当月厂家与免上传厂家
当月厂家完整展示,订单合同及现结厂家独立成卡,其余进度仍按应上传范围统计。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-04 18:02:44 +08:00
824ab74c1a 快递补款按退回规则自动计入小汇总 (#1739) 2026-12-04 17:47:05 +08:00
cab621058a fix(附加费对账): 保留逐票买家原因确认 (#1738) 2026-12-04 17:39:30 +08:00
bb2082730b feat(供应商对账): 按结算方式排除无需上传厂家
结算方式为订单合同或现结的厂家不再计入未上传进度,也不发送群催办。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-04 17:13:51 +08:00
d5b4f4d476 fix(发票数据): 正确处理跨月分次付款索引 (#1736) 2026-12-04 17:05:36 +08:00
1840d98f32 fix(发票数据): 增加有票无票筛选并自动接入新月份 (#1735) 2026-12-04 16:58:02 +08:00
eeb3b33d64 快递账单保留历史记账明细并展示退回补款核对 (#1734) 2026-12-04 15:59:03 +08:00
ffcd457d12 fix(科目映射): 未映射清单仅保留经营平台账单 (#1733)
过滤支付宝资金渠道和未识别店铺,未映射清单只保留经营平台账单。
2026-12-04 15:19:53 +08:00
de1888879b fix(附加费对账): 按工单买家原因核算拦截费 (#1732) 2026-12-04 15:17:03 +08:00
0a5f8744ce fix(附加费对账): 统一匹配账单当月起三个月数据 (#1731) 2026-12-04 14:29:18 +08:00
9cf28bcb3a fix(附加费对账): 每票报价不按出库记录重复累计 (#1730) 2026-12-04 14:13:45 +08:00
42014e56a3 fix(附加费对账): 账单缺少结算时按有效报价自动核价 (#1729) 2026-12-04 14:01:44 +08:00
5349a3c8a5 feat(附加费对账): 按账单匹配自算金额和商品信息 (#1728) 2026-12-04 12:27:08 +08:00
ebcec21bd1 feat(快递账单): 补充河北及德邦顺丰联合上传 (#1727) 2026-12-04 11:14:38 +08:00
341e298981 fix(附加费结算): 补齐客服审核通过费用同步 (#1726) 2026-12-04 11:07:18 +08:00
c24615450b fix(科目映射): 保留未映射清单并改为每月刷新 (#1725)
未映射清单持久保留;本月首次自动刷新一次,页面进入只读,手动刷新另排队。
2026-12-04 10:56:41 +08:00
632a8407da fix(银行账单): 显示个人卡账户筛选 (#1724)
个人卡账单账户加入页面下拉与表头筛选,并回显当前选中账户;仅有账单的个人卡进入选项。

验证:BankBillPageTest 32 项通过,293 个断言。
2026-12-04 10:53:26 +08:00
2197444889 fix(供应商对账): 上传后先发送成功回执 (#1723)
上传账单保存成功后固定先发回执,零差异时随后发送货款确认卡。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-04 10:51:55 +08:00
0a3a09dbd5 fix(银行账单): 正确导入个人卡流水 (#1722)
修正华夏个人卡卡号匹配,并新增招商个人卡 CSV 导入支持。
2026-12-04 10:38:32 +08:00
398cf9690c feat(快递账单): 樵舍与圆通联合上传链接 (#1721) 2026-12-04 10:21:19 +08:00
aea68c2d2d feat(供应商对账): 原始账单支持 Excel 导出 (#1720)
原始账单支持按厂家流式导出完整 Excel,保持模板表头并限制为财务端权限。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-04 10:01:10 +08:00
9b465c111a feat(供应商对账): 新增厂家原始账单查看页 (#1719)
财务端可查看厂家最新上传账单原始行、上传记录和文件名,并从列表及比对详情直达。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-04 09:50:28 +08:00
b7f768d371 fix(供应商对账): 默认显示上一个账期 (#1718)
财务端供应商对账和汇总卡默认显示上一个自然月,历史账期仍可手动切换。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-04 09:20:22 +08:00
a75b0ee1ac feat(快递应付): 退回件明细与定时进仓同步 (#1717) 2026-12-03 19:38:44 +08:00
4722c93d57 docs(供应商对账): 说明确认与差异汇总项可重叠 (#1716)
同一厂家可能同时计入已确认和有差异,页面补充口径说明。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-03 19:23:58 +08:00
d6842648e3 perf(供应商对账): 拆分退货月度索引查询 (#1715)
退货厂家月度筛选改用已有日期索引并拆分查询,保持厂家名单一致,将生产筛选从约 7.5 秒降至约 1 秒。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-03 19:11:24 +08:00
50359f10fb fix(快递账单): 补记账并保证补款金额完整性 2026-12-03 19:04:00 +08:00
db28cf4f0f perf(供应商对账): 使用日期索引优化退货厂家月度筛选 (#1712)
退货厂家按月筛选改用已有日期索引,并保留异常数据 JSON 回退,生产对照名单一致。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-03 18:46:29 +08:00
aadf5682e2 feat(供应商对账): 增加财务端对账进度汇总 (#1711)
财务端新增对账进度汇总,并支持展开查看需要对账、已确认、有差异和未上传账单的厂家名单。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-03 18:33:29 +08:00
d7b664ad53 fix(供应商对账): 批量推送命令切换到指定公司上下文 (#1710)
批量推送命令先激活指定公司上下文,确保读取网页中已配置的钉钉机器人和对账设置。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-03 18:20:14 +08:00
2a908b9292 feat(供应商对账): 零差异上传自动推送确认 (#1709)
厂家上传账单后,双方明细、件数和货款金额完全一致时自动发送货款确认;有差异时保持原回执流程。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-03 18:12:29 +08:00
2cab94b773 fix(运费核算): 四强圆通计费重量向上取整 (#1708) 2026-12-03 17:59:37 +08:00
ef7e3acbc8 fix(银行账单): 补日期区间筛选 (#1707)
在银行账单页恢复账户、来源和共享双月日期区间筛选,并补充回归测试。
2026-12-03 17:42:29 +08:00
19c5555373 feat: 增加小额打款店铺汇总 (#1706) 2026-12-03 17:39:28 +08:00
b33b87a161 fix: 统一非直连账户余额基准 (#1705)
修复非直连账户在月度期初与阶段银行账单并存时的余额基准选择,并移除保留账户期初覆盖户数展示。
2026-12-03 17:37:50 +08:00
dd822e59ba feat(科目映射): 补映射自动带入同名规则 (#1704)
补映射时按同名账单项目带入一致的科目模板;冲突时不猜测。
2026-12-03 17:23:28 +08:00
3953c69192 feat(账单同步): 每日先核对前一日并补齐 (#1703)
> 开工时标题使用 `WIP: <任务名称>` 并先填写“任务占用与边界”。Codex 完成独立合并前自审后补齐其余内容并移除 `WIP:`。

## 任务占用与边界

- 任务名称:
- 实际开发者:
- 任务来源/团队分工:
- 目标结果:
- 预计修改路径:
- 将写入的公共契约(路由、Controller 方法、Repository、表/视图、`source_key`、`scope`、权限名、菜单键或共享组件):
- 仅复用、明确不修改的公共契约:
- 数据源、表/视图和字段:
- 上游 `source_key` / `scope`:
- 权限名、菜单键或共享组件:
- 明确不修改的范围:

## 开工碰撞检查

- [ ] Codex 已执行 `scripts/codex-task-preflight.ps1`
- [ ] 已检查最新 `main` 和所有远程任务分支
- [ ] 已搜索主线既有页面、接口、Repository 和数据查询
- [ ] 已把“将写入”和“仅复用、不修改”的公共契约分开;仅复用项不作为单独阻断条件
- [ ] 未发现实际写入重叠;或已在下方写明相关分支、具体重叠项和协调结论

相关分支、重叠项与协调结论:

## 实际改动

- 完成内容:
- Codex 实际修改的文件:
- 新增或变更的公共契约:
- 与原计划的差异:

## 验证证据

- 正常流程:
- 空数据/错误输入/无权限场景:
- 受影响旧功能:
- 自动测试及结果:
- 实际页面、接口或只读业务查询结果:

## 风险检查

- [ ] 不涉及金额、权限、审批、数据库迁移、生产配置或数据修复
- [ ] 如涉及上述高风险内容,已在下方写明影响、回滚和所需授权
- [ ] 未提交 `.env`、密码、Token、私钥、真实财务数据、生产日志或构建产物
- [ ] 前端改动符合 `DESIGN.md`;无前端改动则写“不适用”

高风险影响、回滚和授权状态:

## 合并前复查

- [ ] 已重新拉取远程引用并用实际修改范围再次运行碰撞检查
- [ ] PR 不再是 `WIP:`,所有测试结果已经补齐
- [ ] Codex 已重新读取原始需求和验收标准,并逐文件审核 `origin/main...任务分支` 的完整 diff
- [ ] Codex 自审确认无越界修改、重复实现、敏感内容、未处理冲突和未验证结果
- [ ] 合并顺序不会覆盖其他未合并任务
- [ ] 已授权当前任务的 Codex 执行 Squash merge、验证 `main` 并清理任务分支
- [ ] 如涉及生产迁移、数据修复、删除、覆盖配置或部署,已另行取得对应高风险授权

Co-authored-by: qiuxiang <qiuxiang@local>
Reviewed-on: #1703
2026-12-03 16:20:25 +08:00
3f1bfc5f79 fix(快递应付): 记账明细移至普通快递应付入口 (#1702) 2026-12-03 16:15:57 +08:00
b591eff505 fix: 修正费用明细主体口径说明 2026-12-03 16:13:16 +08:00
ea3d428262 fix: 费用明细按发生时间匹配主体 2026-12-03 15:41:47 +08:00
00811970fc feat(科目映射): 未映射清单改为跨月汇总 (#1699) 2026-12-03 15:37:42 +08:00
d9ae8fdffe fix(财务导入): 兼容Excel金额浮点尾差 (#1698) 2026-12-03 15:36:35 +08:00
28247a0897 fix(记账明细): 按财务导入表调整34列字段 (#1697) 2026-12-03 15:26:39 +08:00
245 changed files with 20299 additions and 1543 deletions

View File

@ -96,6 +96,36 @@ class CourierContractPageData
} }
} }
/** @return array<string,array{start_date:?string,end_date:?string}> 同名快递取最新归档合作合同的日期。 */
public function datesByCourierNames(array $names): array
{
$names = array_values(array_unique(array_filter(array_map('trim', $names))));
if ($names === [] || ! Schema::hasTable('business_courier_agreement_signatures')) {
return [];
}
$dates = [];
foreach (array_chunk($names, 500) as $chunk) {
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
->whereIn('courier_name', $chunk)
->select(['id', 'courier_name', 'payload', 'document_type', 'status'])
->orderByDesc('archived_at')->orderByDesc('id')->cursor();
foreach ($signatures as $signature) {
$name = trim((string) $signature->courier_name);
if (isset($dates[$name]) || ($payload = $signature->archivedCourierContractPayload()) === null) {
continue;
}
$dates[$name] = [
'start_date' => $this->date($payload['cooperation_start_date'] ?? null),
'end_date' => $this->date($payload['cooperation_end_date'] ?? null),
];
}
}
return $dates;
}
private function filters(): array private function filters(): array
{ {
$search = request()->query('contract_search'); $search = request()->query('contract_search');

View File

@ -0,0 +1,383 @@
<?php
namespace App\Business\KukaPostingBase;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
class KukaPostingAmountPoster
{
public const POSTING_LABEL = '过账标签';
public const POSTED_LABEL = '是';
public const SUPPLEMENT_LABEL = '补单(订单四组)';
private const UPDATE_CHUNK = 500;
public function __construct(
private readonly DatabaseManager $databases,
private readonly KukaPostingBaseRepository $repository,
private readonly KukaPostingAmountSelection $selection,
) {
}
/**
* @return array<string,mixed>
*/
public function plan(int $companyId, string $period, string $targetAmount): array
{
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
}
$targetCents = $this->amountToCents($targetAmount);
if ($targetCents <= 0) {
throw new InvalidArgumentException('整月过账金额必须大于 0。');
}
$import = $this->repository->importFor($companyId, $period);
if ($import === null) {
throw new RuntimeException('当前账期尚未导入发货明细。');
}
$connection = $this->connection();
$sourceRows = [];
$itemNumbers = [];
$storedMaterialNumbers = [];
$connection->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->select([
'id',
'send_date',
'order_date',
'source_row_number',
'source_values',
])
->orderBy('id')
->chunkById(1000, function ($rows) use (
&$sourceRows,
&$itemNumbers,
&$storedMaterialNumbers,
): void {
foreach ($rows as $row) {
try {
$values = json_decode(
(string) $row->source_values,
true,
512,
JSON_THROW_ON_ERROR,
);
} catch (Throwable) {
$values = [];
}
if (! is_array($values)) {
$values = [];
}
$itemNumber = trim((string) ($values['货号'] ?? ''));
if ($itemNumber !== '') {
$itemNumbers[$itemNumber] = true;
}
$storedMaterialNumber = trim((string) ($values['物料编号'] ?? ''));
$usesRepairedMaterial = trim((string) (
$values['物料信息修正'] ?? ''
)) === '是';
if ($usesRepairedMaterial && $storedMaterialNumber !== '') {
$storedMaterialNumbers[$storedMaterialNumber] = true;
}
$sourceRows[] = [
'id' => (int) $row->id,
'item_number' => $itemNumber,
'stored_material_number' => $storedMaterialNumber,
'uses_repaired_material' => $usesRepairedMaterial,
'quantity' => $this->decimalString($values['实发数量'] ?? null),
'date' => (string) ($row->send_date ?? $row->order_date ?? ''),
'source_row_number' => (int) $row->source_row_number,
];
}
});
if ($sourceRows === []) {
throw new RuntimeException('当前账期没有发货明细行。');
}
$maps = $this->repository->materialMaps($companyId, array_keys($itemNumbers));
$quotations = $this->repository->effectiveQuotations(
$companyId,
collect($maps)
->pluck('material_number')
->filter()
->merge(array_keys($storedMaterialNumbers))
->unique()
->values()
->all(),
);
$groups = [];
$eligibleRows = 0;
foreach ($sourceRows as $row) {
$materialNumber = trim((string) ($row['stored_material_number'] ?? ''));
if (! $row['uses_repaired_material'] || $materialNumber === '') {
$materialNumber = trim((string) (
$maps[$row['item_number']]->material_number ?? ''
));
}
$quotation = $materialNumber === '' ? null : ($quotations[$materialNumber] ?? null);
if ($materialNumber === '' || $quotation === null || $row['quantity'] === null) {
continue;
}
$amount = bcmul(
$this->decimalString($quotation->price_including_tax) ?? '0',
$row['quantity'],
4,
);
$amountCents = $this->amountToCents($amount);
if ($amountCents <= 0) {
continue;
}
$groups[$materialNumber][] = [
'id' => (int) $row['id'],
'amount_cents' => $amountCents,
'date' => (string) $row['date'],
'source_row_number' => (int) $row['source_row_number'],
];
$eligibleRows++;
}
$result = $this->selection->select($groups, $targetCents);
$fingerprint = hash('sha256', json_encode([
'company_id' => $companyId,
'period' => $period,
'target_cents' => $targetCents,
'file_sha256' => (string) $import->file_sha256,
'selected_ids' => $result['selected_ids'],
'selected_cents' => $result['selected_cents'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
return [
'company_id' => $companyId,
'period' => $period,
'target_cents' => $result['target_cents'],
'target_amount' => $this->formatAmount($result['target_cents']),
'total_cents' => $result['total_cents'],
'total_amount' => $this->formatAmount($result['total_cents']),
'selected_cents' => $result['selected_cents'],
'selected_amount' => $this->formatAmount($result['selected_cents']),
'difference_cents' => $result['difference_cents'],
'difference_amount' => $this->formatAmount(abs($result['difference_cents'])),
'is_exact' => (bool) $result['exact'],
'rows_total' => count($sourceRows),
'eligible_rows' => $eligibleRows,
'uncalculable_rows' => count($sourceRows) - $eligibleRows,
'selected_rows' => (int) $result['selected_rows'],
'material_count' => count($groups),
'selected_material_count' => (int) $result['selected_materials'],
'selected_ids' => $result['selected_ids'],
'allocations' => $result['allocations'],
'preview_hash' => $fingerprint,
];
}
/**
* @param array<string,mixed> $plan
* @return array{updated:int,unchanged:int}
*/
public function apply(array $plan, ?int $userId = null): array
{
if (($plan['is_exact'] ?? false) !== true) {
throw new InvalidArgumentException('过账金额与选中发货金额仍有差额,未写入过账标签。');
}
$companyId = (int) ($plan['company_id'] ?? 0);
$period = (string) ($plan['period'] ?? '');
$selectedIds = array_fill_keys(array_map('intval', (array) ($plan['selected_ids'] ?? [])), true);
$connection = $this->connection();
$now = now();
$updated = 0;
$unchanged = 0;
$connection->transaction(function () use (
$connection,
$companyId,
$period,
$selectedIds,
$now,
$userId,
$plan,
&$updated,
&$unchanged,
): void {
$batch = [];
$flush = static function () use ($connection, &$batch): void {
if ($batch === []) {
return;
}
$connection->table('kuka_posting_base_rows')->upsert(
$batch,
['company_id', 'period', 'source_row_number'],
[
'store_name',
'internal_order_no',
'online_order_no',
'product_code',
'source_values',
'row_hash',
'imported_at',
],
);
$batch = [];
};
$connection->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->orderBy('id')
->chunkById(self::UPDATE_CHUNK, function ($rows) use (
$selectedIds,
&$updated,
&$unchanged,
&$batch,
$flush,
): void {
foreach ($rows as $row) {
try {
$values = json_decode(
(string) $row->source_values,
true,
512,
JSON_THROW_ON_ERROR,
);
} catch (Throwable) {
$values = [];
}
if (! is_array($values)) {
$values = [];
}
$label = isset($selectedIds[(int) $row->id])
? self::POSTED_LABEL
: self::SUPPLEMENT_LABEL;
if (trim((string) ($values[self::POSTING_LABEL] ?? '')) === $label) {
$unchanged++;
continue;
}
$values[self::POSTING_LABEL] = $label;
$encoded = json_encode(
$values,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
);
$batch[] = [
'company_id' => (int) $row->company_id,
'period' => (string) $row->period,
'source_row_number' => (int) $row->source_row_number,
'store_name' => (string) $row->store_name,
'internal_order_no' => $row->internal_order_no,
'online_order_no' => $row->online_order_no,
'product_code' => $row->product_code,
'source_values' => $encoded,
'row_hash' => hash('sha256', $encoded),
'imported_at' => $row->imported_at,
];
$updated++;
if (count($batch) >= self::UPDATE_CHUNK) {
$flush();
}
}
});
$flush();
$connection->table('kuka_posting_base_imports')
->where('company_id', $companyId)
->where('period', $period)
->update([
'posting_target_amount' => $plan['target_amount'],
'posting_selected_amount' => $plan['selected_amount'],
'posting_difference_amount' => '0.00',
'posting_selected_rows' => (int) $plan['selected_rows'],
'posting_material_count' => (int) $plan['material_count'],
'posting_uncalculable_rows' => (int) $plan['uncalculable_rows'],
'posting_allocation_json' => json_encode(
$plan['allocations'],
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
),
'posting_snapshot_hash' => (string) $plan['preview_hash'],
'posting_applied_by' => $userId,
'posting_applied_at' => $now,
'updated_at' => $now,
]);
});
return ['updated' => $updated, 'unchanged' => $unchanged];
}
/**
* @param array<string,mixed> $plan
* @return array<string,mixed>
*/
public function previewSummary(array $plan): array
{
return [
'period' => (string) $plan['period'],
'target_cents' => (int) $plan['target_cents'],
'target_amount' => (string) $plan['target_amount'],
'total_cents' => (int) $plan['total_cents'],
'total_amount' => (string) $plan['total_amount'],
'selected_cents' => (int) $plan['selected_cents'],
'selected_amount' => (string) $plan['selected_amount'],
'difference_cents' => (int) $plan['difference_cents'],
'difference_amount' => (string) $plan['difference_amount'],
'is_exact' => (bool) $plan['is_exact'],
'rows_total' => (int) $plan['rows_total'],
'uncalculable_rows' => (int) $plan['uncalculable_rows'],
'selected_rows' => (int) $plan['selected_rows'],
'material_count' => (int) $plan['material_count'],
'selected_material_count' => (int) $plan['selected_material_count'],
'preview_hash' => (string) $plan['preview_hash'],
];
}
private function decimalString(mixed $value): ?string
{
$normalized = str_replace(',', '', trim((string) $value));
if ($normalized === '' || ! is_numeric($normalized)) {
return null;
}
return $normalized;
}
private function amountToCents(string $amount): int
{
$normalized = str_replace([',', ' '], '', trim($amount));
if (preg_match('/^(\d+)(?:\.(\d+))?$/', $normalized, $matches) !== 1) {
throw new InvalidArgumentException('金额格式不正确。');
}
$whole = (int) $matches[1];
$fraction = str_pad($matches[2] ?? '', 3, '0');
$cents = ($whole * 100) + (int) substr($fraction, 0, 2);
if ((int) $fraction[2] >= 5) {
$cents++;
}
return $cents;
}
private function formatAmount(int $cents): string
{
return bcdiv((string) $cents, '100', 2);
}
private function connection(): ConnectionInterface
{
return $this->databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
}

View File

@ -0,0 +1,418 @@
<?php
namespace App\Business\KukaPostingBase;
use InvalidArgumentException;
/**
* 按料号分配整月过账金额,并在每个料号内按发货日期优先选行。
*/
class KukaPostingAmountSelection
{
/**
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
* @return array{
* exact: bool,
* target_cents: int,
* total_cents: int,
* selected_cents: int,
* difference_cents: int,
* selected_ids: list<int>,
* selected_rows: int,
* selected_materials: int,
* allocations: list<array{
* material_number: string,
* total_cents: int,
* allocated_cents: int,
* selected_cents: int,
* selected_rows: int,
* row_count: int
* }>
* }
*/
public function select(array $groups, int $targetCents): array
{
if ($targetCents <= 0) {
throw new InvalidArgumentException('整月过账金额必须大于 0。');
}
$groups = $this->normalizeGroups($groups);
if ($groups === []) {
throw new InvalidArgumentException('当前账期没有可用于过账的料号和发货金额。');
}
$totalCents = 0;
$minimumCents = 0;
foreach ($groups as $rows) {
$totalCents += array_sum(array_column($rows, 'amount_cents'));
$minimumCents += (int) $rows[0]['amount_cents'];
}
if ($targetCents > $totalCents) {
throw new InvalidArgumentException('整月过账金额不能大于可计算发货金额合计。');
}
$allocations = $this->proportionalAllocations($groups, $targetCents, $minimumCents);
$selected = [];
foreach ($groups as $materialNumber => $rows) {
$allocation = $allocations[$materialNumber];
$prefixCents = 0;
$bestCount = 1;
$bestDifference = PHP_INT_MAX;
foreach ($rows as $index => $row) {
$prefixCents += (int) $row['amount_cents'];
$difference = abs($allocation - $prefixCents);
if ($difference < $bestDifference) {
$bestDifference = $difference;
$bestCount = $index + 1;
}
}
for ($index = 0; $index < $bestCount; $index++) {
$selected[(int) $rows[$index]['id']] = true;
}
}
[$selected, $selectedCents] = $this->calibrate(
$groups,
$selected,
$targetCents,
);
$selectedByMaterial = [];
foreach ($groups as $materialNumber => $rows) {
foreach ($rows as $row) {
if (isset($selected[(int) $row['id']])) {
$selectedByMaterial[$materialNumber][] = $row;
}
}
}
$allocationRows = [];
foreach ($groups as $materialNumber => $rows) {
$selectedRows = $selectedByMaterial[$materialNumber] ?? [];
$allocationRows[] = [
'material_number' => (string) $materialNumber,
'total_cents' => array_sum(array_column($rows, 'amount_cents')),
'allocated_cents' => $allocations[$materialNumber],
'selected_cents' => array_sum(array_column($selectedRows, 'amount_cents')),
'selected_rows' => count($selectedRows),
'row_count' => count($rows),
];
}
usort(
$allocationRows,
static fn (array $left, array $right): int => strnatcasecmp(
$left['material_number'],
$right['material_number'],
),
);
$selectedIds = array_keys($selected);
sort($selectedIds, SORT_NUMERIC);
$differenceCents = $targetCents - $selectedCents;
return [
'exact' => $differenceCents === 0,
'target_cents' => $targetCents,
'total_cents' => $totalCents,
'selected_cents' => $selectedCents,
'difference_cents' => $differenceCents,
'selected_ids' => $selectedIds,
'selected_rows' => count($selectedIds),
'selected_materials' => count($selectedByMaterial),
'allocations' => $allocationRows,
];
}
/**
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
* @return array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>>
*/
private function normalizeGroups(array $groups): array
{
$normalized = [];
foreach ($groups as $materialNumber => $rows) {
$materialNumber = trim((string) $materialNumber);
if ($materialNumber === '') {
continue;
}
$validRows = array_values(array_filter(
$rows,
static fn (array $row): bool => (int) ($row['amount_cents'] ?? 0) > 0
&& (int) ($row['id'] ?? 0) > 0,
));
if ($validRows === []) {
continue;
}
usort($validRows, static function (array $left, array $right): int {
$dateComparison = strcmp((string) $left['date'], (string) $right['date']);
return $dateComparison !== 0
? $dateComparison
: ((int) $left['source_row_number'] <=> (int) $right['source_row_number']);
});
$normalized[$materialNumber] = $validRows;
}
ksort($normalized, SORT_NATURAL | SORT_FLAG_CASE);
return $normalized;
}
/**
* 先保证每个料号选中最早一行,再按剩余发货金额占比分配剩余过账金额。
*
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
* @return array<string,int>
*/
private function proportionalAllocations(
array $groups,
int $targetCents,
int $minimumCents,
): array {
if ($targetCents < $minimumCents) {
throw new InvalidArgumentException(sprintf(
'整月过账金额不足:每个料号至少选择一行需要 %s。',
number_format($minimumCents / 100, 2, '.', ','),
));
}
$extraTotal = 0;
$extraByMaterial = [];
$baseByMaterial = [];
foreach ($groups as $materialNumber => $rows) {
$base = (int) $rows[0]['amount_cents'];
$total = array_sum(array_column($rows, 'amount_cents'));
$baseByMaterial[$materialNumber] = $base;
$extraByMaterial[$materialNumber] = $total - $base;
$extraTotal += $total - $base;
}
$remaining = $targetCents - $minimumCents;
$allocations = [];
$remainders = [];
$assigned = 0;
foreach ($groups as $materialNumber => $rows) {
$extra = $extraByMaterial[$materialNumber];
$share = 0;
$remainder = '0';
if ($remaining > 0 && $extraTotal > 0 && $extra > 0) {
$numerator = bcmul((string) $extra, (string) $remaining, 0);
$share = (int) bcdiv($numerator, (string) $extraTotal, 0);
$remainder = bcmod($numerator, (string) $extraTotal);
}
$allocations[$materialNumber] = $baseByMaterial[$materialNumber] + $share;
$assigned += $share;
$remainders[$materialNumber] = $remainder;
}
$left = $remaining - $assigned;
if ($left > 0) {
$ordered = array_keys($groups);
usort($ordered, static function (string $leftMaterial, string $rightMaterial) use (
$remainders,
$extraByMaterial,
): int {
if ($extraByMaterial[$leftMaterial] <= 0) {
return 1;
}
if ($extraByMaterial[$rightMaterial] <= 0) {
return -1;
}
return bccomp($remainders[$rightMaterial], $remainders[$leftMaterial], 0)
?: strnatcasecmp($leftMaterial, $rightMaterial);
});
foreach ($ordered as $materialNumber) {
if ($left <= 0) {
break;
}
if ($extraByMaterial[$materialNumber] > $allocations[$materialNumber]
- $baseByMaterial[$materialNumber]) {
$allocations[$materialNumber]++;
$left--;
}
}
}
return $allocations;
}
/**
* @param array<string,list<array{id:int,amount_cents:int,date:string,source_row_number:int}>> $groups
* @param array<int,true> $selected
* @return array{0:array<int,true>,1:int}
*/
private function calibrate(array $groups, array $selected, int $targetCents): array
{
$rowsById = [];
foreach ($groups as $materialNumber => $rows) {
foreach ($rows as $row) {
$id = (int) $row['id'];
$row['material_number'] = $materialNumber;
$rowsById[$id] = $row;
}
}
for ($attempt = 0; $attempt < count($groups) + 2; $attempt++) {
$selectedCents = 0;
foreach ($rowsById as $id => $row) {
if (isset($selected[$id])) {
$selectedCents += (int) $row['amount_cents'];
}
}
$difference = $targetCents - $selectedCents;
if ($difference === 0) {
return [$selected, $selectedCents];
}
$options = $this->prefixOptions($groups, $selected);
$adjustments = $this->exactPrefixAdjustment($options, $difference);
if ($adjustments === null) {
$adjustment = $this->bestApproximatePrefixOption($options, $difference);
if ($adjustment === null) {
return [$selected, $selectedCents];
}
if (abs($difference - $adjustment['delta']) >= abs($difference)) {
return [$selected, $selectedCents];
}
$adjustments = [$adjustment];
}
foreach ($adjustments as $adjustment) {
$materialNumber = $adjustment['material_number'];
foreach ($groups[$materialNumber] as $row) {
unset($selected[(int) $row['id']]);
}
for ($index = 0; $index < $adjustment['count']; $index++) {
$selected[(int) $groups[$materialNumber][$index]['id']] = true;
}
}
}
$selectedCents = 0;
foreach (array_keys($selected) as $id) {
$selectedCents += (int) $rowsById[$id]['amount_cents'];
}
return [$selected, $selectedCents];
}
/**
* @param array<string,list<array<string,mixed>>> $groups
* @param array<int,true> $selected
* @return list<array{
* material_number:string,
* count:int,
* delta:int,
* count_change:int
* }>
*/
private function prefixOptions(
array $groups,
array $selected,
): array {
$options = [];
foreach ($groups as $materialNumber => $rows) {
$currentCents = 0;
$currentCount = 0;
foreach ($rows as $row) {
if (isset($selected[(int) $row['id']])) {
$currentCents += (int) $row['amount_cents'];
$currentCount++;
}
}
$prefixCents = 0;
foreach ($rows as $index => $row) {
$prefixCents += (int) $row['amount_cents'];
$count = $index + 1;
$delta = $prefixCents - $currentCents;
if ($delta !== 0) {
$options[] = [
'material_number' => (string) $materialNumber,
'count' => $count,
'delta' => $delta,
'count_change' => abs($count - $currentCount),
];
}
}
}
return $options;
}
/**
* 调整一个或两个料号的日期前缀,寻找精确差额。
*
* @param list<array{
* material_number:string,
* count:int,
* delta:int,
* count_change:int
* }> $options
* @return list<array{material_number:string,count:int,delta:int,count_change:int}>|null
*/
private function exactPrefixAdjustment(array $options, int $difference): ?array
{
$single = null;
foreach ($options as $option) {
if ($option['delta'] === $difference
&& ($single === null || $option['count_change'] < $single['count_change'])) {
$single = $option;
}
}
if ($single !== null) {
return [$single];
}
$byDelta = [];
foreach ($options as $option) {
$byDelta[$option['delta']][] = $option;
}
foreach ($options as $left) {
$needed = $difference - $left['delta'];
foreach ($byDelta[$needed] ?? [] as $right) {
if ($left['material_number'] === $right['material_number']) {
continue;
}
return [
$left,
$right,
];
}
}
return null;
}
/**
* @param list<array{
* material_number:string,
* count:int,
* delta:int,
* count_change:int
* }> $options
* @return array{material_number:string,count:int,delta:int,count_change:int}|null
*/
private function bestApproximatePrefixOption(
array $options,
int $difference,
): ?array {
$best = null;
$bestRemaining = abs($difference);
foreach ($options as $option) {
$remaining = abs($difference - $option['delta']);
if ($remaining < $bestRemaining
|| ($remaining === $bestRemaining
&& $best !== null
&& $option['count_change'] < $best['count_change'])) {
$best = $option;
$bestRemaining = $remaining;
}
}
return $best;
}
}

View File

@ -21,6 +21,7 @@ class KukaPostingBasePageData
* statuses: list<string>, * statuses: list<string>,
* stores: list<string>, * stores: list<string>,
* import: ?array<string, mixed>, * import: ?array<string, mixed>,
* posting_amount: ?array<string, mixed>,
* summary: array<string, mixed>, * summary: array<string, mixed>,
* error: ?string * error: ?string
* } * }
@ -182,6 +183,7 @@ class KukaPostingBasePageData
$import = $available ? $this->repository->importFor($companyId, $period) : null; $import = $available ? $this->repository->importFor($companyId, $period) : null;
$importData = null; $importData = null;
$postingAmount = null;
if ($import !== null) { if ($import !== null) {
$storeCounts = json_decode((string) ($import->store_counts ?? ''), true); $storeCounts = json_decode((string) ($import->store_counts ?? ''), true);
$importData = [ $importData = [
@ -195,6 +197,20 @@ class KukaPostingBasePageData
'source_sheet' => (string) $import->source_sheet, 'source_sheet' => (string) $import->source_sheet,
'completed_at' => (string) $import->completed_at, 'completed_at' => (string) $import->completed_at,
]; ];
if (property_exists($import, 'posting_target_amount')
&& $import->posting_target_amount !== null) {
$postingAmount = [
'target_amount' => bcdiv((string) $import->posting_target_amount, '1', 2),
'selected_amount' => bcdiv((string) $import->posting_selected_amount, '1', 2),
'difference_amount' => bcdiv((string) $import->posting_difference_amount, '1', 2),
'selected_rows' => (int) $import->posting_selected_rows,
'material_count' => (int) $import->posting_material_count,
'uncalculable_rows' => (int) $import->posting_uncalculable_rows,
'applied_at' => $import->posting_applied_at
? (string) $import->posting_applied_at
: null,
];
}
} }
return [ return [
@ -211,6 +227,7 @@ class KukaPostingBasePageData
'statuses' => $statuses, 'statuses' => $statuses,
'stores' => $stores, 'stores' => $stores,
'import' => $importData, 'import' => $importData,
'posting_amount' => $postingAmount,
'summary' => [ 'summary' => [
'filtered_rows' => $rows->total(), 'filtered_rows' => $rows->total(),
'rows' => (int) ($importData['row_count'] ?? 0), 'rows' => (int) ($importData['row_count'] ?? 0),

View File

@ -0,0 +1,76 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use App\Support\DropshipFreight\{DropshipConfirmation, FactoryBillParser};
use Illuminate\Console\Command;
use Illuminate\Support\Facades\{Cache, DB, Storage};
/** 只从已上传原件回补缺失重量,不重导运费、附加费或确认记录。 */
final class BackfillDropshipBillWeights extends Command
{
protected $signature = 'dropship-freight:backfill-weights {--file=*} {--all} {--company=1} {--apply}';
protected $description = '预演或备份回补厂家原账单重量,保留所有已有金额';
public function handle(FactoryBillParser $parser, DropshipConfirmation $confirmation): int
{
if (! $this->option('all') && $this->option('file') === []) {
$this->error('请选择 --file 或 --all'); return self::FAILURE;
}
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
$this->error('请通过 run-finance-batch.sh 执行'); return self::FAILURE;
}
$company = (int) $this->option('company'); Company::findOrFail($company)->makeCurrent(true);
$lock = Cache::lock('dropship-freight:backfill-weights', 3900);
if (! $lock->get()) { $this->error('重量回补正在执行'); return self::FAILURE; }
$db = DB::connection('business_mirror'); $started = microtime(true); $queries = 0; $sqlMs = 0;
DB::listen(static function ($q) use (&$queries, &$sqlMs) { $queries++; $sqlMs += $q->time; });
$folder = 'private/dropship-weight/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4));
try {
foreach ($db->table('dropship_bill_files')->where('status', 'parsed')->whereNotNull('factory_id')
->when(! $this->option('all'), fn ($q) => $q->whereIn('id', $this->option('file')))->orderBy('id')->lazyById(20) as $file) {
if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') {
$this->line(json_encode(['file' => $file->id, 'skipped' => '厂家已确认'], JSON_UNESCAPED_UNICODE)); continue;
}
$path = Storage::disk('local')->path($file->stored_path);
if (! is_file($path)) throw new \RuntimeException('原件缺失:' . $file->id);
$parsed = $parser->parse($path, pathinfo($path, PATHINFO_EXTENSION))['lines'];
$report = $db->transaction(function () use ($db, $file, $parsed, $folder, $confirmation, $company) {
$db->table('dropship_bill_files')->where('id', $file->id)->lockForUpdate()->first();
if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') {
return ['file' => $file->id, 'skipped' => '厂家已确认'];
}
$stream = null; $scanned = $filled = $missing = $mismatched = 0;
if ($this->option('apply')) {
Storage::disk('local')->put($folder . '/' . $file->id . '.ndjson', '');
$stream = fopen(Storage::disk('local')->path($folder . '/' . $file->id . '.ndjson'), 'wb');
if (! $stream) throw new \RuntimeException('无法创建备份');
fwrite($stream, json_encode(['file' => $file], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
}
try {
foreach ($db->table('dropship_bill_lines')->where('file_id', $file->id)->orderBy('id')->lazyById(500) as $line) {
$scanned++;
if ($stream) fwrite($stream, json_encode(['line' => $line], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
if ($line->bill_weight !== null) continue;
$source = $parsed[$line->waybill_no] ?? null;
if ($source === null || mb_substr($source['sheet'], 0, 64) !== $line->sheet || $source['row'] !== $line->row_no
|| abs($source['amount'] - (float) $line->amount) > 0.0001) { $mismatched++; continue; }
if ($source['weight'] === null) { $missing++; continue; }
$filled++;
if ($this->option('apply')) $db->table('dropship_bill_lines')->where('id', $line->id)->whereNull('bill_weight')
->update(['bill_weight' => $source['weight']]);
}
} finally { if ($stream) fclose($stream); }
return ['file' => $file->id, 'month' => $file->bill_month, 'factory' => $file->factory_id,
'scanned' => $scanned, 'filled' => $filled, 'missing' => $missing, 'mismatched' => $mismatched, 'applied' => (bool) $this->option('apply')];
});
unset($parsed); $this->line(json_encode($report, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
$this->info(json_encode(['backup' => $this->option('apply') ? $folder : null, 'seconds' => round(microtime(true) - $started, 3),
'peak_mib' => memory_get_peak_usage(true) / 1048576, 'queries' => $queries, 'sql_ms' => round($sqlMs, 2)], JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
} catch (\Throwable $e) { report($e); $this->error($e->getMessage()); return self::FAILURE; }
finally { $lock->release(); }
}
}

View File

@ -49,10 +49,7 @@ class ImportPayablesFinal extends Command
} }
$fields = $registry->fields($section, $dataset); $fields = $registry->fields($section, $dataset);
$storeDataset = 'final:' $storeDataset = $registry->storeDataset($section, $dataset);
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
. ':'
. $dataset;
$totalCreated = 0; $totalCreated = 0;
$totalUpdated = 0; $totalUpdated = 0;
$totalRows = 0; $totalRows = 0;

View File

@ -0,0 +1,93 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use App\Support\CourierBills\Rebooks;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Throwable;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
class MatchBillSurcharges extends Command
{
public const AUTO_MATCH_HOLDS = 'bill-surcharge-auto-match-holds';
protected $signature='courier-surcharge:match-bills {--month= : 账单月份 YYYY-MM,默认上月} {--all-months : 刷新全部已有账期,需同时指定 --all --existing-only} {--refresh-rebooks : 同时刷新未确认账单的补记账汇总} {--statement=* : 指定快递对账单} {--factory=* : 指定代发厂家} {--all : 匹配该月全部未确认账单} {--existing-only : 只更新已建立附加费匹配的账单} {--company=1}';
protected $description='匹配指定月份账单的附加费金额及商品信息,已确认账单不变';
public function handle(SurchargeSettlementMatcher $matcher): int
{
\App\Models\Common\Company::findOrFail((int) $this->option('company'))->makeCurrent();
if ($this->option('all-months')) {
if (! $this->option('all') || ! $this->option('existing-only') || $this->option('month')) {
$this->error('--all-months 需要 --all --existing-only,且不能指定 --month');
return self::FAILURE;
}
$months = DB::connection('business_mirror')->table(SurchargeSettlementMatcher::TABLE)->select('bill_month')
->union(DB::connection('business_mirror')->table('courier_bill_statements')->select('bill_month')->where('status', '<>', 'confirmed'))
->orderBy('bill_month')->pluck('bill_month');
foreach ($months as $month) {
$status = $this->call(self::class, ['--month' => $month, '--all' => true,
'--existing-only' => true, '--refresh-rebooks' => (bool) $this->option('refresh-rebooks'), '--company' => $this->option('company')]);
if ($status !== self::SUCCESS) return $status;
}
return self::SUCCESS;
}
$month=(string)($this->option('month')?:now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m'));
if(!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D',$month)){$this->error('请填写有效账单月份 YYYY-MM');return self::FAILURE;}
if(!$this->option('all')&&$this->option('statement')===[]&&$this->option('factory')===[]){$this->error('请选择对账单、厂家或 --all');return self::FAILURE;}
if(app()->environment('production')&&!env('FINANCE_BATCH_CONTAINER')){$this->error('请通过 run-finance-batch.sh 执行。');return self::FAILURE;}
$lock=Cache::lock('bill-surcharge-matching',3900);if(!$lock->get()){$this->error('附加费匹配正在运行');return self::FAILURE;}
$started = microtime(true);
try{
$db=DB::connection('business_mirror');$statements=[];$factories=[];
$holds=[];
if($this->option('existing-only'))foreach(app(SupplierPayableOverrideStore::class)->listRows(self::AUTO_MATCH_HOLDS,(int)$this->option('company')) as $hold){
if(($hold['enabled']??false)===true)$holds[$hold['_action_key']]=true;
}
if($this->option('all')||$this->option('statement')!==[]){
$statements=$db->table('courier_bill_statements')->where('bill_month',$month)->where('status','<>','confirmed')
->when($this->option('existing-only'),fn($q)=>$q->whereIn('id',$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('bill_month',$month)->select('owner_id')))
->when(!$this->option('all'),fn($q)=>$q->whereIn('id',array_map('intval',$this->option('statement'))))->orderBy('id')->pluck('id')->all();
foreach($statements as $id){app(CourierBillMatcher::class)->refreshSurchargeSummary((int)$id);$this->line('快递对账单 #'.$id.' 附加费已匹配');}
}
if($this->option('all')||$this->option('factory')!==[]){
$store=app(DropshipFreightStore::class);
$factories=$db->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')->whereNotNull('factory_id')
->when($this->option('existing-only'),fn($q)=>$q->whereIn('factory_id',$db->table('dropship_bill_surcharges')->where('bill_month',$month)->select('factory_id')))
->when(!$this->option('all'),fn($q)=>$q->whereIn('factory_id',array_map('intval',$this->option('factory'))))->distinct()->pluck('factory_id')->all();
foreach($factories as $id){
if(isset($holds['dropship|'.$id.'|'.$month])){$this->line('厂家 #'.$id.' 已保留当前附加费,跳过自动重匹配');continue;}
$state=app(DropshipConfirmation::class)->state($month,(int)$id,(int)$this->option('company'));
if(($state['status']??'')==='confirmed'){$this->line('厂家 #'.$id.' 已确认,跳过');continue;}
$db->transaction(function()use($db,$store,$id,$month){foreach($db->table('dropship_bill_files')->where('factory_id',$id)->where('bill_month',$month)->where('status','parsed')->get() as $file)$store->storeSurchargeRows($file,(int)$id);});
$matcher->dropship((int)$id,$month);$this->line('代发厂家 #'.$id.' 附加费已匹配');
}
}
if ($this->option('refresh-rebooks')) {
foreach ($db->table('courier_bill_statements')->where('bill_month', $month)->where('status', '<>', 'confirmed')
->when(! $this->option('all'), fn ($q) => $q->whereIn('id', array_map('intval', $this->option('statement'))))->orderBy('id')->pluck('id') as $id) {
$db->transaction(function () use ($db, $id): void {
$statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first();
if (! $statement || $statement->status === 'confirmed') return;
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->get();
foreach (app(Rebooks::class)->summaryItems((int) $id, $items) as $item) {
if (! $item->manual && Rebooks::isRebookLabel($item->label)) {
$db->table('courier_bill_summary_items')->where('id', $item->id)->update(['self_amount' => $item->self_amount]);
}
}
});
}
}
$this->info('附加费匹配完成:'.$month.';快递对账单 '.count($statements).' 张,代发厂家 '.count($factories).' 家。');
$this->line(sprintf('耗时 %.2f 秒,PHP 峰值 %.2f MiB。', microtime(true) - $started, memory_get_peak_usage(true) / 1048576));
return self::SUCCESS;
}catch(Throwable $e){report($e);$this->error('附加费匹配失败:'.$e->getMessage());return self::FAILURE;}
finally{$lock->release();}
}
}

View File

@ -0,0 +1,60 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\ReturnPickupLookup;
use App\Support\CourierBills\ShippingLookup;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
/** 指定一张逆向账单预演/重算,保留原始账单与手工处理。 */
final class MatchReverseCourierBill extends Command
{
protected $signature = 'courier-bills:match-reverse {statement : 对账单ID} {--company=1} {--apply : 备份后更新该未确认账单}';
protected $description = '按退件取件资料和当前有效报价核对指定逆向快递账单';
public function handle(ShippingLookup $lookup, CourierBillMatcher $matcher): int
{
Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
$id = (int) $this->argument('statement');
$lock = Cache::lock('courier-bills:match-reverse:' . $id, 600);
if (! $lock->get()) { $this->error('该账单正在核对'); return self::FAILURE; }
try {
$start = microtime(true);
$db = CourierBillMatcher::db();
$statement = $db->table('courier_bill_statements')->find($id);
if (! $statement || $statement->status === 'confirmed') { $this->error('账单不存在或已确认'); return self::FAILURE; }
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$names = (array) json_decode($group->express_names, true);
if (! ReturnPickupLookup::supports($names)) { $this->error('指定账单不属于逆向快递'); return self::FAILURE; }
$lines = $db->table('courier_bill_lines')->where('statement_id', $id)->orderBy('id')->get();
$rows = $lookup->summaries($lines->pluck('waybill_no')->unique()->all(), $names);
$total = $calculated = $matched = 0;
foreach ($rows as $row) {
$matched += ($row['data_source'] ?? '') === '退件取件管理' ? 1 : 0;
if ($row['calc_freight'] !== null) { $calculated++; $total += $row['calc_freight']; }
}
$this->line(json_encode(['statement' => $id, 'group' => $group->name, 'month' => $statement->bill_month,
'lines' => $lines->count(), 'return_matches' => $matched, 'calculated_waybills' => $calculated,
'calculated_total' => round($total, 2)], JSON_UNESCAPED_UNICODE));
if ($this->option('apply')) {
$path = 'private/operation-backups/reverse-bill-' . $id . '-' . gmdate('Ymd-His') . '.json';
$tables = ['courier_bill_lines', 'courier_bill_unprovided', 'courier_bill_summary_items'];
$backup = ['statement' => $statement, 'group' => $group];
foreach ($tables as $table) $backup[$table] = $db->table($table)->where('statement_id', $id)->get()->all();
Storage::disk('local')->put($path, json_encode($backup, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
$this->line('备份:' . $path);
$matcher->match($id);
$this->line(json_encode(['categories' => $db->table('courier_bill_lines')->where('statement_id', $id)
->groupBy('category')->selectRaw('category, COUNT(*) as count, SUM(bill_amount) as bill, SUM(self_amount) as self')->get(),
'unprovided' => $db->table('courier_bill_unprovided')->where('statement_id', $id)->count()], JSON_UNESCAPED_UNICODE));
}
$this->line(json_encode(['elapsed_seconds' => round(microtime(true) - $start, 3),
'peak_memory_mb' => round(memory_get_peak_usage(true) / 1048576, 1)]));
return self::SUCCESS;
} finally { $lock->release(); }
}
}

View File

@ -13,7 +13,7 @@ use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench; use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
use Throwable; use Throwable;
/** 每天 11:20 生成当天种菜报销批次:把可报销合计、要取消的单和放行检查结果推到钉钉群并 @ 报销人,并自动发不予报销通知(@ 发起人)。不改聚工单。 */ /** 每天 11:20 推送种菜报销批次汇总;逐单不予报销通知须已启用。不改聚工单。 */
class PlantingReimbursementDailyDigest extends Command class PlantingReimbursementDailyDigest extends Command
{ {
protected $signature = 'planting-reimbursement:daily-digest protected $signature = 'planting-reimbursement:daily-digest
@ -48,7 +48,9 @@ class PlantingReimbursementDailyDigest extends Command
} }
try { try {
[$title, $text] = $this->message($workbench, $repository, $robot, (int) $company->id, $date, ! $this->option('dry-run')); $liveRun = ! $this->option('dry-run');
$sendNotices = $liveRun && $robot->cancelNoticesEnabled();
[$title, $text] = $this->message($workbench, $repository, $robot, (int) $company->id, $date, $liveRun, $sendNotices);
if ($this->option('dry-run')) { if ($this->option('dry-run')) {
$this->line($title . "\n" . $text); $this->line($title . "\n" . $text);
continue; continue;
@ -67,7 +69,7 @@ class PlantingReimbursementDailyDigest extends Command
} }
/** @return array{0:string,1:string} */ /** @return array{0:string,1:string} */
private function message(Workbench $workbench, Repository $repository, Robot $robot, int $companyId, string $date, bool $sendNotices): array private function message(Workbench $workbench, Repository $repository, Robot $robot, int $companyId, string $date, bool $liveRun, bool $sendNotices): array
{ {
$sync = $repository->syncStatus(); $sync = $repository->syncStatus();
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]); $url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
@ -92,7 +94,7 @@ class PlantingReimbursementDailyDigest extends Command
$confirmedNow = false; $confirmedNow = false;
if ($result === null) { if ($result === null) {
$result = $workbench->build($companyId, $date); $result = $workbench->build($companyId, $date);
if ($sendNotices && Gate::check($result)['ok']) { if ($liveRun && Gate::check($result)['ok']) {
$result = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto'); $result = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
$confirmedNow = true; $confirmedNow = true;
} }
@ -118,6 +120,8 @@ class PlantingReimbursementDailyDigest extends Command
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']); $lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
} elseif ($s['notices'] === []) { } elseif ($s['notices'] === []) {
$lines[] = '- 没有要取消或复查的工单'; $lines[] = '- 没有要取消或复查的工单';
} elseif (! $robot->cancelNoticesEnabled()) {
$lines[] = '- 取消 / 待复查逐单通知已暂停,测试完成前不会发送';
} elseif ($sendNotices) { } elseif ($sendNotices) {
$sent = $robot->sendNotices($companyId, $date, $s['notices']); $sent = $robot->sendNotices($companyId, $date, $s['notices']);
$lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : ''); $lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : '');

View File

@ -120,7 +120,7 @@ class PullCourierSurchargeOverlength extends Command
$condition = (string) $rule->condition; $condition = (string) $rule->condition;
$standard = (string) $rule->standard; $standard = (string) $rule->standard;
if (preg_match('/单边超\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米|CM|㎝)/u', $condition, $matched) !== 1) { if (preg_match('/单边(?:长)?超\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米|CM|㎝)/u', $condition, $matched) !== 1) {
$this->warn('规则 #' . $rule->id . ' 的生效条件解析不出单边阈值,已跳过:' . $condition); $this->warn('规则 #' . $rule->id . ' 的生效条件解析不出单边阈值,已跳过:' . $condition);
continue; continue;
} }

View File

@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer;
use Throwable;
class PullCustomerServiceSurcharges extends Command
{
protected $signature = 'courier-surcharge:pull-customer-service {--courier= : 报价中的完整快递名称} {--company=1} {--from= : 工单创建日期起(含),默认报价生效日} {--to= : 工单创建日期止(含),默认今天}';
protected $description = '同步聚工单客服逐行审核通过的附加费,完整校验后替换指定快递的派生结算明细';
public function handle(CustomerServiceSurchargeSynchronizer $sync): int
{
$courier = trim((string) $this->option('courier'));
if ($courier === '' || (int) $this->option('company') < 1) { $this->error('请指定快递完整名称及有效公司。'); return self::FAILURE; }
foreach (['from','to'] as $option) {
$date = $this->option($option);
if ($date && (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/D', $date, $parts)
|| ! checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1]))) {
$this->error('日期需要 YYYY-MM-DD。'); return self::FAILURE;
}
}
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
$this->error('请使用服务器 run-finance-batch.sh 执行。'); return self::FAILURE;
}
$lock = Cache::lock(CustomerServiceSurchargeSynchronizer::dataset((int) $this->option('company'), $courier), 2100);
if (! $lock->get()) { $this->error('该快递附加费同步正在执行。'); return self::FAILURE; }
try {
$result = $sync->sync((int) $this->option('company'), $courier, $this->option('from'), $this->option('to'),
fn ($done, $total) => $this->line("已扫描 {$done} / {$total} 张查件工单"));
$this->info(sprintf('%s 附加费同步完成:%s 至 %s,%d 条,金额 %s 元,耗时 %.2f 秒,PHP 峰值 %.2f MiB。',
$courier, $result['from'], $result['to'], $result['rows'], $result['amount'], $result['seconds'], $result['peak_mb']));
return self::SUCCESS;
} catch (Throwable $e) {
report($e); $this->error('附加费同步失败,保留上次完整结果:' . $e->getMessage()); return self::FAILURE;
} finally { $lock->release(); }
}
}

View File

@ -0,0 +1,110 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\SupplierStatementStore;
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
class PushSupplierZeroDifferenceConfirmations extends Command
{
protected $signature = 'supplier-reconciliation:push-zero-difference-confirmations
{--month= : 账期 YYYY-MM,默认上月}
{--company=1 : 公司 ID}
{--supplier=* : 只处理指定厂家,可重复传入}
{--dry-run : 只检查,不发送}
{--force : 已有待确认或已确认记录时仍重新推送}';
protected $description = '扫描厂家上传的账单,双方完全一致时自动推送货款确认';
public function handle(
SupplierStatementStore $statements,
SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
): int {
$companyId = max(1, (int) $this->option('company'));
$month = trim((string) $this->option('month'));
if ($month === '') {
$month = now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m');
}
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) {
$this->error('账期格式必须为 YYYY-MM。');
return self::FAILURE;
}
Company::findOrFail($companyId)->makeCurrent();
$suppliers = array_values(array_filter(array_map(
static fn (mixed $supplier): string => trim((string) $supplier),
(array) $this->option('supplier'),
)));
if ($suppliers === []) {
$suppliers = $statements->uploadedSuppliers($companyId);
}
$suppliers = array_values(array_unique($suppliers));
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
if ($suppliers === []) {
$this->info('没有找到已上传对账单的厂家。');
return self::SUCCESS;
}
$dryRun = (bool) $this->option('dry-run');
$force = (bool) $this->option('force');
$rows = [];
$pushed = 0;
$failed = 0;
$skipped = 0;
foreach ($suppliers as $supplier) {
if ($dryRun) {
$assessment = $zeroDifferenceConfirmations->assess($supplier, $companyId, $month);
$status = $assessment['eligible'] ? '可推送' : '不推送';
$reason = $assessment['reason'];
$qty = $assessment['qty'];
$amount = $assessment['amount'];
} else {
$result = $zeroDifferenceConfirmations->pushMonth(
$supplier,
$companyId,
$month,
null,
! $force,
);
$status = match ($result['status']) {
'pushed' => '已推送',
'failed' => '失败',
default => '跳过',
};
$reason = $result['reason'];
$qty = $result['qty'];
$amount = $result['amount'];
if ($result['status'] === 'pushed') {
$pushed++;
} elseif ($result['status'] === 'failed') {
$failed++;
} else {
$skipped++;
}
}
$rows[] = [
$supplier,
$status,
rtrim(rtrim(number_format($qty, 2, '.', ''), '0'), '.'),
rtrim(rtrim(number_format($amount, 2, '.', ''), '0'), '.'),
$reason,
];
}
$this->table(['厂家', '状态', '件数', '货款金额', '说明'], $rows);
if ($dryRun) {
$this->info("{$month} 检查完成,共 " . count($suppliers) . ' 家;未发送任何消息。');
} else {
$this->info("{$month} 处理完成:已推送 {$pushed} 家,跳过 {$skipped} 家,失败 {$failed} 家。");
}
return $failed > 0 ? self::FAILURE : self::SUCCESS;
}
}

View File

@ -7,13 +7,14 @@ use Modules\EcommerceFinance\Services\AccountMappingCoverage;
use Throwable; use Throwable;
/** /**
* 后台重建某月账单项目覆盖快照,供科目映射页即时读取。 * 后台重建跨月或指定月份账单项目覆盖快照,供科目映射页即时读取。
*/ */
class RefreshAccountMappingCoverage extends Command class RefreshAccountMappingCoverage extends Command
{ {
protected $signature = 'account-mapping:refresh-coverage protected $signature = 'account-mapping:refresh-coverage
{month? : 账单月份,格式 YYYY-MM} {month? : all 或账单月份 YYYY-MM}
{--pending : 处理页面登记的下一个刷新请求}'; {--pending : 处理页面登记的下一个刷新请求}
{--monthly : 本月尚未成功刷新时执行跨月刷新}';
protected $description = '刷新科目映射的未映射账单项目清单'; protected $description = '刷新科目映射的未映射账单项目清单';
@ -21,6 +22,12 @@ class RefreshAccountMappingCoverage extends Command
{ {
$runningPath = null; $runningPath = null;
$month = trim((string) $this->argument('month')) ?: null; $month = trim((string) $this->argument('month')) ?: null;
$monthly = (bool) $this->option('monthly');
if ($monthly && $this->option('pending')) {
$this->error('--monthly 与 --pending 不能同时使用。');
return self::FAILURE;
}
if ($this->option('pending')) { if ($this->option('pending')) {
$request = $coverage->claimPendingRefresh(); $request = $coverage->claimPendingRefresh();
if ($request === null) { if ($request === null) {
@ -31,9 +38,20 @@ class RefreshAccountMappingCoverage extends Command
$month = $request['month']; $month = $request['month'];
$runningPath = $request['path']; $runningPath = $request['path'];
} }
if ($monthly) {
if (! $coverage->monthlyRefreshDue()) {
$this->line('本月未映射清单已生成,无需重复刷新。');
return self::SUCCESS;
}
$month = 'all';
}
try { try {
$raw = $coverage->refreshForMonth($month); $isAll = $month === 'all';
$raw = $isAll
? $coverage->refreshAllMonths()
: $coverage->refreshForMonth($month);
if (($raw['status'] ?? '') === 'refreshing') { if (($raw['status'] ?? '') === 'refreshing') {
$this->warn('已有刷新任务正在执行,本次跳过。'); $this->warn('已有刷新任务正在执行,本次跳过。');
if ($runningPath !== null) { if ($runningPath !== null) {
@ -43,10 +61,12 @@ class RefreshAccountMappingCoverage extends Command
return self::SUCCESS; return self::SUCCESS;
} }
$summary = $coverage->missingForMonth($month); $summary = $isAll
? $coverage->missingAcrossMonths()
: $coverage->missingForMonth($month);
$this->info(sprintf( $this->info(sprintf(
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。', '%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。',
(string) $summary['month'], $isAll ? '跨月全部账单' : (string) $summary['month'],
(int) $summary['missing_item_count'], (int) $summary['missing_item_count'],
(int) $summary['missing_row_count'], (int) $summary['missing_row_count'],
(int) $summary['source_rows'], (int) $summary['source_rows'],

View File

@ -0,0 +1,116 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use App\Support\CourierBills\{Category, CourierBillMatcher, SummaryMapper, WeightDifferenceSubsidy};
use Illuminate\Console\Command;
use Illuminate\Support\Facades\{Cache, DB, Storage};
/** 只重新应用结算口径,不重算报价或覆盖人工处理。 */
final class RefreshCourierSettlement extends Command
{
protected $signature = 'courier-bills:refresh-settlement {--statement=*} {--all-open} {--express=* : 仅刷新指定快递的运费,保留附加费} {--company=1} {--apply : 备份后更新未确认账单}';
protected $description = '应用快递运费结算口径(含按核算值结算的例外),并刷新附加费及武进韵达补款';
public function handle(CourierBillMatcher $matcher, WeightDifferenceSubsidy $subsidy): int
{
if (! $this->option('all-open') && $this->option('statement') === []) {
$this->error('请选择对账单或 --all-open');
return self::FAILURE;
}
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
$this->error('请通过 run-finance-batch.sh 执行');
return self::FAILURE;
}
Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
$lock = Cache::lock('courier-bills:refresh-settlement', 3900);
if (! $lock->get()) { $this->error('结算刷新正在运行'); return self::FAILURE; }
$started = microtime(true);
$queries = 0; $sqlMs = 0.0;
DB::listen(static function ($query) use (&$queries, &$sqlMs): void { $queries++; $sqlMs += $query->time; });
$db = CourierBillMatcher::db();
$folder = 'private/courier-settlement/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4));
try {
$ids = $db->table('courier_bill_statements')->where('status', '<>', 'confirmed')
->when(! $this->option('all-open'), fn ($q) => $q->whereIn('id', $this->option('statement')))
->where('line_count', '>', 0)->orderBy('id')->pluck('id');
foreach ($ids as $id) {
$result = $db->transaction(function () use ($db, $id, $matcher, $subsidy, $folder) {
$statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first();
if (! $statement || $statement->status === 'confirmed') return ['statement' => $id, 'skipped' => true];
$beforeSummary = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('id')->get();
$beforeFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->orderBy('id')->get();
$stream = null;
if ($this->option('apply')) {
$path = $folder . '/' . $id . '.ndjson';
Storage::disk('local')->put($path, '');
$stream = fopen(Storage::disk('local')->path($path), 'wb');
if (! $stream) throw new \RuntimeException('无法保存备份');
fwrite($stream, json_encode(['statement' => $statement, 'summary' => $beforeSummary, 'surcharges' => $beforeFees], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
}
$changed = 0; $decrease = 0.0; $scanned = 0;
try {
foreach ($db->table('courier_bill_lines')->where('statement_id', $id)
->when($this->option('express') !== [], fn ($q) => $q->whereIn('express_name', $this->option('express')))
->orderBy('id')->lazyById(500) as $line) {
$scanned++;
if ($stream) fwrite($stream, json_encode(['line' => $line], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
if ($line->resolution !== null || ! in_array($line->category, [...Category::PAYABLE, Category::PRIOR], true)) continue;
$amount = CourierBillMatcher::selfAmount((string) $line->category, $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $line->resolution, $line->express_name);
if (($amount === null) === ($line->self_amount === null) && ($amount === null || abs($amount - (float) $line->self_amount) < 0.00001)) continue;
$changed++; $decrease += (float) $line->self_amount - (float) $amount;
if ($this->option('apply')) $db->table('courier_bill_lines')->where('id', $line->id)->update(['self_amount' => $amount]);
}
} finally { if ($stream) fclose($stream); }
$weight = $subsidy->summary((int) $id);
$existing = $beforeSummary->firstWhere('label', WeightDifferenceSubsidy::LABEL);
$subsidyChanged = ! ($existing?->manual) && abs((float) ($existing?->self_amount ?? 0) - $weight['amount']) > 0.00001;
$feeChanges = 0; $feeDecrease = 0.0;
foreach ($beforeFees as $fee) {
if ($this->option('express') === [] && $fee->self_amount !== null && $fee->bill_amount !== null && (float) $fee->bill_amount < (float) $fee->self_amount) {
$feeChanges++; $feeDecrease += (float) $fee->self_amount - round((float) $fee->bill_amount, 2);
if ($this->option('apply')) $db->table('bill_surcharge_matches')->where('id', $fee->id)->update([
'self_amount' => round((float) $fee->bill_amount, 2),
'match_note' => $fee->match_note . ';快递提供金额较低,按快递金额结算',
]);
}
}
if ($this->option('apply') && ($changed > 0 || $subsidyChanged || $feeChanges > 0)) {
$matcher->refreshSummary((int) $id, false);
// 只允许报价核价金额按较低的快递提供金额下调。
$fields = ['file_id', 'sheet', 'row_no', 'waybill_no', 'item', 'bill_amount', 'self_amount'];
$normalize = static fn ($rows) => $rows->map(fn ($r) => array_intersect_key((array) $r, array_flip($fields)))->sortBy(fn ($r) => json_encode($r))->values()->all();
$expectedFees = $beforeFees->map(function ($fee) {
$copy = clone $fee;
if ($this->option('express') === [] && $copy->self_amount !== null && $copy->bill_amount !== null && (float) $copy->bill_amount < (float) $copy->self_amount) $copy->self_amount = number_format((float) $copy->bill_amount, 2, '.', '');
return $copy;
});
$afterFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->get();
if ($normalize($expectedFees) != $normalize($afterFees)) throw new \RuntimeException('附加费来源发生变化,本张账单已回退');
$protected = static fn ($rows) => $rows->filter(fn ($r) => $r->manual || ($r->label !== WeightDifferenceSubsidy::LABEL
&& in_array(SummaryMapper::classify($r->label), ['AL', 'supplement'], true)))
->map(fn ($r) => [$r->label, $r->bill_amount === null ? null : (float) $r->bill_amount,
$r->self_amount === null ? null : (float) $r->self_amount, (bool) $r->manual])
->sortBy(fn ($r) => json_encode($r))->values()->all();
if ($protected($beforeSummary) != $protected($db->table('courier_bill_summary_items')->where('statement_id', $id)->get())) {
throw new \RuntimeException('人工金额、配件扣款或补记账发生变化,本张账单已回退');
}
}
return ['statement' => $id, 'month' => $statement->bill_month, 'scanned' => $scanned,
'changed' => $changed, 'settlement_decrease' => round($decrease, 2), 'weight_subsidy' => $weight,
'fee_changes' => $feeChanges, 'fee_decrease' => round($feeDecrease, 2),
'applied' => (bool) $this->option('apply')];
});
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
$this->info(json_encode(['backup' => $this->option('apply') ? $folder : null,
'seconds' => round(microtime(true) - $started, 3), 'peak_mib' => round(memory_get_peak_usage(true) / 1048576, 2),
'queries' => $queries, 'sql_ms' => round($sqlMs, 2)], JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
} catch (\Throwable $e) {
report($e); $this->error($e->getMessage());
return self::FAILURE;
} finally { $lock->release(); }
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Console\Commands;
use App\Support\ShippingTrackingRefresh;
use Illuminate\Console\Command;
class RefreshShippingTracking extends Command
{
protected $signature='jushuitan:refresh-tracking {--source-id=* : 定向校准包裹源键,最多500个} {--max-batches=4}';
protected $description='按上游更新时间校准现有发货单号并保留换单前信息,不重算运费';
public function handle(ShippingTrackingRefresh $refresh): int
{
if(app()->environment('production')&&!env('FINANCE_BATCH_CONTAINER')){$this->error('请通过 run-finance-batch.sh 执行。');return self::FAILURE;}
ini_set('memory_limit', '512M');
set_time_limit(1800);
$ids=$this->option('source-id');
if(count($ids)>500||collect($ids)->contains(fn($id)=>!ctype_digit((string)$id)||(int)$id<1)){$this->error('包裹源键无效。');return self::FAILURE;}
$started=microtime(true);$queries=0;$sqlMs=0;
\Illuminate\Support\Facades\DB::listen(function($q)use(&$queries,&$sqlMs){$queries++;$sqlMs+=$q->time;});
$r=$refresh->sync($ids,min(4,max(1,(int)$this->option('max-batches'))));
$this->line('运单校准:扫描 '.$r['scanned'].' 个源键,更新 '.$r['changed'].' 个包裹,补回 '.$r['names'].' 条旧快递名称,状态 '.$r['status']);
$this->line(sprintf('耗时 %.3f 秒,PHP 峰值 %.1f MiB,数据库查询 %d 次 / %.1f ms',microtime(true)-$started,memory_get_peak_usage(true)/1048576,$queries,$sqlMs));
return self::SUCCESS;
}
}

View File

@ -89,12 +89,13 @@ class SendSupplierStatementReminders extends Command
} }
$this->line(sprintf( $this->line(sprintf(
'#%d %s %s %s:00: 入库供应商 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,本时段已提醒 %d 家,未配置机器人 %d 家,失败 %d 家', '#%d %s %s %s:00: 需上传供应商 %d 家,无需上传 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,本时段已提醒 %d 家,未配置机器人 %d 家,失败 %d 家',
$company->id, $company->id,
$company->name, $company->name,
$result['accounting_month'], $result['accounting_month'],
$slot, $slot,
$result['source_suppliers'], $result['source_suppliers'],
count($result['exempt_suppliers']),
$result['configured'], $result['configured'],
$dryRun ? '将提醒' : '已发送', $dryRun ? '将提醒' : '已发送',
count($dryRun ? $result['previewed'] : $result['sent']), count($dryRun ? $result['previewed'] : $result['sent']),

View File

@ -0,0 +1,192 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\JdDailyBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
use Throwable;
class SummarizeBillRange extends Command
{
private const ALLOWED_TABS = [
'taobao-alipay',
'taobao-wechat',
'pinduoduo',
'jd-wallet',
'jd-transactions',
'jingxi',
'douyin',
'dewu',
'dewu-alipay',
'xiaohongshu',
];
protected $signature = 'bill-sync:summarize-range
{--tabs= : 逗号分隔的账单页签}
{--from= : 开始日期 YYYY-MM-DD}
{--to= : 截止日期 YYYY-MM-DD}
{--company-id=1 : 公司 ID}
{--json : 输出 JSON}';
protected $description = '按指定日期范围和页签汇总财务系统账单笔数、收入与支出';
public function handle(): int
{
$tabs = array_values(array_unique(array_filter(array_map(
static fn (string $tab): string => trim($tab),
explode(',', (string) $this->option('tabs')),
))));
$unknownTabs = array_values(array_diff($tabs, self::ALLOWED_TABS));
if ($tabs === [] || $unknownTabs !== []) {
$this->error('账单页签无效:' . ($unknownTabs ? implode(',', $unknownTabs) : '不能为空'));
return self::FAILURE;
}
$from = $this->date((string) $this->option('from'));
$to = $this->date((string) $this->option('to'));
if ($from === null || $to === null || $from->gt($to)) {
$this->error('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。');
return self::FAILURE;
}
$companyId = max(1, (int) $this->option('company-id'));
$fromText = $from->toDateString();
$toText = $to->toDateString();
$platforms = [];
$rowCount = 0;
$incomeCents = 0;
$expenseCents = 0;
foreach ($tabs as $tab) {
try {
$summary = $this->summary($tab, $fromText, $toText, $companyId);
} catch (Throwable $exception) {
report($exception);
$this->error("账单页签 {$tab} 汇总失败。");
return self::FAILURE;
}
$platforms[$tab] = $summary;
$rowCount += $summary['row_count'];
$incomeCents += $summary['income_cents'];
$expenseCents += $summary['expense_cents'];
}
$result = [
'from' => $fromText,
'to' => $toText,
'company_id' => $companyId,
'row_count' => $rowCount,
'income_cents' => $incomeCents,
'expense_cents' => $expenseCents,
'platforms' => $platforms,
];
if ((bool) $this->option('json')) {
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
} else {
$this->table(
['页签', '笔数', '收入', '支出'],
array_map(
static fn (string $tab, array $summary): array => [
$tab,
number_format($summary['row_count']),
number_format($summary['income_cents'] / 100, 2),
number_format($summary['expense_cents'] / 100, 2),
],
array_keys($platforms),
array_values($platforms),
),
);
$this->line(sprintf(
'合计:%d 笔,收入 %.2f,支出 %.2f',
$rowCount,
$incomeCents / 100,
$expenseCents / 100,
));
}
return self::SUCCESS;
}
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
private function summary(string $tab, string $from, string $to, int $companyId): array
{
if ($tab === 'xiaohongshu') {
$summary = DB::table('ec_account_bills')
->where('company_id', $companyId)
->where('bill_type', 'xiaohongshu')
->where('occurred_at', '>=', $from . ' 00:00:00')
->where('occurred_at', '<', Carbon::parse($to)->addDay()->toDateString() . ' 00:00:00')
->selectRaw(
'COUNT(*) AS row_count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense'
)
->first();
return $this->normalize($summary->row_count, $summary->income, $summary->expense);
}
$filters = ['start' => $from, 'end' => $to];
$result = match ($tab) {
'taobao-alipay' => app(StoreReceivingAlipayBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'taobao-wechat' => app(TaobaoWechatSettlementBillRepository::class)
->paginateAccountBills($filters, 'occurred_at', 'desc', 1, 1),
'pinduoduo' => app(StoreReceivingPinduoduoBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'jd-wallet' => app(StoreReceivingJdWalletBillRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'jd-transactions' => app(JdDailyBillRepository::class)
->forPlatform('jd')
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'jingxi' => app(JdDailyBillRepository::class)
->forPlatform('jingxi')
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'douyin' => app(StoreReceivingDouyinBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'dewu' => app(StoreReceivingDewuBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
'dewu-alipay' => app(StoreReceivingDewuAlipayBillMirrorRepository::class)
->paginate($filters, 'occurred_at', 'desc', 1, 1),
};
return $this->normalize(
$result['total'] ?? ($result['summary']['count'] ?? 0),
$result['summary']['income'] ?? 0,
$result['summary']['expense'] ?? 0,
);
}
/** @return array{row_count:int,income_cents:int,expense_cents:int} */
private function normalize(mixed $rows, mixed $income, mixed $expense): array
{
return [
'row_count' => (int) $rows,
'income_cents' => (int) round((float) $income * 100),
'expense_cents' => (int) round((float) $expense * 100),
];
}
private function date(string $value): ?Carbon
{
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
return null;
}
$date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
}
}

View File

@ -6,6 +6,9 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use InvalidArgumentException; use InvalidArgumentException;
use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository; use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository;
use Modules\EcommerceFinance\Repositories\LinehaulFreightRepository;
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry; use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer; use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer;
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer; use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
@ -92,6 +95,19 @@ class SyncBusinessMirrors extends Command
$result['batches'], $result['batches'],
$result['rows'], $result['rows'],
)); ));
if ($key === LinehaulFreightRepository::DATASET && $result['status'] === 'succeeded'
&& ((bool) $task['full'] || $result['rows'] > 0)) {
try {
$freight = app(ShippingFreightService::class)->recalculate(
FreightCarrierRules::START_DATE, now()->addDay()->format('Y-m-d'), LinehaulFreightRepository::CARRIERS);
$this->info(sprintf('专线运费已更新:%d 个包裹,匹配成功 %d 个,待核对 %d 个。',
$freight['packages'], $freight['ok'], $freight['packages'] - $freight['ok']));
} catch (Throwable $exception) {
$failed = true;
Log::error('专线镜像已同步,核算结果更新失败。', ['exception' => $exception::class]);
$this->error('专线镜像已同步,发货数据核算结果未完成更新,请重跑专线运费核算。');
}
}
} }
// 每日退款专属批次只处理配置内的退款表,不能继续进入 // 每日退款专属批次只处理配置内的退款表,不能继续进入

View File

@ -0,0 +1,60 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
use Throwable;
class SyncReturnedParcels extends Command
{
protected $signature = 'business-mirror:sync-returned-parcels {--from= : 进仓开始日期(含)} {--to= : 进仓结束日期(含)} {--deduplicate : 只合并现有镜像中两来源相同的售后商品,不读取上游} {--match-surcharges : 同步成功后刷新已有未确认账单附加费}';
protected $description = '同步聚水潭售后退货退款到快递应付退回件明细';
public function handle(ReturnedParcelSynchronizer $synchronizer): int
{
$from = (string) ($this->option('from') ?: ReturnedParcelSynchronizer::START);
$to = (string) ($this->option('to') ?: now('Asia/Shanghai')->toDateString());
foreach ([$from, $to] as $date) {
if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/D', $date, $parts)
|| ! checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) {
$this->error('日期需要 YYYY-MM-DD。');
return self::FAILURE;
}
}
if ($from < ReturnedParcelSynchronizer::START || $from > $to) {
$this->error('开始日期不得早于 2026-10-01,且不能晚于结束日期。');
return self::FAILURE;
}
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
$this->error('请通过服务器 run-finance-batch.sh 执行同步。');
return self::FAILURE;
}
$lock = Cache::lock('courier-returned-parcels-sync', 2100);
if (! $lock->get()) {
$this->warn('退回件同步正在运行,本次跳过。');
return self::SUCCESS;
}
try {
if ($this->option('deduplicate')) {
$this->info('退回件来源校准完成:合并重复商品明细 '.$synchronizer->deduplicate().' 行。');
return self::SUCCESS;
}
$result = $synchronizer->sync($from, $to, fn (int $n, int $total) => $this->line("已扫描 {$n} / {$total} 行"));
$this->info(sprintf('退回件同步完成:%s 至 %s,%d 条商品明细,耗时 %.2f 秒,PHP 峰值 %.2f MiB。',
$from, $to, $result['rows'], $result['seconds'], $result['peak_mb']));
if ($this->option('match-surcharges')) {
// 新退回可能属于更早账期,沿用既有确认和人工保留保护。
return $this->call(MatchBillSurcharges::class, ['--all' => true, '--existing-only' => true, '--all-months' => true, '--refresh-rebooks' => true]);
}
return self::SUCCESS;
} catch (Throwable $exception) {
report($exception);
$this->error('退回件同步失败,保留上次完整结果;使用相同日期可继续未完成批次。');
return self::FAILURE;
} finally {
$lock->release();
}
}
}

View File

@ -2,28 +2,76 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Support\UnshippedSourceSynchronizer;
use App\Support\UnshippedWaybills; use App\Support\UnshippedWaybills;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Throwable;
final class SyncUnshippedWaybills extends Command final class SyncUnshippedWaybills extends Command
{ {
protected $signature = 'courier:sync-unshipped-waybills'; protected $signature = 'courier:sync-unshipped-waybills {--source= : 只刷新指定来源} {--skip-returned : 退回件已刷新时复用该完整结果} {--max-batches=0 : 仓内工单每轮最大批次,0表示至完成}';
protected $description = '从共享镜像和已导入订单日志重算未发出明细'; protected $description = '从当前业务副本和发货换单记录刷新未发出明细';
public function handle(UnshippedWaybills $waybills): int public function handle(UnshippedWaybills $waybills, UnshippedSourceSynchronizer $sources): int
{ {
$failed = false; if (app()->environment('production') && !env('FINANCE_BATCH_CONTAINER')) {
foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) { $this->error('请通过 run-finance-batch.sh 执行。');
if (!$waybills->sync($source)) { return self::FAILURE;
$warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning'); }
$this->warn($label.':'.$warning); $selected = (string) $this->option('source');
$failed = true; if ($selected !== '' && !array_key_exists($selected, UnshippedWaybills::SYNC_SOURCES)) {
} else { $this->error('未知来源');
$state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first(); return self::FAILURE;
$this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。'); }
} $lock = Cache::lock('courier-unshipped-sync', 2100);
if (!$lock->get()) {
$this->warn('未发出明细正在同步,本次跳过。');
return self::SUCCESS;
}
$failed = false;
try {
$returnedOk = true;
if (!$this->option('skip-returned') && ($selected === '' || str_starts_with($selected, 'intercept_'))) {
$returnedOk = $this->call('business-mirror:sync-returned-parcels') === self::SUCCESS;
}
foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) {
if ($selected !== '' && $selected !== $source) continue;
try {
if ($source === 'warehouse') {
$result = $sources->warehouse(max(0, (int) $this->option('max-batches')),
fn ($n, $last, $high) => $this->line("仓内未发:已扫描 {$n} 行,游标 {$last}/{$high}"));
if ($result['status'] === 'running') {
$this->line('仓内未发:分批同步进行中,保留上次完整结果。');
continue;
}
$ok = true;
} elseif (str_starts_with($source, 'intercept_')) {
if (!$returnedOk) throw new \RuntimeException('退回件刷新失败,保留上次未发出结果。');
$sources->intercept($source);
$ok = true;
} else {
$ok = $waybills->sync($source);
}
} catch (Throwable $error) {
report($error);
$ok = false;
$safeMessages = ['退回件明细尚未完成刷新,保留上次结果。', '退回件来源覆盖不足,保留上次结果。', '退回件刷新失败,保留上次未发出结果。'];
$warning = in_array($error->getMessage(), $safeMessages, true) ? $error->getMessage() : '来源读取失败,保留上次完整结果。';
$waybills->connection()->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], ['warning' => $warning]);
}
if (!$ok) {
$warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning');
$this->warn($label.':'.$warning);
$failed = true;
} else {
$state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first();
$this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。');
}
}
return $failed ? self::FAILURE : self::SUCCESS;
} finally {
$lock->release();
} }
return $failed ? self::FAILURE : self::SUCCESS;
} }
} }

View File

@ -71,6 +71,14 @@ class Kernel extends ConsoleKernel
->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log')) ->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log'))
->runInBackground(); ->runInBackground();
// 使用生产批处理入口,避免在网页容器运行全量退回件同步。
$schedule->exec('sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels')
->cron('0 10,16 * * *')
->timezone('Asia/Shanghai')
->withoutOverlapping(60)
->appendOutputTo(storage_path('logs/returned-parcels-sync.log'))
->runInBackground();
// 上游店铺档案每日刷新后留存一份完整基础信息,方便按日期复查负责人等字段。 // 上游店铺档案每日刷新后留存一份完整基础信息,方便按日期复查负责人等字段。
$schedule->command('business-mirror:archive-store-information') $schedule->command('business-mirror:archive-store-information')
->dailyAt('07:00') ->dailyAt('07:00')

View File

@ -12,6 +12,7 @@ use Modules\EcommerceFinance\Services\AccountMappingCoa;
use Modules\EcommerceFinance\Services\AccountMappingCoverage; use Modules\EcommerceFinance\Services\AccountMappingCoverage;
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher; use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
use Modules\EcommerceFinance\Services\AccountMappingStore; use Modules\EcommerceFinance\Services\AccountMappingStore;
use Modules\EcommerceFinance\Services\AccountMappingSuggestion;
use Modules\EcommerceFinance\Services\AccountMappingValidator; use Modules\EcommerceFinance\Services\AccountMappingValidator;
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter; use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
use RuntimeException; use RuntimeException;
@ -74,6 +75,7 @@ class AccountMappingActions extends Controller
private readonly AccountMappingCoa $coa, private readonly AccountMappingCoa $coa,
private readonly AccountMappingWorkbookImporter $importer, private readonly AccountMappingWorkbookImporter $importer,
private readonly AccountMappingCoverage $coverage, private readonly AccountMappingCoverage $coverage,
private readonly AccountMappingSuggestion $suggestion,
) { ) {
$this->middleware('auth'); $this->middleware('auth');
$this->middleware('company.identify'); $this->middleware('company.identify');
@ -96,11 +98,13 @@ class AccountMappingActions extends Controller
]); ]);
try { try {
return response()->json($this->coverage->missingForMonth( $month = trim((string) ($data['month'] ?? ''));
trim((string) ($data['month'] ?? '')) ?: null, $refresh = (bool) ($data['refresh'] ?? false);
(bool) ($data['refresh'] ?? false), $payload = $month === ''
false, ? $this->coverage->missingAcrossMonths($refresh, false)
)); : $this->coverage->missingForMonth($month, $refresh, false);
return response()->json($payload);
} catch (\InvalidArgumentException $exception) { } catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages(['month' => $exception->getMessage()]); throw ValidationException::withMessages(['month' => $exception->getMessage()]);
} catch (Throwable $exception) { } catch (Throwable $exception) {
@ -112,6 +116,20 @@ class AccountMappingActions extends Controller
} }
} }
/** 补映射时按同名账单项目查找可带入的既有规则。 */
public function suggest(Request $request): JsonResponse
{
$data = $request->validate([
'platform' => ['required', 'string', 'max:120'],
'item' => ['required', 'string', 'max:500'],
]);
return response()->json($this->suggestion->suggest(
(string) $data['platform'],
(string) $data['item'],
));
}
public function store(Request $request): JsonResponse public function store(Request $request): JsonResponse
{ {
$values = $this->payloadValues($request); $values = $this->payloadValues($request);

View File

@ -7,6 +7,7 @@ use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\CourierBillStore; use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\StatementExporter; use App\Support\CourierBills\StatementExporter;
use App\Support\CourierBills\StreamingWorkbook; use App\Support\CourierBills\StreamingWorkbook;
use App\Support\CourierBills\Rebooks;
use App\Support\CourierBills\Waybill; use App\Support\CourierBills\Waybill;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@ -80,7 +81,7 @@ final class CourierBillController extends Controller
})->all(); })->all();
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all(); $without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbTotals' => [ return ['cbRows' => $rows, 'cbWithout' => $without, 'cbConfirmationStates' => app(\App\Support\CourierBills\FreightConfirmation::class)->states($month,(int)(company_id()?:1)), 'cbTotals' => [
'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')), 'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')),
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')), 'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
]]; ]];
@ -120,6 +121,8 @@ final class CourierBillController extends Controller
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString(); 'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
} }
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get(); $items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
$items=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->summaryItems((int)$statement->id,$items);
$items=app(Rebooks::class)->summaryItems((int)$statement->id,$items);
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id'); $fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get(); $files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
$shippingSync = null; $shippingSync = null;
@ -133,9 +136,31 @@ final class CourierBillController extends Controller
->whereIn('s.id', $related)->pluck('g.name', 's.id'); ->whereIn('s.id', $related)->pluck('g.name', 's.id');
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(), return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
'cbConfirmation' => app(\App\Support\CourierBills\FreightConfirmation::class)->state($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
'cbDisputes' => app(\App\Support\CourierBills\FreightConfirmation::class)->disputes($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
'cbConfirmHistory' => app(\App\Support\CourierBills\FreightConfirmation::class)->history($statement->bill_month,(int)$statement->id,(int)(company_id()?:1)),
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines, 'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync, 'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync,
'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id)]; 'cbFeeLabels' => $this->matcher->feeLabels((int) $statement->id), 'cbRebook' => $this->rebookSummary((int) $statement->id),
'cbSurchargeRows' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('courier',(int)$statement->id)->orderBy('id')->paginate(50,['*'],'fee_page')->withQueryString() : null];
}
/** 单家对账单上的补记账说明:补几个月、本期补几单多少、还有几单待复核。 @return array<string,mixed>|null */
private function rebookSummary(int $statementId): ?array
{
try {
$plan = app(Rebooks::class)->forStatement($statementId);
} catch (\Throwable $error) {
report($error);
return null;
}
$rows = collect($plan['rows']);
return ['months' => $plan['months'], 'source' => $plan['source'], 'window' => $plan['window'],
'count' => $rows->where('amount', '>', 0)->count(), 'amount' => round((float) $rows->sum('amount'), 2),
'pending' => $rows->where('status', '资料缺失待核对')->count(), 'done' => $rows->filter(fn ($r) => str_starts_with($r['status'], '已补'))->count()];
} }
private function detailsData(Request $request, string $month): array private function detailsData(Request $request, string $month): array
@ -191,10 +216,28 @@ final class CourierBillController extends Controller
private function uploadData(string $month): array private function uploadData(string $month): array
{ {
return ['cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id') $jointUploads = [];
foreach (\App\Support\CourierBills\CourierJointUploads::SETS as $key => $set) {
try {
app(\App\Support\CourierBills\CourierJointUploads::class)->resolve($key);
$jointUploads[$key] = $set;
} catch (RuntimeException) { /* 分组未配置的环境不显示入口。 */ }
}
return ['cbJointUploads' => $jointUploads, 'cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])]; ->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
} }
public function jointUploadLink(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'],
'joint' => ['required', Rule::in(array_keys(\App\Support\CourierBills\CourierJointUploads::SETS))]]);
$url = $this->guard(fn () => app(\App\Support\CourierBills\CourierUploadLink::class)
->jointPageUrl((int) (company_id() ?: 1), $data['joint'], $data['month']));
return redirect()->away($url);
}
private function ledgerData(Request $request): array private function ledgerData(Request $request): array
{ {
$db = $this->store->db(); $db = $this->store->db();
@ -208,6 +251,16 @@ final class CourierBillController extends Controller
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id') 'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']), ->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
'cbSearch' => $search, 'cbSearch' => $search,
'cbRebookStats' => $db->table('courier_bill_rebooks as r')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'r.group_id')
->groupBy('r.refund_month', 'r.deduct_month', 'g.name', 'r.source')
->selectRaw(sprintf('%s as refund_month, %s as deduct_month, %s as group_name, %s as source, COUNT(*) as n, SUM(%s) as amount',
...array_map(static fn (string $c): string => $db->getQueryGrammar()->wrap($c), ['r.refund_month', 'r.deduct_month', 'g.name', 'r.source', 'r.amount'])))
->orderByDesc('r.refund_month')->orderBy('r.deduct_month')->orderBy('g.name')->limit(500)->get(),
'cbRebookReviews' => $db->table('courier_bill_rebook_reviews')->groupBy('deduct_month')
->selectRaw('deduct_month, COUNT(*) as n, MAX(updated_at) as at')->orderByDesc('deduct_month')->limit(24)->get(),
'cbRebookHits' => $search === null ? collect() : $db->table('courier_bill_rebooks as r')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'r.group_id')
->where('r.waybill_no', $search)->orderBy('r.deduct_month')->get(['r.*', 'g.name as group_name']),
'cbRebookReviewHits' => $search === null ? collect() : $db->table('courier_bill_rebook_reviews')->where('waybill_no', $search)->orderBy('deduct_month')->get(),
]; ];
} }
@ -409,14 +462,17 @@ final class CourierBillController extends Controller
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'], 'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
'summary_carrier' => ['nullable', 'string', 'max:128'], 'bundle' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'], 'summary_carrier' => ['nullable', 'string', 'max:128'], 'bundle' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'],
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'], 'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
], [], ['name' => '分组名称', 'express_names' => '快递名称1']); 'rebook_months' => ['nullable', 'in:0,1,2'],
], [], ['name' => '分组名称', 'express_names' => '快递名称1', 'rebook_months' => '补记账']);
$data['rebook_months'] ??= null;
$exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name'])) $exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name']))
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists(); ->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
if ($exists) { if ($exists) {
throw ValidationException::withMessages(['name' => '分组名称已存在。']); throw ValidationException::withMessages(['name' => '分组名称已存在。']);
} }
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: []; $data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
$this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data); $id = $this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
$this->refreshOpenStatements($id);
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。'); return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
} }
@ -437,6 +493,49 @@ final class CourierBillController extends Controller
return $this->back($request, ['cb_view' => 'ledger'], $message . '。'); return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
} }
/** 导入已经补过的记账(系统上线前手工补的),补过的单以后不再补。 */
public function importRebooks(Request $request)
{
return $this->importRebookFile($request, 'rebooks', '已补记录', function (string $path, string $extension): string {
$r = app(Rebooks::class)->importRefunds($path, $extension);
return '读到 ' . $r['rows'] . ' 行,新增 ' . $r['inserted'] . ' 条已补记录' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
});
}
/** 导入复核记账:这单现在应扣多少,本期补款 = 当时扣的 − 现在应扣。 */
public function importRebookReviews(Request $request)
{
return $this->importRebookFile($request, 'reviews', '复核记账', function (string $path, string $extension, string $name): string {
$r = app(Rebooks::class)->importReviews($path, $extension, $name);
return '读到 ' . $r['rows'] . ' 行,导入 ' . $r['inserted'] . ' 条复核记账' . ($r['rejected'] > 0 ? ',' . $r['rejected'] . ' 行单号、月份或金额认不出,未导入' : '');
});
}
/** 补记账规则改了、复核导了之后,重排还没确认的对账单小汇总。 */
private function importRebookFile(Request $request, string $field, string $label, callable $import)
{
$file = $request->validate([$field => ['required', 'file', 'max:51200']], [], [$field => $label . '文件'])[$field];
$extension = strtolower($file->getClientOriginalExtension());
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
throw ValidationException::withMessages([$field => '只支持 xlsx、xls、csv。']);
}
$message = $this->guard(fn () => $import($file->getRealPath(), $extension, $file->getClientOriginalName()));
$this->refreshOpenStatements();
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
}
private function refreshOpenStatements(?int $groupId = null): void
{
$matcher = app(\App\Support\CourierBills\CourierBillMatcher::class);
$this->store->db()->table('courier_bill_statements')->where('status', 'open')
->when($groupId !== null, fn ($q) => $q->where('group_id', $groupId))
->where('bill_month', '>=', now()->subMonthsNoOverflow(2)->format('Y-m'))->pluck('id')
->each(fn ($id) => $matcher->refreshSummary((int) $id));
}
public function exportStatement(Request $request, int $statement) public function exportStatement(Request $request, int $statement)
{ {
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id') $row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
@ -463,13 +562,16 @@ final class CourierBillController extends Controller
return response()->streamDownload(function () use ($query): void { return response()->streamDownload(function () use ($query): void {
$book = new StreamingWorkbook(); $book = new StreamingWorkbook();
$book->row('对账明细', ['账单月份', '对账分组', '负责人', '快递单号', '快递提供运费', '快递提供重量', '分类', '发货时间', '发货数据快递名称1', $book->row('对账明细', ['账单月份', '对账分组', '负责人', '快递单号', '快递提供运费', '快递提供重量', '分类', '发货时间', '发货数据快递名称1',
'核算运费', '计费重量', '自算金额', '差异', '未发出来源', '处理结果', '处理人'], true); '核算运费', '结算重量', '结算运费', '运费差', '计费重量', '重量差', '未发出来源', '处理结果', '处理人'], true);
foreach ($query->orderBy('l.id')->select(['l.*', 's.bill_month', 'g.name as group_name', 'g.owner'])->lazyById(1000, 'l.id', 'id') as $line) { foreach ($query->orderBy('l.id')->select(['l.*', 's.bill_month', 'g.name as group_name', 'g.owner'])->lazyById(1000, 'l.id', 'id') as $line) {
$comparison = \App\Support\CourierBills\SettlementComparison::courier($line);
$book->row('对账明细', [$line->bill_month, $line->group_name, $line->owner, (string) $line->waybill_no, $book->row('对账明细', [$line->bill_month, $line->group_name, $line->owner, (string) $line->waybill_no,
$line->bill_amount === null ? null : (float) $line->bill_amount, $line->bill_weight === null ? null : (float) $line->bill_weight, $line->bill_amount === null ? null : (float) $line->bill_amount, $line->bill_weight === null ? null : (float) $line->bill_weight,
Category::label((string) $line->category, $line->category_month), $line->ship_time, $line->express_name, Category::label((string) $line->category, $line->category_month), $line->ship_time, $line->express_name,
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->charge_weight === null ? null : (float) $line->charge_weight, $line->calc_freight === null ? null : (float) $line->calc_freight,
$line->self_amount === null ? null : (float) $line->self_amount, round((float) $line->bill_amount - (float) $line->self_amount, 2), $comparison['settlement_weight'],
$line->self_amount === null ? null : (float) $line->self_amount, $comparison['freight_diff'],
$line->charge_weight === null ? null : (float) $line->charge_weight, $comparison['weight_diff'],
$line->unshipped_sources, Category::RESOLUTIONS[$line->resolution] ?? null, $line->resolved_by]); $line->unshipped_sources, Category::RESOLUTIONS[$line->resolution] ?? null, $line->resolved_by]);
} }
$book->writeTo(fopen('php://output', 'wb')); $book->writeTo(fopen('php://output', 'wb'));

View File

@ -3,6 +3,7 @@
namespace App\Http\Controllers\Business; namespace App\Http\Controllers\Business;
use App\Support\CourierBills\CourierBillStore; use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\CourierJointUploads;
use App\Support\CourierBills\CourierUploadLink; use App\Support\CourierBills\CourierUploadLink;
use App\Support\CourierBills\FreightBillTemplate; use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBillImports; use App\Support\CourierBills\PortalFreightBillImports;
@ -30,17 +31,20 @@ final class CourierUploadShare extends Controller
{ {
$t = $this->target($request, $token); $t = $this->target($request, $token);
$expires = $this->expiresAt($request); $expires = $this->expiresAt($request);
$files = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']) $query = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']);
->orderByDesc('id')->limit(20)->get(); if ($t['joint'] !== null) $query->where('extra_group_ids', json_encode(['joint_upload' => $t['payload']['joint']]));
else $query->where(fn ($q) => $q->whereNull('extra_group_ids')->orWhere('extra_group_ids', 'not like', '%"joint_upload"%'));
$files = $query->orderByDesc('id')->limit(20)->get();
$pending = array_map(static fn (array $file): object => (object) [ $pending = array_map(static fn (array $file): object => (object) [
'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'], 'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'],
'status' => $file['status'], 'message' => $file['message'], 'created_at' => $file['at'], 'status' => $file['status'], 'message' => $file['message'], 'created_at' => $file['at'],
], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'])); ], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'], $t['joint']['key'] ?? null));
$files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values(); $files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values();
return response()->view('business.pages.courier-payables.courier-bills.upload-share', [ return response()->view('business.pages.courier-payables.courier-bills.upload-share', [
'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files, 'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files,
'expiresAt' => $expires, 'confirmed' => $t['confirmed'], 'expiresAt' => $expires, 'confirmed' => $t['confirmed'],
'joint' => $t['joint'], 'uploadLabel' => $t['joint']['label'] ?? $t['group']->name,
'uploadUrl' => $this->links->signedRoute('signed.courier-bill-upload.upload', $token, $t['companyId'], $expires), 'uploadUrl' => $this->links->signedRoute('signed.courier-bill-upload.upload', $token, $t['companyId'], $expires),
'templateUrl' => $this->links->signedRoute('signed.courier-bill-upload.template', $token, $t['companyId'], $expires), 'templateUrl' => $this->links->signedRoute('signed.courier-bill-upload.template', $token, $t['companyId'], $expires),
])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive', ])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive',
@ -51,7 +55,7 @@ final class CourierUploadShare extends Controller
{ {
$t = $this->target($request, $token); $t = $this->target($request, $token);
return $this->template->download($t['group']->name . '_' . $t['month'] . '_账单上传模板.xlsx'); return $this->template->download(($t['joint']['label'] ?? $t['group']->name) . '_' . $t['month'] . '_账单上传模板.xlsx');
} }
public function upload(Request $request, string $token): RedirectResponse public function upload(Request $request, string $token): RedirectResponse
@ -71,13 +75,14 @@ final class CourierUploadShare extends Controller
'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'], 'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'],
'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'], 'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'],
'source' => 'courier_upload_link', 'source' => 'courier_upload_link',
'joint' => $t['payload']['joint'],
'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64), 'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64),
]); ]);
return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。'); return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。');
} }
/** @return array{companyId:int,group:object,month:string,confirmed:bool} */ /** @return array{companyId:int,group:object,month:string,confirmed:bool,joint:?array,payload:array} */
private function target(Request $request, string $token): array private function target(Request $request, string $token): array
{ {
$companyId = (int) ($request->route('company_id') ?: company_id() ?: 1); $companyId = (int) ($request->route('company_id') ?: company_id() ?: 1);
@ -85,10 +90,15 @@ final class CourierUploadShare extends Controller
abort_if($payload === null, 404, '链接无效或已过期。'); abort_if($payload === null, 404, '链接无效或已过期。');
$group = collect($this->store->groups())->firstWhere('id', $payload['group_id']); $group = collect($this->store->groups())->firstWhere('id', $payload['group_id']);
abort_if($group === null, 404, '链接无效或已过期。'); abort_if($group === null, 404, '链接无效或已过期。');
$confirmed = $this->store->db()->table('courier_bill_statements')->where('group_id', $group->id) $joint = null;
if ($payload['joint'] !== null) {
try { $joint = app(CourierJointUploads::class)->verify($payload['joint']); }
catch (\RuntimeException $e) { abort(410, $e->getMessage()); }
}
$confirmed = $this->store->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$group->id])
->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists(); ->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists();
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed]; return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed, 'joint' => $joint, 'payload' => $payload];
} }
private function expiresAt(Request $request): CarbonImmutable private function expiresAt(Request $request): CarbonImmutable

View File

@ -4,8 +4,11 @@ namespace App\Http\Controllers\Business;
use App\Support\CourierBills\Category; use App\Support\CourierBills\Category;
use App\Support\CourierBills\StreamingWorkbook; use App\Support\CourierBills\StreamingWorkbook;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use App\Support\DropshipFreight\DropshipConfirmation; use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipBillSummary;
use App\Support\DropshipFreight\DropshipExporter; use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipOverviewExporter;
use App\Support\DropshipFreight\DropshipFees; use App\Support\DropshipFreight\DropshipFees;
use App\Support\DropshipFreight\DropshipFreightStore; use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipReconciler; use App\Support\DropshipFreight\DropshipReconciler;
@ -95,6 +98,20 @@ final class DropshipFreightController extends Controller
$result = $this->reconciler->factoryMonth($factory, $month); $result = $this->reconciler->factoryMonth($factory, $month);
$status = (string) $request->query('status', ''); $status = (string) $request->query('status', '');
$rows = $result['rows']; $rows = $result['rows'];
if (in_array($status, ['weight_diff', 'price_diff', 'missing_weight'], true)) {
$rows = array_values(array_filter($rows, static fn (array $r): bool => $r['diff_kind'] === $status));
}
$state = $this->confirmations->state($month, (int) $factory->id, self::companyId());
$disputes = $this->confirmations->disputes($month, (int) $factory->id, self::companyId());
$currentDisputes = array_values(array_filter($disputes, fn ($d) => (int) $d['version'] === (int) ($state['version'] ?? 0)));
$disputeMap = array_column($currentDisputes, null, 'waybill');
if ($status === 'disputed') {
$rows = array_values(array_filter($rows, fn ($r) => isset($disputeMap[$r['waybill']])));
}
$search = mb_substr(trim((string) $request->query('q', '')), 0, 64);
if ($search !== '') {
$rows = array_values(array_filter($rows, fn ($r) => str_contains(strtoupper($r['waybill']), strtoupper($search))));
}
if ($status === 'attention') { if ($status === 'attention') {
$rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true))); $rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true)));
} elseif (array_key_exists($status, DropshipReconciler::LABELS)) { } elseif (array_key_exists($status, DropshipReconciler::LABELS)) {
@ -106,9 +123,16 @@ final class DropshipFreightController extends Controller
$files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get(); $files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get();
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files, return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files,
'dfState' => $this->confirmations->state($month, (int) $factory->id, self::companyId()), 'dfBillSummary' => app(DropshipBillSummary::class)->build($factory, $month, $result['rows']),
'dfDisputes' => $this->confirmations->disputes($month, (int) $factory->id, self::companyId()), 'dfState' => $state, 'dfDisputes' => $disputes, 'dfCurrentDisputes' => $currentDisputes, 'dfDisputeMap' => $disputeMap,
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name)]; 'dfSearch' => $search, 'dfFactoryStates' => $this->confirmations->states($month,self::companyId()), 'dfHistory' => $this->confirmations->history($month, (int)$factory->id, self::companyId()),
'dfFeesDetail' => app(DropshipFees::class)->rows($month, [(int)$factory->id => $result['summary']['settle']], self::companyId())[(int)$factory->id],
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name),
'dfSurchargeRows' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('dropship',(int)$factory->id,$month)->orderBy('id')->paginate(50,['*'],'fee_page')->withQueryString() : null,
'dfSurchargeSummary' => app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->ready()
? app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->query('dropship',(int)$factory->id,$month)
->selectRaw('item,SUM(bill_amount) AS bill,SUM(self_amount) AS self')->groupBy('item')->get() : collect()];
} }
private function uploadData(string $month): array private function uploadData(string $month): array
@ -202,6 +226,26 @@ final class DropshipFreightController extends Controller
. ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。'); . ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。');
} }
public function rematch(Request $request, int $factory)
{
$data = $request->validate([
'month' => ['required', 'date_format:Y-m'],
'df_view' => ['nullable', 'in:overview,factory'],
]);
$f = $this->factory($factory);
$state = $this->confirmations->state($data['month'], (int) $f->id, self::companyId());
if (($state['status'] ?? null) === DropshipConfirmation::CONFIRMED) {
throw ValidationException::withMessages(['dropship' => '厂家已确认的账单不能重新匹配。']);
}
$this->guard(fn () => app(SurchargeSettlementMatcher::class)->dropship((int) $f->id, $data['month']));
// 运费分类实时计算,返回页面时读取最新发货和核算数据;附加费需刷新持久化的匹配结果。
$view = $data['df_view'] ?? 'factory';
return $this->back($request, ['df_view' => $view, 'month' => $data['month'],
...($view === 'factory' ? ['factory' => (int) $f->id] : [])],
'已按最新发货数据、核算运费和附加费重新匹配「' . $f->name . '」' . $data['month'] . ' 的账单。');
}
/** 财务点「核对完成」/「撤销」:核对完成的厂家才能推送给厂家确认。 */ /** 财务点「核对完成」/「撤销」:核对完成的厂家才能推送给厂家确认。 */
public function check(Request $request, int $factory) public function check(Request $request, int $factory)
{ {
@ -238,13 +282,19 @@ final class DropshipFreightController extends Controller
$f = $this->factory($factory); $f = $this->factory($factory);
$result = $this->reconciler->factoryMonth($f, $month); $result = $this->reconciler->factoryMonth($f, $month);
$summary = $result['summary']; $summary = $result['summary'];
$feeDetail = app(DropshipFees::class)->rows($month, [(int)$f->id => $summary['settle']], self::companyId())[(int)$f->id];
$summary['total'] = $feeDetail['total'];
$fees = [];
foreach (DropshipFees::COLUMNS as $key => $label) {
$fees[] = ['label' => $label, 'amount' => $key === 'booking' ? -abs($feeDetail['values'][$key]) : $feeDetail['values'][$key]];
}
$attention = self::attention($result['rows']); $attention = self::attention($result['rows']);
$notifier = app(SupplierDingTalkNotifier::class); $notifier = app(SupplierDingTalkNotifier::class);
if (! $notifier->configuration((string) $f->name)['configured']) { if (! $notifier->configuration((string) $f->name)['configured']) {
throw ValidationException::withMessages(['dropship' => '「' . $f->name . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']); throw ValidationException::withMessages(['dropship' => '「' . $f->name . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']);
} }
$companyId = self::companyId(); $companyId = self::companyId();
$version = $this->guard(fn () => $this->confirmations->startPush($month, $f, $summary, $attention, $companyId, user()?->id, self::user())); $version = $this->guard(fn () => $this->confirmations->startPush($month, $f, $summary, $attention, $companyId, user()?->id, self::user(), $result['rows'], $fees));
$url = app(DropshipShareLink::class)->pageUrl($companyId, (int) $f->id, $month, $version); $url = app(DropshipShareLink::class)->pageUrl($companyId, (int) $f->id, $month, $version);
try { try {
$notifier->pushDropshipFreight((string) $f->name, $month, $summary, $attention, $version, $url); $notifier->pushDropshipFreight((string) $f->name, $month, $summary, $attention, $version, $url);
@ -321,8 +371,14 @@ final class DropshipFreightController extends Controller
public function export(Request $request) public function export(Request $request)
{ {
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]); $data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer'], 'summary' => ['nullable', 'boolean']]);
$month = $data['month']; $month = $data['month'];
if ($request->boolean('summary')) {
$overview = $this->overviewData($month);
return response()->streamDownload(static function () use ($overview): void {
app(DropshipOverviewExporter::class)->write($overview, fopen('php://output', 'wb'));
}, '代发运费各厂家汇总_' . $month . '.xlsx');
}
$factories = collect($this->store->factories()); $factories = collect($this->store->factories());
if (! empty($data['factory'])) { if (! empty($data['factory'])) {
$factories = $factories->where('id', (int) $data['factory'])->values(); $factories = $factories->where('id', (int) $data['factory'])->values();
@ -372,10 +428,10 @@ final class DropshipFreightController extends Controller
} }
foreach ($details as [$factory, $rows]) { foreach ($details as [$factory, $rows]) {
$sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28); $sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28);
$book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '最终结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true); $book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算重量', '结算运费', '最终结算运费', '运费差', '厂家重量', '我方计费重量', '重量差', '状态', '说明', '核算公式'], true);
foreach ($rows as $r) { foreach ($rows as $r) {
$book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settle'], $book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settlement_weight'], $r['settle'],
$r['final'] ?? $r['settle'], $r['diff'], $r['label'], $r['note'], $r['formula']]); $r['final'] ?? $r['settle'], $r['freight_diff'], $r['bill_weight'], $r['charge_weight'], $r['weight_diff'], $r['label'], $r['note'], $r['formula']]);
} }
} }
$book->writeTo(fopen('php://output', 'wb')); $book->writeTo(fopen('php://output', 'wb'));

View File

@ -2,180 +2,7 @@
namespace App\Http\Controllers\Business; namespace App\Http\Controllers\Business;
use App\Support\CourierBills\Category; final class DropshipFreightShare extends FreightConfirmationShare
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipReconciler;
use App\Support\DropshipFreight\DropshipShareLink;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
/**
* 钉钉群推送的代发运费确认页(免登录,同供应商对账的货款确认页):
* 厂家看本账期每一单的结算结果,没有异议点「确认无异议」,对某一单有异议就勾选那一单写原因提交。
*/
final class DropshipFreightShare extends Controller
{ {
/** 确认页上逐单列出的「要看的单」最多这么多行,其余可下载 Excel 后在文本框里填。 */ protected string $kind = 'dropship';
private const MAX_ROWS = 500; }
public function __construct(
private readonly DropshipFreightStore $store,
private readonly DropshipReconciler $reconciler,
private readonly DropshipConfirmation $confirmations,
private readonly DropshipShareLink $links,
) {}
public function show(Request $request, string $token): Response
{
$t = $this->target($request, $token);
$current = (int) ($t['state']['version'] ?? 0) === $t['version'];
$rows = $t['rows'];
$attention = array_values(array_filter($rows, static fn (array $r): bool => $r['status'] !== Category::MATCH));
$expires = $this->expiresAt($request);
$submitted = in_array($t['state']['status'] ?? '', [DropshipConfirmation::CONFIRMED, DropshipConfirmation::DISPUTED], true);
return response()->view('business.pages.courier-payables.dropship-freight.share', [
'factory' => $t['factory']->name, 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']),
'version' => $t['version'], 'current' => $current, 'state' => $t['state'], 'submitted' => $current && $submitted,
'summary' => $t['summary'], 'attention' => array_slice($attention, 0, self::MAX_ROWS), 'attentionTotal' => count($attention),
'matchCount' => count($rows) - count($attention), 'maxRows' => self::MAX_ROWS,
'disputes' => $current ? $this->confirmations->disputes($t['month'], (int) $t['factory']->id, $t['companyId'], $t['version']) : [],
'expiresAt' => $expires,
'submitUrl' => $this->links->signedRoute('signed.dropship-freight.submit', $token, $t['companyId'], $expires),
'excelUrl' => $this->links->signedRoute('signed.dropship-freight.excel', $token, $t['companyId'], $expires),
])->withHeaders([
'Cache-Control' => 'private, no-store, max-age=0',
'X-Robots-Tag' => 'noindex, nofollow, noarchive',
'Referrer-Policy' => 'no-referrer',
]);
}
public function submit(Request $request, string $token): RedirectResponse
{
$t = $this->target($request, $token);
$data = $request->validate([
'd' => ['nullable', 'array', 'max:' . self::MAX_ROWS], 'd.*' => ['string', 'max:64'],
'r' => ['nullable', 'array'], 'r.*' => ['nullable', 'string', 'max:200'],
'other' => ['nullable', 'string', 'max:20000'],
]);
$billed = array_flip(array_map(static fn (array $r): string => strtoupper((string) $r['waybill']), $t['rows']));
$byUpper = [];
foreach ($t['rows'] as $r) {
$byUpper[strtoupper((string) $r['waybill'])] = (string) $r['waybill'];
}
$disputes = [];
foreach ((array) ($data['d'] ?? []) as $waybill) {
$reason = trim((string) (($data['r'] ?? [])[$waybill] ?? ''));
if ($reason === '') {
throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 勾选了有异议,请写上原因。']);
}
$disputes[$waybill] = $reason;
}
foreach (preg_split('/\R/u', (string) ($data['other'] ?? '')) ?: [] as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$parts = preg_split('/[\s,,::\t]+/u', $line, 2) ?: [];
$waybill = trim((string) ($parts[0] ?? ''), " \t@");
$reason = trim((string) ($parts[1] ?? ''));
if ($reason === '') {
throw ValidationException::withMessages(['dispute' => '「' . $line . '」:请按「单号 原因」填写,单号后面写上原因。']);
}
$disputes[$waybill] = mb_substr($reason, 0, 200);
}
$normalized = [];
foreach ($disputes as $waybill => $reason) {
$key = strtoupper(trim((string) $waybill));
if (! isset($billed[$key])) {
throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 不在本账期你们开的运费账单里,请核对单号。']);
}
$normalized[$byUpper[$key]] = $reason;
}
try {
$state = $this->confirmations->submit($t['month'], (int) $t['factory']->id, $t['version'], $normalized, $t['companyId']);
} catch (RuntimeException $error) {
throw ValidationException::withMessages(['dispute' => $error->getMessage()]);
}
$message = $normalized === [] ? '已确认无异议,财务系统已实时收到。' : '已提交 ' . count($normalized) . ' 单异议,财务核实后会在群里回复。';
try {
if (app(SupplierDingTalkNotifier::class)->sendDropshipFreightReceipt((string) $t['factory']->name, $t['month'],
(float) ($state['settle'] ?? $t['summary']['settle']), $normalized)) {
$message .= '回执已发到钉钉群。';
}
} catch (Throwable $error) {
report($error);
}
return redirect()->to($this->links->signedRoute('signed.dropship-freight.show', $token, $t['companyId'], $this->expiresAt($request)))
->with('success', $message);
}
/** 厂家版对账单:汇总 + 明细(每单的厂家运费、应结运费、状态和说明),不含内部核算公式。 */
public function excel(Request $request, string $token): StreamedResponse
{
$t = $this->target($request, $token);
$s = $t['summary'];
$name = str_replace(['/', '\\'], '-', (string) $t['factory']->name) . '_' . $t['month'] . '_代发运费对账单.xlsx';
return response()->streamDownload(function () use ($t, $s): void {
$book = new StreamingWorkbook();
$book->row('汇总', ['厂家', '账期', '厂家开运费单数', '厂家运费', '应结运费', '差额(厂家−应结)'], true);
$book->row('汇总', [$t['factory']->name, self::monthLabel($t['month']), $s['billed'], $s['bill'], $s['settle'], $s['diff']]);
$book->row('汇总', []);
$book->row('汇总', ['分类', '单数'], true);
foreach (DropshipReconciler::LABELS as $key => $label) {
if ($key !== Category::UNPROVIDED && ($s['counts'][$key] ?? 0) > 0) {
$book->row('汇总', [$label, $s['counts'][$key]]);
}
}
$book->row('明细', ['快递单号', '发货时间', '快递名称', '厂家运费', '应结运费', '差额(厂家−应结)', '状态', '说明'], true);
foreach ($t['rows'] as $r) {
$book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['final'] ?? $r['settle'] ?? 0,
round((float) $r['bill'] - (float) ($r['final'] ?? $r['settle'] ?? 0), 2), $r['label'], $r['note']]);
}
$book->writeTo(fopen('php://output', 'wb'));
}, $name);
}
/** @return array{companyId:int,factory:object,month:string,version:int,state:array,rows:list<array>,summary:array} */
private function target(Request $request, string $token): array
{
$companyId = (int) ($request->route('company_id') ?: company_id() ?: 1);
$payload = $this->links->resolveToken($token, $companyId);
abort_if($payload === null, 404, '链接无效或已过期。');
$factory = collect($this->store->factories())->firstWhere('id', $payload['factory_id']);
abort_if($factory === null, 404, '链接无效或已过期。');
$result = $this->reconciler->factoryMonth($factory, $payload['month']);
// 厂家看的是他们开了运费的单;厂家没开的单(厂家未提供)本来就不付,不放在确认页
$rows = array_values(array_filter($result['rows'], static fn (array $r): bool => $r['bill'] !== null));
return ['companyId' => $companyId, 'factory' => $factory, 'month' => $payload['month'], 'version' => $payload['version'],
'state' => $this->confirmations->state($payload['month'], (int) $factory->id, $companyId) ?? [],
'rows' => $rows, 'summary' => $result['summary']];
}
private function expiresAt(Request $request): CarbonImmutable
{
$expires = (int) $request->query('expires', 0);
return $expires > 0 ? CarbonImmutable::createFromTimestamp($expires) : CarbonImmutable::now()->addDays(DropshipShareLink::TTL_DAYS);
}
private static function monthLabel(string $month): string
{
[$y, $m] = explode('-', $month);
return (int) $y . '年' . (int) $m . '月';
}
}

View File

@ -0,0 +1,160 @@
<?php
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\{Category, CourierBillStore, CourierFreightLink, FreightConfirmation, Rebooks, SurchargeSettlementMatcher};
use App\Support\DropshipFreight\{DropshipConfirmation, DropshipFreightStore, DropshipReconciler};
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Throwable;
final class FreightConfirmationController extends Controller
{
public static function courierData(int $id): array
{
$db = app(CourierBillStore::class)->db();
$statement = $db->table('courier_bill_statements')->find($id);
abort_if(!$statement, 404);
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$party = (object) ['id' => $id, 'name' => $group->name];
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get();
$items = app(SurchargeSettlementMatcher::class)->summaryItems($id, $items);
$items = app(Rebooks::class)->summaryItems($id, $items);
$sum = $db->table('courier_bill_lines')->where('statement_id', $id)->selectRaw('COUNT(*) as n, SUM(bill_amount) as bill, SUM(self_amount) as settle')->first();
$summary = ['billed' => (int) $sum->n, 'bill' => round((float) $sum->bill, 2), 'settle' => round((float) $sum->settle, 2), 'diff' => round((float) $sum->bill - (float) $sum->settle, 2), 'total' => round($items->sum(fn ($r) => (float) $r->self_amount), 2)];
$fees = $items->map(fn ($r) => ['label' => $r->label, 'amount' => (float) $r->self_amount])->all();
return compact('statement', 'party', 'summary', 'fees');
}
public function push(Request $request, int $statement)
{
$t = self::courierData($statement);
$company = (int) (company_id() ?: 1);
if ($t['statement']->status !== 'confirmed') {
throw ValidationException::withMessages(['confirmation' => '请先完成核对并确认结算,再推送本组账单。']);
}
$notifier = app(SupplierDingTalkNotifier::class);
if (!$notifier->configuration($t['party']->name)['configured']) {
throw ValidationException::withMessages(['confirmation' => '请先为这个对账分组配置钉钉群机器人。']);
}
$c = app(FreightConfirmation::class);
$month = $t['statement']->bill_month;
$db = app(CourierBillStore::class)->db();
$attention = $db->table('courier_bill_lines')->where('statement_id', $statement)->where('category', '<>', Category::MATCH)->count();
try {
if (!$c->state($month, $statement, $company)) {
$c->check($month, $t['party'], $t['summary'], true, $company, user()?->id, self::by());
}
$rows = (function () use ($db, $statement) {
foreach ($db->table('courier_bill_lines')->where('statement_id', $statement)->orderBy('id')->lazyById(500) as $r) {
yield ['waybill' => $r->waybill_no, 'ship_time' => $r->ship_time, 'express' => $r->express_name, 'bill' => $r->bill_amount === null ? null : (float) $r->bill_amount, 'final' => $r->self_amount === null ? null : (float) $r->self_amount, 'status' => $r->category, 'label' => Category::label($r->category, $r->category_month), 'note' => Category::RESOLUTIONS[$r->resolution ?? ''] ?? Category::label($r->category, $r->category_month)];
}
})();
$version = $db->transaction(function () use ($db, $statement, $c, $month, $t, $attention, $company, $rows) {
// Prevent an unconfirm/rematch from changing the source while this version is copied.
$locked = $db->table('courier_bill_statements')->lockForUpdate()->find($statement);
if (!$locked || $locked->status !== 'confirmed' || $locked->updated_at !== $t['statement']->updated_at) {
throw new RuntimeException('对账单已发生变化,请刷新后再推送。');
}
return $c->startPush($month, $t['party'], $t['summary'], $attention, $company, user()?->id, self::by(), $rows, $t['fees']);
});
} catch (RuntimeException $e) {
throw ValidationException::withMessages(['confirmation' => $e->getMessage()]);
}
try {
$url = app(CourierFreightLink::class)->pageUrl($company, $statement, $month, $version);
$notifier->pushFreightConfirmation($t['party']->name, $month, $t['summary'], $version, $url);
$c->markPushed($month, $statement, $company);
} catch (Throwable $e) {
$c->markFailed($month, $statement, $company, '群推送失败,请检查机器人后重试。');
report($e);
throw ValidationException::withMessages(['confirmation' => '群推送失败,账单已保留,可重新推送。']);
}
return back()->with('courier_bills_message', '已推送到「' . $t['party']->name . '」钉钉群,版本 V' . $version . '。');
}
public function review(Request $request, int $owner)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'version' => ['required', 'integer', 'min:1'], 'waybill' => ['required', 'string', 'max:64'], 'decision' => ['required', 'in:accept,reject'], 'reply' => ['required', 'string', 'max:1000']]);
$kind = $request->route('kind');
$company = (int) (company_id() ?: 1);
[$c, $party] = $this->context($kind, $owner, $data['month']);
// Refresh only this owner's existing calculation. No source price or ledger changes are made by feedback.
if ($kind === 'dropship') {
$row = collect(app(DropshipReconciler::class)->factoryMonth($party, $data['month'])['rows'])->firstWhere('waybill', $data['waybill']);
$amount = $row['final'] ?? null;
} else {
$row = app(CourierBillStore::class)->db()->table('courier_bill_lines')->where('statement_id', $owner)->where('waybill_no', $data['waybill'])->selectRaw('SUM(self_amount) as amount')->first();
$amount = $row?->amount === null ? null : (float) $row->amount;
}
try {
$review = $c->review($data['month'], $owner, (int) $data['version'], $data['waybill'], $data['decision'], $data['reply'], $amount, $company, user()?->id, self::by());
} catch (RuntimeException $e) {
throw ValidationException::withMessages(['confirmation' => $e->getMessage()]);
}
$this->sendReview($c, $party->name, $kind, $owner, $data['month'], (int) $data['version'], $company, $review);
return back()->with($kind === 'dropship' ? 'dropship_message' : 'courier_bills_message', '已保存财务处理结果;金额有变化时请重新推送新版账单。');
}
public function retry(Request $request, int $owner)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'waybill' => ['nullable', 'string', 'max:64']]);
$kind = $request->route('kind');
$company = (int) (company_id() ?: 1);
[$c, $party] = $this->context($kind, $owner, $data['month']);
$state = $c->state($data['month'], $owner, $company);
abort_if(!$state, 404);
$version = (int) $state['version'];
if (!empty($data['waybill'])) {
$review = collect($c->disputes($data['month'], $owner, $company, $version))->firstWhere('waybill', $data['waybill']);
abort_if(!$review || !isset($review['decision']) || ($review['receipt_status'] ?? '') === 'sent', 422);
$this->sendReview($c, $party->name, $kind, $owner, $data['month'], $version, $company, $review);
} else {
abort_if(($state['receipt_status'] ?? '') !== 'failed', 422);
$disputes = array_column($c->disputes($data['month'], $owner, $company, $version), 'reason', 'waybill');
$error = null;
try {
$n = app(SupplierDingTalkNotifier::class);
$sent = $kind === 'dropship' ? $n->sendDropshipFreightReceipt($party->name, $data['month'], (float) $state['settle'], $disputes) : $n->sendFreightConfirmationReceipt($party->name, $data['month'], (float) $state['settle'], $disputes);
if (!$sent) {
throw new RuntimeException('未配置群机器人');
}
} catch (Throwable $e) {
report($e);
$error = '群回执发送失败,请检查机器人后重试。';
}
$c->markReceipt($data['month'], $owner, $version, $company, $error);
}
return back()->with($kind === 'dropship' ? 'dropship_message' : 'courier_bills_message', '回执发送已处理,请查看回执状态。');
}
private function context(string $kind, int $owner, string $month): array
{
if ($kind === 'dropship') {
$party = collect(app(DropshipFreightStore::class)->factories())->firstWhere('id', $owner);
abort_if(!$party, 404);
return [app(DropshipConfirmation::class), $party];
}
$t = self::courierData($owner);
abort_if($t['statement']->bill_month !== $month, 404);
return [app(FreightConfirmation::class), $t['party']];
}
private function sendReview(FreightConfirmation $c, string $name, string $kind, int $owner, string $month, int $version, int $company, array $review): void
{
$error = null;
try {
app(SupplierDingTalkNotifier::class)->sendFreightReview($name, $kind, $month, $version, $review);
} catch (Throwable $e) {
report($e);
$error = '群回复发送失败,请重试。';
}
$c->markReceipt($month, $owner, $version, $company, $error, $review['waybill']);
}
private static function by(): string
{
return (string) (user()?->name ?? user()?->email ?? 'system');
}
}

View File

@ -0,0 +1,181 @@
<?php
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\{Category, CourierBillStore, CourierFreightLink, FreightConfirmation, StreamingWorkbook};
use App\Support\DropshipFreight\{DropshipConfirmation, DropshipFreightStore, DropshipReconciler, DropshipShareLink};
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Throwable;
class FreightConfirmationShare extends Controller
{
protected string $kind = 'courier';
protected function confirmations(): FreightConfirmation
{
return app($this->kind === 'dropship' ? DropshipConfirmation::class : FreightConfirmation::class);
}
protected function links(): DropshipShareLink|CourierFreightLink
{
return app($this->kind === 'dropship' ? DropshipShareLink::class : CourierFreightLink::class);
}
private function url(Request $request, string $token, int $company, string $action, array $query = []): string
{
return $this->links()->signedRoute('signed.' . ($this->kind === 'dropship' ? 'dropship' : 'courier') . '-freight.' . $action, $token, $company, CarbonImmutable::createFromTimestamp((int) $request->query('expires')), $query);
}
private function target(Request $request, string $token): array
{
$company = (int) (($request->route('company_id') ?: company_id()) ?: 1);
$p = $this->links()->resolveToken($token, $company);
abort_if(!$p, 404);
$owner = $p['factory_id'];
$month = $p['month'];
$version = $p['version'];
if ($this->kind === 'dropship') {
$party = collect(app(DropshipFreightStore::class)->factories())->firstWhere('id', $owner);
} else {
$db = app(CourierBillStore::class)->db();
$statement = $db->table('courier_bill_statements')->where('id', $owner)->where('bill_month', $month)->first();
$party = $statement ? $db->table('courier_bill_groups')->find($statement->group_id) : null;
}
abort_if(!$party, 404);
$c = $this->confirmations();
$state = $c->state($month, $owner, $company) ?? [];
$snapshot = $c->snapshot($month, $owner, $version, $company);
$legacy = [];
$legacyVersion = !$snapshot;
if (!$snapshot && $this->kind === 'dropship') {
$result = app(DropshipReconciler::class)->factoryMonth($party, $month);
$legacy = array_values(array_filter($result['rows'], fn ($r) => $r['bill'] !== null));
$snapshot = ['summary' => $result['summary'], 'fees' => [], 'rows' => count($legacy)];
}
abort_if(!$snapshot, 404);
return compact('company', 'owner', 'month', 'version', 'party', 'state', 'snapshot', 'legacy', 'legacyVersion');
}
public function show(Request $request, string $token)
{
$t = $this->target($request, $token);
$data = $request->validate(['q' => ['nullable', 'string', 'max:64'], 'filter' => ['nullable', 'in:all,attention'], 'page' => ['nullable', 'integer', 'min:1']]);
$q = trim($data['q'] ?? '');
$filter = $data['filter'] ?? 'attention';
$page = max(1, (int) ($data['page'] ?? 1));
$c = $this->confirmations();
if ($t['legacy'] !== []) {
$all = array_values(array_filter($t['legacy'], fn ($r) => ($filter === 'all' || $r['status'] !== Category::MATCH) && ($q === '' || str_contains($r['waybill'], $q))));
$rows = array_slice($all, ($page - 1) * 50, 50);
$total = count($all);
} else {
$query = $c->snapshotQuery($t['month'], $t['owner'], $t['version'], $t['company']);
if ($filter !== 'all') {
$query->where('values->status', '<>', Category::MATCH);
}
if ($q !== '') {
$query->where('values->waybill', 'like', '%' . addcslashes($q, '%_\\') . '%');
}
$total = (clone $query)->count();
$rows = $query->orderBy('id')->offset(($page - 1) * 50)->limit(50)->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
}
$current = (int) ($t['state']['version'] ?? 0) === $t['version'];
$disputes = $c->disputes($t['month'], $t['owner'], $t['company'], $t['version']);
return response()->view('business.pages.courier-payables.confirmation.share', $t + ['kind' => $this->kind, 'q' => $q, 'filter' => $filter, 'rows' => $rows, 'total' => $total, 'page' => $page, 'current' => $current, 'submitted' => in_array($t['state']['status'] ?? '', [FreightConfirmation::CONFIRMED, FreightConfirmation::DISPUTED], true), 'disputes' => $disputes, 'summary' => $t['snapshot']['summary'], 'draftKey' => hash('sha256', $token), 'expiresAt' => CarbonImmutable::createFromTimestamp((int) $request->query('expires'))->setTimezone('Asia/Shanghai'), 'submitUrl' => $this->url($request, $token, $t['company'], 'submit'), 'viewUrl' => $this->url($request, $token, $t['company'], 'view'), 'excelUrl' => $this->url($request, $token, $t['company'], 'excel'), 'prevUrl' => $page > 1 ? $this->url($request, $token, $t['company'], 'show', ['q' => $q, 'filter' => $filter, 'page' => $page - 1]) : null, 'nextUrl' => $page * 50 < $total ? $this->url($request, $token, $t['company'], 'show', ['q' => $q, 'filter' => $filter, 'page' => $page + 1]) : null])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive', 'Referrer-Policy' => 'no-referrer']);
}
public function submit(Request $request, string $token)
{
$t = $this->target($request, $token);
$data = $request->validate(['d' => ['nullable', 'array', 'max:500'], 'd.*' => ['string', 'max:64'], 'r' => ['nullable', 'array', 'max:500'], 'r.*' => ['nullable', 'string', 'max:200'], 'other' => ['nullable', 'string', 'max:20000'], 'draft' => ['nullable', 'json', 'max:200000']]);
$disputes = [];
if (!empty($data['draft'])) {
$draft = json_decode($data['draft'], true);
if (!is_array($draft) || count($draft) > 500) throw ValidationException::withMessages(['dispute' => '一次最多提交 500 单异议。']);
foreach ($draft as $waybill => $reason) {
if (!is_string($reason) || trim($reason) === '' || mb_strlen($reason) > 200 || strlen((string)$waybill) > 64) {
throw ValidationException::withMessages(['dispute' => '请检查异议单号及原因,每单原因最多 200 字。']);
}
$disputes[strtoupper(trim((string)$waybill))] = trim($reason);
}
}
foreach ($data['d'] ?? [] as $waybill) {
$reason = trim($data['r'][$waybill] ?? '');
if ($reason === '') {
throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 请写上异议原因。']);
}
$disputes[strtoupper(trim($waybill))] = $reason;
}
foreach (preg_split('/\R/u', $data['other'] ?? '') as $line) {
if (trim($line) === '') {
continue;
}
$parts = preg_split('/[\s,,::]+/u', trim($line), 2);
if (count($parts) !== 2) {
throw ValidationException::withMessages(['dispute' => '请按「单号 原因」逐行填写。']);
}
$disputes[strtoupper($parts[0])] = mb_substr(trim($parts[1]), 0, 200);
}
if ($t['legacy'] !== []) {
$allowed = [];
foreach ($t['legacy'] as $row) $allowed[strtoupper($row['waybill'])] = $row['waybill'];
if (array_diff(array_keys($disputes), array_keys($allowed))) {
throw ValidationException::withMessages(['dispute' => '单号不在本期账单中。']);
}
$normalized = [];
foreach ($disputes as $waybill => $reason) $normalized[$allowed[$waybill]] = $reason;
$disputes = $normalized;
}
$c = $this->confirmations();
try {
$state = $c->submit($t['month'], $t['owner'], $t['version'], $disputes, $t['company']);
} catch (RuntimeException $e) {
throw ValidationException::withMessages(['dispute' => $e->getMessage()]);
}
$message = $disputes === [] ? '已确认无异议,财务系统已实时收到。' : '已提交 ' . count($disputes) . ' 单异议,财务核实后会在群里回复。';
$error = null;
try {
$notifier = app(SupplierDingTalkNotifier::class);
$sent = $this->kind === 'dropship' ? $notifier->sendDropshipFreightReceipt($t['party']->name, $t['month'], (float) $state['settle'], $disputes) : $notifier->sendFreightConfirmationReceipt($t['party']->name, $t['month'], (float) $state['settle'], $disputes);
if (!$sent) {
throw new RuntimeException('未配置群机器人');
}
$message .= '回执已发到钉钉群。';
} catch (Throwable $e) {
report($e);
$error = '群回执发送失败,请财务重发。';
$message .= $error;
}
$c->markReceipt($t['month'], $t['owner'], $t['version'], $t['company'], $error);
return redirect()->to($this->url($request, $token, $t['company'], 'show'))->with('success', $message);
}
public function excel(Request $request, string $token)
{
$t = $this->target($request, $token);
return response()->streamDownload(function () use ($t) {
$book = new StreamingWorkbook();
$s = $t['snapshot']['summary'];
$book->row('汇总', ['合作方', '账期', '账单金额', '应结运费', '差额', '版本'], true);
$book->row('汇总', [$t['party']->name, $t['month'], $s['bill'], $s['settle'], $s['diff'], $t['version']]);
$book->row('费用', ['项目', '应结金额'], true);
foreach ($t['snapshot']['fees'] ?? [] as $fee) {
$book->row('费用', [$fee['label'], $fee['amount']]);
}
$book->row('明细', ['快递单号', '发货时间', '快递名称', '账单运费', '应结运费', '差额', '状态', '说明'], true);
$rows = $t['legacy'] ?: $this->confirmations()->snapshotQuery($t['month'], $t['owner'], $t['version'], $t['company'])->orderBy('id')->lazyById(500);
foreach ($rows as $record) {
$r = is_array($record) ? $record : json_decode($record->values, true);
$book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['final'], round($r['bill'] - (float) $r['final'], 2), $r['label'], $r['note']]);
}
$book->row('异议处理', ['快递单号', '异议原因', '财务结果', '回复', '复核应结运费'], true);
foreach ($this->confirmations()->disputes($t['month'], $t['owner'], $t['company'], $t['version']) as $d) {
$book->row('异议处理', [$d['waybill'], $d['reason'], ['accept' => '采纳', 'reject' => '不采纳'][$d['decision'] ?? ''] ?? '待处理', $d['reply'] ?? '', $d['review_amount'] ?? null]);
}
$book->writeTo(fopen('php://output', 'wb'));
}, str_replace(['/', '\\'], '-', $t['party']->name) . '_' . $t['month'] . '_对账确认V' . $t['version'] . '.xlsx', ['Cache-Control' => 'private, no-store', 'X-Robots-Tag' => 'noindex, nofollow']);
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace App\Http\Controllers\Business;
use App\Business\KukaPostingBase\KukaPostingAmountPoster;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
class KukaPostingAmountPosting extends Controller
{
public function preview(
Request $request,
KukaPostingAmountPoster $poster,
): RedirectResponse {
$data = $this->validatePlan($request);
$companyId = (int) (company_id() ?: 1);
try {
$plan = $poster->plan($companyId, $data['period'], $data['target_amount']);
} catch (InvalidArgumentException | RuntimeException $exception) {
return $this->redirectToPage($request, $data['period'])
->withInput()
->withErrors(['posting_amount' => $exception->getMessage()]);
} catch (Throwable $exception) {
report($exception);
return $this->redirectToPage($request, $data['period'])
->withInput()
->withErrors(['posting_amount' => '过账金额暂时无法计算,请稍后重试。']);
}
return $this->redirectToPage($request, $data['period'])
->withInput()
->with('kuka_posting_amount_preview', $poster->previewSummary($plan));
}
public function apply(
Request $request,
KukaPostingAmountPoster $poster,
): RedirectResponse {
$data = $request->validate([
'period' => ['required', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
'target_amount' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/', 'not_in:0,0.0,0.00'],
'preview_hash' => ['required', 'string', 'size:64'],
], $this->messages());
$companyId = (int) (company_id() ?: 1);
try {
$plan = $poster->plan($companyId, $data['period'], $data['target_amount']);
if (! hash_equals((string) $plan['preview_hash'], (string) $data['preview_hash'])) {
throw new InvalidArgumentException('发货明细或物料金额已经变化,请重新计算过账方案。');
}
if (($plan['is_exact'] ?? false) !== true) {
throw new InvalidArgumentException(sprintf(
'过账金额与选中发货金额仍有差额 %s,未写入过账标签。',
number_format((int) $plan['difference_cents'] / 100, 2, '.', ','),
));
}
$result = $poster->apply($plan, auth()->id());
} catch (InvalidArgumentException | RuntimeException $exception) {
return $this->redirectToPage($request, $data['period'])
->withInput()
->withErrors(['posting_amount' => $exception->getMessage()]);
} catch (Throwable $exception) {
report($exception);
return $this->redirectToPage($request, $data['period'])
->withInput()
->withErrors(['posting_amount' => '过账标签写入失败,原有标签已保留。']);
}
return $this->redirectToPage($request, $data['period'])->with(
'success',
sprintf(
'整月过账标签已更新:%s 行标记为“是”,其余标记为“补单(订单四组)”;本次变更 %s 行。',
number_format((int) $plan['selected_rows']),
number_format((int) $result['updated']),
),
);
}
/**
* @return array{period:string,target_amount:string}
*/
private function validatePlan(Request $request): array
{
return $request->validate([
'period' => ['required', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
'target_amount' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/', 'not_in:0,0.0,0.00'],
], $this->messages());
}
/**
* @return array<string,string>
*/
private function messages(): array
{
return [
'period.required' => '请选择需要过账的账期。',
'period.regex' => '账期格式必须为 YYYY-MM。',
'target_amount.required' => '请填写整月过账金额。',
'target_amount.regex' => '整月过账金额最多保留两位小数。',
'target_amount.not_in' => '整月过账金额必须大于 0。',
'preview_hash.required' => '请先计算过账方案。',
'preview_hash.size' => '过账方案已失效,请重新计算。',
];
}
private function redirectToPage(Request $request, string $period): RedirectResponse
{
return redirect()->route('business.pages.show', [
'company_id' => company_id() ?: 1,
'section' => 'posting-data',
'page' => 'kuka-basic-data',
'submenu' => 'shipments',
'period' => $period,
'store_name' => mb_substr(trim((string) $request->input('store_name', '')), 0, 191),
'status' => mb_substr(trim((string) $request->input('status', '')), 0, 64),
'keyword' => mb_substr(trim((string) $request->input('keyword', '')), 0, 120),
'per_page' => max(1, min(200, (int) $request->input('per_page', 50))),
]);
}
}

View File

@ -5038,17 +5038,14 @@ class Pages extends Controller
} }
/** /**
* 「终版」目录的按表数据:独立存放,初始为空,由页面上的导入/导出/查询/编辑维护。 * 按表维护的页面数据:终版页签及快递记账明细使用各自的独立数据集。
* *
* @return array<string,mixed>|null * @return array<string,mixed>|null
*/ */
protected function payablesFinalData(array $section, ?array $page): ?array protected function payablesFinalData(array $section, ?array $page): ?array
{ {
$sectionSlug = (string) ($section['slug'] ?? ''); $sectionSlug = (string) ($section['slug'] ?? '');
if (empty($page) || ! in_array($sectionSlug, [ if (empty($page)) {
PayablesFinalRegistry::SECTION_SUPPLIER,
PayablesFinalRegistry::SECTION_COURIER,
], true)) {
return null; return null;
} }
@ -5067,9 +5064,7 @@ class Pages extends Controller
} }
$keyword = trim((string) request('keyword', '')); $keyword = trim((string) request('keyword', ''));
$storeDataset = PayablesFinalActions::DATASET_PREFIX $storeDataset = $registry->storeDataset($sectionSlug, $dataset);
. ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:')
. $dataset;
$isSupplierPayablesReport = $dataset === 'supplier-payables-report'; $isSupplierPayablesReport = $dataset === 'supplier-payables-report';
$requestedMonth = trim((string) request('month', '')); $requestedMonth = trim((string) request('month', ''));
$month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1 $month = $isSupplierPayablesReport && preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
@ -5977,6 +5972,7 @@ class Pages extends Controller
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()), 'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
'shipping-data' => $this->contentForShippingData(), 'shipping-data' => $this->contentForShippingData(),
'return-pickup-management' => $this->contentForReturnPickupManagement(), 'return-pickup-management' => $this->contentForReturnPickupManagement(),
'returned-parcels' => app(ReturnedParcelController::class)->page(request()),
'withdrawal-management' => $this->contentForWithdrawalManagement(), 'withdrawal-management' => $this->contentForWithdrawalManagement(),
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(), 'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(), 'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
@ -6006,6 +6002,7 @@ class Pages extends Controller
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(), 'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),
'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(), 'planting-loss' => app(\Modules\EcommerceFinance\View\PlantingLossPageData::class)->page(),
'finance-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->financeData(), 'finance-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->financeData(),
'raw-statements' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->rawStatementsData(),
'supplier-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->supplierData(), 'supplier-data' => app(\Modules\EcommerceFinance\View\SupplierReconciliationPageData::class)->supplierData(),
'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab), 'supplier-negative-alert', 'courier-negative-alert' => $this->negativeAlertContent($page, $tab),
'store-report-data-logic' => $this->prepareStoreReportLogic(), 'store-report-data-logic' => $this->prepareStoreReportLogic(),
@ -8811,6 +8808,7 @@ class Pages extends Controller
$syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null]; $syncStatus = ['code' => 'unavailable', 'last_succeeded_at' => null];
$pagePaymentAmount = '0.00'; $pagePaymentAmount = '0.00';
$filteredPaymentAmount = '0.00'; $filteredPaymentAmount = '0.00';
$storePaymentSummary = [];
$shopNames = []; $shopNames = [];
$paymentReasons = []; $paymentReasons = [];
$error = null; $error = null;
@ -8855,6 +8853,9 @@ class Pages extends Controller
); );
$pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00'); $pagePaymentAmount = (string) ($result['page_payment_amount'] ?? '0.00');
$filteredPaymentAmount = (string) ($result['filtered_payment_amount'] ?? '0.00'); $filteredPaymentAmount = (string) ($result['filtered_payment_amount'] ?? '0.00');
$storePaymentSummary = is_array($result['store_summary'] ?? null)
? $result['store_summary']
: [];
} }
} }
} catch (Throwable $exception) { } catch (Throwable $exception) {
@ -8869,6 +8870,7 @@ class Pages extends Controller
'smallPaymentSyncStatus' => $syncStatus, 'smallPaymentSyncStatus' => $syncStatus,
'smallPaymentPageAmount' => $pagePaymentAmount, 'smallPaymentPageAmount' => $pagePaymentAmount,
'smallPaymentFilteredAmount' => $filteredPaymentAmount, 'smallPaymentFilteredAmount' => $filteredPaymentAmount,
'smallPaymentStoreSummary' => $storePaymentSummary,
'smallPaymentShops' => $shopNames, 'smallPaymentShops' => $shopNames,
'smallPaymentReasons' => $paymentReasons, 'smallPaymentReasons' => $paymentReasons,
'smallPaymentStatuses' => [ 'smallPaymentStatuses' => [

View File

@ -16,8 +16,7 @@ use RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\StreamedResponse;
/** /**
* 「终版」目录的按表数据:界面与基础页面一致,数据独立存放 * 终版页签和快递记账明细的导入、导出及编辑,各入口使用独立数据集。
* (数据集键 final:<目录>:<页面>),初始为空,由页面上的导入、导出、查询、编辑维护。
*/ */
class PayablesFinalActions extends Controller class PayablesFinalActions extends Controller
{ {
@ -171,9 +170,7 @@ class PayablesFinalActions extends Controller
private function storeDataset(Request $request): string private function storeDataset(Request $request): string
{ {
$section = $this->section($request) === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier'; return $this->registry->storeDataset($this->section($request), $this->dataset($request));
return self::DATASET_PREFIX . $section . ':' . $this->dataset($request);
} }
private function csvText(mixed $value): string private function csvText(mixed $value): string

View File

@ -88,14 +88,21 @@ class PlantingReimbursementWorkbench extends Controller
'digest_webhook' => (string) $request->input('digest_webhook', ''), 'digest_webhook' => (string) $request->input('digest_webhook', ''),
'digest_secret' => (string) $request->input('digest_secret', ''), 'digest_secret' => (string) $request->input('digest_secret', ''),
'clear_digest' => $request->boolean('clear_digest'), 'clear_digest' => $request->boolean('clear_digest'),
'cancel_notices_enabled' => $request->has('cancel_notices_enabled')
? $request->boolean('cancel_notices_enabled')
: $robot->cancelNoticesEnabled(),
]); ]);
return $this->back($request)->with('success', '钉钉机器人设置已保存。'); return $this->back($request)->with('success', '钉钉机器人设置已保存。');
} }
/** 按发起人把取消 / 待复查通知发到钉钉群(放行检查通过才发;每天 11:20 也会自动发)。 */ /** 按发起人发送取消 / 待复查通知,须已启用逐单通知且放行检查通过。 */
public function notify(Request $request, PageData $page, Robot $robot) public function notify(Request $request, PageData $page, Robot $robot)
{ {
if (! $robot->cancelNoticesEnabled()) {
return $this->back($request)->with('error', '取消 / 待复查工单通知已暂停,测试完成前不会发送。');
}
$filters = $page->filters(); $filters = $page->filters();
try { try {
$result = $page->build($filters); $result = $page->build($filters);

View File

@ -0,0 +1,89 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer as Sync;
use Throwable;
class ReturnedParcelController extends Controller
{
public const COLUMNS = [
'received_at' => '进仓时间', 'after_sales_id' => '售后单号', 'online_after_sales_no' => '线上售后单号',
'waybill' => '退回快递单号', 'courier' => '快递公司', 'shop' => '店铺', 'warehouse' => '收货仓库',
'order_id' => '内部订单号', 'online_order_no' => '线上订单号', 'sku' => '商品编码', 'style_code' => '款式编码',
'product_name' => '商品名称', 'properties' => '颜色规格', 'applied_qty' => '申请数量',
'returned_qty' => '实退数量', 'price' => '商品单价', 'item_amount' => '明细金额',
'status' => '售后状态', 'type' => '售后类型', 'goods_status' => '货物状态', 'reason' => '问题类型',
'remark' => '备注', 'source_kind' => '数据来源', 'source_id' => '源明细编号',
];
public function page(Request $request): array
{
$filters = $this->filters($request);
$data = ['view' => 'business.pages.courier-payables.returned-parcels', 'filters' => $filters,
'columns' => self::COLUMNS, 'rows' => null, 'summary' => null, 'state' => null, 'error' => null];
try {
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
if (! Schema::connection($db->getName())->hasTable(Sync::TABLE)) {
$data['error'] = '退回件明细尚未完成首次同步,请稍后刷新。';
return $data;
}
$query = $this->query($filters);
$data['summary'] = (clone $query)->selectRaw('COUNT(*) AS rows_count, COALESCE(SUM(returned_qty),0) AS quantity')->first();
$data['summary']->orders_count = $db->query()->fromSub((clone $query)->select(['source_kind', 'after_sales_id'])->distinct(), 'returned_orders')->count();
$data['rows'] = $query->orderByDesc('received_at')->orderByDesc('source_kind')->orderByDesc('source_id')->paginate(50)->withQueryString();
$data['state'] = $db->table('business_mirror_table_states')->where('dataset_key', Sync::DATASET)->first();
} catch (Throwable $exception) {
report($exception);
$data['error'] = '退回件明细暂时无法读取,请稍后重试。';
}
return $data;
}
public function export(Request $request)
{
$query = $this->query($this->filters($request));
$selected = array_values(array_intersect(explode(',', (string) $request->query('columns', '')), array_keys(self::COLUMNS)));
$selected = $selected ?: array_keys(self::COLUMNS);
return response()->streamDownload(function () use ($query, $selected): void {
$file = fopen('php://output', 'w');
fwrite($file, "\xEF\xBB\xBF");
fputcsv($file, array_map(fn ($key) => self::COLUMNS[$key], $selected));
foreach (['regular', 'taobao'] as $source) foreach ((clone $query)->where('source_kind', $source)->orderBy('source_id')->lazyById(1000, 'source_id') as $row) {
fputcsv($file, array_map(function ($key) use ($row) {
$value = $key === 'source_kind' ? ($row->$key === 'taobao' ? '淘系' : '普通') : (string) ($row->$key ?? '');
if ($value !== '' && in_array($key, ['after_sales_id','online_after_sales_no','waybill','order_id','online_order_no','sku','style_code','source_id'], true)) return "'" . $value;
return preg_match('/^[=+@\-\t\r]/u', $value) ? "'" . $value : $value;
}, $selected));
}
fclose($file);
}, '退回件明细.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
private function filters(Request $request): array
{
return validator($request->query(), [
'from' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:2026-10-01'],
'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'],
'waybill' => ['nullable', 'string', 'max:255'], 'shop' => ['nullable', 'string', 'max:255'],
'warehouse' => ['nullable', 'string', 'max:255'], 'sku' => ['nullable', 'string', 'max:255'],
])->validate() + ['from' => Sync::START, 'to' => now('Asia/Shanghai')->toDateString(),
'waybill' => '', 'shop' => '', 'warehouse' => '', 'sku' => ''];
}
private function query(array $filters)
{
$query = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))->table(Sync::TABLE)
->where('received_at', '>=', $filters['from'] ?: Sync::START);
if ($filters['to']) $query->where('received_at', '<', Carbon::parse($filters['to'])->addDay()->toDateString());
foreach (['waybill', 'shop', 'warehouse', 'sku'] as $field) {
if (filled($filters[$field])) $query->where($field, trim($filters[$field]));
}
return $query;
}
}

View File

@ -12,10 +12,11 @@ use Modules\EcommerceFinance\Services\SupplierComparisonCsvExporter;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier; use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter; use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation; use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
use Modules\EcommerceFinance\Services\SupplierStatementMatcher;
use Modules\EcommerceFinance\Services\SupplierStatementStore; use Modules\EcommerceFinance\Services\SupplierStatementStore;
use Modules\EcommerceFinance\Services\SupplierStatementTemplate; use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
use Modules\EcommerceFinance\Services\SupplierStatementWorkbookExporter;
use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation; use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation;
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
use Modules\EcommerceFinance\View\SupplierReconciliationPageData; use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\StreamedResponse;
@ -26,6 +27,8 @@ use Throwable;
*/ */
class SupplierReconciliation extends Controller class SupplierReconciliation extends Controller
{ {
private const RAW_STATEMENT_PER_PAGE = 50;
public function __construct( public function __construct(
private readonly SupplierStatementTemplate $template, private readonly SupplierStatementTemplate $template,
private readonly SupplierStatementStore $statements, private readonly SupplierStatementStore $statements,
@ -36,6 +39,8 @@ class SupplierReconciliation extends Controller
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter, private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
private readonly SupplierPortalAccess $supplierPortalAccess, private readonly SupplierPortalAccess $supplierPortalAccess,
private readonly SupplierSummaryConfirmation $summaryConfirmations, private readonly SupplierSummaryConfirmation $summaryConfirmations,
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
private readonly SupplierStatementWorkbookExporter $statementWorkbookExporter,
) { ) {
$this->middleware('auth'); $this->middleware('auth');
$this->middleware('company.identify'); $this->middleware('company.identify');
@ -58,18 +63,29 @@ class SupplierReconciliation extends Controller
$supplierPortalUpload = $request->user() $supplierPortalUpload = $request->user()
&& SupplierPortalAccess::isSupplierUser($request->user()); && SupplierPortalAccess::isSupplierUser($request->user());
$supplier = $this->effectiveSupplier($request); $supplier = $this->effectiveSupplier($request);
$companyId = (int) (company_id() ?: 1);
$uploadWindow = $this->pageData->statementUploadWindow($supplier, $companyId);
if ($uploadWindow['locked']) {
$errors = ['import' => $uploadWindow['message']];
if ($request->expectsJson()) {
throw ValidationException::withMessages($errors);
}
return back()->withErrors($errors);
}
$records = $this->template->parse($request->file('import'), $supplier); $records = $this->template->parse($request->file('import'), $supplier);
$rows = $this->statements->save( $rows = $this->statements->save(
$supplier, $supplier,
$records, $records,
(string) $request->file('import')->getClientOriginalName(), (string) $request->file('import')->getClientOriginalName(),
(int) (company_id() ?: 1), $companyId,
user_id() ? (int) user_id() : null, user_id() ? (int) user_id() : null,
); );
$message = "对账单已保存:{$supplier} 共 {$rows} 行"; $message = "对账单已保存:{$supplier} 共 {$rows} 行";
$receiptNotice = ''; $notices = [];
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
if ($supplierPortalUpload) { if ($supplierPortalUpload) {
try { try {
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt( $receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
@ -78,14 +94,30 @@ class SupplierReconciliation extends Controller
$records, $records,
); );
if ($receiptSent) { if ($receiptSent) {
$receiptNotice = ';上传回执已发送到该厂家钉钉群。'; $notices[] = '上传回执已发送到该厂家钉钉群';
} }
} catch (Throwable $exception) { } catch (Throwable $exception) {
report($exception); report($exception);
$receiptNotice = ';上传回执发送失败,对账单已正常保存。'; $notices[] = '上传回执发送失败,对账单已正常保存';
}
try {
$autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload(
$supplier,
$companyId,
$records,
user_id() ? (int) user_id() : null,
);
$autoPushNotice = $this->zeroDifferenceConfirmations->uploadNotice($autoPush);
if ($autoPushNotice !== '') {
$notices[] = $autoPushNotice;
}
} catch (Throwable $exception) {
report($exception);
$notices[] = '零差异对账确认自动推送失败,对账单已正常保存';
} }
} }
$message .= $receiptNotice !== '' ? $receiptNotice : '。'; $message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。';
return $request->expectsJson() return $request->expectsJson()
? response()->json(['message' => $message, 'rows' => $rows]) ? response()->json(['message' => $message, 'rows' => $rows])
@ -145,6 +177,66 @@ class SupplierReconciliation extends Controller
); );
} }
public function exportRawStatement(Request $request): StreamedResponse
{
[$supplier, $companyId] = $this->returnTarget($request);
$latestUpload = $this->statements->uploads($supplier, $companyId, 1)[0] ?? null;
if ($latestUpload === null) {
throw ValidationException::withMessages([
'raw_statement_export' => '该厂家还没有上传对账单,暂无原始账单可导出。',
]);
}
return $this->statementWorkbookExporter->download(
$this->statements->streamRows($supplier, $companyId),
$supplier,
(string) ($latestUpload['uploaded_at'] ?? ''),
);
}
public function rawStatementRows(Request $request): JsonResponse
{
$request->validate([
'page' => ['nullable', 'integer', 'min:1', 'max:100000'],
'keyword' => ['nullable', 'string', 'max:100'],
'barcode' => ['nullable', 'string', 'max:191'],
'purchase_no' => ['nullable', 'string', 'max:191'],
]);
[$supplier, $companyId] = $this->returnTarget($request);
$page = max((int) $request->query('page', 1), 1);
$keyword = trim((string) $request->query('keyword', ''));
$exactFilters = array_filter([
'barcode' => trim((string) $request->query('barcode', '')),
'purchaseNo' => trim((string) $request->query('purchase_no', '')),
], static fn (string $value): bool => $value !== '');
$result = $this->statements->paginateFiltered(
$supplier,
$companyId,
self::RAW_STATEMENT_PER_PAGE,
$page,
$keyword,
$exactFilters,
);
$total = (int) ($result['total'] ?? 0);
$pages = max((int) ceil($total / self::RAW_STATEMENT_PER_PAGE), 1);
$page = min($page, $pages);
$latestUpload = $this->statements->uploads($supplier, $companyId, 1)[0] ?? null;
return response()->json([
'supplier' => $supplier,
'rows' => array_values((array) ($result['rows'] ?? [])),
'total' => $total,
'page' => $page,
'pages' => $pages,
'per_page' => self::RAW_STATEMENT_PER_PAGE,
'upload' => $latestUpload === null ? null : [
'uploaded_at' => (string) ($latestUpload['uploaded_at'] ?? ''),
'filename' => (string) ($latestUpload['filename'] ?? ''),
'rows' => (int) ($latestUpload['rows'] ?? 0),
],
])->header('Cache-Control', 'no-store');
}
public function saveDingTalkRobot(Request $request): RedirectResponse public function saveDingTalkRobot(Request $request): RedirectResponse
{ {
$request->validate([ $request->validate([
@ -283,7 +375,7 @@ class SupplierReconciliation extends Controller
} }
$differences = array_values(array_filter( $differences = array_values(array_filter(
$detail['rows'], $detail['rows'],
static fn (array $row): bool => ($row['type'] ?? '') !== SupplierStatementMatcher::TYPE_MATCH, fn (array $row): bool => $this->pageData->requiresSupplierCorrection($row),
)); ));
if ($request->input('scope') === 'row') { if ($request->input('scope') === 'row') {

View File

@ -65,13 +65,17 @@ final class UnshippedWaybillController extends Controller
public function export(Request $request) public function export(Request $request)
{ {
$query = $this->filtered($request); $query = $this->filtered($request);
return response()->streamDownload(function () use ($query): void { $replacementOnly = (array) $request->input('sources', []) === ['replacement'];
return response()->streamDownload(function () use ($query, $replacementOnly): void {
$book = new Spreadsheet(); $book = new Spreadsheet();
$sheet = $book->getActiveSheet(); $sheet = $book->getActiveSheet();
$sheet->fromArray(['快递单号', '来源']); $sheet->fromArray([$replacementOnly ? '换单前单号' : '快递单号', '来源',
$replacementOnly ? '换单前快递名称' : '快递名称', '换单后单号', '换单后快递名称', '依据时间']);
$line = 2; $line = 2;
foreach ($query->orderBy('id')->lazyById(1000) as $row) { foreach ($query->orderBy('id')->lazyById(1000) as $row) {
$values = [$row->waybill_no, UnshippedWaybills::label($row->source)]; $isReplacement = $row->source === 'replacement';
$values = [$row->waybill_no, UnshippedWaybills::label($row->source), $row->courier_name,
$isReplacement ? $row->new_waybill_no : null, $isReplacement ? $row->new_courier_name : null, $row->evidence_time];
foreach ($values as $column => $value) { foreach ($values as $column => $value) {
$sheet->setCellValueExplicit(chr(65 + $column).$line, (string) $value, DataType::TYPE_STRING); $sheet->setCellValueExplicit(chr(65 + $column).$line, (string) $value, DataType::TYPE_STRING);
} }

View File

@ -7,12 +7,14 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Routing\Controller; use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View; use Illuminate\View\View;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier; use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter; use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation; use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
use Modules\EcommerceFinance\Services\SupplierStatementStore; use Modules\EcommerceFinance\Services\SupplierStatementStore;
use Modules\EcommerceFinance\Services\SupplierStatementTemplate; use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation;
use Modules\EcommerceFinance\View\SupplierReconciliationPageData; use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\StreamedResponse;
@ -30,6 +32,7 @@ class SupplierReconciliation extends Controller
private readonly SupplierReconciliationPageData $pageData, private readonly SupplierReconciliationPageData $pageData,
private readonly SupplierReturnCsvExporter $returnCsvExporter, private readonly SupplierReturnCsvExporter $returnCsvExporter,
private readonly SupplierDingTalkNotifier $dingTalkNotifier, private readonly SupplierDingTalkNotifier $dingTalkNotifier,
private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations,
) { ) {
} }
@ -64,6 +67,15 @@ class SupplierReconciliation extends Controller
'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200'], 'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200'],
]); ]);
[, $supplier, $companyId] = $this->supplierContext(); [, $supplier, $companyId] = $this->supplierContext();
$uploadWindow = $this->pageData->statementUploadWindow($supplier, $companyId);
if ($uploadWindow['locked']) {
$errors = ['import' => $uploadWindow['message']];
if ($request->expectsJson()) {
throw ValidationException::withMessages($errors);
}
return back()->withErrors($errors);
}
$records = $this->template->parse($request->file('import'), $supplier); $records = $this->template->parse($request->file('import'), $supplier);
$rows = $this->statements->save( $rows = $this->statements->save(
@ -74,7 +86,7 @@ class SupplierReconciliation extends Controller
user_id() ? (int) user_id() : null, user_id() ? (int) user_id() : null,
); );
$message = "对账单已保存:{$supplier} 共 {$rows} 行"; $message = "对账单已保存:{$supplier} 共 {$rows} 行";
$receiptNotice = ''; $notices = [];
try { try {
$receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt( $receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt(
$supplier, $supplier,
@ -82,13 +94,30 @@ class SupplierReconciliation extends Controller
$records, $records,
); );
if ($receiptSent) { if ($receiptSent) {
$receiptNotice = ';上传回执已发送到该厂家钉钉群。'; $notices[] = '上传回执已发送到该厂家钉钉群';
} }
} catch (Throwable $exception) { } catch (Throwable $exception) {
report($exception); report($exception);
$receiptNotice = ';上传回执发送失败,对账单已正常保存。'; $notices[] = '上传回执发送失败,对账单已正常保存';
} }
$message .= $receiptNotice !== '' ? $receiptNotice : '。';
$autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []];
try {
$autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload(
$supplier,
$companyId,
$records,
user_id() ? (int) user_id() : null,
);
$autoPushNotice = $this->zeroDifferenceConfirmations->uploadNotice($autoPush);
if ($autoPushNotice !== '') {
$notices[] = $autoPushNotice;
}
} catch (Throwable $exception) {
report($exception);
$notices[] = '零差异对账确认自动推送失败,对账单已正常保存';
}
$message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。';
return $request->expectsJson() return $request->expectsJson()
? response()->json(['message' => $message, 'rows' => $rows]) ? response()->json(['message' => $message, 'rows' => $rows])

View File

@ -169,7 +169,7 @@ final class BillParser
} }
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? ''; $amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) { if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
$skip[$sheet] = ['附加费表:只读金额进小汇总,没有逐单核对', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount]; $skip[$sheet] = ['附加费表:按单号和费用类型匹配结算', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') { } elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
$freight[] = $sheet; $freight[] = $sheet;
} else { } else {

View File

@ -0,0 +1,355 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer as ServiceFees;
use Modules\EcommerceFinance\Services\WorkOrderWaybillLookup;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
/** 账单按票核价:只读现有报价及共享镜像,不将账单金额当作结算依据。 */
final class BillSurchargeQuoteCalculator
{
public const BUYER_CONFIRMATIONS = 'courier-surcharge-buyer-confirmations';
public static function buyerConfirmationKey(int $ruleId, string $month, string $waybill, string $workOrder): string
{
return implode('|', [$ruleId, $month, strtoupper(trim($waybill)), $workOrder]);
}
/** 发货、查件工单按账单当月及前两个月匹配;退回进仓不受此窗口限制。 */
public static function window(string $month): array
{
$start = Carbon::parse($month . '-01')->startOfMonth();
$months = 3;
return ['from' => $start->copy()->subMonthsNoOverflow($months - 1)->toDateString(),
'until' => $start->copy()->addMonth()->toDateString(), 'months' => $months];
}
public function calculate(array $input, string $scope, string $month, array $allowedCouriers): array
{
if ($input === [] || $allowedCouriers === []) return ['rows' => [], 'notes' => [], 'metadata' => []];
$rules = DB::table('business_courier_surcharge_quotes')->where('company_id', (int) (company_id() ?: 1))
->where('status', 'active')->whereNull('deleted_at')->whereIn('courier', $allowedCouriers)
->where('scope', $scope === 'dropship' ? '代发仓' : '自有快递')
->orderByDesc('effective_at')->orderByDesc('id')->get();
$waybills = array_values(array_unique(array_column($input, 'waybill_no')));
$shipping = app(ShippingLookup::class);
$ships = $shipping->details($waybills, $allowedCouriers);
$freights = $shipping->summaries($waybills, $allowedCouriers);
$needsService = $rules->contains(fn ($r) => in_array($r->mode, ['聚工单客服核实', '固定单价'], true)
|| ($r->mode === '取发出运费' && trim($r->condition) === '查件扣单并且买家原因'));
$workOrders = $needsService ? $this->workOrders($waybills, $month) : [];
$returns = $rules->contains(fn ($r) => $r->mode === '固定单价' && str_contains($r->condition, '已退回'))
? $this->receivedReturns($workOrders, $waybills) : [];
$confirmations = $this->buyerConfirmations($rules, $workOrders, $month);
$rows = $notes = $metadata = [];
$window = self::window($month);
foreach ($input as $fee) {
$wb = strtoupper($fee['waybill_no']); $type = SurchargeSettlementMatcher::type($fee['item']);
$ship = $ships[$wb] ?? []; $courier = $ship['express_name1'] ?? '';
$date = substr((string) ($ship['ship_time'] ?? ''), 0, 10);
$metadata[$wb] = ['courier_name' => $courier ?: null, 'platform_product_id' => $ship['item_id'] ?? null,
'product_code' => $ship['barcode'] ?? null, 'shop_name' => $ship['shop_name'] ?? null,
'online_order_no' => $ship['trade_no'] ?? null];
if($date !== '' && $date >= date('Y-m-d', strtotime($month . '-01 +1 month'))){
$notes[$wb][$type]='发货日期晚于账单月份,未计入本月';
continue;
}
$candidates = $rules->filter(fn ($r) => $r->courier === $courier
&& in_array($type, array_map([SurchargeSettlementMatcher::class, 'type'], json_decode($r->types, true) ?: []), true));
$rule = $candidates->first(fn ($r) => $date !== '' && substr($r->effective_at, 0, 10)
<= ($r->mode === '聚工单客服核实' ? $month . '-31' : $date));
if ($rule === null) {
$notes[$wb][$type] = $candidates->isEmpty() ? '该快递没有启用的对应费用报价' : '发货日期未达到报价生效日或没有发货记录';
continue;
}
// 买家原因必须按当前工单核验,缺少依据时不能回退到旧结算金额。
if ($rule->mode === '固定单价'
|| ($rule->mode === '取发出运费' && trim($rule->condition) === '查件扣单并且买家原因')) $rows[$wb][$type] = [];
if ($date < $window['from']) {
$notes[$wb][$type] = '发货日期超出匹配范围:' . $window['from'] . ' 至 ' . Carbon::parse($window['until'])->subDay()->toDateString();
continue;
}
$base = ['rule_id' => $rule->id, 'courier_name' => $courier, 'waybill' => $wb, 'surcharge_type' => $type,
'shipped_at' => $ship['ship_time'] ?? null, 'source_created_at' => null,
'platform_product_id' => $ship['item_id'] ?? null, 'product_code' => $ship['barcode'] ?? null,
'shop_name' => $ship['shop_name'] ?? null, 'online_order_no' => $ship['trade_no'] ?? null,
'source_kind' => 'bill_quote', 'source_key' => $wb . '|' . $type, 'outbound_io_id' => null];
$feeReturns = $returns;
if (isset($returns['waybill:' . $wb])) $feeReturns['_waybill'] = $returns['waybill:' . $wb];
$result = $this->price($rule, $type, $ship, $freights[$wb] ?? [], $workOrders[$wb] ?? [],
$confirmations[$rule->id][$wb] ?? [], $feeReturns);
if (is_string($result)) { $notes[$wb][$type] = '报价 #' . $rule->id . ':' . $result; continue; }
foreach ($result as $price) $rows[$wb][$type][] = (object) array_replace($base, $price,
['settlement_status' => '已计算', 'evidence' => '报价 #' . $rule->id . ';' . $price['evidence']]);
}
return compact('rows', 'notes', 'metadata');
}
private function price(object $rule, string $type, array $ship, array $freight, array $orders, array $confirmations, array $returns): array|string
{
if ($rule->mode === '固定单价') return $this->fixedPrice($rule, $type, $orders, $returns);
if ($rule->mode === '取发出运费') {
if (! in_array(trim($rule->condition), ['取发出运费', '等于发出运费', '查件扣单并且买家原因'], true)) return '计费条件尚未支持自动核验';
if (! in_array(trim($rule->standard), ['取发出运费', '等于发出运费'], true)) return '计价标准尚未支持自动核验';
$evidence = '';
if (trim($rule->condition) === '查件扣单并且买家原因') {
$reason = $this->buyerReason($rule, $orders, $confirmations);
if (is_string($reason)) return $reason;
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
$evidence = $reason['evidence'] . ';';
}
if (($freight['calc_freight'] ?? null) === null) return '发出运费尚未核算完成';
$amount = round($freight['calc_freight'], 2);
return [['settlement_amount' => $amount, 'evidence' => $evidence . '取本票已核算发出运费 ' . number_format($amount, 2, '.', '') . ' 元']];
}
if ($rule->mode === '按尺寸/最长边') {
$combined = $this->sizeWeightRule($rule);
if ($combined !== null) {
$weight = $freight['charge_weight'] ?? null;
if (! is_numeric($weight) || (float) $weight <= 0) return '缺少已核算计费重量,无法检查超长超重费';
$sides = [(float) ($ship['length_cm'] ?? 0), (float) ($ship['width_cm'] ?? 0), (float) ($ship['height_cm'] ?? 0)];
if (min($sides) <= 0) return '发货商品缺少完整尺寸,无法检查超长超重费';
$max = max($sides);
$eligible = $max > $combined['length_cm'] || (float) $weight > $combined['weight'];
$amount = $eligible ? round(max($combined['minimum'], (float) $weight * $combined['rate']), 2) : 0.0;
return [['settlement_amount' => $amount, 'evidence' =>
'最长边 ' . $max . 'cm,计费重量 ' . $weight . 'kg;报价条件:最长边>' . $combined['length_cm']
. 'cm 或计费重量>' . $combined['weight'] . 'kg;'
. ($eligible ? 'max(' . $weight . '×' . $combined['rate'] . '元/kg,最低' . $combined['minimum'] . '元)' : '未达到条件,不计费')
. ',按票计一次']];
}
if (! preg_match('/^(?:单边(?:长)?超|最长边超过?)\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米)$/iu', trim($rule->condition), $threshold)
|| ! preg_match('/^(\d+(?:\.\d+)?)\s*元?\s*\/\s*单$/u', trim($rule->standard), $price)) return '尺寸计费条件或单价尚未支持自动核验';
$sides = [(float) ($ship['length_cm'] ?? 0), (float) ($ship['width_cm'] ?? 0), (float) ($ship['height_cm'] ?? 0)];
if (min($sides) <= 0) return '发货商品缺少完整尺寸';
$max = max($sides); $amount = $max > (float) $threshold[1] ? (float) $price[1] : 0;
return [['settlement_amount' => $amount, 'evidence' => '最长边 ' . $max . 'cm,报价阈值 ' . $threshold[1] . 'cm,按票计费']];
}
if ($rule->mode !== '聚工单客服核实') return '计费方式“' . $rule->mode . '”尚未接入账单自动核价';
if (trim($rule->standard) !== '读取聚工单附加费明细') return '客服计价标准尚未支持自动核验';
$condition = trim($rule->condition);
if (preg_match('/^重量\s*(\d+(?:\.\d+)?)\s*(?:kg|公斤|千克)以上[,,、]?上楼费聚工单客服回复通过$/iu', $condition, $weight)) {
if (($freight['charge_weight'] ?? null) === null) return '缺少已核算计费重量,无法检查上楼费门槛';
if ((float) $freight['charge_weight'] < (float) $weight[1]) return [['settlement_amount' => 0,
'evidence' => '本票计费重量 ' . $freight['charge_weight'] . 'kg,未达到 ' . $weight[1] . 'kg 门槛,不计费']];
} elseif (! in_array($condition, ['聚工单客服回复通过', '改地址客服回复通过'], true)) return '客服附加条件尚未支持自动核验';
$result = []; $found = false;
foreach ($orders as $order) {
$fields = [];
foreach (json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [] as $f) if (isset($f['fieldId'])) $fields[$f['fieldId']] = $f;
if (($fields['logisticsField']['value'] ?? '') !== $rule->courier
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
$cents = 0;
foreach ($fields[ServiceFees::FEE_TABLE]['childFieldList'] ?? [] as $line) {
$v = array_column($line, 'value', 'fieldId');
$actualType = SurchargeSettlementMatcher::type((string) ($v[ServiceFees::FEE_TYPE] ?? ''));
if ($actualType !== $type) continue;
$found = true;
if (($v[ServiceFees::FEE_APPROVAL] ?? '') !== '通过') continue;
$amount = trim((string) ($v[ServiceFees::FEE_AMOUNT] ?? ''));
if (! preg_match('/^\d{1,9}(?:\.\d{1,2})?$/D', $amount)) return '客服已通过的费用金额无效';
$cents += (int) round((float) $amount * 100);
}
if ($cents > 0) $result[] = ['settlement_amount' => $cents / 100,
'source_kind' => ServiceFees::KIND, 'source_key' => $order->woNo, 'source_created_at' => $order->created,
'evidence' => '聚工单 ' . $order->woNo . ' 附加费明细逐项审核通过'];
}
return $result ?: ($found ? '对应工单附加费未审核通过' : '未找到对应单号、费用类型和快递的客服费用明细');
}
/** 同一张报价明确列出超长或超重条件,按整票计费重量和最低金额收取。 */
private function sizeWeightRule(object $rule): ?array
{
$pattern = '/^最长边大于(\d+(?:\.\d+)?)米[;;]②?计费重量大于(\d+(?:\.\d+)?)KG[,,]即认定为超长超重货[,,]该单货物将在原收费基础上加收超长超重费[。.]加收标准按照计费重量[×*](\d+(?:\.\d+)?)元\/KG计算[,,]最低加收(\d+(?:\.\d+)?)元\/(?:票|单)[。.]?$/iu';
$condition = preg_replace('/\s+/u', '', $rule->condition);
$standard = preg_replace('/\s+/u', '', $rule->standard);
if (! preg_match($pattern, $condition, $c) || ! preg_match($pattern, $standard, $s)
|| array_map('floatval', array_slice($c, 1)) !== array_map('floatval', array_slice($s, 1))) return null;
if (min(array_map('floatval', array_slice($c, 1))) <= 0) return null;
return ['length_cm' => (float) $c[1] * 100, 'weight' => (float) $c[2],
'rate' => (float) $c[3], 'minimum' => (float) $c[4]];
}
private function buyerReason(object $rule, array $orders, array $confirmations, bool $requireBuyer = true, bool $allowDamage = false): array|string
{
$reasons = [];
foreach ($orders as $order) {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
if (($fields['logisticsField'] ?? '') !== $rule->courier
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
$reasons[] = ['order' => $order, 'order_id' => (string) ($fields['o_id'] ?? ''),
'reason' => trim((string) ($fields['SELECT_CASCADEField1413856620250813172526'] ?? ''))];
}
if ($reasons === []) return '未找到有效的同快递查件工单,无法核实买家原因';
// 同票多工单以最新扣单原因核验;其他查件操作不覆盖扣单原因,费用仍按票只计一次。
usort($reasons, fn ($a, $b) => [$b['order']->created, $b['order']->source_id] <=> [$a['order']->created, $a['order']->source_id]);
$deductions = array_values(array_filter($reasons, fn ($r) => trim(explode('/', $r['reason'], 2)[0]) === '扣单'));
$latest = $deductions[0] ?? $reasons[0];
[$operation, $cause] = array_map('trim', array_pad(explode('/', $latest['reason'], 2), 2, ''));
if ($operation === '' || ($requireBuyer && ($cause === '' || $cause === '买家-'))) return '查件工单原因不完整,无法核实买家原因';
$eligible = $operation === '扣单' && (! $requireBuyer || str_starts_with($cause, '买家-')
|| ($allowDamage && in_array($cause, ['快递-破损', '破损'], true)));
$confirmation = $confirmations[$latest['order']->woNo] ?? [];
if (! $eligible && $operation === '扣单' && ($confirmation['buyer_reason_confirmed'] ?? false) === true
&& ($confirmation['original_reason'] ?? '') === $latest['reason'] && trim($confirmation['evidence'] ?? '') !== '') {
return ['eligible' => true, 'evidence' => '聚工单 ' . $latest['order']->woNo . ' 原因:' . $latest['reason']
. ';人工确认买家原因:' . $confirmation['evidence']];
}
return ['eligible' => $eligible, 'order_id' => $latest['order_id'], 'operation' => $operation,
'evidence' => '聚工单 ' . $latest['order']->woNo . ' 原因:' . $latest['reason']
. ($eligible ? ($requireBuyer ? ($allowDamage ? ',符合买家原因或破损条件' : ',符合买家原因条件') : ',符合扣单条件')
: ($allowDamage ? ',不符合买家原因或破损条件,不计费' : ',不符合扣单且买家原因条件,不计费'))];
}
private function fixedPrice(object $rule, string $type, array $orders, array $returns): array|string
{
if (! preg_match('/^(\d{1,9}(?:\.\d{1,2})?)\s*元?\s*\/\s*(?:单|票)$/u', trim($rule->standard), $price)) {
return '固定单价格式不支持,请填写如30元/单';
}
$condition = trim($rule->condition);
$evidence = '';
if (in_array($condition, ['查件扣单', '查件扣单并且买家原因', '查件扣单并且买家原因或破损', '查件扣单并且买家原因已退回', '查件扣单并且买家原因已退回的'], true)) {
$reason = $this->buyerReason($rule, $orders, [], $condition !== '查件扣单', $condition === '查件扣单并且买家原因或破损');
if (is_string($reason)) return $reason;
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
$evidence = $reason['evidence'];
if (str_contains($condition, '已退回')) {
$received = $returns['_waybill'] ?? $returns[$reason['order_id']] ?? null;
if ($received === null) return '未找到对应订单的有效退回进仓明细,待核实';
$evidence .= ';退回进仓 ' . $received;
}
} elseif (preg_match('/^查件类型\/查件原因是([^\/]+)\/([^\/]+)$/u', $condition, $path)) {
$expected = trim($path[1]) . '/' . trim($path[2]);
$allowedReasons = array_map(static fn ($reason) => trim($path[1]) . '/' . trim($reason), explode('或', $path[2]));
$candidates = array_filter($orders, static function ($order) use ($rule): bool {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
return ($fields['logisticsField'] ?? '') === $rule->courier
&& substr($order->created, 0, 10) >= substr($rule->effective_at, 0, 10)
&& ! in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true);
});
if ($candidates === []) return '未找到同快递的有效查件工单,无法核验查件类型和原因';
usort($candidates, static fn ($a, $b) => [$b->created, $b->source_id] <=> [$a->created, $a->source_id]);
$latest = $candidates[0];
$fields = array_column(json_decode($latest->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
$actual = trim((string) ($fields['SELECT_CASCADEField1413856620250813172526'] ?? ''));
if ($actual === '') return '查件工单未填写查件类型和原因,待核实';
$evidence = '聚工单 ' . $latest->woNo . ' 查件类型/原因为“' . $actual . '”';
if (! in_array($actual, $allowedReasons, true)) return [['settlement_amount' => 0, 'evidence' => $evidence . ',不符合报价条件“' . $expected . '”,不计费']];
$evidence .= ',符合报价条件';
} elseif (in_array($condition, ['聚工单客服回复通过', '改地址客服回复通过'], true)) {
$approved = false;
foreach ($orders as $order) {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], null, 'fieldId');
if (($fields['logisticsField']['value'] ?? '') !== $rule->courier
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
// 改地址固定报价也接受工单中明确的客服通过回复,不把“已联系快递修改”视作通过。
$reason = (string) ($fields['SELECT_CASCADEField1413856620250813172526']['value'] ?? '');
if ($type === '改地址' && str_starts_with($reason, '改地址')
&& (in_array(trim((string) ($fields['SELECT_CASCADEField1413856620250814100750']['value'] ?? '')), ['通过', '已通过'], true)
|| in_array(trim((string) ($fields['TEXTField1413856620250902151101']['value'] ?? '')), ['通过', '已通过', '客服回复已通过'], true))) {
$approved = true;
$evidence = '聚工单 ' . $order->woNo . ' 改地址客服明确回复已通过';
}
foreach ($fields[ServiceFees::FEE_TABLE]['childFieldList'] ?? [] as $line) {
$values = array_column($line, 'value', 'fieldId');
if (SurchargeSettlementMatcher::type((string) ($values[ServiceFees::FEE_TYPE] ?? '')) === $type
&& ($values[ServiceFees::FEE_APPROVAL] ?? '') === '通过') {
$approved = true;
$evidence = '聚工单 ' . $order->woNo . ' 对应费用客服审核通过';
}
}
}
if (! $approved) return '未找到同快递、同费用类型的客服审核通过明细';
} elseif (! in_array($condition, ['', '固定单价', '按单收取', '每单收取'], true)) {
return '固定单价的计费条件尚未支持自动核验';
}
$amount = (float) $price[1];
return [['settlement_amount' => $amount, 'evidence' => ($evidence === '' ? '' : $evidence . ';')
. '固定单价 ' . number_format($amount, 2, '.', '') . ' 元/单,按票计一次']];
}
/** 按本批订单索引查询最新普通/淘系退回件,旧售后镜像补充历史;不限制进仓日期。 */
private function receivedReturns(array $orders, array $waybills): array
{
$ids = [];
foreach ($orders as $records) foreach ($records as $order) {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
$id = trim((string) ($fields['o_id'] ?? ''));
if (ctype_digit($id) && $id !== '0') $ids[$id] = true;
}
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
$schema = $db->getSchemaBuilder();
$hasReturnedParcels = $schema->hasTable('courier_returned_parcels');
$legacySources = array_filter([
['ops_jst_return_refund_info', 'ops_jst_return_refund_item'],
['ops_jst_qmcust_refunds', 'ops_jst_qmcust_refund_items'],
], fn ($tables) => $schema->hasTable($tables[0]) && $schema->hasTable($tables[1]));
$result = [];
foreach (array_chunk(array_keys($ids), 300) as $chunk) {
if ($hasReturnedParcels) {
$rows = $db->table('courier_returned_parcels')->whereIn('order_id', array_map('strval', $chunk))
->where('returned_qty', '>', 0)->whereNotNull('received_at')
->select('order_id', 'waybill')->selectRaw('MIN(received_at) AS received_at')
->groupBy('order_id', 'waybill')->orderBy('received_at')->get();
foreach ($rows as $row) $result[(string) $row->order_id] ??= $row->received_at
. (trim((string) $row->waybill) !== '' ? ';退回单号 ' . $row->waybill : '');
}
foreach ($legacySources as [$header, $items]) {
$remaining = array_values(array_filter($chunk, fn ($id) => ! isset($result[(string) $id])));
if ($remaining === []) break;
$rows = $db->table($header . ' as h')->join($items . ' as i', 'i.as_id', '=', 'h.as_id')
->whereIn('h.o_id', $remaining)->where('i.r_qty', '>', 0)->whereNotNull('i.receive_date')
->select('h.o_id')->selectRaw('MIN(' . $db->getQueryGrammar()->wrap('i.receive_date') . ') AS received_at')->groupBy('h.o_id')->get();
foreach ($rows as $row) $result[(string) $row->o_id] = $row->received_at;
}
}
if ($hasReturnedParcels) {
$query = $db->table('courier_returned_parcels')->where('returned_qty', '>', 0)->whereNotNull('received_at');
foreach (WaybillMatch::find($query, 'waybill', $waybills, ['waybill', 'received_at']) as $number => $match) {
$records = $match['rows'];
usort($records, fn ($a, $b) => $a->received_at <=> $b->received_at);
$result['waybill:' . strtoupper($number)] = $records[0]->received_at . ';退回单号 ' . $records[0]->waybill
. ($match['exact'] ? '(精确匹配)' : '(模糊匹配:格式或T前缀)');
}
}
return $result;
}
private function buyerConfirmations(iterable $rules, array $orders, string $month): array
{
$rows = [];
foreach ($rules as $rule) {
if ($rule->mode !== '取发出运费' || trim($rule->condition) !== '查件扣单并且买家原因') continue;
foreach ($orders as $waybill => $records) foreach ($records as $order) {
$rows[] = ['id' => self::buyerConfirmationKey((int) $rule->id, $month, $waybill, $order->woNo),
'rule_id' => $rule->id, 'waybill' => $waybill, 'work_order' => $order->woNo];
}
}
if ($rows === []) return [];
$result = [];
foreach (app(SupplierPayableOverrideStore::class)->decorate(self::BUYER_CONFIRMATIONS, $rows, (int) (company_id() ?: 1)) as $row) {
if ($row['_overridden']) $result[$row['rule_id']][$row['waybill']][$row['work_order']] = $row;
}
return $result;
}
private function workOrders(array $waybills, string $month): array
{
if (! app(WorkOrderWaybillLookup::class)->ready()) return [];
$rows = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))
->table(WorkOrderWaybillLookup::TABLE . ' as l')->join(WorkOrderWaybillLookup::SOURCE . ' as w', 'w._mirror_key', '=', 'l.mirror_key')
->whereIn('l.waybill', $waybills)->where('w.created', '>=', self::window($month)['from'])
->where('w.created', '<', self::window($month)['until'])
->orderBy('w.Id')->get(['l.waybill', 'w.Id as source_id', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']);
$result = [];
foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row;
return $result;
}
}

View File

@ -12,6 +12,9 @@ use RuntimeException;
*/ */
final class CourierBillMatcher final class CourierBillMatcher
{ {
/** 这两家运费按我方核算结算,不能因合并分组而影响同组其他快递。 */
public const ACTUAL_FREIGHT_EXPRESSES = ['中铁物流', '武进安能'];
private ?AccessoryDeductions $deductions = null; private ?AccessoryDeductions $deductions = null;
public function __construct( public function __construct(
@ -52,7 +55,12 @@ final class CourierBillMatcher
} }
$unshipped = $this->unshipped->unshippedSources($waybills); $unshipped = $this->unshipped->unshippedSources($waybills);
$unshipped = array_change_key_case($unshipped, CASE_UPPER); $unshipped = array_change_key_case($unshipped, CASE_UPPER);
$shipping = $this->shipping->summaries($waybills); $shipping = $this->shipping->summaries($waybills, $names);
foreach ($shipping as $key => $ship) {
if (($ship['data_source'] ?? null) !== '退件取件管理') continue;
unset($unshipped[$key]);
if (filled($ship['unshipped_source'] ?? null)) $unshipped[$key] = [$ship['unshipped_source']];
}
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号 // 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w]))); $missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) { foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
@ -78,7 +86,7 @@ final class CourierBillMatcher
'calc_freight' => $ship['calc_freight'] ?? null, 'calc_freight' => $ship['calc_freight'] ?? null,
'charge_weight' => $ship['charge_weight'] ?? null, 'charge_weight' => $ship['charge_weight'] ?? null,
'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null, 'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null,
'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution), 'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution, $ship['express_name'] ?? null),
]; ];
} }
@ -89,7 +97,7 @@ final class CourierBillMatcher
$unprovided[$row['waybill']] = $row; $unprovided[$row['waybill']] = $row;
} }
} }
$unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided)); $unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided), $names);
$db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void { $db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void {
foreach ($updates as $id => $values) { foreach ($updates as $id => $values) {
@ -148,13 +156,15 @@ final class CourierBillMatcher
return [Category::DIFF, null]; return [Category::DIFF, null];
} }
/** 自算金额:处理结果优先;否则一致类和前月补提供按核算运费,其余为 0。 */ /** 人工处理优先;中铁物流、武进安能运费取核算值,其他正常应付取较低值,缺少核算依据保持空白。 */
public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution, ?string $expressName = null): ?float
{ {
return match ($resolution) { return match ($resolution) {
'agree' => $billAmount === null ? null : (float) $billAmount, 'agree' => $billAmount === null ? null : (float) $billAmount,
'exclude', 'defer' => 0.0, 'exclude', 'defer' => 0.0,
default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) ? $calcFreight : 0.0, default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true)
? (in_array(trim((string) $expressName), self::ACTUAL_FREIGHT_EXPRESSES, true) ? $calcFreight
: ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight)) : 0.0,
}; };
} }
@ -169,14 +179,14 @@ final class CourierBillMatcher
$db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void { $db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void {
foreach (array_chunk($lineIds, 500) as $chunk) { foreach (array_chunk($lineIds, 500) as $chunk) {
$lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk) $lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk)
->get(['id', 'category', 'calc_freight', 'bill_amount']); ->get(['id', 'category', 'calc_freight', 'bill_amount', 'express_name']);
foreach ($lines as $line) { foreach ($lines as $line) {
$db->table('courier_bill_lines')->where('id', $line->id)->update([ $db->table('courier_bill_lines')->where('id', $line->id)->update([
'resolution' => $resolution, 'resolution' => $resolution,
'resolved_by' => $resolution === null ? null : $user, 'resolved_by' => $resolution === null ? null : $user,
'resolved_at' => $resolution === null ? null : now(), 'resolved_at' => $resolution === null ? null : now(),
'self_amount' => self::selfAmount((string) $line->category, 'self_amount' => self::selfAmount((string) $line->category,
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution), $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution, $line->express_name),
]); ]);
$count++; $count++;
} }
@ -191,7 +201,7 @@ final class CourierBillMatcher
* 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列: * 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列:
* 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。 * 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。
*/ */
public function refreshSummary(int $statementId): void public function refreshSummary(int $statementId, bool $refreshSources = true): void
{ {
$db = self::db(); $db = self::db();
$month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month'); $month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month');
@ -250,17 +260,36 @@ final class CourierBillMatcher
} }
} }
uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']); uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']);
$this->addAccessoryDeduction($statementId, $month, $items); if ($refreshSources) {
$this->addAccessoryDeduction($statementId, $month, $items);
} else {
// 仅调整结算口径时,沿用已保存的配件扣款和补记账,不重新读取来源。
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->get() as $saved) {
if ($saved->label !== WeightDifferenceSubsidy::LABEL && in_array(SummaryMapper::classify($saved->label), ['AL', 'supplement'], true)) {
$items[$saved->label] = ['bill' => $saved->bill_amount, 'self' => $saved->self_amount, 'sort' => $saved->sort];
$kinds[$saved->label] = 'saved';
}
}
}
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label') $manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip(); ->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
$subsidy = app(WeightDifferenceSubsidy::class)->summary($statementId);
if ($subsidy['count'] > 0 && ! isset($manualLabels[WeightDifferenceSubsidy::LABEL])) {
$items[WeightDifferenceSubsidy::LABEL] = ['bill' => null, 'self' => $subsidy['amount'], 'sort' => 9200];
$kinds[WeightDifferenceSubsidy::LABEL] = 'weight-subsidy';
}
$kinds['配件补发扣款'] = 'accessory'; $kinds['配件补发扣款'] = 'accessory';
$surchargeMatcher=app(SurchargeSettlementMatcher::class);
if ($refreshSources) $surchargeMatcher->courier($statementId);
$matchedFees=$surchargeMatcher->ready()?$surchargeMatcher->query('courier',$statementId)
->selectRaw('summary_label, SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all():[];
$fees = $this->surchargeItems($statementId); $fees = $this->surchargeItems($statementId);
$template = $this->templateFor($statementId); $template = $this->templateFor($statementId);
if ($refreshSources) $this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
$sort = 8000; $sort = 8000;
foreach ($fees as $item => $sum) { foreach ($fees as $item => $sum) {
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) { if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
// 附加费不逐单核对:自算先放 0,手工核对后在小汇总里回填 $items[$item] = ['bill' => $sum, 'self' => isset($matchedFees[$item]) ? (float)$matchedFees[$item] : 0.0, 'sort' => $sort++];
$items[$item] = ['bill' => $sum, 'self' => 0.0, 'sort' => $sort++];
$kinds[$item] = 'fee'; $kinds[$item] = 'fee';
} }
} }
@ -292,7 +321,7 @@ final class CourierBillMatcher
foreach ($items as $name => $item) { foreach ($items as $name => $item) {
$db->table('courier_bill_summary_items')->insert([ $db->table('courier_bill_summary_items')->insert([
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4), 'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4),
'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort, 'self_amount' => $item['self'] === null ? null : round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
]); ]);
} }
} }
@ -302,6 +331,34 @@ final class CourierBillMatcher
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(), 'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
]); ]);
} }
/** 历史账单补接附加费时只更新费用行,保留原运费与手工小汇总。 */
public function refreshSurchargeSummary(int $statementId): void
{
$db=self::db();
$db->transaction(function()use($db,$statementId):void{
$statement=$db->table('courier_bill_statements')->where('id',$statementId)->lockForUpdate()->first();
if(!$statement||$statement->status==='confirmed')return;
$matcher=app(SurchargeSettlementMatcher::class);$matcher->courier($statementId);
if(!$matcher->ready())return;
$sums=$matcher->query('courier',$statementId)->selectRaw('summary_label,SUM(bill_amount) AS bill,SUM(self_amount) AS self')
->groupBy('summary_label')->get();
$auto=[];foreach($sums as $sum)$auto[$sum->summary_label]=['bill'=>(float)$sum->bill,'self'=>(float)$sum->self,'kind'=>'fee'];
$template=$this->templateFor($statementId);
$rows=$template===null?array_map(fn($label,$v)=>['label'=>$label]+$v,array_keys($auto),array_values($auto))
:array_values(array_filter(SummaryTemplate::apply($template,$auto,(int)substr($statement->bill_month,5,2)),fn($r)=>$r['fee']));
foreach($rows as $row){
$existing=$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->where('label',$row['label'])->orderBy('id')->first();
if($existing){
if(!$existing->manual)$db->table('courier_bill_summary_items')->where('id',$existing->id)->update(['self_amount'=>round((float)$row['self'],2)]);
}else{
$sort=(int)$db->table('courier_bill_summary_items')->where('statement_id',$statementId)->max('sort')+1;
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$statementId,'label'=>$row['label'],
'bill_amount'=>$row['bill'],'self_amount'=>round((float)$row['self'],2),'manual'=>false,'sort'=>$sort]);
}
}
});
}
/** /**
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。 * 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。 * 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
@ -329,6 +386,38 @@ final class CourierBillMatcher
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000]; $items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
} }
} }
/**
* 补记账:按扣款月份各一行「补X月记账」(快递金额空、自算为补款金额),照模板落到「补9月记账」「2026.8-9月记账补款」「补记账」这类行。
* 已经手工加了补记账行时不再自动加,免得补两次;记账明细、复核还没导时不加。
*
* @param list<string>|null $template
* @param \Illuminate\Support\Collection<string,int> $manualLabels
* @param array<string,array{bill:?float,self:float,sort:int}> $items
* @param array<string,string> $kinds
*/
private function addRebooks(int $statementId, ?array $template, $manualLabels, array &$items, array &$kinds): void
{
foreach ($manualLabels->keys() as $label) {
if (Rebooks::isRebookLabel((string) $label)) {
return;
}
}
try {
$plan = app(Rebooks::class)->forStatement($statementId, $template);
} catch (\Throwable $error) {
report($error);
return;
}
$totals = Rebooks::totals($plan['rows']);
foreach (array_unique(array_column($plan['rows'], 'deduct_month')) as $deductMonth) {
$amount = $totals[$deductMonth] ?? 0.0;
$label = Rebooks::label($deductMonth);
$items[$label] = ['bill' => null, 'self' => $amount, 'sort' => 9100 + (int) substr($deductMonth, 5, 2)];
$kinds[$label] = 'rebook:' . (int) substr($deductMonth, 5, 2);
}
}
/** 小汇总里哪些行是账单读出来的附加费(可以回填自算金额)。 @return list<string> */ /** 小汇总里哪些行是账单读出来的附加费(可以回填自算金额)。 @return list<string> */
public function feeLabels(int $statementId): array public function feeLabels(int $statementId): array
{ {
@ -380,7 +469,7 @@ final class CourierBillMatcher
/** /**
* 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应; * 这张对账单分到的附加费:一张附加费表一行,名字就用快递账单里的表名(如「山东中通快运加收&上楼费」),方便和账单对应;
* 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计。快递开的金额,自算先放 0,不逐单核对。 * 运费表里用「费用项目」分出来的附加费行,没有单独的表名,按费用项目合计;自算另取逐票匹配结果。
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。 * 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
* *
* @return array<string,float> * @return array<string,float>
@ -395,9 +484,11 @@ final class CourierBillMatcher
return []; return [];
} }
$result = []; $result = [];
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id'); $files = $db->table('courier_bill_files')->whereIn('id', $fileIds)->get(['id', 'statement_id', 'extra_group_ids']);
foreach ($primaryIds as $fileId => $primaryId) { foreach ($files as $file) {
$primary = (int) $primaryId; $fileId = (int) $file->id;
$primary = (int) $file->statement_id;
$joint = isset(json_decode((string) $file->extra_group_ids, true)['joint_upload']);
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId); $rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
if (! (clone $rows)->exists()) { if (! (clone $rows)->exists()) {
continue; continue;
@ -415,11 +506,14 @@ final class CourierBillMatcher
} }
} }
} }
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, &$result): void { $rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, $joint, $fileId, &$result): void {
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all()); $assigned = $joint ? self::db()->table('courier_bill_lines')->where('file_id', $fileId)
->whereIn('waybill_no', $chunk->pluck('waybill_no'))->pluck('statement_id', 'waybill_no')->all() : [];
$shipping = $joint || $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all(), array_keys($names));
foreach ($chunk as $row) { foreach ($chunk as $row) {
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? ''; $express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
if (($names[$express] ?? $primary) !== $statementId) { $owner = $joint ? (int) ($assigned[$row->waybill_no] ?? 0) : ($names[$express] ?? $primary);
if ($owner !== $statementId) {
continue; continue;
} }
$label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet; $label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet;

View File

@ -54,6 +54,10 @@ final class CourierBillStore
'weight_header' => self::blank($data['weight_header'] ?? null), 'weight_header' => self::blank($data['weight_header'] ?? null),
'updated_at' => now(), 'updated_at' => now(),
]; ];
if (array_key_exists('rebook_months', $data)) {
// 补记账补几个月:空 = 按小汇总识别
$values['rebook_months'] = in_array($data['rebook_months'], [null, ''], true) ? null : min(max((int) $data['rebook_months'], 0), Rebooks::MAX_MONTHS);
}
if ($id === null) { if ($id === null) {
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]); return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
} }
@ -362,6 +366,31 @@ final class CourierBillStore
return $id; return $id;
} }
public function uploadJoint(UploadedFile $file, string $month, array $scope, string $user): int
{
return $this->db()->transaction(function () use ($file, $month, $scope, $user): int {
$set = app(CourierJointUploads::class)->verify($scope);
$this->lockJointTargets($set['group_ids'], $month);
$id = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month,
$set['group_ids'], $set['groups'], $user, true, $scope);
if ($this->db()->table('courier_bill_files')->where('id', $id)->value('status') === 'parsed') {
foreach ($this->statementsOfFiles([$id]) as $statementId) $this->matcher->match($statementId);
}
return $id;
});
}
private function lockJointTargets(array $ids, string $month): void
{
$db = $this->db();
$db->table('courier_bill_groups')->whereIn('id', $ids)->orderBy('id')->lockForUpdate()->get();
if ($db->table('courier_bill_statements')->whereIn('group_id', $ids)->where('bill_month', $month)
->orderBy('id')->lockForUpdate()->get()->contains('status', 'confirmed')) {
throw new RuntimeException('联合上传范围中有分组本月已确认结算,请联系财务。');
}
}
/** 给待选分组的文件指定分组,读入并对账。 */ /** 给待选分组的文件指定分组,读入并对账。 */
public function assign(int $fileId, int $groupId): void public function assign(int $fileId, int $groupId): void
{ {
@ -394,6 +423,7 @@ final class CourierBillStore
$db->transaction(function () use ($db, $file): void { $db->transaction(function () use ($db, $file): void {
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete(); $db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
$db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete(); $db->table('courier_bill_surcharges')->where('file_id', $file->id)->delete();
if(app(SurchargeSettlementMatcher::class)->ready())$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('file_id',$file->id)->delete();
$db->table('courier_bill_files')->where('id', $file->id)->delete(); $db->table('courier_bill_files')->where('id', $file->id)->delete();
}); });
Storage::disk(self::DISK)->delete($file->stored_path); Storage::disk(self::DISK)->delete($file->stored_path);
@ -423,7 +453,7 @@ final class CourierBillStore
* @param list<int> $groupIds * @param list<int> $groupIds
* @param list<object> $groups * @param list<object> $groups
*/ */
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false): int private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false, ?array $joint = null): int
{ {
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension; $stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
@ -436,7 +466,7 @@ final class CourierBillStore
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([ $id = (int) $this->db()->table('courier_bill_files')->insertGetId([
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(), 'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
'extra_group_ids' => $extra === [] ? null : json_encode($extra), 'extra_group_ids' => $joint !== null ? json_encode(['joint_upload' => $joint]) : ($extra === [] ? null : json_encode($extra)),
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null, 'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
]); ]);
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
@ -456,6 +486,12 @@ final class CourierBillStore
{ {
$db = $this->db(); $db = $this->db();
$file = $db->table('courier_bill_files')->find($fileId); $file = $db->table('courier_bill_files')->find($fileId);
$joint = json_decode((string) $file->extra_group_ids, true)['joint_upload'] ?? null;
if ($joint !== null) {
$set = app(CourierJointUploads::class)->verify($joint);
$this->lockJointTargets($set['group_ids'], (string) $file->bill_month);
$portal = true;
}
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first(); $statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
if ($statement !== null && $statement->status === 'confirmed') { if ($statement !== null && $statement->status === 'confirmed') {
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id, $db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
@ -481,7 +517,7 @@ final class CourierBillStore
$feeCount = 0; $feeCount = 0;
$overlap = null; $overlap = null;
try { try {
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string { $split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, $joint, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') { if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。'); throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
} }
@ -562,7 +598,7 @@ final class CourierBillStore
$db->table('courier_bill_surcharges')->insert($fees); $db->table('courier_bill_surcharges')->insert($fees);
} }
return $portal ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread); return $portal && $joint === null ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
}); });
} catch (Throwable $error) { } catch (Throwable $error) {
if ($reread) { if ($reread) {
@ -593,7 +629,7 @@ final class CourierBillStore
$notes[] = '没有找到含单号和运费列的工作表'; $notes[] = '没有找到含单号和运费列的工作表';
} }
if ($feeCount > 0) { if ($feeCount > 0) {
$notes[] = '附加费只读了金额进小汇总,没有逐单核对:' . $feeCount . ' 行,合计 ' . number_format($feeTotal, 2); $notes[] = '附加费已按单号和费用类型匹配结算表:' . $feeCount . ' 行,对方合计 ' . number_format($feeTotal, 2);
} }
$unread = []; $unread = [];
foreach ($sheets as $sheet) { foreach ($sheets as $sheet) {
@ -641,6 +677,8 @@ final class CourierBillStore
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
{ {
$db = $this->db(); $db = $this->db();
$metadata = json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true);
if (isset($metadata['joint_upload'])) return $this->splitJoint($fileId, $month, $metadata['joint_upload']);
$groups = collect($this->groups()); $groups = collect($this->groups());
$extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true)); $extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true));
$bundle = trim((string) ($primary->bundle ?? '')); $bundle = trim((string) ($primary->bundle ?? ''));
@ -663,7 +701,8 @@ final class CourierBillStore
} }
$lines = $db->table('courier_bill_lines')->where('file_id', $fileId)->where('statement_id', $primaryStatementId)->orderBy('id')->get(['id', 'waybill_no']); $lines = $db->table('courier_bill_lines')->where('file_id', $fileId)->where('statement_id', $primaryStatementId)->orderBy('id')->get(['id', 'waybill_no']);
$ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all()); $ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all(),
array_values(array_unique([...array_keys($own), ...array_keys($byName)])));
$moves = []; $moves = [];
$strangers = []; $strangers = [];
foreach ($lines as $line) { foreach ($lines as $line) {
@ -721,6 +760,56 @@ final class CourierBillStore
return implode(';', $parts); return implode(';', $parts);
} }
/** 只在签名授权范围内逐批归组;任何无法归属的行整份退回,避免留在错误的主分组。 */
private function splitJoint(int $fileId, string $month, array $scope): string
{
$db = $this->db();
$set = app(CourierJointUploads::class)->verify($scope);
$this->lockJointTargets($set['group_ids'], $month);
$owners = [];
$statements = [];
foreach ($set['groups'] as $g) {
foreach (array_intersect(array_unique([$g->name, ...$g->express_names]), $set['names']) as $name) {
if (isset($owners[$name]) && $owners[$name] !== (int) $g->id) throw new RuntimeException('联合上传快递名称重复,请联系财务。');
$owners[$name] = (int) $g->id;
}
$statement = $db->table('courier_bill_statements')->where('group_id', $g->id)->where('bill_month', $month)->first();
if ($statement !== null) $statements[(int) $g->id] = (int) $statement->id;
}
$counts = [];
$db->table('courier_bill_lines')->where('file_id', $fileId)->orderBy('id')->chunkById(500, function ($lines) use ($db, $owners, $month, &$statements, &$counts): void {
$shipping = $this->shipping->summaries($lines->pluck('waybill_no')->all(), array_keys($owners));
$moves = [];
foreach ($lines as $line) {
$raw = json_decode((string) $line->raw, true);
$declared = trim((string) ($raw[4] ?? ''));
if ($declared !== '' && ! isset($owners[$declared])) throw new RuntimeException('第 ' . $line->row_no . ' 行快递名称不在本链接范围内。整份文件未读入。');
$name = trim((string) ($shipping[strtoupper($line->waybill_no)]['express_name'] ?? ''));
if ($name === '') $name = $declared;
$groupId = $owners[$name] ?? null;
if ($groupId === null) throw new RuntimeException('第 ' . $line->row_no . ' 行单号 ' . $line->waybill_no . ' 无法归到本链接范围;系统查不到时请填写范围内的快递名称。整份文件未读入。');
$statements[$groupId] ??= (int) $db->table('courier_bill_statements')->insertGetId([
'group_id' => $groupId, 'bill_month' => $month, 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]);
$moves[$statements[$groupId]][] = (int) $line->id;
$counts[$groupId] = ($counts[$groupId] ?? 0) + 1;
}
foreach ($moves as $statementId => $ids) $db->table('courier_bill_lines')->whereIn('id', $ids)->update(['statement_id' => $statementId]);
});
// 附加费沿用同单号的运费归属,不把找不到归属的费用默认塞给主分组。
$missingFee = $db->table('courier_bill_surcharges as fee')->where('fee.file_id', $fileId)
->whereNotExists(fn ($q) => $q->selectRaw('1')->from('courier_bill_lines as line')
->whereColumn('line.file_id', 'fee.file_id')->whereColumn('line.waybill_no', 'fee.waybill_no'))->first();
if ($missingFee !== null) throw new RuntimeException('附加费单号 ' . $missingFee->waybill_no . ' 缺少对应运费明细,无法确定分组。整份文件未读入。');
$ambiguous = $db->table('courier_bill_lines')->where('file_id', $fileId)->groupBy('waybill_no')
->havingRaw('COUNT(DISTINCT statement_id) > 1')->first(['waybill_no']);
if ($ambiguous !== null) throw new RuntimeException('单号 ' . $ambiguous->waybill_no . ' 填写了不同快递名称,请核对。整份文件未读入。');
$notes = [];
foreach ($set['groups'] as $g) if (isset($counts[$g->id])) $notes[] = $g->name . ' ' . $counts[$g->id] . ' 行';
return '联合上传已归组:' . implode('、', $notes);
}
/** /**
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。 * 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
* 涉及的对账单有已确认结算的就不动。 * 涉及的对账单有已确认结算的就不动。
@ -926,7 +1015,7 @@ final class CourierBillStore
return $files; return $files;
} }
/** 确认结算:锁定对账单,结算台账记下这批单号。 */ /** 确认结算:锁定对账单,结算台账记下这批单号;这期补记账补的单记进补记账台账(补过的不再补)。 */
public function confirm(int $statementId, string $user): void public function confirm(int $statementId, string $user): void
{ {
$db = $this->db(); $db = $this->db();
@ -959,6 +1048,9 @@ final class CourierBillStore
if ($buffer !== []) { if ($buffer !== []) {
$db->table('courier_bill_ledger')->insertOrIgnore($buffer); $db->table('courier_bill_ledger')->insertOrIgnore($buffer);
} }
$rebooks = app(Rebooks::class);
$rebooks->forget((int) $statement->id);
$rebooks->record((int) $statement->id);
$db->table('courier_bill_statements')->where('id', $statement->id)->update([ $db->table('courier_bill_statements')->where('id', $statement->id)->update([
'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(), 'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(),
]); ]);
@ -970,6 +1062,7 @@ final class CourierBillStore
$db = $this->db(); $db = $this->db();
$db->transaction(function () use ($db, $statementId): void { $db->transaction(function () use ($db, $statementId): void {
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete(); $db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
app(Rebooks::class)->forget($statementId);
$db->table('courier_bill_statements')->where('id', $statementId)->update([ $db->table('courier_bill_statements')->where('id', $statementId)->update([
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(), 'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
]); ]);

View File

@ -0,0 +1,50 @@
<?php
namespace App\Support\CourierBills;
use DateTimeInterface;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* 快递账单确认链接。factory_id 保留共享令牌结构,表示对账单 ID;
* 公司、对账单、账期和推送版本均被加密签名约束,不沿用联合上传链接的范围。
*/
final class CourierFreightLink
{
public const TTL_DAYS = 30;
public function pageUrl(int $companyId, int $factoryId, string $month, int $version): string
{
return $this->signedRoute('signed.courier-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId);
}
public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null, array $query = []): string
{
$url = URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]);
return $query === [] ? $url : $url . '&' . http_build_query($query);
}
/** @return array{factory_id:int,month:string,version:int}|null */
public function resolveToken(string $token, int $companyId): ?array
{
try {
$padding = (4 - strlen($token) % 4) % 4;
$encrypted = base64_decode(strtr($token . str_repeat('=', $padding), '-_', '+/'), true);
if ($encrypted === false) {
return null;
}
$payload = json_decode(Crypt::decryptString($encrypted), true, flags: JSON_THROW_ON_ERROR);
} catch (Throwable) {
return null;
}
if (!is_array($payload) || (int) ($payload['company_id'] ?? 0) !== $companyId || (int) ($payload['factory_id'] ?? 0) <= 0 || preg_match('/^\d{4}-\d{2}$/', (string) ($payload['month'] ?? '')) !== 1 || (int) ($payload['version'] ?? 0) <= 0) {
return null;
}
return ['factory_id' => (int) $payload['factory_id'], 'month' => (string) $payload['month'], 'version' => (int) $payload['version']];
}
private function token(int $companyId, int $factoryId, string $month, int $version): string
{
$payload = json_encode(['company_id' => $companyId, 'factory_id' => $factoryId, 'month' => $month, 'version' => $version], JSON_THROW_ON_ERROR);
return rtrim(strtr(base64_encode(Crypt::encryptString($payload)), '+/', '-_'), '=');
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Support\CourierBills;
use RuntimeException;
/** 明确授权的联合上传范围,不从机器人、文件名或合并账单配置推断。 */
final class CourierJointUploads
{
public const SETS = [
'qiaoshe' => ['label' => '樵舍联合上传', 'names' => ['江西新建中通', '江西中通快运', '樵舍中通', '樵舍中通-上楼', '山东中通快运', '西安圆通', '西安中通快运']],
'yuantong' => ['label' => '圆通联合上传', 'names' => ['常州圆通其他', '常州圆通-上楼', '小件宿迁圆通', '睢宁宿迁圆通', '苏北宿迁圆通']],
'hebei' => ['label' => '河北中通与霸州百世联合上传', 'names' => ['河北中通-江三', '河北中通小件-江三', '霸州百世快运-雅柏']],
'debang-shunfeng' => ['label' => '德邦与顺丰干配联合上传', 'names' => ['睢宁德邦', '崔桥顺丰干配', '山东顺丰干配', '山东顺丰大件', '苏北顺丰干配大件', '苏北顺丰干配小件']],
];
public function resolve(string $key): array
{
$set = self::SETS[$key] ?? throw new RuntimeException('联合上传范围不存在。');
$groups = app(CourierBillStore::class)->groups();
$selected = [];
foreach ($set['names'] as $name) {
$matches = array_values(array_filter($groups, static fn ($g) => $g->name === $name || in_array($name, $g->express_names, true)));
if (count($matches) !== 1) throw new RuntimeException('联合上传分组「' . $name . '」未配置或存在重名,请联系财务。');
$g = $matches[0];
// 可通过别名定位既有分组;上传时仍只允许本集合列出的名称。
$selected[(int) $g->id] = $g;
}
ksort($selected);
$fingerprint = [];
foreach ($selected as $id => $group) {
$names = $group->express_names;
sort($names);
$fingerprint[] = [$id, $group->name, $names];
}
return $set + ['key' => $key, 'groups' => array_values($selected), 'group_ids' => array_keys($selected),
'fingerprint' => hash('sha256', json_encode($fingerprint, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))];
}
public function snapshot(string $key): array
{
$set = $this->resolve($key);
return array_intersect_key($set, array_flip(['key', 'group_ids', 'fingerprint']));
}
public function verify(array $snapshot): array
{
$set = $this->resolve((string) ($snapshot['key'] ?? ''));
if ($set['group_ids'] !== ($snapshot['group_ids'] ?? null) || $set['fingerprint'] !== ($snapshot['fingerprint'] ?? null)) {
throw new RuntimeException('联合上传分组设置已变化,请联系财务重新生成链接。');
}
return $set;
}
}

View File

@ -19,12 +19,21 @@ final class CourierUploadLink
return $this->signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $companyId); return $this->signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $companyId);
} }
public function jointPageUrl(int $companyId, string $key, string $month): string
{
$joint = app(CourierJointUploads::class)->snapshot($key);
$payload = ['company_id' => $companyId, 'group_id' => $joint['group_ids'][0], 'month' => $month, 'joint' => $joint];
$token = rtrim(strtr(base64_encode(Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR))), '+/', '-_'), '=');
return $this->signedRoute('signed.courier-bill-upload.show', $token, $companyId);
}
public function signedRoute(string $routeName, string $token, int $companyId, ?\DateTimeInterface $expires = null): string public function signedRoute(string $routeName, string $token, int $companyId, ?\DateTimeInterface $expires = null): string
{ {
return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]); return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]);
} }
/** @return array{group_id:int,month:string}|null */ /** @return array{group_id:int,month:string,joint:?array}|null */
public function resolveToken(string $token, int $companyId): ?array public function resolveToken(string $token, int $companyId): ?array
{ {
try { try {
@ -42,7 +51,7 @@ final class CourierUploadLink
return null; return null;
} }
return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month']]; return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month'], 'joint' => $payload['joint'] ?? null];
} }
private function token(int $companyId, int $groupId, string $month): string private function token(int $companyId, int $groupId, string $month): string

View File

@ -112,6 +112,27 @@ final class FreightBillTemplate
return $result; return $result;
} }
/** 逐行保留单号与类型,不能只汇总账单金额后丢失匹配依据。 */
public function surchargeRows(string $path,string $extension): \Generator
{
foreach($this->reader->sheets($path,$extension) as $name=>$rows){
if(!str_contains(trim((string)$name),self::SURCHARGE_SHEET))continue;
$header=false;
foreach($rows as $number=>$row){
$cells=array_slice(array_map(static fn($v):string=>trim((string)$v),$row),0,3);
if(implode('',$cells)==='')continue;
if(!$header){
if(array_values(self::trimTail($cells))!==self::SURCHARGE_HEADERS)throw new RuntimeException('附加费表头不符合模板,无法逐单核对。');
$header=true;continue;
}
if(in_array($cells[0]??'',self::TOTAL_WORDS,true))continue;
$waybill=Waybill::normalize($cells[0]??'');$amount=BillParser::number($cells[1]??null);$type=$cells[2]??'';
if($waybill===null||$amount===null||$type==='')throw new RuntimeException('附加费第 '.$number.' 行缺少完整单号、金额或类型。');
yield ['sheet'=>(string)$name,'row_no'=>(int)$number,'waybill_no'=>$waybill,'item'=>$type,'amount'=>$amount];
}
}
}
/** @return array{rows:int,waybills:int,amount:float} */ /** @return array{rows:int,waybills:int,amount:float} */
private function validateBill(?iterable $rows): array private function validateBill(?iterable $rows): array
{ {

View File

@ -0,0 +1,294 @@
<?php
namespace App\Support\CourierBills;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use RuntimeException;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;
/**
* 快递与代发共用的对方确认流程,财务结算台账仍由原业务负责。
*
* 和供应商对账一样存在通用数据表 supplier_payable_overrides 里,不加新表:
* 状态、版本快照、逐单异议与处理记录分别存储,每次读写限定公司、合作方和账期。
* 每次推送版本号加一,旧链接随之作废;历史异议保留,按版本区分。
*/
class FreightConfirmation
{
public const DATASET = 'courier-freight-confirm';
public const DISPUTES = 'courier-freight-dispute:';
public const OPEN = 'open';
public const CHECKED = 'checked';
public const SENDING = 'sending';
public const PUSHED = 'pushed';
public const FAILED = 'failed';
public const CONFIRMED = 'confirmed';
public const DISPUTED = 'disputed';
public const LABELS = [self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中', self::PUSHED => '已推送,待快递确认', self::FAILED => '推送失败', self::CONFIRMED => '快递已确认', self::DISPUTED => '快递有异议'];
public function __construct(private readonly SupplierPayableOverrideStore $store)
{
}
public static function key(string $month, int $factoryId): string
{
return $month . '|' . $factoryId;
}
public static function label(?array $state): string
{
return static::LABELS[(string) ($state['status'] ?? self::OPEN)] ?? static::LABELS[self::OPEN];
}
public function state(string $month, int $factoryId, int $companyId): ?array
{
return $this->store->findRow(static::DATASET, self::key($month, $factoryId), $companyId);
}
/** @return array<int,array<string,mixed>> 厂家ID => 状态 */
public function states(string $month, int $companyId): array
{
$out = [];
foreach ($this->query(static::DATASET, $companyId)->where('record_key', 'like', $month . '|%')->get(['values'])->map(fn ($r) => json_decode($r->values, true)) as $row) {
if (($row['month'] ?? '') === $month) {
$out[(int) ($row['factory_id'] ?? 0)] = $row;
}
}
return $out;
}
/** 财务点「核对完成」/「撤销核对完成」。厂家已确认后不能再撤销,要改就重新推送。 */
public function check(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
{
return $this->locked($month, (int) $factory->id, $companyId, fn () => $this->checkLocked($month, $factory, $summary, $checked, $companyId, $userId, $by));
}
private function checkLocked(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
{
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
$status = (string) ($state['status'] ?? self::OPEN);
if ($checked && !in_array($status, [self::OPEN, self::CHECKED, self::FAILED], true)) {
throw new RuntimeException('账单已经推送,请通过重新推送更新版本。');
}
if (!$checked && in_array($status, [self::PUSHED, self::CONFIRMED, self::DISPUTED, self::SENDING], true)) {
throw new RuntimeException('已经推送给厂家,不能撤销;有改动请改完后重新推送。');
}
$values = array_merge($this->base($state, $month, $factory), ['status' => $checked ? $status === self::OPEN || $status === self::FAILED ? self::CHECKED : $status : self::OPEN, 'checked_at' => $checked ? now()->toDateTimeString() : null, 'checked_by' => $checked ? $by : null, 'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff']]);
$this->store->save(static::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_check');
return $values;
}
/** 开始一次推送:版本号加一并记下这次的金额快照,返回新版本号。 */
public function startPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by, ?iterable $rows = null, array $fees = []): int
{
return $this->locked($month, (int) $factory->id, $companyId, function () use ($month, $factory, $summary, $attention, $companyId, $userId, $by, $rows, $fees) {
$version = $this->beginPush($month, $factory, $summary, $attention, $companyId, $userId, $by);
if ($rows !== null) {
$dataset = $this->snapshotDataset($month, (int) $factory->id, $version);
$batch = [];
$count = 0;
foreach ($rows as $row) {
if ($row['bill'] === null) {
continue;
}
$batch['line:' . str_pad((string) ++$count, 10, '0', STR_PAD_LEFT)] = array_intersect_key($row, array_flip([
'waybill', 'ship_time', 'express', 'bill', 'final', 'status', 'label', 'note',
'warehouse', 'calc', 'bill_weight', 'charge_weight', 'settlement_weight', 'weight_diff',
'diff_kind', 'settle', 'freight_diff', 'diff', 'status_month', 'formula', 'ship_waybill',
'file_id', 'sheet', 'row_no',
]));
if (count($batch) === 500) {
$this->store->saveBatch($dataset, $batch, $companyId, $userId, 'freight_snapshot');
$batch = [];
}
}
$this->store->saveBatch($dataset, $batch, $companyId, $userId, 'freight_snapshot');
$this->store->save($dataset, 'meta', ['summary' => $summary, 'fees' => $fees, 'rows' => $count], $companyId, $userId, 'freight_snapshot');
}
return $version;
});
}
private function beginPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by): int
{
if ((int) ($summary['billed'] ?? 0) === 0) {
throw new RuntimeException('本期没有可推送的账单明细。');
}
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
if (($state['status'] ?? self::OPEN) === self::OPEN) {
throw new RuntimeException('先点「核对完成」再推送给厂家。');
}
if (($state['status'] ?? '') === self::SENDING) {
throw new RuntimeException('正在推送,请稍后刷新查看结果。');
}
$version = (int) ($state['version'] ?? 0) + 1;
$values = array_merge($this->base($state, $month, $factory), ['status' => self::SENDING, 'version' => $version, 'pushed_by' => $by, 'push_requested_at' => now()->toDateTimeString(), 'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'], 'billed' => $summary['billed'], 'attention' => $attention, 'confirmed_at' => null, 'disputed_count' => 0, 'push_error' => null, 'receipt_error' => null, 'receipt_status' => null, 'pushed_at' => null]);
$this->store->save(static::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_push');
return $version;
}
public function markPushed(string $month, int $factoryId, int $companyId): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::PUSHED, 'pushed_at' => now()->toDateTimeString()], 'dropship_pushed');
}
public function markFailed(string $month, int $factoryId, int $companyId, string $message): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::FAILED, 'push_error' => mb_strimwidth($message, 0, 300, '…', 'UTF-8')], 'dropship_push_failed');
}
/**
* 厂家在确认页提交:没有异议 = 确认;有异议的单逐单记原因。同一版本只能提交一次。
*
* @param array<string,string> $disputes 快递单号 => 原因
* @return array<string,mixed> 提交后的状态
*/
public function submit(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
{
return $this->locked($month, $factoryId, $companyId, fn () => $this->submitLocked($month, $factoryId, $version, $disputes, $companyId));
}
private function submitLocked(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
{
$state = $this->state($month, $factoryId, $companyId);
if ($state === null || (int) ($state['version'] ?? 0) !== $version) {
throw new RuntimeException('这个链接已经不是最新一次推送,请以群里最新的推送为准。');
}
if (in_array($state['status'] ?? '', [self::CONFIRMED, self::DISPUTED], true)) {
throw new RuntimeException('本次对账已经提交,请查看已提交的结果。');
}
if (($state['status'] ?? '') !== self::PUSHED) {
throw new RuntimeException('本次对账尚未推送成功,请等待财务重新推送。');
}
if (count($disputes) > 500) {
throw new RuntimeException('一次最多提交 500 单异议。');
}
foreach ($disputes as $reason) {
if (trim((string) $reason) === '') {
throw new RuntimeException('请填写每单异议原因。');
}
}
if ($this->snapshot($month, $factoryId, $version, $companyId)) {
$query = $this->snapshotQuery($month, $factoryId, $version, $companyId);
$field = $query->getGrammar()->wrap('values->waybill');
$keys = array_map(fn ($w) => strtoupper((string)$w), array_keys($disputes));
$found = $keys === [] ? collect() : $query->whereRaw('UPPER('.$field.') IN ('.implode(',',array_fill(0,count($keys),'?')).')',$keys)
->get(['values'])->mapWithKeys(fn ($r) => [strtoupper((string)json_decode($r->values,true)['waybill']) => (string)json_decode($r->values,true)['waybill']]);
if ($found->count() !== count($disputes)) {
throw new RuntimeException('单号不在本次推送账单中。');
}
$canonical = [];
foreach ($disputes as $waybill => $reason) $canonical[$found[strtoupper((string)$waybill)]] = $reason;
$disputes = $canonical;
}
$now = now()->toDateTimeString();
$this->store->transaction(function () use ($month, $factoryId, $version, $disputes, $companyId, $now): void {
foreach ($disputes as $waybill => $reason) {
$this->store->save(static::DISPUTES . self::key($month, $factoryId), $version . '|' . $waybill, ['waybill' => (string) $waybill, 'reason' => $reason, 'version' => $version, 'submitted_at' => $now], $companyId, null, 'manufacturer_link');
}
$this->merge($month, $factoryId, $companyId, ['status' => $disputes === [] ? self::CONFIRMED : self::DISPUTED, 'confirmed_at' => $now, 'disputed_count' => count($disputes)], 'manufacturer_link');
});
return $this->state($month, $factoryId, $companyId) ?? [];
}
/** @return list<array<string,mixed>> 这家这个月的异议,最新版本在前 */
public function disputes(string $month, int $factoryId, int $companyId, ?int $version = null): array
{
$q = $this->query(static::DISPUTES . self::key($month, $factoryId), $companyId);
if ($version !== null) {
$q->where('record_key', 'like', $version . '|%');
}
$rows = $q->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
if ($version !== null) {
$rows = array_values(array_filter($rows, static fn (array $r): bool => (int) ($r['version'] ?? 0) === $version));
}
usort($rows, static fn (array $a, array $b): int => [(int) ($b['version'] ?? 0), (string) ($a['waybill'] ?? '')] <=> [(int) ($a['version'] ?? 0), (string) ($b['waybill'] ?? '')]);
return $rows;
}
private function base(array $state, string $month, object $factory): array
{
$keep = array_diff_key($state, array_flip(['_action_key']));
return array_merge($keep, ['factory_id' => (int) $factory->id, 'factory' => (string) $factory->name, 'supplier' => (string) $factory->name, 'month' => $month]);
}
private function merge(string $month, int $factoryId, int $companyId, array $values, string $source): void
{
$state = $this->state($month, $factoryId, $companyId) ?? [];
unset($state['_action_key']);
$this->store->save(static::DATASET, self::key($month, $factoryId), array_merge($state, $values), $companyId, null, $source);
if (($state['version'] ?? 0) > 0) {
$this->store->save(static::DATASET . ':history:' . self::key($month, $factoryId), (string) $state['version'], array_merge($state, $values), $companyId, null, $source);
}
}
public function locked(string $month, int $owner, int $company, callable $action): mixed
{
return $this->store->transaction(function () use ($month, $owner, $company, $action) {
$this->query(static::DATASET, $company)->where('record_key', self::key($month, $owner))->lockForUpdate()->first();
return $action();
});
}
protected function query(string $dataset, int $company): Builder
{
return DB::connection(config('database.supplier_payable_maintenance_connection'))->table('supplier_payable_overrides')->where('company_id', $company)->where('dataset', $dataset);
}
private function snapshotDataset(string $month, int $owner, int $version): string
{
return static::DATASET . ':snapshot:' . self::key($month, $owner) . ':' . $version;
}
public function snapshot(string $month, int $owner, int $version, int $company): ?array
{
return $this->store->findRow($this->snapshotDataset($month, $owner, $version), 'meta', $company);
}
public function snapshotQuery(string $month, int $owner, int $version, int $company): Builder
{
return $this->query($this->snapshotDataset($month, $owner, $version), $company)->where('record_key', 'like', 'line:%');
}
public function history(string $month, int $owner, int $company): array
{
return $this->query(static::DATASET . ':history:' . self::key($month, $owner), $company)->orderByDesc('id')->limit(20)->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all();
}
public function review(string $month, int $owner, int $version, string $waybill, string $decision, string $reply, ?float $amount, int $company, ?int $user, string $by): array
{
return $this->locked($month, $owner, $company, function () use ($month, $owner, $version, $waybill, $decision, $reply, $amount, $company, $user, $by) {
$state = $this->state($month, $owner, $company);
if ((int) ($state['version'] ?? 0) !== $version || ($state['status'] ?? '') !== self::DISPUTED) {
throw new RuntimeException('账单版本或状态已变化,请刷新后处理。');
}
$dataset = static::DISPUTES . self::key($month, $owner);
$row = $this->store->findRow($dataset, $version . '|' . $waybill, $company);
if (!$row) {
throw new RuntimeException('没有这条异议。');
}
if (isset($row['decision'])) {
throw new RuntimeException('这条异议已经处理,请勿重复提交。');
}
if (!in_array($decision, ['accept', 'reject'], true) || trim($reply) === '') {
throw new RuntimeException('请选择处理结果并填写核实依据。');
}
unset($row['_action_key']);
$row += ['decision' => $decision, 'reply' => trim($reply), 'reviewed_at' => now()->toDateTimeString(), 'reviewed_by' => $by, 'review_amount' => $amount, 'receipt_status' => 'pending'];
$this->store->save($dataset, $version . '|' . $waybill, $row, $company, $user, 'freight_review');
return $row;
});
}
public function markReceipt(string $month, int $owner, int $version, int $company, ?string $error, ?string $waybill = null): void
{
$this->locked($month, $owner, $company, function () use ($month, $owner, $version, $company, $error, $waybill) {
if ((int) ($this->state($month, $owner, $company)['version'] ?? 0) !== $version) {
return;
}
$values = ['receipt_status' => $error === null ? 'sent' : 'failed', 'receipt_error' => $error === null ? null : mb_substr($error, 0, 200)];
if ($waybill === null) {
$this->merge($month, $owner, $company, $values, 'freight_receipt');
return;
}
$dataset = static::DISPUTES . self::key($month, $owner);
$row = $this->store->findRow($dataset, $version . '|' . $waybill, $company);
if ($row) {
unset($row['_action_key']);
$this->store->save($dataset, $version . '|' . $waybill, array_merge($row, $values), $company, null, 'freight_receipt');
}
});
}
}

View File

@ -2,6 +2,7 @@
namespace App\Support\CourierBills; namespace App\Support\CourierBills;
use App\Business\CourierContractPageData;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository; use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use RuntimeException; use RuntimeException;
@ -38,7 +39,10 @@ final class PayableSummary
/** 有对账单时由小汇总覆盖的列。 */ /** 有对账单时由小汇总覆盖的列。 */
private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT']; private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT'];
public function __construct(private readonly CourierInformationMirrorRepository $couriers) {} public function __construct(
private readonly CourierInformationMirrorRepository $couriers,
private readonly CourierContractPageData $contractDates,
) {}
public function db(): ConnectionInterface public function db(): ConnectionInterface
{ {
@ -66,6 +70,7 @@ final class PayableSummary
report($error); report($error);
$contracts = []; $contracts = [];
} }
$contractDates = $this->contractDates->datesByCourierNames($stored->pluck('carrier')->all());
$today = now()->toDateString(); $today = now()->toDateString();
$rows = []; $rows = [];
foreach ($stored as $row) { foreach ($stored as $row) {
@ -77,6 +82,9 @@ final class PayableSummary
$cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null); $cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null);
$cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null); $cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null);
} }
$dates = $contractDates[$row->carrier] ?? [];
$cells['A'] = $dates['start_date'] ?? ($cells['A'] ?? null);
$cells['B'] = $dates['end_date'] ?? ($cells['B'] ?? null);
$mine = $statements[$row->carrier] ?? []; $mine = $statements[$row->carrier] ?? [];
// 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对; // 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对;
// 新建的月份金额是空的,才用对账单的小汇总填。 // 新建的月份金额是空的,才用对账单的小汇总填。
@ -189,6 +197,10 @@ final class PayableSummary
throw new RuntimeException(self::COLUMNS[$column] . '须为数字。'); throw new RuntimeException(self::COLUMNS[$column] . '须为数字。');
} }
$cells[$column] = $number; $cells[$column] = $number;
if ($column === 'S') {
// 手工实付(含 0)优先保留;清空后恢复按应付金额自动带出。
$cells['_paid_manual'] = $number !== null;
}
} else { } else {
$cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500); $cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500);
} }

View File

@ -32,7 +32,7 @@ final class PortalFreightBillImports
touch($queue . '/' . $token); touch($queue . '/' . $token);
} }
public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null): array public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null, ?string $jointKey = null): array
{ {
$files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: []; $files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: [];
rsort($files); rsort($files);
@ -42,6 +42,7 @@ final class PortalFreightBillImports
if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue; if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue;
if ($targetId !== null && (int) $task['target_id'] !== $targetId) continue; if ($targetId !== null && (int) $task['target_id'] !== $targetId) continue;
if ($month !== null && $task['month'] !== $month) continue; if ($month !== null && $task['month'] !== $month) continue;
if (($task['joint']['key'] ?? null) !== $jointKey) continue;
$out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'], $out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'],
'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'], 'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'],
'message' => $task['message'], 'at' => $task['created_at']]; 'message' => $task['message'], 'at' => $task['created_at']];
@ -89,7 +90,8 @@ final class PortalFreightBillImports
\App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true); \App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true);
if (($task['source'] ?? null) === 'courier_upload_link') { if (($task['source'] ?? null) === 'courier_upload_link') {
if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。'); if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。');
if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->where('group_id', $task['target_id']) $joint = isset($task['joint']) ? app(CourierJointUploads::class)->verify($task['joint']) : null;
if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$task['target_id']])
->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) { ->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) {
throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。'); throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。');
} }
@ -110,7 +112,9 @@ final class PortalFreightBillImports
} else { } else {
if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。'); if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。');
$store = app(CourierBillStore::class); $store = app(CourierBillStore::class);
$id = $store->uploadFor(new UploadedFile($path, $task['original_name'], null, null, true), $task['month'], $task['target_id'], $task['uploader']); $file = new UploadedFile($path, $task['original_name'], null, null, true);
$id = isset($joint) ? $store->uploadJoint($file, $task['month'], $task['joint'], $task['uploader'])
: $store->uploadFor($file, $task['month'], $task['target_id'], $task['uploader']);
$row = $store->db()->table('courier_bill_files')->find($id); $row = $store->db()->table('courier_bill_files')->find($id);
} }
if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。')); if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。'));

View File

@ -0,0 +1,138 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Support\Facades\Schema;
/** 仅用于补记账复核;原始退回和记账记录均保持不变。 */
final class RebookReturns
{
/** @param list<array<string,mixed>> $rows @return list<array<string,mixed>> */
public function annotate(array $rows): array
{
$wanted = [];
foreach ($rows as $row) {
foreach (self::numbers($row) as $number) {
$wanted[$number] = true;
}
}
$db = Rebooks::db();
$available = $wanted !== [] && Schema::connection($db->getName())->hasTable('courier_returned_parcels');
$found = [];
if ($available) {
$found = WaybillMatch::find($db->table('courier_returned_parcels')->where('returned_qty', '>', 0)
->whereNotNull('received_at'), 'waybill', array_keys($wanted), ['waybill', 'received_at']);
}
$byOrder = [];
$orderIds = [];
$sourceOrders = [];
$fallbackNumbers = [];
foreach ($rows as $row) {
$numbers = self::numbers($row);
if (!$available || empty($row['product_code']) || array_intersect($numbers, array_keys($found)) !== []) continue;
foreach ($numbers as $number) $fallbackNumbers[$number]=true;
$order = trim((string)($row['internal_order_id'] ?? $row['o_id'] ?? ''));
$online=trim((string)($row['online_order_no']??$row['trade_no']??''));
if ($order !== '' && $online !== '') $orderIds[$order.'|'.$online]=true;
}
// 通过原发货包裹明确的内部订单号匹配,不能把同一线上订单的补发包裹互相抵扣。
if ($fallbackNumbers !== [] && Schema::connection($db->getName())->hasTable('js_jst_order_express_details')) {
$packageKeys = [];
foreach (array_chunk(array_keys($fallbackNumbers),250) as $chunk) {
$aliases = [];
foreach ($chunk as $number) {
$key=self::key($number);
foreach ([$number, $key, '@'.$key, 'T'.$key, '@T'.$key] as $alias) $aliases[]=$alias;
}
$aliases = array_values(array_unique(array_map('strval', $aliases)));
// 运单索引定位包裹,随后只按主键读宽镜像,避免扫描数百万行 logistic_id。
foreach ($db->table('jst_oms_shipping')->whereIn('express_no',$aliases)
->distinct()->get(['source_id','express_no']) as $ship) {
$packageKeys[(int)$ship->source_id][self::key((string)$ship->express_no)]=true;
}
foreach ($db->table('courier_unshipped_waybills')->where('source','replacement')->whereIn('waybill_no',$aliases)
->get(['evidence_no','waybill_no']) as $replacement) {
if(preg_match('/^shipping:(\d+)$/',$replacement->evidence_no,$m))$packageKeys[(int)$m[1]][self::key($replacement->waybill_no)]=true;
}
}
foreach (array_chunk(array_keys($packageKeys),500) as $chunk) {
foreach ($db->table('js_jst_order_express_details')->whereIn('id',$chunk)->get(['id','inner_order_id','so_id']) as $source) {
if (!$source->inner_order_id || !$source->so_id) continue;
$orderKey=$source->inner_order_id.'|'.$source->so_id;
$orderIds[$orderKey]=true;
foreach ($packageKeys[(int)$source->id] as $key=>$_) $sourceOrders[$key][$orderKey]=true;
}
}
}
if ($available && $orderIds !== [] && Schema::connection($db->getName())->hasColumns('courier_returned_parcels', ['order_id','online_order_no','sku'])) {
// 用内部订单索引缩小范围,两来源同数字键均参与,不全表扫描。
$ids=array_unique(array_map(fn($key)=>explode('|',$key,2)[0],array_keys($orderIds)));
foreach (array_chunk($ids,200) as $chunk) {
foreach ($db->table('courier_returned_parcels')->whereIn('order_id',$chunk)
->where('returned_qty','>',0)->whereNotNull('received_at')
->cursor(['waybill','received_at','order_id','online_order_no','sku']) as $record) {
$order=$record->order_id.'|'.$record->online_order_no;
$sku=trim((string)$record->sku);
if(isset($orderIds[$order]) && $sku!=='')$byOrder[$order][$sku][]=[
'waybill'=>trim((string)$record->waybill),'received_at'=>(string)$record->received_at];
}
}
}
foreach ($rows as &$row) {
$exact = $fuzzy = [];
foreach (self::numbers($row) as $number) {
$match = $found[$number] ?? [];
foreach ($match['rows'] ?? [] as $record) {
$value = ['waybill' => $record->waybill, 'received_at' => $record->received_at];
if ($match['exact']) $exact[] = $value;
else $fuzzy[] = $value;
}
}
$fuzzy = $exact === [] ? WaybillMatch::uniqueFuzzy($fuzzy) : [];
$matches = $exact ?: $fuzzy;
$orderMatches=[];
if($matches===[]){
$orders=[];$explicit=trim((string)($row['internal_order_id']??$row['o_id']??''));
$online=trim((string)($row['online_order_no']??$row['trade_no']??''));
if($explicit!=='' && $online!=='')$orders[$explicit.'|'.$online]=true;
foreach(self::numbers($row) as $number)foreach(array_keys($sourceOrders[self::key($number)]??[]) as $order)$orders[$order]=true;
$sku=trim((string)($row['product_code']??''));
if(count($orders)===1 && $sku!=='')$orderMatches=$byOrder[(string)array_key_first($orders)][$sku]??[];
$matches=$orderMatches;
}
$analysis = trim((string) ($row['analysis'] ?? ''));
$historicReturn = str_contains($analysis, '已退回') || str_contains($analysis, '原单退回改0') || str_contains($analysis, '换单退回');
$row['_return_status'] = $matches !== [] ? '已退回' : ($historicReturn ? '历史记账已记退回' : ($available ? '未匹配退回记录' : '退回数据未就绪'));
$row['_return_method'] = $exact !== [] ? '精确匹配' : ($fuzzy !== [] ? '模糊匹配(格式或T前缀)' : ($orderMatches!==[]?'原内部订单及商品匹配':''));
$row['_matched_return_no'] = implode('、', array_unique(array_column($matches, 'waybill')));
$row['_return_received_at'] = $matches === [] ? '' : max(array_column($matches, 'received_at'));
// 只重判此前“未退回”的行,不覆盖未发出、取消记账等已有财务判定。
if ($analysis === '未退回' && $matches !== []) {
$lossFreight = preg_match('/丢件|双面单|违规件|站点异常/u', (string) ($row['bookkeeping_reason'] ?? '')) === 1;
$cost = $row['cost'] ?? null;
$freight = $row['settle_freight'] ?? null;
if (! $lossFreight || (is_numeric($cost) && is_numeric($freight))) {
$row['_return_current'] = $lossFreight ? round((float) $freight + round((float) $cost * .2, 2), 2) : 0.0;
$row['_return_analysis'] = $lossFreight ? '记账损耗+运费' : '原单退回改0';
} else {
$row['_return_status'] = '已退回,成本或结算运费缺失待核对';
}
}
}
unset($row);
return $rows;
}
/** @return list<string> */
private static function numbers(array $row): array
{
return array_values(array_unique(array_filter(array_map(static fn ($v): string => trim((string) $v),
[$row['tracking_no_clean'] ?? '', $row['tracking_no'] ?? '', $row['return_no'] ?? '']), static fn (string $v): bool => self::key($v) !== null)));
}
private static function key(string $number): ?string
{
return WaybillMatch::key($number);
}
}

View File

@ -0,0 +1,548 @@
<?php
namespace App\Support\CourierBills;
use Carbon\CarbonImmutable;
use Generator;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
/**
* 补记账:记账扣过的单,快递后来退回了,在后面的账期把多扣的补回去。
*
* - 补哪几个月:对账分组里设(不补 / 补上月 / 补前两个月),没设就按上月小汇总里的补记账类目识别
* (「补9月记账」「补8月记账」→ 补前两个月;「2026.8-9月记账补款」→ 补前两个月;「补记账」「9月记账补款」→ 补上月)。最多补两个月,超期不补。
* - 当时扣的:记账明细里那个扣款月份这单的「结算记账」合计。
* - 现在应扣:优先采用人工复核;否则按原未退回行的退回匹配和原因自动计算,资料缺失先不补。
* - 本期补款 = 当时扣的 − 现在应扣;补记账台账里补过的单不再补。
* - 对账单确认时,这期补的单记进补记账台账;取消确认就撤掉。
*/
final class Rebooks
{
/** 记账明细的数据集(快递应付 → 记账明细)。 */
public const BOOKKEEPING_DATASET = 'courier:bookkeeping-details';
public const MAX_MONTHS = 2;
public const RULES = [0 => '不补', 1 => '补上月', 2 => '补前两个月'];
private ?bool $hasMonthIndex = null;
public static function db(): ConnectionInterface
{
return CourierBillMatcher::db();
}
/**
* 小汇总里补记账类目(已顺延到本月)要补几个月:类目里提到的扣款月份离本月最远的那个;没写月份的算补上月。0 = 小汇总里没有补记账。
*
* @param list<string>|null $labels
*/
public static function monthsFromLabels(?array $labels, string $month): int
{
$current = (int) substr($month, 5, 2);
$result = 0;
foreach ($labels ?? [] as $label) {
$label = SummaryTemplate::normalize((string) $label);
if (! self::isRebookLabel($label)) {
continue;
}
$mentioned = self::monthsIn($label);
if ($mentioned === []) {
$result = max($result, 1);
continue;
}
foreach ($mentioned as $m) {
$lag = ($current - $m + 12) % 12;
if ($lag >= 1) {
$result = max($result, min($lag, self::MAX_MONTHS));
}
}
}
return $result;
}
/** 是不是补记账类目:「补9月记账」「2026.8-9月记账补款」「补记账」「9月记账补款」。 */
public static function isRebookLabel(string $label): bool
{
$label = SummaryTemplate::normalize($label);
return str_contains($label, '记账') && (str_starts_with($label, '补') || str_contains($label, '记账补'));
}
/** 类目里写到的月份(「2026.8-9月」→ 8、9)。 @return list<int> */
public static function monthsIn(string $label): array
{
$months = [];
preg_match_all('/(?:\d{4}[.年])?(\d{1,2})(?:-(?:\d{4}[.年])?(\d{1,2}))?月/u', $label, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$a = (int) $m[1];
$b = isset($m[2]) && $m[2] !== '' ? (int) $m[2] : $a;
if ($a < 1 || $a > 12 || $b < 1 || $b > 12) {
continue;
}
for ($i = $a, $n = 0; $n < 12; $i = $i % 12 + 1, $n++) {
$months[] = $i;
if ($i === $b) {
break;
}
}
}
return array_values(array_unique($months));
}
/** 小汇总类目是不是这个扣款月份的补记账行:写了这个月、或范围里含这个月、或没写月份。 */
public static function labelCovers(string $label, int $deductMonth): bool
{
if (! self::isRebookLabel($label)) {
return false;
}
$months = self::monthsIn(SummaryTemplate::normalize($label));
return $months === [] || in_array($deductMonth, $months, true);
}
/**
* 这家这个月补几个月。
*
* @param list<string>|null $template 上月小汇总类目(已顺延)
* @return array{months:int,source:string}
*/
public static function rule(object $group, string $month, ?array $template): array
{
if (isset($group->rebook_months) && $group->rebook_months !== null && $group->rebook_months !== '') {
return ['months' => min(max((int) $group->rebook_months, 0), self::MAX_MONTHS), 'source' => 'group'];
}
return ['months' => self::monthsFromLabels($template, $month), 'source' => 'summary'];
}
/** 要补的扣款月份:本月往前 1..n 个月。 @return list<string> */
public static function window(string $month, int $months): array
{
$base = CarbonImmutable::createFromFormat('Y-m-d', $month . '-01');
$result = [];
for ($i = min($months, self::MAX_MONTHS); $i >= 1; $i--) {
$result[] = $base->subMonthsNoOverflow($i)->format('Y-m');
}
return $result;
}
/**
* 一张对账单的补记账明细(含资料缺失、已经补过的,金额为 0 的不补)。
*
* @return array{months:int,source:string,window:list<string>,rows:list<array<string,mixed>>}
*/
public function forStatement(int $statementId, ?array $template = null): array
{
$db = self::db();
$statement = $db->table('courier_bill_statements')->find($statementId);
if ($statement === null) {
throw new RuntimeException('对账单不存在。');
}
if ($statement->status === 'confirmed') {
return $this->confirmedPlan($statement);
}
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$template ??= app(CourierBillMatcher::class)->templateFor($statementId);
$rule = self::rule($group, (string) $statement->bill_month, $template);
$window = self::window((string) $statement->bill_month, $rule['months']);
$names = array_values(array_filter(array_map('trim', (array) json_decode((string) $group->express_names, true))));
return $rule + ['window' => $window, 'rows' => $window === [] || $names === []
? [] : $this->rows($names, $window, (string) $statement->bill_month, $statementId)];
}
/** 已确认账单只读确认时记录,不随复核、分组或原记账明细变化。 */
private function confirmedPlan(object $statement): array
{
$rows = [];
foreach (self::db()->table('courier_bill_rebooks')->where('statement_id', $statement->id)
->orderBy('deduct_month')->orderBy('waybill_no')->cursor() as $record) {
$info = json_decode((string) $record->details, true) ?: [];
$rows[] = ['deduct_month' => $record->deduct_month, 'waybill' => $record->waybill_no,
'carrier' => $info['carrier'] ?? '', 'deducted' => (float) $record->deducted,
'refunded' => null, 'current' => (float) $record->current, 'amount' => (float) $record->amount,
'status' => '本期补款', 'info' => $info];
}
$window = array_values(array_unique(array_column($rows, 'deduct_month')));
$months = $window === [] ? 0 : min(self::MAX_MONTHS, (int) CarbonImmutable::parse($window[0] . '-01')
->diffInMonths(CarbonImmutable::parse($statement->bill_month . '-01')));
return ['months' => $months, 'source' => 'confirmed', 'window' => $window, 'rows' => $rows];
}
/**
* 这家的扣款单:按单号 + 扣款月份合计「结算记账」,带上已补、复核和本期补款。
*
* @param list<string> $names 快递名称1
* @param list<string> $window 扣款月份
* @return list<array<string,mixed>>
*/
public function rows(array $names, array $window, string $month, ?int $statementId = null): array
{
$names = array_flip($names);
$deductions = [];
$sourceRows = [];
foreach ($this->bookkeeping($window) as $row) {
$carrier = trim((string) ($row['carrier'] ?? ''));
if (! isset($names[$carrier])) {
continue;
}
$sourceRows[] = $row;
}
$sourceRows = app(RebookReturns::class)->annotate($sourceRows);
foreach ($sourceRows as $row) {
$carrier = trim((string) ($row['carrier'] ?? ''));
$waybill = Waybill::normalize((string) (($row['tracking_no_clean'] ?? '') ?: ($row['tracking_no'] ?? '')));
if ($waybill === null) {
continue;
}
$key = $waybill . '|' . $row['summary_month'];
$deductions[$key] ??= ['deduct_month' => (string) $row['summary_month'], 'waybill' => $waybill, 'carrier' => $carrier,
'deducted' => '0', 'info' => $row, 'sources' => []];
$deductions[$key]['sources'][] = $row;
$deductions[$key]['deducted'] = bcadd($deductions[$key]['deducted'], (string) (($row['settle_bookkeeping'] ?? '') ?: '0'), 4);
}
if ($deductions === []) {
return [];
}
$waybills = array_values(array_unique(array_column($deductions, 'waybill')));
$refunded = [];
$reviews = [];
foreach (array_chunk($waybills, 1000) as $chunk) {
foreach (self::db()->table('courier_bill_rebooks')->whereIn('waybill_no', $chunk)->whereIn('deduct_month', $window)
->when($statementId !== null, fn ($q) => $q->where(fn ($q) => $q->whereNull('statement_id')->orWhere('statement_id', '<>', $statementId)))
->get(['waybill_no', 'deduct_month', 'refund_month', 'amount']) as $r) {
$k = strtoupper($r->waybill_no) . '|' . $r->deduct_month;
$refunded[$k] = ['amount' => (float) ($refunded[$k]['amount'] ?? 0) + (float) $r->amount,
'month' => min($refunded[$k]['month'] ?? $r->refund_month, $r->refund_month)];
}
foreach (self::db()->table('courier_bill_rebook_reviews')->whereIn('waybill_no', $chunk)->whereIn('deduct_month', $window)
->get(['waybill_no', 'deduct_month', 'current_amount']) as $r) {
$reviews[strtoupper($r->waybill_no) . '|' . $r->deduct_month] = (float) $r->current_amount;
}
}
$rows = [];
foreach ($deductions as $key => $d) {
$k = strtoupper($d['waybill']) . '|' . $d['deduct_month'];
$deducted = round((float) $d['deducted'], 2);
$current = $reviews[$k] ?? null;
$automatic = false;
$missingData = false;
foreach ($d['sources'] as $source) {
$missingData = $missingData || str_contains((string) ($source['_return_status'] ?? ''), '缺失');
}
if ($current === null) {
$current = self::returnedAmount($d['sources']);
$automatic = $current !== null;
}
$done = $refunded[$k] ?? null;
[$status, $amount] = match (true) {
$done !== null => ['已补(' . $done['month'] . ')', 0.0],
$deducted <= 0 => ['没扣', 0.0],
$current === null && $missingData => ['资料缺失待核对', 0.0],
$current === null => ['无新增退回,不补', 0.0],
$current >= $deducted => ['仍应扣,不补', 0.0],
default => ['本期补款', round($deducted - $current, 2)],
};
$d['info']['_rebook_sources'] = $d['sources'];
$d['info']['_automatic_current'] = $automatic;
$rows[] = ['deduct_month' => $d['deduct_month'], 'waybill' => $d['waybill'], 'carrier' => $d['carrier'],
'deducted' => $deducted, 'refunded' => $done === null ? null : round($done['amount'], 2), 'current' => $current,
'amount' => $amount, 'status' => $status, 'info' => $d['info']];
}
usort($rows, static fn (array $a, array $b): int => [$a['deduct_month'], $a['waybill']] <=> [$b['deduct_month'], $b['waybill']]);
return $rows;
}
/** 只重算有退回证据的原未退回行;同单其他行沿用原应扣,缺少任一行金额则整单暂缓。 */
private static function returnedAmount(array $sources): ?float
{
$matched = false;
$amount = '0';
foreach ($sources as $source) {
if (str_contains((string) ($source['_return_status'] ?? ''), '缺失')) {
return null;
}
$matched = $matched || isset($source['_return_current']);
$amount = bcadd($amount, (string) ($source['_return_current'] ?? (($source['settle_bookkeeping'] ?? '') ?: '0')), 4);
}
return $matched ? round((float) $amount, 2) : null;
}
/** 页面、导出共用自动补款金额;人工填写的小汇总不覆盖,已确认账单不重算。 */
public function summaryItems(int $statementId, iterable $items, ?array $plan = null): \Illuminate\Support\Collection
{
$items = collect($items);
$plan ??= $this->forStatement($statementId);
if ($plan['source'] === 'confirmed') return $items;
$automaticMonths = [];
foreach ($plan['rows'] as $row) {
if ($row['info']['_automatic_current'] ?? false) $automaticMonths[$row['deduct_month']] = true;
}
if ($automaticMonths === []) return $items;
$totals = self::totals($plan['rows']);
$allocated = [];
$affected = [];
foreach ($plan['window'] as $month) {
$item = $items->first(fn ($item) => SummaryTemplate::normalize($item->label) === self::label($month))
?? $items->first(fn ($item) => self::labelCovers($item->label, (int) substr($month, 5, 2)));
if ($item === null || $item->manual) continue;
$allocated[$item->id] = round(($allocated[$item->id] ?? 0) + ($totals[$month] ?? 0), 2);
if (isset($automaticMonths[$month])) $affected[$item->id] = true;
}
return $items->map(function ($item) use ($allocated, $affected) {
$copy = clone $item;
if (isset($affected[$item->id])) $copy->self_amount = $allocated[$item->id];
return $copy;
});
}
/** 各扣款月份本期补款合计(只算要补的)。 @param list<array<string,mixed>> $rows @return array<string,float> */
public static function totals(array $rows): array
{
$totals = [];
foreach ($rows as $row) {
if ($row['amount'] > 0) {
$totals[$row['deduct_month']] = round(($totals[$row['deduct_month']] ?? 0) + $row['amount'], 2);
}
}
ksort($totals);
return $totals;
}
/** 小汇总里补记账那一行的名字:「补9月记账」。 */
public static function label(string $deductMonth): string
{
return '补' . (int) substr($deductMonth, 5, 2) . '月记账';
}
/** 导出子表名:一个月「补9月记账」,两个月「2026.9-10月记账补款」。 @param list<string> $window */
public static function sheetName(array $window): string
{
if (count($window) <= 1) {
return self::label($window[0] ?? '');
}
$first = $window[0];
$last = $window[count($window) - 1];
return substr($first, 0, 4) . '.' . (int) substr($first, 5, 2) . '-' . (substr($last, 0, 4) !== substr($first, 0, 4) ? substr($last, 0, 4) . '.' : '')
. (int) substr($last, 5, 2) . '月记账补款';
}
/** 对账单确认:这期补的单记进补记账台账。 */
public function record(int $statementId): int
{
$statement = self::db()->table('courier_bill_statements')->find($statementId);
$plan = $this->forStatement($statementId);
$items = self::db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->orderBy('sort')->get();
foreach ($this->summaryItems($statementId, $items, $plan) as $item) {
if ($item->self_amount !== $items->firstWhere('id', $item->id)->self_amount) {
self::db()->table('courier_bill_summary_items')->where('id', $item->id)->update(['self_amount' => $item->self_amount]);
}
}
$this->assertSummaryMatches($statementId, $plan['rows']);
$now = now();
$buffer = [];
foreach ($plan['rows'] as $row) {
if ($row['amount'] <= 0) {
continue;
}
$buffer[] = ['group_id' => $statement->group_id, 'waybill_no' => $row['waybill'], 'deduct_month' => $row['deduct_month'],
'refund_month' => $statement->bill_month, 'deducted' => $row['deducted'], 'current' => $row['current'],
'amount' => $row['amount'], 'statement_id' => $statementId, 'source' => 'statement',
'details' => json_encode($row['info'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), 'created_at' => $now];
}
$inserted = 0;
foreach (array_chunk($buffer, 500) as $chunk) {
$count = self::db()->table('courier_bill_rebooks')->insertOrIgnore($chunk);
if ($count !== count($chunk)) {
throw new RuntimeException('补记账状态已变化,存在已经补过的单号,请重新匹配核对后确认。');
}
$inserted += $count;
}
return $inserted;
}
/** 手工回填或复核变化不能让小汇总金额与逐单补款记录不一致。 */
private function assertSummaryMatches(int $statementId, array $rows): void
{
$actual = [];
foreach (self::db()->table('courier_bill_summary_items')->where('statement_id', $statementId)
->orderBy('sort')->get(['label', 'self_amount']) as $item) {
$label = SummaryTemplate::normalize($item->label);
if (self::isRebookLabel($label)) {
$actual[$label] = round(($actual[$label] ?? 0) + (float) $item->self_amount, 2);
}
}
$expected = [];
foreach (self::totals($rows) as $month => $amount) {
$label = self::label($month);
if (! array_key_exists($label, $actual)) {
foreach (array_keys($actual) as $candidate) {
if (self::labelCovers($candidate, (int) substr($month, 5, 2))) {
$label = $candidate;
break;
}
}
}
$expected[$label] = round(($expected[$label] ?? 0) + $amount, 2);
}
foreach (array_unique([...array_keys($actual), ...array_keys($expected)]) as $label) {
if (bccomp((string) ($actual[$label] ?? 0), (string) ($expected[$label] ?? 0), 2) !== 0) {
throw new RuntimeException('补记账小汇总与逐单复核金额不一致,请更新复核记账并重新匹配核对后确认。');
}
}
}
public function forget(int $statementId): void
{
self::db()->table('courier_bill_rebooks')->where('statement_id', $statementId)->delete();
}
/**
* 导入已经补过的记录(系统上线前手工补的):单号、扣款月份、补款账期、补款金额,可带「对账分组」。
*
* @return array{rows:int,inserted:int,rejected:int}
*/
public function importRefunds(string $path, string $extension): array
{
$groups = collect(app(CourierBillStore::class)->groups())->keyBy(static fn ($g): string => (string) $g->name);
return $this->importSheet($path, $extension, [
'waybill' => ['单号', '快递单号', '物流单号', '运单号'], 'deduct' => ['扣款月份', '记账月份', '月份'],
'refund' => ['补款账期', '补款月份'], 'amount' => ['补款金额', '需补款', '补款'], 'group' => ['对账分组', '快递名称', '账单快递名称'],
], ['waybill', 'deduct', 'refund', 'amount'], function (array $v) use ($groups): ?array {
$amount = BillParser::number($v['amount'] ?? null);
if ($amount === null || ($refund = CourierBillStore::month((string) ($v['refund'] ?? ''))) === null) {
return null;
}
return ['table' => 'courier_bill_rebooks', 'row' => ['group_id' => $groups->get(trim((string) ($v['group'] ?? '')))?->id,
'refund_month' => $refund, 'amount' => round($amount, 2), 'deducted' => null, 'current' => null,
'statement_id' => null, 'source' => 'import', 'created_at' => now()]];
});
}
/**
* 导入复核记账(这单现在应扣多少):单号、扣款月份、现应扣。同一单号同一扣款月份再导就覆盖。
*
* @return array{rows:int,inserted:int,rejected:int}
*/
public function importReviews(string $path, string $extension, string $sourceName): array
{
return $this->importSheet($path, $extension, [
'waybill' => ['单号', '快递单号', '物流单号', '运单号'], 'deduct' => ['扣款月份', '记账月份', '月份'],
'current' => ['现应扣', '现在应扣', '复核记账', '应扣金额'],
], ['waybill', 'deduct', 'current'], function (array $v) use ($sourceName): ?array {
$current = BillParser::number($v['current'] ?? null);
if ($current === null) {
return null;
}
return ['table' => 'courier_bill_rebook_reviews', 'upsert' => ['current_amount', 'source_name', 'updated_at'],
'row' => ['current_amount' => round($current, 2), 'source_name' => mb_substr($sourceName, 0, 255), 'updated_at' => now()]];
});
}
/**
* @param array<string,list<string>> $columns
* @param list<string> $required
* @param callable(array<string,mixed>):?array{table:string,row:array<string,mixed>,upsert?:list<string>} $build
* @return array{rows:int,inserted:int,rejected:int}
*/
private function importSheet(string $path, string $extension, array $columns, array $required, callable $build): array
{
$reader = new BillWorkbookReader();
$rows = $inserted = $rejected = 0;
$buffers = [];
$flush = function () use (&$buffers, &$inserted): void {
foreach ($buffers as $table => [$upsert, $records]) {
foreach (array_chunk(array_values($records), 500) as $chunk) {
$inserted += $upsert === null ? self::db()->table($table)->insertOrIgnore($chunk)
: self::db()->table($table)->upsert($chunk, ['waybill_no', 'deduct_month'], $upsert);
}
}
$buffers = [];
};
foreach ($reader->sheets($path, $extension) as $sheetRows) {
$index = null;
foreach ($sheetRows as $row) {
if ($index === null) {
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
$found = [];
foreach ($columns as $field => $names) {
foreach ($names as $name) {
if (($i = array_search($name, $header, true)) !== false) {
$found[$field] = $i;
break;
}
}
}
if (array_diff($required, array_keys($found)) !== []) {
throw new RuntimeException('表头须含' . implode('', array_map(static fn (string $f): string => '「' . $columns[$f][0] . '」', $required)) . '。');
}
$index = $found;
continue;
}
$values = [];
foreach ($index as $field => $i) {
$values[$field] = $row[$i] ?? null;
}
if (trim((string) ($values['waybill'] ?? '')) === '' && trim((string) ($values['deduct'] ?? '')) === '') {
continue;
}
$rows++;
$waybill = Waybill::normalize((string) ($values['waybill'] ?? ''));
$deduct = CourierBillStore::month((string) ($values['deduct'] ?? ''));
$built = $waybill === null || $deduct === null ? null : $build($values);
if ($built === null) {
$rejected++;
continue;
}
$record = ['waybill_no' => strtoupper($waybill), 'deduct_month' => $deduct] + $built['row'];
$key = $record['waybill_no'] . '|' . $deduct . '|' . ($record['refund_month'] ?? '');
$buffers[$built['table']] ??= [$built['upsert'] ?? null, []];
$buffers[$built['table']][1][$key] = $record; // 同一文件里重复的后一行为准
if (count($buffers[$built['table']][1]) >= 500) {
$flush();
}
}
break; // 只读第一张表
}
$flush();
return ['rows' => $rows, 'inserted' => $inserted, 'rejected' => $rejected];
}
/**
* 记账明细里这几个扣款月份的行。
*
* @param list<string> $months
* @return Generator<int,array<string,mixed>>
*/
private function bookkeeping(array $months): Generator
{
$connection = DB::connection(config('database.supplier_payable_maintenance_connection'));
$this->hasMonthIndex ??= Schema::connection($connection->getName())->hasColumn('supplier_payable_overrides', 'summary_month_key');
$query = $connection->table('supplier_payable_overrides')->select(['id', 'values'])
->where('company_id', (int) (company_id() ?: 1))->where('dataset', self::BOOKKEEPING_DATASET)
->whereIn($this->hasMonthIndex ? 'summary_month_key' : 'values->summary_month', $months);
// 保留 rows() 的 trim 后精确匹配,避免 SQL 原值筛选漏掉带首尾空白的快递名称。
foreach ($query->lazyById(500) as $record) {
$values = json_decode((string) $record->values, true);
if (is_array($values)) {
yield $values;
}
}
}
}

View File

@ -0,0 +1,236 @@
<?php
namespace App\Support\CourierBills;
use App\Models\Business\CourierQuoteVersion;
use App\Support\CourierRequoteService;
use App\Support\ReturnPickupFreightCalculator;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
use Modules\EcommerceFinance\Services\Freight\QuoteSheet;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightCalculator;
use RuntimeException;
/** 逆向账单只读退件镜像;原退货单号和实退单号指向同一票,不能重复计费。 */
final class ReturnPickupLookup
{
public const CARRIERS = [
'中通快运' => '中通快运逆向', '中通快运逆向' => '中通快运逆向',
'德邦' => '常州德邦逆向', '常州德邦逆向' => '常州德邦逆向',
'速寄递' => '申通退货', '申通' => '申通退货', '申通退货' => '申通退货',
'好省邮' => '好省邮快递', '好省邮快递' => '好省邮快递',
'百世' => '好省邮快递', '顺心捷达' => '好省邮快递', '顺丰' => '好省邮快递',
];
private const HAO_QUOTES = ['百世' => '好省邮百世', '顺心捷达' => '好省邮顺心捷达', '顺丰' => '好省邮顺丰'];
private array $versions = [];
private const MAIN = 'js_ekf_return_pickup_management';
private const ITEMS = 'js_ekf_return_pickup_management_item';
private const TRUTH = 'js_ekf_return_pickup_truth_express';
private const CHUNK = 500;
public function __construct(private readonly ReturnPickupFreightCalculator $calculator) {}
public static function supports(array $names): bool
{
return array_intersect($names, array_values(self::CARRIERS)) !== [];
}
private function connection(): ConnectionInterface
{
return DB::connection('business_mirror');
}
private function assertReady(): void
{
$schema = Schema::connection('business_mirror');
foreach ([self::MAIN, self::ITEMS, self::TRUTH] as $table) {
if (! $schema->hasTable($table)) {
throw new RuntimeException('退件取件镜像未就绪,未更新逆向账单。');
}
}
if (! $schema->hasTable('business_mirror_table_states') || $this->connection()->table('business_mirror_table_states')
->whereIn('target_table', [self::MAIN, self::ITEMS, self::TRUTH])->whereNotNull('initial_completed_at')->count() !== 3) {
throw new RuntimeException('退件取件镜像首次同步未完成,未更新逆向账单。');
}
}
/** @return array<string,array<string,mixed>> 大写单号 => 与发货明细相同的导出字段 */
public function details(array $waybills, array $names): array
{
if ($waybills === [] || ! self::supports($names)) return [];
$this->assertReady();
$db = $this->connection();
$result = [];
foreach (array_chunk(array_values(array_unique(array_map([self::class, 'number'], $waybills))), self::CHUNK) as $chunk) {
$links = [];
$direct = $db->table(self::MAIN)->whereIn('returnExpressNo', $chunk)->get();
foreach ($direct as $main) $links[self::number($main->returnExpressNo)][(int) $main->Id] = true;
foreach ($db->table(self::TRUTH)->whereIn('truthExpressNumber', $chunk)->get(['mId', 'truthExpressNumber']) as $link) {
$links[self::number($link->truthExpressNumber)][(int) $link->mId] = true;
}
$ids = [];
foreach ($links as $set) $ids += $set;
if ($ids === []) continue;
$mains = $db->table(self::MAIN)->whereIn('Id', array_keys($ids))->get()->keyBy('Id');
$items = $db->table(self::ITEMS)->whereIn('mainTableId', array_keys($ids))->orderBy('id')->get()->groupBy('mainTableId');
$truth = $db->table(self::TRUTH)->whereIn('mId', array_keys($ids))->get(['mId', 'truthExpressNumber'])->groupBy('mId');
foreach ($links as $number => $set) {
$number = (string) $number;
$candidates = $mains->only(array_keys($set))->filter(fn ($m) => isset(self::CARRIERS[trim((string) $m->express_company)]));
if ($candidates->isEmpty()) continue;
$main = $candidates->first();
$actual = array_values(array_unique(array_filter(array_map([self::class, 'number'], ($truth[$main->Id] ?? collect())->pluck('truthExpressNumber')->all()))));
$row = $this->row($main, ($items[$main->Id] ?? collect())->all(), $number);
if ($candidates->count() !== 1 || count($actual) > 1) {
$row = $this->uncalculated($row, '同号多张取件单或一单多个实退单号,需核实包裹归属');
} elseif ($actual !== [] && ! in_array($number, $actual, true)) {
$row = $this->uncalculated($row, '退件已换单:' . implode('、', $actual));
$row['_unshipped'] = $row['qc_status'];
}
$result[$number] = $row;
}
}
return $result;
}
/** 仅实际取件月份内的有效单号;分批读取,不加载整张退件表。 */
public function monthWaybills(array $names, string $month): \Generator
{
if (! self::supports($names)) return;
$this->assertReady();
$sources = array_keys(array_filter(self::CARRIERS, fn ($name) => in_array($name, $names, true)));
$query = $this->connection()->table(self::MAIN)->whereIn('express_company', $sources)
->where('expressPickupTime', '>=', $month . '-01')
->where('expressPickupTime', '<', date('Y-m-d', strtotime($month . '-01 +1 month')))
->whereNotIn('orderStatus', ['ExpCanceled', 'TicketTimeoutClose'])->orderBy('Id');
$lastId = 0;
do {
$mains = (clone $query)->where('Id', '>', $lastId)->limit(self::CHUNK)->get();
if ($mains->isEmpty()) break;
$truth = $this->connection()->table(self::TRUTH)->whereIn('mId', $mains->pluck('Id'))->get(['mId', 'truthExpressNumber'])->groupBy('mId');
foreach ($mains as $main) {
$actual = ($truth[$main->Id] ?? collect())->pluck('truthExpressNumber')->all();
$numbers = array_values(array_unique(array_filter(array_map([self::class, 'number'], $actual))));
if ($numbers === []) $numbers = array_filter([self::number($main->returnExpressNo)]);
foreach ($numbers as $number) yield ['waybill' => $number, 'ship_time' => (string) $main->expressPickupTime,
'express_name' => self::CARRIERS[$main->express_company]];
}
$lastId = (int) $mains->last()->Id;
} while ($mains->count() === self::CHUNK);
}
private function row(object $main, array $items, string $number): array
{
$carrier = self::CARRIERS[trim((string) $main->express_company)];
$package = $items === [] ? null : clone $items[0];
if ($package !== null) {
$package->grossWeight = $package->packageVolume = 0.0;
$package->length = $package->width = $package->height = 0.0;
foreach ($items as $item) {
$quantity = max(0, (float) ($item->returnQuantity ?? 0));
$package->grossWeight += (float) $item->grossWeight * $quantity;
$package->packageVolume += (float) $item->length * (float) $item->width * (float) $item->height * $quantity;
foreach (['length', 'width', 'height'] as $dimension) $package->$dimension = max($package->$dimension, (float) $item->$dimension);
}
}
$row = ['express_no' => $number, 'express_name1' => $carrier, 'ship_time' => $main->expressPickupTime,
'trade_no' => $main->transactionNo ?? null, 'shop_name' => $main->shopName ?? null,
'origin_state' => $main->province, 'origin_city' => $main->city ?? null,
'data_source' => '退件取件管理', 'qc_freight' => 0.0, 'qc_charge_weight' => 0.0,
'qc_settle_weight' => 0.0, 'qc_miandan' => 0.0, 'qc_extra_fee' => 0.0, 'qty' => 0.0,
'weight_kg' => 0.0, 'qc_status' => 'OK', 'qc_quote_version' => '逆向物流报价/' . $carrier];
$formulas = $products = $barcodes = [];
$reason = $items === [] ? '退件缺少商品重量尺寸明细' : null;
$rate = $package === null ? null : $this->calculate($main, $package, $carrier);
if ($rate !== null) {
if (! $rate['covered']) $reason = $rate['reason'];
$row['qc_freight'] += (float) $rate['total'];
$row['qc_charge_weight'] += (float) $rate['billable'];
$row['qc_settle_weight'] += (float) $rate['settlement'];
$row['qc_miandan'] += (float) $rate['base_amount'];
$row['qc_extra_fee'] += (float) $rate['surcharge'];
$row['qc_rate'] = $rate['increment_amount'];
if (isset($rate['quote_version'])) $row['qc_quote_version'] = $rate['quote_version'];
$formulas[] = '整票商品重量/体积合计,面单只计一次;' . ($rate['process'] ?? $rate['reason']);
}
$destinations = [];
foreach ($items as $item) {
$quantity = max(0, (float) ($item->returnQuantity ?? 0));
if ($quantity <= 0 || ((float) $item->grossWeight <= 0 && (float) $item->length * (float) $item->width * (float) $item->height <= 0)) {
$reason = '退件商品缺少有效数量或重量';
}
$row['qty'] += $quantity;
$row['weight_kg'] += (float) $item->grossWeight * $quantity;
$destinations[trim((string) $item->receiverAddress)] = true;
$row['receiver_address'] ??= $item->receiverAddress;
$row['receiver_state'] ??= ReturnPickupFreightCalculator::destinationProvince((string) $item->receiverAddress);
$row['receiver_name'] ??= $item->receiverName ?? null;
$row['warehouse_name'] ??= $item->warehouse ?? null;
foreach (['length_cm' => 'length', 'width_cm' => 'width', 'height_cm' => 'height'] as $field => $source) {
$row[$field] = max((float) ($row[$field] ?? 0), (float) $item->$source);
}
$products[] = $item->productName ?? '';
$barcodes[] = $item->barcode ?? '';
}
$row['volume_cm3'] = $package?->packageVolume;
if (count($destinations) > 1) $reason = '同一运单存在不同收件地址,需核实';
$row['qc_freight'] = round($row['qc_freight'], 2);
$row['product_name'] = implode(',', array_unique(array_filter($products)));
$row['barcode'] = implode(',', array_unique(array_filter($barcodes)));
$row['qc_formula'] = implode(';', array_filter($formulas));
if (in_array($main->orderStatus, ['ExpCanceled', 'TicketTimeoutClose'], true) || empty($main->expressPickupTime)) {
$row['_unshipped'] = '退件已取消、关闭或尚无实际取件时间';
$reason = $row['_unshipped'];
}
return $reason === null ? $row : $this->uncalculated($row, $reason);
}
private function calculate(object $main, object $item, string $carrier): array
{
if ($carrier !== '好省邮快递') {
return $this->calculator->calculate($carrier, $main->province, $item->receiverAddress,
(float) $item->grossWeight, $item->length, $item->width, $item->height,
$main->expressPickupTime ? substr($main->expressPickupTime, 0, 10) : null, $item->packageVolume);
}
$name = self::HAO_QUOTES[trim((string) $main->express_company)] ?? null;
$empty = ['covered' => false, 'total' => null, 'billable' => null, 'settlement' => null,
'base_amount' => null, 'surcharge' => null, 'increment_amount' => null, 'process' => null];
if ($name === null || empty($main->expressPickupTime)) return $empty + ['reason' => '好省邮缺少实际承运快递或取件日期'];
$versions = $this->versions[$name] ??= CourierQuoteVersion::query()->with(['signature', 'change'])->where('company_name', $name)->get();
$version = CourierRequoteService::resolveAt($versions, Carbon::parse($main->expressPickupTime));
if ($version === null) return $empty + ['reason' => '取件日期没有生效的' . $name . '报价'];
$values = json_decode((string) $version->values_json, true) ?: [];
$destination = ReturnPickupFreightCalculator::destinationProvince((string) $item->receiverAddress);
$city = null;
if (preg_match('/^(?:.+?省|.+?自治区)(.+?(?:市|自治州|地区|盟))/u', (string) $item->receiverAddress, $m)) $city = $m[1];
elseif (in_array($destination, ['北京', '上海', '天津', '重庆'], true)) $city = $destination;
$cfg = FreightCarrierRules::for($name) + ['_name' => $name];
$result = app(ShippingFreightCalculator::class)->calculate([
'express_name1' => $name, 'sender_state' => $main->province, 'sender_city' => $main->city ?? null,
'receiver_state' => $destination, 'receiver_city' => $city, 'weight_kg' => (float) $item->grossWeight,
'volume_cm3' => $item->packageVolume,
], ['id' => $version->version_code, 'p' => QuoteSheet::parse($values), 'vals' => $values,
'rules' => (string) $version->billing_rules], $cfg);
return ['covered' => $result['status'] === 'OK', 'reason' => $result['status'], 'total' => $result['fee'],
'billable' => $result['charge_w'], 'settlement' => $result['settle_w'],
'base_amount' => $result['first_price'] ?? $result['miandan'], 'surcharge' => $result['extra'],
'increment_amount' => $result['rate'], 'process' => $result['formula'], 'quote_version' => $version->version_code];
}
private function uncalculated(array $row, string $reason): array
{
$row['qc_freight'] = $row['qc_charge_weight'] = null;
$row['qc_status'] = $reason;
return $row;
}
private static function number(mixed $value): string
{
return strtoupper(trim((string) $value));
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Support\CourierBills;
/** 对账展示和导出统一使用最终结算口径,保留原核算字段。 */
final class SettlementComparison
{
public static function difference(mixed $billed, mixed $settled, int $precision = 2): ?float
{
return $billed === null || $settled === null ? null
: round(round((float) $billed, $precision) - round((float) $settled, $precision), $precision);
}
public static function weight(mixed $billFreight, mixed $calcFreight, mixed $billWeight, mixed $chargeWeight, mixed $settled): ?float
{
if ($settled === null) return null;
if ($billFreight !== null && $calcFreight !== null && (float) $billFreight < (float) $calcFreight
&& round((float) $settled, 2) === round((float) $billFreight, 2)) {
return $billWeight === null ? null : (float) $billWeight;
}
return $chargeWeight === null ? null : (float) $chargeWeight;
}
/** @return array{settlement_weight:?float,weight_diff:?float,freight_diff:?float} */
public static function courier(object $line): array
{
$weight = match ($line->resolution) {
'agree' => $line->bill_weight === null ? null : (float) $line->bill_weight,
'exclude', 'defer' => 0.0,
default => in_array($line->category, [...Category::PAYABLE, Category::PRIOR], true)
? (in_array(trim((string) ($line->express_name ?? '')), CourierBillMatcher::ACTUAL_FREIGHT_EXPRESSES, true)
? ($line->self_amount === null || $line->charge_weight === null ? null : (float) $line->charge_weight)
: self::weight($line->bill_amount, $line->calc_freight, $line->bill_weight, $line->charge_weight, $line->self_amount)) : null,
};
return ['settlement_weight' => $weight, 'weight_diff' => self::difference($line->bill_weight, $weight, 4),
'freight_diff' => self::difference($line->bill_amount, $line->self_amount)];
}
}

View File

@ -34,6 +34,8 @@ final class ShippingLookup
'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)', 'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)',
'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)', 'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态', 'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
'data_source' => '数据来源',
'origin_state' => '始发省', 'origin_city' => '始发市',
]; ];
/** 文本列:导出时保持文本,长数字不变科学计数法。 */ /** 文本列:导出时保持文本,长数字不变科学计数法。 */
@ -56,7 +58,7 @@ final class ShippingLookup
* @param list<string> $waybills * @param list<string> $waybills
* @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号 * @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号
*/ */
public function summaries(array $waybills): array public function summaries(array $waybills, array $expressNames = []): array
{ {
$result = []; $result = [];
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) { foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
@ -100,6 +102,11 @@ final class ShippingLookup
} }
} }
foreach (app(ReturnPickupLookup::class)->details($waybills, $expressNames) as $key => $row) {
$result[$key] = ['ship_time' => $row['ship_time'], 'express_name' => $row['express_name1'],
'calc_freight' => $row['qc_freight'], 'charge_weight' => $row['qc_charge_weight'],
'data_source' => $row['data_source'], 'unshipped_source' => $row['_unshipped'] ?? null];
}
return $result; return $result;
} }
@ -109,7 +116,7 @@ final class ShippingLookup
* @param list<string> $waybills * @param list<string> $waybills
* @return array<string,array<string,mixed>> 键为大写单号 * @return array<string,array<string,mixed>> 键为大写单号
*/ */
public function details(array $waybills): array public function details(array $waybills, array $expressNames = []): array
{ {
$result = []; $result = [];
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) { foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
@ -189,7 +196,7 @@ final class ShippingLookup
} }
} }
return $result; return array_replace($result, app(ReturnPickupLookup::class)->details($waybills, $expressNames));
} }
/** /**
@ -203,6 +210,9 @@ final class ShippingLookup
if ($expressNames === []) { if ($expressNames === []) {
return; return;
} }
yield from app(ReturnPickupLookup::class)->monthWaybills($expressNames, $month);
$expressNames = array_values(array_diff($expressNames, array_values(ReturnPickupLookup::CARRIERS)));
if ($expressNames === []) return;
// 按天走 ship_time 索引,单次只扫一天的发货行。 // 按天走 ship_time 索引,单次只扫一天的发货行。
$day = strtotime($month . '-01'); $day = strtotime($month . '-01');
$end = strtotime($month . '-01 +1 month'); $end = strtotime($month . '-01 +1 month');

View File

@ -3,6 +3,7 @@
namespace App\Support\CourierBills; namespace App\Support\CourierBills;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\CourierBookkeepingRegistry;
/** /**
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总, * 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
@ -10,15 +11,15 @@ use Illuminate\Support\Facades\Storage;
* 导出文件以快递发来的原始账单为底:原文件的每张表一个字节不改,后面追加汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、 * 导出文件以快递发来的原始账单为底:原文件的每张表一个字节不改,后面追加汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、
* 匹配不到、未发出、未提供、说明;没有数据的工作表不生成。 * 匹配不到、未发出、未提供、说明;没有数据的工作表不生成。
* *
* 对账类子表的列顺序:快递原始列 → 财务指定的 25 列 → 发货数据其余字段 → 处理结果。 * 对账类子表的列顺序:快递原始列 → 核算及结算对比列 → 发货数据其余字段 → 处理结果。
*/ */
final class StatementExporter final class StatementExporter
{ {
/** 财务指定的 25 列 => 取值来源(发货数据字段,或 _ 开头的计算项)。 */ /** 对账列 => 取值来源(发货数据字段,或 _ 开头的计算项)。 */
public const FRONT = [ public const FRONT = [
'称重重量' => '_measured', '首重' => 'qc_first_price', '面单' => 'qc_miandan', '快递单号' => 'express_no', '称重重量' => '_measured', '首重' => 'qc_first_price', '面单' => 'qc_miandan', '快递单号' => 'express_no',
'交易单号' => 'trade_no', '商品ID' => 'item_id', '条形码' => 'barcode', '商品名称' => 'product_name', '数量' => 'qty', '交易单号' => 'trade_no', '商品ID' => 'item_id', '条形码' => 'barcode', '商品名称' => 'product_name', '数量' => 'qty',
'计费重量' => 'qc_charge_weight', '续重/费率' => 'qc_rate', '核算运费' => 'qc_freight', '重量差' => '_weight_diff', '计费重量' => 'qc_charge_weight', '续重/费率' => 'qc_rate', '核算运费' => 'qc_freight', '结算重量' => '_settlement_weight', '重量差' => '_weight_diff',
'运费差' => '_freight_diff', '省' => 'receiver_state', '买家昵称' => 'buyer_nick', '收货姓名' => 'receiver_name', '运费差' => '_freight_diff', '省' => 'receiver_state', '买家昵称' => 'buyer_nick', '收货姓名' => 'receiver_name',
'店铺名称' => 'shop_name', '快递名称1' => 'express_name1', '仓库' => 'warehouse_name', '发货时间' => 'ship_time', '店铺名称' => 'shop_name', '快递名称1' => 'express_name1', '仓库' => 'warehouse_name', '发货时间' => 'ship_time',
'未发出' => '_unshipped', '运费' => 'freight', '线上重量' => 'online_weight', '实称重量' => 'actual_weight', '未发出' => '_unshipped', '运费' => 'freight', '线上重量' => 'online_weight', '实称重量' => 'actual_weight',
@ -64,6 +65,8 @@ final class StatementExporter
{ {
$db = CourierBillMatcher::db(); $db = CourierBillMatcher::db();
$ids = $this->related($statementId); $ids = $this->related($statementId);
$expressNames = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->whereIn('s.id', $ids)->pluck('g.express_names')->flatMap(fn ($value) => (array) json_decode((string) $value, true))->unique()->values()->all();
$multi = count($ids) > 1; $multi = count($ids) > 1;
$groupNames = []; $groupNames = [];
$book = new StreamingWorkbook(); $book = new StreamingWorkbook();
@ -91,7 +94,8 @@ final class StatementExporter
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true); $book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
$bill = 0.0; $bill = 0.0;
$self = 0.0; $self = 0.0;
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get() as $item) { $items = app(SurchargeSettlementMatcher::class)->summaryItems($id,$db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get());
foreach (app(Rebooks::class)->summaryItems($id, $items) as $item) {
$b = $item->bill_amount === null ? null : (float) $item->bill_amount; $b = $item->bill_amount === null ? null : (float) $item->bill_amount;
$s = $item->self_amount === null ? null : (float) $item->self_amount; $s = $item->self_amount === null ? null : (float) $item->self_amount;
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]); $book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
@ -104,8 +108,14 @@ final class StatementExporter
$groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : []; $groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : [];
[$sources, $original] = $this->originalHeaders($ids); [$sources, $original] = $this->originalHeaders($ids);
$front = [];
foreach (self::FRONT as $label => $field) {
$front[$label] = $field;
if ($field === '_settlement_weight') $front['结算运费'] = '_settlement';
}
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_'))); $rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_')));
$fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '差异原因', '处理结果', ...$tail]; $rest['settle_freight'] = '发货数据结算运费';
$fullHeader = [...$original, ...array_keys($front), ...array_values($rest), '差异原因', '处理结果', ...$tail];
// 原始账单:底文件原封不动;第 2 个及以后的文件按值复制 // 原始账单:底文件原封不动;第 2 个及以后的文件按值复制
$originals = $this->writeOriginal($book, $files, $baseFileId); $originals = $this->writeOriginal($book, $files, $baseFileId);
@ -119,16 +129,20 @@ final class StatementExporter
} }
foreach ($sheets as $name => $filter) { foreach ($sheets as $name => $filter) {
$headerWritten = false; $headerWritten = false;
$this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, &$headerWritten): void { $this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $front, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void {
if (! $headerWritten) { if (! $headerWritten) {
$book->row($name, $fullHeader, true); $book->row($name, $fullHeader, true);
$headerWritten = true; $headerWritten = true;
} }
$details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines)); $details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines), $expressNames);
foreach ($lines as $line) { foreach ($lines as $line) {
$ship = $details[strtoupper($line->waybill_no)] ?? []; $ship = $details[strtoupper($line->waybill_no)] ?? [];
$cells = $this->originalCells($line, $sources, $original); $cells = $this->originalCells($line, $sources, $original);
foreach (self::FRONT as $field) { foreach ($front as $field) {
if ($field === '_settlement') {
$cells[] = $line->self_amount === null ? null : (float) $line->self_amount;
continue;
}
$cells[] = $this->front($field, $line, $ship); $cells[] = $this->front($field, $line, $ship);
} }
foreach (array_keys($rest) as $field) { foreach (array_keys($rest) as $field) {
@ -163,22 +177,158 @@ final class StatementExporter
// 未提供:发货数据有、账单没有 // 未提供:发货数据有、账单没有
$headerWritten = false; $headerWritten = false;
$db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id') $db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id')
->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, &$headerWritten): void { ->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, $expressNames, &$headerWritten): void {
if (! $headerWritten) { if (! $headerWritten) {
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true); $book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true);
$headerWritten = true; $headerWritten = true;
} }
$details = $this->shipping->details($rows->pluck('waybill_no')->all()); $details = $this->shipping->details($rows->pluck('waybill_no')->all(), $expressNames);
foreach ($rows as $row) { foreach ($rows as $row) {
$ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no]; $ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no];
$book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]); $book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]);
} }
}); });
$this->writeRebooks($book, $ids, $tail, $groupNames, $multi);
$subsidy = app(WeightDifferenceSubsidy::class);
foreach ($ids as $id) {
if (! $db->table('courier_bill_summary_items')->where('statement_id', $id)->where('label', WeightDifferenceSubsidy::LABEL)->where('manual', false)->exists()) continue;
$summary = $subsidy->summary($id);
if ($summary['count'] === 0) continue;
$sheet = '重量差补款-' . $id;
$book->row($sheet, ['快递单号', '快递重量', '我方计费重量', '重量差(快递-我方)', '快递运费', '核算运费', '可补运费差额'], true);
foreach ($subsidy->query($id)->orderBy('id')->lazyById(500) as $line) {
$book->row($sheet, [$line->waybill_no, (float) $line->bill_weight, (float) $line->charge_weight,
round((float) $line->bill_weight - (float) $line->charge_weight, 4), (float) $line->bill_amount,
(float) $line->calc_freight, round((float) $line->bill_amount - (float) $line->calc_freight, 4)]);
}
$book->row($sheet, ['差额合计', null, null, null, null, null, $summary['difference']], true);
$book->row($sheet, ['差额合计×50%,补给快递', null, null, null, null, null, $summary['amount']], true);
}
foreach($ids as $id) app(SurchargeSettlementMatcher::class)->write($book,'courier',$id);
$this->writeNotes($book, $ids, $originals); $this->writeNotes($book, $ids, $originals);
$book->writeTo($output); $book->writeTo($output);
} }
/**
* 补记账子表:全部历史记账及本期差额(已补记录不重复计入),表名照手工版「补9月记账」「2026.8-9月记账补款」。
*
* @param list<int> $ids
* @param list<string> $tail
* @param array<int,string> $groupNames
*/
private function writeRebooks(StreamingWorkbook $book, array $ids, array $tail, array $groupNames, bool $multi): void
{
$plans = [];
$window = [];
foreach ($ids as $id) {
try {
$plan = app(Rebooks::class)->forStatement($id);
} catch (\Throwable $error) {
report($error);
continue;
}
if ($plan['window'] !== []) {
// 全部历史记账都展示,已补、未退回等仅供核对,不重复计入本期金额。
$plans[$id] = $plan['rows'];
$window = array_values(array_unique([...$window, ...$plan['window']]));
}
}
if ($plans === []) {
return;
}
sort($window);
$name = Rebooks::sheetName($window);
$fields = ['summary_month' => ['label' => '月份', 'type' => 'text']];
foreach (app(CourierBookkeepingRegistry::class)->fields() as $field => $definition) {
$fields[$field] = $definition;
if ($field === 'settle_bookkeeping') {
$fields['current_bookkeeping'] = ['label' => '现结算记账金额', 'type' => 'number'];
$fields['rebook_amount'] = ['label' => '需补款记账金额', 'type' => 'number'];
}
}
foreach (['return_status' => '退回核对状态', 'return_match' => '退回匹配方式', 'matched_return' => '匹配退回单号',
'received_at' => '退回进仓时间', 'refund_status' => '补款状态'] as $field => $label) {
$fields[$field] = ['label' => $label, 'type' => 'text'];
}
$fields['refunded'] = ['label' => '历史已补金额', 'type' => 'number'];
$fields['payable_refund'] = ['label' => '本期补款金额', 'type' => 'number'];
$book->row($name, [...array_column($fields, 'label'), ...$tail], true);
$rowNumber = 1;
$settleColumn = array_search('settle_bookkeeping', array_keys($fields), true) + 1;
$currentColumn = $settleColumn + 1;
foreach ($plans as $id => $rows) {
foreach ($rows as $r) {
$sources = $r['info']['_rebook_sources'] ?? [$r['info']];
$remainingCurrent = (float) ($r['current'] ?? $r['deducted']);
$remainingRefund = (float) $r['amount'];
$last = array_key_last($sources);
$automatic = $r['info']['_automatic_current'] ?? false;
$weights = [];
foreach ($sources as $index => $source) {
$old = (float) ($source['settle_bookkeeping'] ?? $r['deducted']);
$weights[$index] = $automatic ? max(0, round($old - (float) ($source['_return_current'] ?? $old), 2)) : max(0, $old);
}
$totalWeight = array_sum($weights);
$lastRefund = array_key_last(array_filter($weights, static fn ($weight) => $weight > 0));
$historyWritten = false;
foreach ($sources as $index => $source) {
$rowNumber++;
$values = $source;
$old = (float) ($source['settle_bookkeeping'] ?? $r['deducted']);
$share = $r['deducted'] > 0 ? $old / $r['deducted'] : 0;
$current = $automatic || $r['current'] === null ? (float) ($source['_return_current'] ?? $old)
: ($index === $last ? $remainingCurrent : round((float) $r['current'] * $share, 2));
$payable = $weights[$index] <= 0 || $totalWeight <= 0 ? 0.0
: ($index === $lastRefund ? $remainingRefund : round((float) $r['amount'] * $weights[$index] / $totalWeight, 2));
$remainingCurrent = round($remainingCurrent - $current, 2);
$remainingRefund = round($remainingRefund - $payable, 2);
$values['summary_month'] = $r['deduct_month'];
$values['tracking_no'] = $values['tracking_no'] ?? $r['waybill'];
$values['tracking_no_clean'] = $r['waybill'];
$values['carrier'] = $source['carrier'] ?? $r['carrier'];
$values['settle_bookkeeping'] = $old;
$values['current_bookkeeping'] = $current;
if (isset($source['_return_analysis'])) {
$values['analysis'] = $source['_return_analysis'];
}
$values['rebook_amount'] = new XlsxFormula(
self::columnName($settleColumn) . $rowNumber . '-' . self::columnName($currentColumn) . $rowNumber,
round($old - $current, 2),
);
$values['return_status'] = $source['_return_status'] ?? '';
$values['return_match'] = $source['_return_method'] ?? '';
$values['matched_return'] = $source['_matched_return_no'] ?? '';
$values['received_at'] = $source['_return_received_at'] ?? '';
$values['refund_status'] = $r['status'];
$values['refunded'] = $historyWritten ? null : $r['refunded'];
$historyWritten = true;
$values['payable_refund'] = $payable;
$cells = [];
foreach ($fields as $field => $definition) {
$value = $values[$field] ?? null;
$cells[] = $value instanceof XlsxFormula ? $value : ($definition['type'] === 'number'
? ($value === null || $value === '' ? null : (float) $value)
: ($value === null || $value === '' ? null : (string) $value));
}
$book->row($name, [...$cells, ...($multi ? [$groupNames[$id] ?? ''] : [])]);
}
}
}
}
private static function columnName(int $column): string
{
$name = '';
while ($column > 0) {
$column--;
$name = chr(65 + $column % 26) . $name;
$column = intdiv($column, 26);
}
return $name;
}
/** /**
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。 * 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
* *
@ -248,7 +398,7 @@ final class StatementExporter
} }
$rows = [ $rows = [
...$rows, ...$rows,
[$book->nameOf('对账'), '本月发货、发货数据里找得到、属于这家快递的单号(运费一致或有差)。前面是快递原始列,后面接我方核算的 25 列(称重重量、首重、面单、计费重量、续重/费率、核算运费、重量差、运费差……)和发货数据其余字段。', $count(Category::PAYABLE)], [$book->nameOf('对账'), '本月发货、发货数据里找得到、属于这家快递的单号(运费一致或有差)。前面是快递原始列,后面接核算与结算对比列;运费差为快递运费减结算运费,重量差为快递重量减结算重量。', $count(Category::PAYABLE)],
['前月补提供-X月', '发货时间在账单月之前、结算台账里没结算过的单号:快递之前漏报、这次补上的。', $count([Category::PRIOR])], ['前月补提供-X月', '发货时间在账单月之前、结算台账里没结算过的单号:快递之前漏报、这次补上的。', $count([Category::PRIOR])],
['跨月订单-X月', '发货时间在账单月之后的单号,本月不结算。', $count([Category::LATER])], ['跨月订单-X月', '发货时间在账单月之后的单号,本月不结算。', $count([Category::LATER])],
[$book->nameOf('快递不符'), '发货数据里有这个单号,但快递名称1 不是这家(也不在同一张合并账单里)。', $count([Category::MISMATCH])], [$book->nameOf('快递不符'), '发货数据里有这个单号,但快递名称1 不是这家(也不在同一张合并账单里)。', $count([Category::MISMATCH])],
@ -338,10 +488,9 @@ final class StatementExporter
return match ($field) { return match ($field) {
'_measured' => $ship['qc_measured_weight'] ?? null, '_measured' => $ship['qc_measured_weight'] ?? null,
'_unshipped' => $line->unshipped_sources, '_unshipped' => $line->unshipped_sources,
'_weight_diff' => $line->bill_weight !== null && ($ship['qc_charge_weight'] ?? null) !== null '_settlement_weight' => SettlementComparison::courier($line)['settlement_weight'],
? round((float) $line->bill_weight - (float) $ship['qc_charge_weight'], 4) : null, '_weight_diff' => SettlementComparison::courier($line)['weight_diff'],
'_freight_diff' => $line->bill_amount !== null && ($ship['qc_freight'] ?? null) !== null '_freight_diff' => SettlementComparison::courier($line)['freight_diff'],
? round((float) $line->bill_amount - (float) $ship['qc_freight'], 2) : null,
default => self::value($field, $ship[$field] ?? null), default => self::value($field, $ship[$field] ?? null),
}; };
} }

View File

@ -126,12 +126,15 @@ final class SummaryMapper
]; ];
} }
/** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L。 */ /** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L;未手工填写时,R > 0 则实付 S = R。 */
public static function totals(array $cells): array public static function totals(array $cells): array
{ {
$n = static fn (string $key): float => (float) ($cells[$key] ?? 0); $n = static fn (string $key): float => (float) ($cells[$key] ?? 0);
$cells['M'] = round($n('K') - $n('L'), 2); $cells['M'] = round($n('K') - $n('L'), 2);
$cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2); $cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2);
if ($cells['R'] > 0 && empty($cells['_paid_manual'])) {
$cells['S'] = $cells['R'];
}
return $cells; return $cells;
} }

View File

@ -52,7 +52,7 @@ final class SummaryTemplate
$index = []; $index = [];
foreach ($template as $label) { foreach ($template as $label) {
$key = self::normalize($label); $key = self::normalize($label);
if ($key === '') { if ($key === '' || ($key === WeightDifferenceSubsidy::LABEL && ! isset($auto[$key]))) {
continue; continue;
} }
// 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行 // 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行
@ -74,7 +74,9 @@ final class SummaryTemplate
unset($row); unset($row);
} }
return [...$rows, ...$extras]; // 这些费用已由账单附加费归集,不再沿用上月没有金额的占位类目;有实际费用的行仍保留。
return array_values(array_filter([...$rows, ...$extras], static fn (array $row): bool =>
! $row['blank'] || ! preg_match('/拦截|改地址|超长/u', $row['label'])));
} }
/** 模板里属于附加费的那几行(自算先放 0,可回填)。 @param list<string> $feeLabels @return list<string> */ /** 模板里属于附加费的那几行(自算先放 0,可回填)。 @param list<string> $feeLabels @return list<string> */
@ -95,7 +97,7 @@ final class SummaryTemplate
$result = []; $result = [];
foreach ($labels as $label) { foreach ($labels as $label) {
$label = trim((string) $label); $label = trim((string) $label);
if ($label !== '' && ! preg_match(self::TRANSIENT, $label)) { if ($label !== '' && $label !== WeightDifferenceSubsidy::LABEL && ! preg_match(self::TRANSIENT, $label)) {
$result[] = self::roll($label, $delta); $result[] = self::roll($label, $delta);
} }
} }
@ -187,6 +189,7 @@ final class SummaryTemplate
$kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)), $kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)),
$kind === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')), $kind === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')),
$kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'), $kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'),
str_starts_with($kind, 'rebook:') => $find(static fn (string $n): bool => Rebooks::labelCovers($n, (int) substr($kind, 7))),
$kind === 'fee' => self::feeSlot($key, $find), $kind === 'fee' => self::feeSlot($key, $find),
default => null, default => null,
}; };

View File

@ -0,0 +1,259 @@
<?php
namespace App\Support\CourierBills;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
/** 按账单月份归集,逐票/费用类型匹配结算表;不改来源报价和费用。 */
class SurchargeSettlementMatcher
{
public const TABLE = 'bill_surcharge_matches';
public const PAID_HISTORY = 'bill-surcharge-paid-history';
public const HEADERS = ['账单月份','来源工作表','原始行号','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'];
public function ready(): bool
{
return DB::connection('business_mirror')->getSchemaBuilder()->hasTable(self::TABLE);
}
public static function paidHistoryKey(string $scope, int $owner, string $month, string $waybill, string $type): string
{
return implode('|', [$scope, $owner, $month, strtoupper(trim($waybill)), self::type($type)]);
}
public static function type(string $type): string
{
$type = preg_replace('/\s+/u', '', $type) ?? '';
if (str_contains($type, '拦截费')) return '拦截费';
return match ($type) {
'改地址费','改址费','改址' => '改地址',
'上楼','直客上楼费' => '上楼费', '超长' => '超长费',
'退件费','退货费','退回运费' => '退回费', '拦截','拦截退回','拦截退回运费' => '拦截费',
'派送费','派件费','直客派送费' => '送货费', '保价费' => '保费',
'入仓费' => '进仓费', '直客超区费' => '超区费', default => $type,
};
}
/** 不刷新已确认账单;只更新附加费派生匹配记录。 */
public function courier(int $id): void
{
if (! $this->ready()) return;
$db = DB::connection('business_mirror');
$s = $db->table('courier_bill_statements')->find($id);
if (! $s || $s->status === 'confirmed') return;
$group = $db->table('courier_bill_groups')->find($s->group_id);
$names = (array) json_decode($group->express_names, true);
$files = $db->table('courier_bill_lines')->where('statement_id', $id)->distinct()->pluck('file_id')
->merge($db->table('courier_bill_files')->where('statement_id', $id)->pluck('id'))->unique()->all();
$seen = [];
$db->transaction(function () use ($db, $s, $id, $names, $files, &$seen): void {
if($db->table('courier_bill_statements')->where('id',$id)->lockForUpdate()->value('status')==='confirmed')return;
$db->table(self::TABLE)->where('scope','courier')->where('owner_id',$id)->delete();
foreach ($files as $fileId) {
$file = $db->table('courier_bill_files')->find($fileId);
if (! $file || $file->status !== 'parsed') continue;
$shared = $db->table('courier_bill_lines')->where('file_id',$fileId)->distinct()->pluck('statement_id')
->push($file->statement_id)->filter()->unique()->values()->all();
$ownership = [];
if (count($shared)>1) {
foreach ($db->table('courier_bill_statements as s')->join('courier_bill_groups as g','g.id','=','s.group_id')
->whereIn('s.id',$shared)->orderBy('s.id')->get(['s.id','g.express_names']) as $owner) {
foreach ((array) json_decode($owner->express_names,true) as $name) $ownership[trim($name)] ??= (int)$owner->id;
}
}
$joint = isset(json_decode($file->extra_group_ids ?? '[]',true)['joint_upload']);
$freightSheets=$db->table('courier_bill_lines')->where('file_id',$fileId)->distinct()->pluck('sheet')->flip()->all();
$db->table('courier_bill_surcharges')->where('file_id',$fileId)->orderBy('id')->chunkById(300,
function ($fees) use ($db,$s,$id,$names,$file,$joint,$ownership,$freightSheets,&$seen): void {
$ships=$ownership!==[]&&!$joint?$this->ships($fees->pluck('waybill_no')->all()):[];
$assigned=$joint?$db->table('courier_bill_lines')->where('file_id',$file->id)->whereIn('waybill_no',$fees->pluck('waybill_no'))
->pluck('statement_id','waybill_no')->all():[];
$input=[];
foreach($fees as $f){
$ship=$ships[strtoupper($f->waybill_no)]??[];
$owner=$joint?($assigned[$f->waybill_no]??0):($ownership[$ship['express']??'']??$file->statement_id);
if((int)$owner!==$id)continue;
$label=isset($freightSheets[$f->sheet])||trim($f->sheet)===''?$f->item:$f->sheet;
$input[]=['file_id'=>$f->file_id,'sheet'=>$f->sheet,'row_no'=>$f->row_no,'waybill_no'=>$f->waybill_no,
'item'=>$f->item,'amount'=>$f->amount,'label'=>preg_replace('/\s+/u','',$label)];
}
$this->storeMatches('courier',$id,$s->bill_month,$input,$names,null,$seen);
});
}
});
}
/** 页面只叠加附加费自算值;已确认对账单继续读取确认时保存的金额。 */
public function summaryItems(int $id,iterable $items): \Illuminate\Support\Collection
{
$items=collect($items);$db=DB::connection('business_mirror');
if(!$this->ready()||$db->table('courier_bill_statements')->where('id',$id)->value('status')==='confirmed')return $items;
$sums=$this->query('courier',$id)->selectRaw('summary_label,SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all();
if($sums===[])return $items;
$month=(int)substr((string)$db->table('courier_bill_statements')->where('id',$id)->value('bill_month'),5,2);
$labels=$items->pluck('label')->all();$auto=[];
foreach($sums as $label=>$amount)$auto[$label]=['bill'=>null,'self'=>$amount===null?null:(float)$amount,'kind'=>'fee'];
$mapped=SummaryTemplate::apply($labels,$auto,$month);$byLabel=[];
foreach($mapped as $row)if($row['fee'])$byLabel[$row['label']]=$row['self'];
return $items->map(function($item)use($byLabel){
$copy=clone $item;if(!$copy->manual&&array_key_exists($copy->label,$byLabel))$copy->self_amount=$byLabel[$copy->label];return $copy;
});
}
public function dropship(int $factoryId, string $month): void
{
if (! $this->ready()) return;
$db=DB::connection('business_mirror');$factory=$db->table('dropship_factories')->find($factoryId);
if(!$factory)throw new RuntimeException('厂家不存在');
$state=app(\App\Support\DropshipFreight\DropshipConfirmation::class)->state($month,$factoryId,(int)(company_id()?:1));
if(($state['status']??'')==='confirmed')return;
$seen=[];
$db->transaction(function () use($db,$factory,$factoryId,$month,&$seen): void {
$db->table(self::TABLE)->where('scope','dropship')->where('owner_id',$factoryId)->where('bill_month',$month)->delete();
$db->table('dropship_bill_surcharges as f')->join('dropship_bill_files as b','b.id','=','f.file_id')->where('b.status','parsed')
->where('f.factory_id',$factoryId)->where('f.bill_month',$month)->select('f.*')->orderBy('f.id')
->chunkById(300,function($fees)use($factory,$factoryId,$month,&$seen):void{
$input=array_map(fn($f)=>['file_id'=>$f->file_id,'sheet'=>$f->sheet,'row_no'=>$f->row_no,'waybill_no'=>$f->waybill_no,
'item'=>$f->item,'amount'=>$f->amount,'label'=>$f->item],$fees->all());
$this->storeMatches('dropship',$factoryId,$month,$input,[],$factory,$seen);
},'f.id','id');
});
}
private function ships(array $waybills): array
{
$db=DB::connection(config('jushuitan.connection','business_mirror'));
if(!$db->getSchemaBuilder()->hasTable('jst_oms_shipping'))return [];
$result=[];
foreach($db->table('jst_oms_shipping')->whereIn('express_no',array_unique($waybills))->orderBy('id')
->get(['express_no','express_name1','warehouse_name']) as $r){
$key=strtoupper($r->express_no);
$result[$key]['express']=$r->express_name1;
$result[$key]['pairs'][$r->warehouse_name][$r->express_name1]=true;
}
return $result;
}
private function storeMatches(string $scope,int $owner,string $month,array $input,array $names,?object $factory,array &$seen): void
{
if($input===[])return;
$db=DB::connection('business_mirror');$waybills=array_values(array_unique(array_column($input,'waybill_no')));
$source=[];
if($db->getSchemaBuilder()->hasTable('courier_surcharge_settlement_rows')){
$sourceQuery=$db->table('courier_surcharge_settlement_rows')->whereIn('waybill',$waybills)->where('settlement_status','已计算');
$window=BillSurchargeQuoteCalculator::window($month);$end=$window['until'];
if($db->getSchemaBuilder()->hasColumn('courier_surcharge_settlement_rows','source_created_at')){
$sourceQuery->whereRaw('COALESCE(source_created_at,shipped_at) >= ?',[$window['from']])->whereRaw('COALESCE(source_created_at,shipped_at) < ?',[$end]);
}else{$sourceQuery->where('shipped_at','>=',$window['from'])->where('shipped_at','<',$end);}
foreach($sourceQuery
->orderBy('id')->get() as $r)$source[strtoupper($r->waybill)][self::type($r->surcharge_type)][]=$r;
}
$prior=[];
foreach($db->table(self::TABLE)->whereIn('waybill_no',$waybills)
->where(fn($q)=>$q->where('scope','<>',$scope)->orWhere('owner_id','<>',$owner)->orWhere('bill_month','<>',$month))
->where('match_status','已匹配')->get(['settlement_ids','bill_month']) as $r)
foreach(json_decode($r->settlement_ids??'[]',true)?:[] as $sid)$prior[$sid]=$r->bill_month;
$ships=$factory?$this->ships($waybills):[];
$own=$factory?array_fill_keys(app(DropshipFreightStore::class)->ownExpressNames(),true):[];
$allowedCouriers=$names;
if($factory){
$keywords=DropshipFreightStore::splitKeywords($factory->keywords);
foreach($ships as $ship)foreach(array_keys($ship['pairs'][$factory->warehouse]??[]) as $express)
if(!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[])$allowedCouriers[]=$express;
}
$calculated=app(BillSurchargeQuoteCalculator::class)->calculate($input,$scope,$month,array_values(array_unique($allowedCouriers)));
$historyRows = array_map(fn ($fee) => ['id' => self::paidHistoryKey($scope, $owner, $month, $fee['waybill_no'], $fee['item'])], $input);
$history = app(SupplierPayableOverrideStore::class)->decorate(self::PAID_HISTORY, $historyRows, (int) (company_id() ?: 1));
$output=[];
foreach($input as $index=>$f){
$type=self::type($f['item']);$wb=strtoupper($f['waybill_no']);$rows=$source[$wb][$type]??[];
$row=['scope'=>$scope,'owner_id'=>$owner,'file_id'=>$f['file_id'],'sheet'=>$f['sheet'],'row_no'=>$f['row_no'],
'bill_month'=>$month,'waybill_no'=>$wb,'item'=>$type,'summary_label'=>$f['label'],'bill_amount'=>$f['amount'],'self_amount'=>null,
'courier_name'=>null,'platform_product_id'=>null,'product_code'=>null,'shop_name'=>null,'online_order_no'=>null,
'match_status'=>'未匹配','match_note'=>'结算表没有对应的单号及费用类型','settlement_ids'=>null,'matched_at'=>now()];
$allowed=$names;
if($factory){
$ship=$ships[$wb]??[];
$keywords=DropshipFreightStore::splitKeywords($factory->keywords);
$allowed=array_values(array_filter(array_keys($ship['pairs'][$factory->warehouse]??[]),fn($express)=>
!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[]));
$belongs=$allowed!==[];
if(!$belongs)$row['match_note']='无法确认该单属于本厂家代发快递及仓库';
}
$window=BillSurchargeQuoteCalculator::window($month);
$rows=array_values(array_filter($rows,function($r)use($allowed,$window){
$date=substr((string)($r->source_created_at??$r->shipped_at??''),0,10);
$shipped=substr((string)($r->shipped_at??''),0,10);
return in_array($r->courier_name,$allowed,true)&&$date!==''&&$date>=$window['from']&&$date<$window['until']
&&($shipped===''||($shipped>=$window['from']&&$shipped<$window['until']));
}));
$priced=array_values(array_filter($calculated['rows'][$wb][$type]??[],fn($r)=>in_array($r->courier_name,$allowed,true)));
// 已支持的报价按票核价优先,避免同单号多张出库记录把每票费用重复累加。
if(array_key_exists($type,$calculated['rows'][$wb]??[]))$rows=$priced;
if($rows===[]){
if(isset($calculated['notes'][$wb][$type])&&(!$factory||$allowed!==[]))$row['match_note']=$calculated['notes'][$wb][$type];
if(!$factory||$allowed!==[])$row=array_replace($row,$calculated['metadata'][$wb]??[]);
}
$identity=$wb.'|'.$type;
if(isset($seen[$identity])){$row['self_amount']=0;$row['match_status']='重复';$row['match_note']='本月账单已提供该单号及费用类型,不重复结算';}
elseif($rows!==[]){
$unique=[];
foreach($rows as $r){
$identityKey=($r->source_key??'')!==''?'source:'.$r->source_key:'rule:'.$r->rule_id.'|'.($r->outbound_io_id??'');
$unique[$r->courier_name.'|'.($r->source_kind??'').'|'.$identityKey]=$r;
}
$rows=array_values($unique);
$keyOf=fn($r)=>hash('sha256',implode('|',[$r->courier_name,$wb,$type,
$r->source_kind??'', trim((string)($r->source_key??''))!==''?'source:'.$r->source_key:'rule:'.$r->rule_id.'|'.($r->outbound_io_id??'')]));
$notPaid=array_values(array_filter($rows,fn($r)=>!isset($prior[$keyOf($r)])));
if($notPaid===[]){$row['self_amount']=0;$row['match_status']='历史已计入';$row['match_note']='对应费用已计入其他账单,不能重复结算';$seen[$identity]=true;}
else {
$partlyPaid=count($notPaid)!==count($rows);$rows=$notPaid;
$seen[$identity]=true;$row['self_amount']=round(array_sum(array_map(fn($r)=>(float)$r->settlement_amount,$rows)),2);
$row['match_status']='已匹配';$row['settlement_ids']=json_encode(array_map($keyOf,$rows));
$row['match_note']='按单号、费用类型及快递匹配;归入'.$month.'账单'.($partlyPaid?';已扣除其他账单已计入费用':'');
$evidence=array_values(array_unique(array_filter(array_map(fn($r)=>$r->evidence??null,$rows))));
if($evidence!==[])$row['match_note'].=';'.implode(';',$evidence);
if ($scope === 'courier' && $row['bill_amount'] !== null && (float) $row['bill_amount'] < $row['self_amount']) {
$row['self_amount'] = round((float) $row['bill_amount'], 2);
$row['match_note'] .= ';快递提供金额较低,按快递金额结算';
}
foreach(['courier_name','platform_product_id','product_code','shop_name','online_order_no'] as $key)
$row[$key]=implode('、',array_values(array_unique(array_filter(array_map(fn($r)=>trim((string)($r->$key??'')),$rows)))));
}
} elseif($rows===[] && ($source[$wb]??[])!==[]&&!isset($calculated['notes'][$wb][$type])) $row['match_note']='单号存在,但费用类型或快递归属不符';
$paid = $history[$index];
$settledMonth = (string) ($paid['settled_month'] ?? '');
if ($paid['_overridden'] && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D', $settledMonth)
&& $settledMonth < $month) {
$row['self_amount'] = 0;
$row['match_status'] = '历史已计入';
$row['match_note'] = '财务确认:' . $settledMonth . '已结算,本期不重复结算';
$seen[$identity] = true;
}
$output[]=$row;
}
$db->table(self::TABLE)->insert($output);
}
public function query(string $scope,int $owner,?string $month=null)
{
return DB::connection('business_mirror')->table(self::TABLE)->where('scope',$scope)->where('owner_id',$owner)
->when($month,fn($q)=>$q->where('bill_month',$month));
}
public function write(StreamingWorkbook $book,string $scope,int $owner,?string $month=null): void
{
if(!$this->ready()||!$this->query($scope,$owner,$month)->exists())return;
$sheet='附加费核对'.($scope==='courier'?'-'.$owner:'');$book->row($sheet,self::HEADERS,true);
$this->query($scope,$owner,$month)->orderBy('id')->chunkById(300,function($rows)use($book,$sheet){
foreach($rows as $r)$book->row($sheet,[$r->bill_month,$r->sheet,$r->row_no,$r->waybill_no,$r->item,
$r->bill_amount===null?null:(float)$r->bill_amount,$r->self_amount===null?null:(float)$r->self_amount,
$r->self_amount===null?null:round((float)$r->bill_amount-$r->self_amount,2),$r->match_status,$r->courier_name,
$r->platform_product_id,$r->product_code,$r->shop_name,$r->online_order_no,$r->match_note]);
});
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\Support\CourierBills;
/** Only formatting and the established numeric T prefix may be treated as equivalent. */
final class WaybillMatch
{
/** Indexed exact lookup first; formatting fallback only receives unresolved numbers. */
public static function find($query, string $column, array $numbers, array $columns): array
{
$result = [];
$numbers = array_values(array_unique(array_map('strval', $numbers)));
foreach (array_chunk($numbers, 300) as $chunk) {
foreach ((clone $query)->whereIn($column, $chunk)->get($columns) as $row) {
$actual = (string) $row->{$column};
if (in_array($actual, $chunk, true)) {
$result[$actual]['exact'] = true;
$result[$actual]['rows'][] = $row;
}
}
}
$pending = [];
foreach ($numbers as $number) if (! isset($result[$number]) && ($key = self::key($number)) !== null) $pending[$key][] = $number;
$expression = self::expression($query, $column);
foreach (array_chunk(array_keys($pending), 300) as $keys) {
$variants = $keys;
foreach ($keys as $key) {
if (ctype_digit((string) $key)) {
$variants[] = 'T' . $key;
$variants[] = $key . '.0';
}
}
$found = [];
foreach ((clone $query)->whereIn($query->getConnection()->raw($expression), array_map('strval', $variants))->get($columns) as $row) {
$key = self::key((string) $row->{$column});
if ($key !== null && isset($pending[$key])) $found[$key][] = $row;
}
foreach ($found as $key => $rows) {
if (count(array_unique(array_map(fn ($r) => Waybill::normalize(mb_convert_kana((string) $r->{$column}, 'as')), $rows))) !== 1) continue;
foreach ($pending[$key] as $number) $result[$number] = ['exact' => false, 'rows' => $rows];
}
}
return $result;
}
public static function expression($query, string $column): string
{
$expression = $query->getGrammar()->wrap($column);
foreach ([" ", "\t", "\r", "\n", "'", '@', '`', ''', ' '] as $remove) {
$literal = str_replace("'", "''", $remove);
$expression = "REPLACE({$expression}, '{$literal}', '')";
}
return 'UPPER(' . $expression . ')';
}
public static function key(string $number): ?string
{
$number = Waybill::normalize(mb_convert_kana($number, 'as'));
return $number === null ? null : (preg_match('/^T\d{10,30}$/', $number) ? substr($number, 1) : $number);
}
public static function uniqueFuzzy(array $records): array
{
$keys = [];
foreach ($records as $record) {
$number = Waybill::normalize(mb_convert_kana((string) $record['waybill'], 'as'));
if ($number !== null) $keys[$number] = true;
}
return count($keys) === 1 ? $records : [];
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Database\Query\Builder;
/** 武进韵达重量多报超过1kg的运费差额,汇总后补给快递50%。 */
final class WeightDifferenceSubsidy
{
public const LABEL = '补武进韵达重量差运费(50%)';
public function query(int $statementId): Builder
{
return CourierBillMatcher::db()->table('courier_bill_lines')
->where('statement_id', $statementId)->where('express_name', '武进韵达')
->whereIn('category', [...Category::PAYABLE, Category::PRIOR])->whereNull('resolution')
->whereRaw('bill_weight - charge_weight > 1')
->whereColumn('bill_amount', '>', 'calc_freight');
}
/** 按差额合计计算一半,再四舍五入到分,避免逐行四舍五入累积误差。 */
public function summary(int $statementId): array
{
$sum = $this->query($statementId)->selectRaw('COUNT(*) AS n, SUM(bill_amount - calc_freight) AS difference')->first();
return ['count' => (int) $sum->n, 'difference' => round((float) $sum->difference, 4),
'amount' => round((float) $sum->difference / 2, 2)];
}
}

View File

@ -0,0 +1,104 @@
<?php
namespace App\Support\DropshipFreight;
use App\Support\CourierBills\Category;
/** 明细页面与导出共用的小汇总;分类及金额沿用原导出口径。 */
final class DropshipBillSummary
{
public const FEE_LABEL = '厂家账单-附加费';
public function __construct(private readonly DropshipFreightStore $store) {}
/** @param list<array<string,mixed>> $rows 未按页面筛选的整月核算结果 */
public function build(object $factory, string $month, array $rows): array
{
$template = $this->store->summaryTemplate($factory, $month);
$billTotal = $settleTotal = null;
$extras = [];
foreach ([Category::MISMATCH, Category::DUPLICATE, Category::UNMATCHED, Category::UNSHIPPED] as $category) {
$extras[DropshipReconciler::LABELS[$category]] = null;
}
foreach ($rows as $r) {
if ($r['bill'] === null) {
continue;
}
if (in_array($r['status'], DropshipReconciler::PAYABLE, true)) {
$billTotal = (float) $billTotal + (float) $r['bill'];
$final = $r['final'] ?? $r['settle'];
if ($final !== null) {
$settleTotal = (float) $settleTotal + (float) $final;
}
} elseif ($r['status'] === Category::LATER) {
$label = Category::label(Category::LATER, (string) $r['status_month']);
$extras[$label] = (float) ($extras[$label] ?? 0) + (float) $r['bill'];
} elseif (array_key_exists($label = DropshipReconciler::LABELS[$r['status']] ?? '', $extras)) {
$extras[$label] = (float) $extras[$label] + (float) $r['bill'];
}
}
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
// 对方附加费保留原金额,自算合计读取同月逐票匹配结果。
$fee = 0.0;
$hasFee = false;
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
->where('status', 'parsed')->get(['id', 'stored_path', 'sheets']) as $file) {
$fees = $this->store->feesFor($file);
if ($fees !== []) {
$fee += array_sum($fees);
$hasFee = true;
}
}
// 上月手工汇总里的分类行(快递不符、未发出、跨月订单-X月……)这个月没有就不留空行
$labels = array_values(array_filter($template['labels'], static fn (string $l): bool => array_key_exists(trim($l), $extras)
|| ! preg_match('/^(快递不符|重复|匹配不到|未发出|跨月订单)/u', trim($l))));
if (! $hasFee) {
$labels = array_values(array_filter($labels, static fn (string $l): bool => ! str_contains($l, '附加费')));
}
if (($billTotal !== null || $settleTotal !== null || $extras !== []) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) {
array_unshift($labels, '运费');
}
foreach (array_keys($extras) as $label) {
if (! in_array($label, array_map('trim', $labels), true)) {
$labels[] = $label;
}
}
$feeLabel = null;
if ($hasFee) {
$feeLabel = collect($labels)->first(static fn (string $l): bool => str_contains($l, '附加费')) ?? self::FEE_LABEL;
if (! in_array($feeLabel, $labels, true)) {
$labels[] = $feeLabel;
}
}
$items = [];
$sums = ['bill' => 0.0, 'settle' => 0.0];
foreach (array_values($labels) as $label) {
[$bill, $settle] = match (true) {
DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)],
array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0],
$label === $feeLabel => [round($fee, 2), $this->surchargeSelf((int) $factory->id, $month)],
default => [null, null],
};
$items[] = ['label' => $label, 'bill' => $bill, 'settle' => $settle,
'diff' => $bill === null && $settle === null ? null : round((float) $bill - (float) $settle, 2)];
$sums['bill'] += (float) $bill;
$sums['settle'] += (float) $settle;
}
$sums = array_map(static fn (float $value): float => round($value, 2), $sums);
$sums['diff'] = round($sums['bill'] - $sums['settle'], 2);
return ['title' => $template['title'], 'headers' => array_slice(array_pad($template['headers'], 3, ''), 0, 3),
'rows' => $items, 'total_label' => $template['total'], 'totals' => $sums];
}
private function surchargeSelf(int $factoryId, string $month): ?float
{
$matcher = app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
if (! $matcher->ready()) return null;
if (! $this->store->db()->table('dropship_bill_surcharges')->where('factory_id', $factoryId)->where('bill_month', $month)->exists()) return null;
$state = app(DropshipConfirmation::class)->state($month, $factoryId, (int) (company_id() ?: 1));
if (($state['status'] ?? '') === 'confirmed') return null;
return round((float) $matcher->query('dropship', $factoryId, $month)->sum('self_amount'), 2);
}
}

View File

@ -2,174 +2,12 @@
namespace App\Support\DropshipFreight; namespace App\Support\DropshipFreight;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; use App\Support\CourierBills\FreightConfirmation;
use RuntimeException;
/** final class DropshipConfirmation extends FreightConfirmation
* 代发运费对账的「核对完成 → 推送厂家确认 → 厂家确认 / 逐单异议」状态。
*
* 和供应商对账一样存在通用数据表 supplier_payable_overrides 里,不加新表:
* - 数据集 dropship-freight-confirm,记录键「月份|厂家ID」:这家这个月的状态、推送版本、推送时的金额快照;
* - 数据集 dropship-freight-dispute:月份|厂家ID,记录键是快递单号:厂家对这一单的异议原因(带推送版本)。
* 每次推送版本号加一,旧链接随之作废;历史异议保留,按版本区分。
*/
final class DropshipConfirmation
{ {
public const DATASET = 'dropship-freight-confirm'; public const DATASET = 'dropship-freight-confirm';
public const DISPUTES = 'dropship-freight-dispute:'; public const DISPUTES = 'dropship-freight-dispute:';
public const LABELS = [self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中',
public const OPEN = 'open'; self::PUSHED => '已推送,待厂家确认', self::FAILED => '推送失败', self::CONFIRMED => '厂家已确认', self::DISPUTED => '厂家有异议'];
public const CHECKED = 'checked';
public const SENDING = 'sending';
public const PUSHED = 'pushed';
public const FAILED = 'failed';
public const CONFIRMED = 'confirmed';
public const DISPUTED = 'disputed';
public const LABELS = [
self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中', self::PUSHED => '已推送,待厂家确认',
self::FAILED => '推送失败', self::CONFIRMED => '厂家已确认', self::DISPUTED => '厂家有异议',
];
public function __construct(private readonly SupplierPayableOverrideStore $store) {}
public static function key(string $month, int $factoryId): string
{
return $month . '|' . $factoryId;
}
public static function label(?array $state): string
{
return self::LABELS[(string) ($state['status'] ?? self::OPEN)] ?? self::LABELS[self::OPEN];
}
public function state(string $month, int $factoryId, int $companyId): ?array
{
return $this->store->findRow(self::DATASET, self::key($month, $factoryId), $companyId);
}
/** @return array<int,array<string,mixed>> 厂家ID => 状态 */
public function states(string $month, int $companyId): array
{
$out = [];
foreach ($this->store->listRows(self::DATASET, $companyId) as $row) {
if (($row['month'] ?? '') === $month) {
$out[(int) ($row['factory_id'] ?? 0)] = $row;
}
}
return $out;
}
/** 财务点「核对完成」/「撤销核对完成」。厂家已确认后不能再撤销,要改就重新推送。 */
public function check(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
{
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
$status = (string) ($state['status'] ?? self::OPEN);
if (! $checked && in_array($status, [self::PUSHED, self::CONFIRMED, self::DISPUTED, self::SENDING], true)) {
throw new RuntimeException('已经推送给厂家,不能撤销;有改动请改完后重新推送。');
}
$values = array_merge($this->base($state, $month, $factory), [
'status' => $checked ? ($status === self::OPEN || $status === self::FAILED ? self::CHECKED : $status) : self::OPEN,
'checked_at' => $checked ? now()->toDateTimeString() : null,
'checked_by' => $checked ? $by : null,
'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'],
]);
$this->store->save(self::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_check');
return $values;
}
/** 开始一次推送:版本号加一并记下这次的金额快照,返回新版本号。 */
public function startPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by): int
{
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
if (($state['status'] ?? self::OPEN) === self::OPEN) {
throw new RuntimeException('先点「核对完成」再推送给厂家。');
}
if (($state['status'] ?? '') === self::SENDING) {
throw new RuntimeException('正在推送,请稍后刷新查看结果。');
}
$version = (int) ($state['version'] ?? 0) + 1;
$values = array_merge($this->base($state, $month, $factory), [
'status' => self::SENDING, 'version' => $version, 'pushed_by' => $by, 'push_requested_at' => now()->toDateTimeString(),
'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'], 'billed' => $summary['billed'],
'attention' => $attention, 'confirmed_at' => null, 'disputed_count' => 0, 'push_error' => null,
]);
$this->store->save(self::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_push');
return $version;
}
public function markPushed(string $month, int $factoryId, int $companyId): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::PUSHED, 'pushed_at' => now()->toDateTimeString()], 'dropship_pushed');
}
public function markFailed(string $month, int $factoryId, int $companyId, string $message): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::FAILED, 'push_error' => mb_strimwidth($message, 0, 300, '…', 'UTF-8')], 'dropship_push_failed');
}
/**
* 厂家在确认页提交:没有异议 = 确认;有异议的单逐单记原因。同一版本只能提交一次。
*
* @param array<string,string> $disputes 快递单号 => 原因
* @return array<string,mixed> 提交后的状态
*/
public function submit(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
{
$state = $this->state($month, $factoryId, $companyId);
if ($state === null || (int) ($state['version'] ?? 0) !== $version) {
throw new RuntimeException('这个链接已经不是最新一次推送,请以群里最新的推送为准。');
}
if (in_array($state['status'] ?? '', [self::CONFIRMED, self::DISPUTED], true)) {
throw new RuntimeException('本次对账已经提交,请查看已提交的结果。');
}
if (($state['status'] ?? '') !== self::PUSHED) {
throw new RuntimeException('本次对账尚未推送成功,请等待财务重新推送。');
}
$now = now()->toDateTimeString();
$this->store->transaction(function () use ($month, $factoryId, $version, $disputes, $companyId, $now): void {
foreach ($disputes as $waybill => $reason) {
$this->store->save(self::DISPUTES . self::key($month, $factoryId), $version . '|' . $waybill,
['waybill' => (string) $waybill, 'reason' => $reason, 'version' => $version, 'submitted_at' => $now],
$companyId, null, 'manufacturer_link');
}
$this->merge($month, $factoryId, $companyId, [
'status' => $disputes === [] ? self::CONFIRMED : self::DISPUTED,
'confirmed_at' => $now, 'disputed_count' => count($disputes),
], 'manufacturer_link');
});
return $this->state($month, $factoryId, $companyId) ?? [];
}
/** @return list<array<string,mixed>> 这家这个月的异议,最新版本在前 */
public function disputes(string $month, int $factoryId, int $companyId, ?int $version = null): array
{
$rows = $this->store->listRows(self::DISPUTES . self::key($month, $factoryId), $companyId);
if ($version !== null) {
$rows = array_values(array_filter($rows, static fn (array $r): bool => (int) ($r['version'] ?? 0) === $version));
}
usort($rows, static fn (array $a, array $b): int => [(int) ($b['version'] ?? 0), (string) ($a['waybill'] ?? '')]
<=> [(int) ($a['version'] ?? 0), (string) ($b['waybill'] ?? '')]);
return $rows;
}
private function base(array $state, string $month, object $factory): array
{
$keep = array_diff_key($state, array_flip(['_action_key']));
return array_merge($keep, ['factory_id' => (int) $factory->id, 'factory' => (string) $factory->name,
'supplier' => (string) $factory->name, 'month' => $month]);
}
private function merge(string $month, int $factoryId, int $companyId, array $values, string $source): void
{
$state = $this->state($month, $factoryId, $companyId) ?? [];
unset($state['_action_key']);
$this->store->save(self::DATASET, self::key($month, $factoryId), array_merge($state, $values), $companyId, null, $source);
}
} }

View File

@ -17,12 +17,12 @@ use RuntimeException;
* 代发运费对账单导出(内部版),和快递账单对账的导出一个样子: * 代发运费对账单导出(内部版),和快递账单对账的导出一个样子:
* 和手工版一样:第一张是「汇总」(照这家上月手工汇总的样子),然后是厂家发来的原始账单(表名改叫「厂家账单」,内容原样不动),后面接 对账、前月补提供-X月、跨月订单-X月、快递不符、重复、匹配不到、未发出、 * 和手工版一样:第一张是「汇总」(照这家上月手工汇总的样子),然后是厂家发来的原始账单(表名改叫「厂家账单」,内容原样不动),后面接 对账、前月补提供-X月、跨月订单-X月、快递不符、重复、匹配不到、未发出、
* 厂家未提供、说明;没有数据的表不生成。 * 厂家未提供、说明;没有数据的表不生成。
* 对账类子表的列顺序:厂家账单原始列(一单多行取第一行)→ 财务指定的 25 列 → 发货数据其余字段 → 厂家运费合计、结算运费、分类、说明。 * 对账类子表的列顺序:厂家账单原始列(一单多行取第一行)→ 核算及结算对比列 → 发货数据其余字段 → 厂家运费合计、结算运费、分类、说明。
*/ */
final class DropshipExporter final class DropshipExporter
{ {
/** 小汇总里放厂家附加费表金额的那一行(手工汇总里已有带「附加费」的类目就填那一行)。 */ /** 小汇总里放厂家附加费表金额的那一行(手工汇总里已有带「附加费」的类目就填那一行)。 */
public const FEE_LABEL = '厂家账单-附加费'; public const FEE_LABEL = DropshipBillSummary::FEE_LABEL;
private const CHUNK = 500; private const CHUNK = 500;
public function __construct( public function __construct(
@ -138,6 +138,7 @@ final class DropshipExporter
} }
$this->writeNotes($book, $rows, $originals); $this->writeNotes($book, $rows, $originals);
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->write($book,'dropship',(int)$factory->id,$month);
$book->writeTo($output); $book->writeTo($output);
} }
@ -150,80 +151,16 @@ final class DropshipExporter
*/ */
private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void
{ {
$template = $this->store->summaryTemplate($factory, $month); $summary = app(DropshipBillSummary::class)->build($factory, $month, $rows);
$billTotal = $settleTotal = null; $book->row('汇总', [$summary['title'], ...$summary['headers']], true);
$extras = []; foreach ($summary['rows'] as $index => $item) {
foreach ([Category::MISMATCH, Category::DUPLICATE, Category::UNMATCHED, Category::UNSHIPPED] as $category) { $book->row('汇总', [$item['label'], $item['bill'], $item['settle'], self::diff($index + 2, $item['bill'], $item['settle'])]);
$extras[DropshipReconciler::LABELS[$category]] = null;
} }
foreach ($rows as $r) { $last = count($summary['rows']) + 1;
if ($r['bill'] === null) {
continue;
}
if (in_array($r['status'], DropshipReconciler::PAYABLE, true)) {
$billTotal = (float) $billTotal + (float) $r['bill'];
$final = $r['final'] ?? $r['settle'];
if ($final !== null) {
$settleTotal = (float) $settleTotal + (float) $final;
}
} elseif ($r['status'] === Category::LATER) {
$label = Category::label(Category::LATER, (string) $r['status_month']);
$extras[$label] = (float) ($extras[$label] ?? 0) + (float) $r['bill'];
} elseif (array_key_exists($label = DropshipReconciler::LABELS[$r['status']] ?? '', $extras)) {
$extras[$label] = (float) $extras[$label] + (float) $r['bill'];
}
}
$extras = array_filter($extras, static fn ($v): bool => $v !== null);
// 厂家按模板填的「附加费」表:金额合计放一行(不逐单核对,简尚核对空着手工填)
$fee = 0.0;
$hasFee = false;
foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
->where('status', 'parsed')->get(['id', 'stored_path', 'sheets']) as $file) {
$fees = $this->store->feesFor($file);
if ($fees !== []) {
$fee += array_sum($fees);
$hasFee = true;
}
}
// 上月手工汇总里的分类行(快递不符、未发出、跨月订单-X月……)这个月没有就不留空行
$labels = array_values(array_filter($template['labels'], static fn (string $l): bool => array_key_exists(trim($l), $extras)
|| ! preg_match('/^(快递不符|重复|匹配不到|未发出|跨月订单)/u', trim($l))));
if (! $hasFee) {
$labels = array_values(array_filter($labels, static fn (string $l): bool => ! str_contains($l, '附加费')));
}
if (($billTotal !== null || $settleTotal !== null || $extras !== []) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) {
array_unshift($labels, '运费');
}
foreach (array_keys($extras) as $label) {
if (! in_array($label, array_map('trim', $labels), true)) {
$labels[] = $label;
}
}
$feeLabel = null;
if ($hasFee) {
$feeLabel = collect($labels)->first(static fn (string $l): bool => str_contains($l, '附加费')) ?? self::FEE_LABEL;
if (! in_array($feeLabel, $labels, true)) {
$labels[] = $feeLabel;
}
}
$book->row('汇总', [$template['title'], ...array_slice(array_pad($template['headers'], 3, ''), 0, 3)], true);
$sums = [0.0, 0.0];
foreach (array_values($labels) as $index => $label) {
$n = $index + 2;
[$bill, $settle] = match (true) {
DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)],
array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0],
$label === $feeLabel => [round($fee, 2), null],
default => [null, null],
};
$sums[0] += (float) $bill;
$sums[1] += (float) $settle;
$book->row('汇总', [$label, $bill, $settle, self::diff($n, $bill, $settle)]);
}
$last = count($labels) + 1;
$n = $last + 1; $n = $last + 1;
$book->row('汇总', [$template['total'], new XlsxFormula('SUM(B2:B' . $last . ')', round($sums[0], 2)), $book->row('汇总', [$summary['total_label'], new XlsxFormula('SUM(B2:B' . $last . ')', $summary['totals']['bill']),
new XlsxFormula('SUM(C2:C' . $last . ')', round($sums[1], 2)), new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', round($sums[0] - $sums[1], 2))], true); new XlsxFormula('SUM(C2:C' . $last . ')', $summary['totals']['settle']),
new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', $summary['totals']['diff'])], true);
} }
private static function diff(int $row, ?float $bill, ?float $settle): XlsxFormula private static function diff(int $row, ?float $bill, ?float $settle): XlsxFormula
@ -321,7 +258,7 @@ final class DropshipExporter
. ';' . ($read ? '读了这张表的运费。' : '这张表没读运费(货款、记账、退货等)。'), $lines]); . ';' . ($read ? '读了这张表的运费。' : '这张表没读运费(货款、记账、退货等)。'), $lines]);
} }
foreach ([ foreach ([
['对账', '本月发货、是这家代发单的单号(一致、运费有差、系统未核算),按我方核算运费结算。前面是厂家账单原始列,后面接我方核算的 25 列和发货数据其余字段。', [Category::MATCH, Category::DIFF, Category::UNCALCULATED]], ['对账', '本月发货、是这家代发单的单号(一致、运费有差、系统未核算)。运费差为厂家运费减最终结算运费,重量差为厂家重量减结算重量。前面是厂家账单原始列,后面接核算及结算对比列和发货数据其余字段。', [Category::MATCH, Category::DIFF, Category::UNCALCULATED]],
['前月补提供-X月', '上月及以前发货、厂家这次才开的单,按我方核算运费结算。', [Category::PRIOR]], ['前月补提供-X月', '上月及以前发货、厂家这次才开的单,按我方核算运费结算。', [Category::PRIOR]],
['跨月订单-X月', '下个月才发货的单,本月不付,留到发货那个月。', [Category::LATER]], ['跨月订单-X月', '下个月才发货的单,本月不付,留到发货那个月。', [Category::LATER]],
['快递不符', '发货数据查得到,但不是这家代发单(不是这家代发仓发的、快递名称1 不含关键字,或是自有快递),不付。', [Category::MISMATCH]], ['快递不符', '发货数据查得到,但不是这家代发单(不是这家代发仓发的、快递名称1 不含关键字,或是自有快递),不付。', [Category::MISMATCH]],
@ -378,13 +315,14 @@ final class DropshipExporter
}, $original); }, $original);
} }
/** 对账表前面几列:照快递对账单的,「核算运费」后面加「最终结算运费」。 @return array<string,string> */ /** 对账表前面几列:核算运费、结算重量、最终结算运费依次相邻。 @return array<string,string> */
private static function frontColumns(): array private static function frontColumns(): array
{ {
$result = []; $result = [];
foreach (StatementExporter::FRONT as $label => $field) { foreach (StatementExporter::FRONT as $label => $field) {
if ($field === 'qc_charge_weight') $result['厂家重量(kg)'] = '_bill_weight';
$result[$label] = $field; $result[$label] = $field;
if ($field === 'qc_freight') { if ($field === '_settlement_weight') {
$result['最终结算运费'] = '_final'; $result['最终结算运费'] = '_final';
} }
} }
@ -397,7 +335,10 @@ final class DropshipExporter
return match ($field) { return match ($field) {
'_measured' => $ship['qc_measured_weight'] ?? null, '_measured' => $ship['qc_measured_weight'] ?? null,
'_unshipped' => null, '_unshipped' => null,
'_weight_diff' => null, '_bill_weight' => $r['bill_weight'],
'qc_charge_weight' => $r['charge_weight'],
'_settlement_weight' => $r['settlement_weight'],
'_weight_diff' => $r['weight_diff'],
'_final' => $r['final'] ?? $r['settle'] ?? null, '_final' => $r['final'] ?? $r['settle'] ?? null,
// 运费差 = 厂家运费 − 最终结算运费 // 运费差 = 厂家运费 − 最终结算运费
'_freight_diff' => $r['bill'] !== null && ($r['final'] ?? $r['settle'] ?? null) !== null '_freight_diff' => $r['bill'] !== null && ($r['final'] ?? $r['settle'] ?? null) !== null

View File

@ -112,6 +112,33 @@ final class DropshipFees
public function auto(string $month): array public function auto(string $month): array
{ {
$result = []; $result = [];
$matcher=app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
$indexed=$matcher->ready()?$this->store->db()->table('dropship_bill_surcharges')->where('bill_month',$month)->distinct()->pluck('factory_id')->all():[];
$hasMatchedFiles=$indexed!==[];
if($hasMatchedFiles){
$rows=$this->store->db()->table($matcher::TABLE)->where('scope','dropship')->where('bill_month',$month)
->selectRaw('owner_id,item,SUM(self_amount) AS amount')->groupBy('owner_id','item')->get();
foreach($rows as $row){
if($row->amount===null)continue;
$key=self::classify($row->item);$id=(int)$row->owner_id;
if($key===null)$result[$id]['other'][$row->item]=(float)$row->amount;
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+(float)$row->amount;
}
// 已确认账期维持原自动值,不因接入新的核对方式重写已确认金额。
$states=app(DropshipConfirmation::class)->states($month,(int)(company_id()?:1));
$confirmed=array_keys(array_filter($states,fn($s)=>($s['status']??'')==='confirmed'));
foreach($confirmed as $id)unset($result[$id]);
$legacy=$this->store->db()->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')
->where(fn($q)=>$q->whereNotIn('factory_id',$indexed)->orWhereIn('factory_id',$confirmed));
foreach($legacy->get(['id','factory_id','stored_path','sheets']) as $file){
foreach($this->store->feesFor($file) as $type=>$amount){
$key=self::classify($type);$id=(int)$file->factory_id;
if($key===null)$result[$id]['other'][$type]=($result[$id]['other'][$type]??0)+$amount;
else $result[$id]['fees'][$key]=($result[$id]['fees'][$key]??0)+$amount;
}
}
return $result;
}
$files = $this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->where('status', 'parsed') $files = $this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->where('status', 'parsed')
->whereNotNull('factory_id')->get(['id', 'factory_id', 'stored_path', 'sheets']); ->whereNotNull('factory_id')->get(['id', 'factory_id', 'stored_path', 'sheets']);
foreach ($files as $file) { foreach ($files as $file) {

View File

@ -6,6 +6,7 @@ use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\CourierBillStore; use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\FreightBillTemplate; use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\ShippingLookup; use App\Support\CourierBills\ShippingLookup;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use Illuminate\Database\ConnectionInterface; use Illuminate\Database\ConnectionInterface;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@ -84,6 +85,21 @@ final class DropshipFreightStore
return $sheets; return $sheets;
} }
/** 新上传时在已有事务内保存;历史文件通过受限批处理命令回读。 */
public function storeSurchargeRows(object $file,int $factoryId): void
{
if(!app(SurchargeSettlementMatcher::class)->ready())return;
$db=$this->db();
$db->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
$rows=[];
foreach((new FreightBillTemplate(new BillWorkbookReader()))->surchargeRows(
Storage::disk(self::DISK)->path($file->stored_path),pathinfo($file->stored_path,PATHINFO_EXTENSION)) as $row){
$rows[]=$row+['file_id'=>$file->id,'factory_id'=>$factoryId,'bill_month'=>$file->bill_month];
if(count($rows)>=300){$db->table('dropship_bill_surcharges')->insert($rows);$rows=[];}
}
if($rows!==[])$db->table('dropship_bill_surcharges')->insert($rows);
}
public function db(): ConnectionInterface public function db(): ConnectionInterface
{ {
return DB::connection('business_mirror'); return DB::connection('business_mirror');
@ -258,9 +274,14 @@ final class DropshipFreightStore
} }
$this->db()->transaction(function () use ($file): void { $this->db()->transaction(function () use ($file): void {
$this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete(); $this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete();
if(app(SurchargeSettlementMatcher::class)->ready()){
$this->db()->table('dropship_bill_surcharges')->where('file_id',$file->id)->delete();
$this->db()->table(SurchargeSettlementMatcher::TABLE)->where('scope','dropship')->where('file_id',$file->id)->delete();
}
$this->db()->table('dropship_bill_files')->where('id', $file->id)->delete(); $this->db()->table('dropship_bill_files')->where('id', $file->id)->delete();
}); });
Storage::disk(self::DISK)->delete($file->stored_path); Storage::disk(self::DISK)->delete($file->stored_path);
if($file->factory_id!==null)app(SurchargeSettlementMatcher::class)->dropship((int)$file->factory_id,$file->bill_month);
} }
/** /**
@ -409,12 +430,13 @@ final class DropshipFreightStore
$lines = array_diff_key($lines, array_flip($others)); $lines = array_diff_key($lines, array_flip($others));
} }
$db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void { $db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void {
$this->storeSurchargeRows($file,$factoryId);
$db->table('dropship_bill_lines')->where('file_id', $fileId)->delete(); $db->table('dropship_bill_lines')->where('file_id', $fileId)->delete();
foreach (array_chunk($lines, 500, true) as $chunk) { foreach (array_chunk($lines, 500, true) as $chunk) {
$insert = []; $insert = [];
foreach ($chunk as $waybill => $line) { foreach ($chunk as $waybill => $line) {
$insert[] = ['file_id' => $fileId, 'factory_id' => $factoryId, 'bill_month' => $file->bill_month, 'waybill_no' => (string) $waybill, $insert[] = ['file_id' => $fileId, 'factory_id' => $factoryId, 'bill_month' => $file->bill_month, 'waybill_no' => (string) $waybill,
'amount' => $line['amount'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']]; 'amount' => $line['amount'], 'bill_weight' => $line['weight'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']];
} }
$db->table('dropship_bill_lines')->insert($insert); $db->table('dropship_bill_lines')->insert($insert);
} }
@ -427,6 +449,7 @@ final class DropshipFreightStore
'updated_at' => now(), 'updated_at' => now(),
]); ]);
}); });
app(SurchargeSettlementMatcher::class)->dropship($factoryId,$file->bill_month);
} }
/** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */ /** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */

View File

@ -0,0 +1,50 @@
<?php
namespace App\Support\DropshipFreight;
use App\Support\CourierBills\StreamingWorkbook;
/** 导出各厂家汇总,数据直接复用页面汇总结果,不导出逐单明细。 */
final class DropshipOverviewExporter
{
public static function headers(): array
{
return ['厂家', ...array_values(DropshipFees::COLUMNS), '合计运费', '备注', '代发仓', '关键字',
'厂家开运费单数', '厂家运费', '结算运费', '差额', '运费有差·厂家多开', '运费有差·厂家少开',
'厂家未提供(不付)', '其他要看的', '厂家确认'];
}
/** @param resource $output */
public function write(array $data, $output): void
{
$book = new StreamingWorkbook();
$book->row('各厂家汇总', self::headers(), true);
foreach ($data['dfRows'] as $row) {
$fee = $data['dfFees'][$row['factory_id']];
$amounts = [];
foreach (array_keys(DropshipFees::COLUMNS) as $key) {
$value = (float) $fee['values'][$key];
$amounts[] = $value == 0 ? null : ($key === 'booking' ? -$value : $value);
}
$notes = $fee['note'];
if ($fee['other'] !== []) {
$other = [];
foreach ($fee['other'] as $type => $amount) $other[] = $type . ' ' . number_format($amount, 2);
$notes .= ($notes !== '' ? "\n" : '') . '未归类附加费(不计入合计):' . implode('、', $other);
}
$book->row('各厂家汇总', [$row['factory'], ...$amounts, $fee['total'], $notes, $row['warehouse'], $row['keywords'],
$row['billed'], $row['bill'], $row['settle'], $row['diff'], $row['over'], $row['under'],
$row['counts']['unprovided'], $row['attention'] - $row['counts']['diff'],
DropshipConfirmation::label($data['dfStates'][$row['factory_id']] ?? null)]);
}
if ($data['dfRows'] !== []) {
$totals = [];
foreach (array_keys(DropshipFees::COLUMNS) as $key) {
$value = (float) ($data['dfFeeTotals'][$key] ?? 0);
$totals[] = $value == 0 ? null : ($key === 'booking' ? -$value : $value);
}
$book->row('各厂家汇总', ['合计', ...$totals, $data['dfFeeTotals']['total'], ...array_fill(0, 12, null)], true);
}
$book->writeTo($output);
}
}

View File

@ -5,6 +5,7 @@ namespace App\Support\DropshipFreight;
use App\Support\CourierBills\Category; use App\Support\CourierBills\Category;
use App\Support\CourierBills\CourierBillMatcher; use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\ShippingLookup; use App\Support\CourierBills\ShippingLookup;
use App\Support\CourierBills\SettlementComparison;
use App\Support\UnshippedWaybills; use App\Support\UnshippedWaybills;
/** /**
@ -46,12 +47,33 @@ final class DropshipReconciler
*/ */
public function factoryMonth(object $factory, string $month, ?array $own = null, bool $withSources = false): array public function factoryMonth(object $factory, string $month, ?array $own = null, bool $withSources = false): array
{ {
$confirmation = app(DropshipConfirmation::class);
$company = (int) company_id();
$state = $confirmation->state($month, (int)$factory->id, $company);
if (($state['status'] ?? '') === DropshipConfirmation::CONFIRMED) {
$version = (int)($state['version'] ?? 0);
$snapshot = $confirmation->snapshot($month, (int)$factory->id, $version, $company);
if ($snapshot !== null) {
$rows = [];
foreach ($confirmation->snapshotQuery($month, (int)$factory->id, $version, $company)->orderBy('id')->cursor() as $record) {
$row = json_decode($record->values, true);
// 旧版本快照仍锁定原金额;没有保存的核算字段留空,不拿当前镜像改写历史。
$rows[] = $row + array_fill_keys(['warehouse','calc','bill_weight','charge_weight','settlement_weight',
'weight_diff','diff_kind','settle','freight_diff','diff','status_month','formula'], null)
+ ['ship_waybill'=>$row['waybill']];
}
return ['rows'=>$rows, 'summary'=>$snapshot['summary']];
}
throw new \RuntimeException('已确认账单缺少确认快照,请核对历史记录。');
}
$own = array_flip($own ?? $this->store->ownExpressNames()); $own = array_flip($own ?? $this->store->ownExpressNames());
$keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords); $keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords);
$columns = $withSources ? ['waybill_no', 'amount', 'file_id', 'sheet', 'row_no'] : ['waybill_no', 'amount']; $columns = $withSources ? ['waybill_no', 'amount', 'bill_weight', 'file_id', 'sheet', 'row_no'] : ['waybill_no', 'amount', 'bill_weight'];
$lines = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month) $lines = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month)
->orderBy('id')->get($columns)->groupBy('waybill_no'); ->orderBy('id')->get($columns)->groupBy('waybill_no');
$bill = $lines->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all(); $bill = $lines->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all();
$weights = $lines->map(static fn ($rows): ?float => $rows->contains(fn ($r) => $r->bill_weight === null)
? null : round((float) $rows->sum('bill_weight'), 4))->all();
$sources = $withSources ? $lines->map(static fn ($rows): array => ['file_id' => (int) $rows->first()->file_id, $sources = $withSources ? $lines->map(static fn ($rows): array => ['file_id' => (int) $rows->first()->file_id,
'sheet' => (string) $rows->first()->sheet, 'row_no' => (int) $rows->first()->row_no])->all() : []; 'sheet' => (string) $rows->first()->sheet, 'row_no' => (int) $rows->first()->row_no])->all() : [];
unset($lines); unset($lines);
@ -114,7 +136,7 @@ final class DropshipReconciler
$note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '') $note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '')
. ($i === null ? ';新单号发货数据里也查不到' : ''); . ($i === null ? ';新单号发货数据里也查不到' : '');
} }
$rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note) + ($sources[$waybill] ?? []) $rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note, $weights[$waybill]) + ($sources[$waybill] ?? [])
+ ['ship_waybill' => $swap ?? $waybill]; + ['ship_waybill' => $swap ?? $waybill];
} }
$system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w]))); $system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w])));
@ -133,14 +155,21 @@ final class DropshipReconciler
? Category::label($status, $month) : (self::LABELS[$status] ?? $status); ? Category::label($status, $month) : (self::LABELS[$status] ?? $status);
} }
private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note, ?float $billWeight = null): array
{ {
$calc = $i['calc'] ?? null; $calc = $i['calc'] ?? null;
$settle = in_array($status, self::PAYABLE, true) ? $calc : null; $settle = in_array($status, self::PAYABLE, true) ? $calc : null;
$chargeWeight = $i['charge_weight'] ?? null;
$weightDiff = $billWeight !== null && $chargeWeight !== null ? round($billWeight - $chargeWeight, 4) : null;
$final = self::final($billed, $settle);
$settlementWeight = SettlementComparison::weight($billed, $calc, $billWeight, $chargeWeight, $final);
return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null, return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null,
'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc, 'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc,
'settle' => $settle, 'final' => self::final($billed, $settle), 'bill_weight' => $billWeight, 'charge_weight' => $chargeWeight, 'settlement_weight' => $settlementWeight,
'weight_diff' => SettlementComparison::difference($billWeight, $settlementWeight, 4),
'diff_kind' => $status !== Category::DIFF ? null : ($weightDiff === null ? 'missing_weight' : (abs($weightDiff) > 0.005 ? 'weight_diff' : 'price_diff')),
'settle' => $settle, 'final' => $final, 'freight_diff' => SettlementComparison::difference($billed, $final),
'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null, 'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null,
'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth), 'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth),
'note' => $note, 'formula' => $i['formula'] ?? null]; 'note' => $note, 'formula' => $i['formula'] ?? null];
@ -158,6 +187,7 @@ final class DropshipReconciler
$counts = array_fill_keys(array_keys(self::LABELS), 0); $counts = array_fill_keys(array_keys(self::LABELS), 0);
$bill = $settle = $calcSettle = 0.0; $bill = $settle = $calcSettle = 0.0;
$billedCount = $over = $under = $capped = 0; $billedCount = $over = $under = $capped = 0;
$diffCounts = ['weight_diff' => 0, 'price_diff' => 0, 'missing_weight' => 0];
foreach ($rows as $row) { foreach ($rows as $row) {
$counts[$row['status']]++; $counts[$row['status']]++;
if ($row['bill'] !== null) { if ($row['bill'] !== null) {
@ -172,6 +202,7 @@ final class DropshipReconciler
} }
if ($row['status'] === Category::DIFF) { if ($row['status'] === Category::DIFF) {
$row['diff'] > 0 ? $over++ : $under++; $row['diff'] > 0 ? $over++ : $under++;
$diffCounts[$row['diff_kind'] ?? 'missing_weight']++;
} }
} }
@ -180,7 +211,7 @@ final class DropshipReconciler
'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2), 'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2),
'calc_settle' => round($calcSettle, 2), 'capped' => $capped, 'calc_settle' => round($calcSettle, 2), 'capped' => $capped,
'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under, 'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under,
'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))]; 'diff_counts' => $diffCounts, 'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))];
} }
public static function matches(string $express, array $keywords): bool public static function matches(string $express, array $keywords): bool
@ -271,9 +302,15 @@ final class DropshipReconciler
} }
foreach ($sources as $key => $set) { foreach ($sources as $key => $set) {
$total = 0.0; $total = 0.0;
$weight = 0.0; $weightComplete = true;
$ok = true; $ok = true;
$status = null; $status = null;
$formulas = []; $formulas = [];
foreach (array_keys($set) as $source) {
$freight = $freights[$source] ?? null;
if ($freight === null || $freight->charge_weight === null) $weightComplete = false;
else $weight += (float) $freight->charge_weight;
}
foreach (array_keys($set) as $source) { foreach (array_keys($set) as $source) {
$freight = $freights[$source] ?? null; $freight = $freights[$source] ?? null;
if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) { if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) {
@ -287,6 +324,7 @@ final class DropshipReconciler
} }
} }
$result[$key]['calc'] = $ok ? round($total, 2) : null; $result[$key]['calc'] = $ok ? round($total, 2) : null;
$result[$key]['charge_weight'] = $weightComplete ? round($weight, 4) : null;
$result[$key]['calc_status'] = $ok ? null : $status; $result[$key]['calc_status'] = $ok ? null : $status;
$result[$key]['formula'] = $formulas === [] ? null : implode(';', $formulas); $result[$key]['formula'] = $formulas === [] ? null : implode(';', $formulas);
} }

View File

@ -20,11 +20,13 @@ final class DropshipShareLink
return $this->signedRoute('signed.dropship-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId); return $this->signedRoute('signed.dropship-freight.show', $this->token($companyId, $factoryId, $month, $version), $companyId);
} }
public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null): string public function signedRoute(string $routeName, string $token, int $companyId, ?DateTimeInterface $expires = null, array $query = []): string
{ {
return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), [ $url = URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), [
'company_id' => $companyId, 'token' => $token, 'company_id' => $companyId, 'token' => $token,
]); ]);
// The project's signature middleware signs the resource and expiry, not view filters.
return $query === [] ? $url : $url . '&' . http_build_query($query);
} }
/** @return array{factory_id:int,month:string,version:int}|null */ /** @return array{factory_id:int,month:string,version:int}|null */

View File

@ -22,6 +22,7 @@ final class FactoryBillParser
public const AMOUNT_HEADERS = ['快递运费', '运费', '快递费', '运费金额', '快递费用', '邮费', '快递']; public const AMOUNT_HEADERS = ['快递运费', '运费', '快递费', '运费金额', '快递费用', '邮费', '快递'];
/** 偏远地区单独一列的运费(浩浦等),和运费列相加。 */ /** 偏远地区单独一列的运费(浩浦等),和运费列相加。 */
public const EXTRA_AMOUNT_HEADERS = ['偏远', '偏远费', '偏远运费', '偏远加收']; public const EXTRA_AMOUNT_HEADERS = ['偏远', '偏远费', '偏远运费', '偏远加收'];
public const WEIGHT_HEADERS = ['计费重量', '结算重量', '厂家重量', '重量', '实际重量'];
/** 表名含这些字的不读:货款/记账/退货/拦截/附加费,以及我方自己做的对账表。 */ /** 表名含这些字的不读:货款/记账/退货/拦截/附加费,以及我方自己做的对账表。 */
public const SKIP_SHEET_WORDS = ['记账', '退货', '退回', '拦截', '附加', '违约', '汇总', '入库', '入仓', '报价', '对账', public const SKIP_SHEET_WORDS = ['记账', '退货', '退回', '拦截', '附加', '违约', '汇总', '入库', '入仓', '报价', '对账',
'我代', '我入', '我退', '少算', '未发出', '补款', '补件', '赔']; '我代', '我入', '我退', '少算', '未发出', '补款', '补件', '赔'];
@ -32,7 +33,7 @@ final class FactoryBillParser
public function __construct(private readonly BillWorkbookReader $reader) {} public function __construct(private readonly BillWorkbookReader $reader) {}
/** /**
* @return array{lines:array<string,array{amount:float,sheet:string,row:int}>,sheets:list<array{sheet:string,read:bool,note:string,rows?:int,amount?:float}>} * @return array{lines:array<string,array{amount:float,weight:?float,sheet:string,row:int}>,sheets:list<array{sheet:string,read:bool,note:string,rows?:int,amount?:float}>}
*/ */
public function parse(string $path, string $extension): array public function parse(string $path, string $extension): array
{ {
@ -71,8 +72,11 @@ final class FactoryBillParser
if ($waybill === null || $amount === null) { if ($waybill === null || $amount === null) {
continue; continue;
} }
$mine[$waybill] ??= ['amount' => 0.0, 'sheet' => $sheet, 'row' => (int) $rowNumber]; $mine[$waybill] ??= ['amount' => 0.0, 'weight' => 0.0, 'weight_complete' => true, 'sheet' => $sheet, 'row' => (int) $rowNumber];
$mine[$waybill]['amount'] += $amount; $mine[$waybill]['amount'] += $amount;
$weight = $columns['weight'] === null ? null : BillParser::number($row[$columns['weight']] ?? null);
if ($weight === null || $weight < 0) $mine[$waybill]['weight_complete'] = false;
else $mine[$waybill]['weight'] += $weight;
} }
if ($columns === null) { if ($columns === null) {
$sheets[] = ['sheet' => $sheet, 'read' => false, 'note' => '没有同时找到单号列和运费列']; $sheets[] = ['sheet' => $sheet, 'read' => false, 'note' => '没有同时找到单号列和运费列'];
@ -83,6 +87,8 @@ final class FactoryBillParser
$repeated = 0; $repeated = 0;
foreach ($mine as $waybill => $line) { foreach ($mine as $waybill => $line) {
$line['amount'] = round($line['amount'], 2); $line['amount'] = round($line['amount'], 2);
$line['weight'] = $line['weight_complete'] ? round($line['weight'], 4) : null;
unset($line['weight_complete']);
if (abs($line['amount']) < 0.005) { if (abs($line['amount']) < 0.005) {
continue; continue;
} }
@ -97,6 +103,7 @@ final class FactoryBillParser
$sheets[] = ['sheet' => $sheet, 'read' => true, 'rows' => $count, 'amount' => round($total, 2), $sheets[] = ['sheet' => $sheet, 'read' => true, 'rows' => $count, 'amount' => round($total, 2),
'note' => '单号列「' . $columns['waybill_header'] . '」、运费列「' . $columns['amount_header'] . '」' 'note' => '单号列「' . $columns['waybill_header'] . '」、运费列「' . $columns['amount_header'] . '」'
. ($columns['extra'] !== [] ? '(加上「' . implode('」「', array_map(static fn (int $i): string => $columns['headers'][$i], $columns['extra'])) . '」)' : '') . ($columns['extra'] !== [] ? '(加上「' . implode('」「', array_map(static fn (int $i): string => $columns['headers'][$i], $columns['extra'])) . '」)' : '')
. ($columns['weight'] !== null ? ';重量列「' . $columns['headers'][$columns['weight']] . '」' : ';未提供重量列')
. ($repeated > 0 ? ';' . $repeated . ' 个单号前面的表已有,没重复算' : '')]; . ($repeated > 0 ? ';' . $repeated . ' 个单号前面的表已有,没重复算' : '')];
} }
@ -116,7 +123,7 @@ final class FactoryBillParser
/** /**
* @param array<int,string> $row * @param array<int,string> $row
* @return array{waybill:int,amount:int,extra:list<int>,headers:list<string>,waybill_header:string,amount_header:string}|null * @return array{waybill:int,amount:int,weight:?int,extra:list<int>,headers:list<string>,waybill_header:string,amount_header:string}|null
*/ */
public static function findColumns(array $row): ?array public static function findColumns(array $row): ?array
{ {
@ -169,7 +176,14 @@ final class FactoryBillParser
} }
} }
return ['waybill' => $waybill, 'amount' => $amount, 'extra' => $extra, 'headers' => array_values($headers), $weight = null;
foreach (self::WEIGHT_HEADERS as $candidate) {
foreach ($headers as $index => $header) {
$base = preg_replace('/[((]?(?:kg|公斤|千克)[))]?$/iu', '', $header);
if ($base === $candidate) { $weight = (int) $index; break 2; }
}
}
return ['waybill' => $waybill, 'amount' => $amount, 'weight' => $weight, 'extra' => $extra, 'headers' => array_values($headers),
'waybill_header' => $headers[$waybill], 'amount_header' => $headers[$amount]]; 'waybill_header' => $headers[$waybill], 'amount_header' => $headers[$amount]];
} }

View File

@ -53,6 +53,8 @@ class ReturnPickupFreightCalculator
?float $length = null, ?float $length = null,
?float $width = null, ?float $width = null,
?float $height = null, ?float $height = null,
?string $pickupDate = null,
?float $volumeCm3 = null,
): array { ): array {
$carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null; $carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null;
@ -63,8 +65,8 @@ class ReturnPickupFreightCalculator
$length = max((float) $length, 0); $length = max((float) $length, 0);
$width = max((float) $width, 0); $width = max((float) $width, 0);
$height = max((float) $height, 0); $height = max((float) $height, 0);
$volumeWeight = ($length > 0 && $width > 0 && $height > 0) $volumeWeight = ($volumeCm3 !== null || ($length > 0 && $width > 0 && $height > 0))
? round($length * $width * $height / 6000, 4) ? round(max(0, $volumeCm3 ?? ($length * $width * $height)) / 6000, 4)
: 0.0; : 0.0;
$settlement = round(max($grossWeight, $volumeWeight), 4); $settlement = round(max($grossWeight, $volumeWeight), 4);
@ -82,6 +84,9 @@ class ReturnPickupFreightCalculator
} }
$rule = $this->rules[$carrier] ?? []; $rule = $this->rules[$carrier] ?? [];
if ($pickupDate !== null && ! empty($rule['effective_date']) && $pickupDate < $rule['effective_date']) {
return $this->missing('取件日期早于该逆向物流报价执行日期');
}
$mode = (string) ($rule['pricing_mode'] ?? ''); $mode = (string) ($rule['pricing_mode'] ?? '');
$maxSide = max($length, $width, $height); $maxSide = max($length, $width, $height);
$sideSum = $length + $width + $height; $sideSum = $length + $width + $height;

View File

@ -0,0 +1,181 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
use RuntimeException;
/** 只校准现有包裹的运单标识,不重算商品、重量或运费。 */
class ShippingTrackingRefresh
{
public const DATASET = 'derived.shipping-tracking-refresh';
private ?bool $hasDetailsMirror = null;
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) {}
public function sync(array $ids = [], int $maxBatches = 4): array
{
$db = DB::connection('business_mirror');
$state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first();
$cursor = $state ? json_decode($state->cursor ?? 'null', true) : null;
$targeted = $ids !== [];
$resume = !$targeted && is_array($cursor) && in_array($state->status, ['running', 'failed'], true);
$watermark = $state ? json_decode($state->high_watermark ?? 'null', true) : null;
$from = $resume ? $cursor['from'] : (isset($watermark['until'])
? \Illuminate\Support\Carbon::parse($watermark['until'])->subHours(48)->format('Y-m-d H:i:s')
: now()->subHours(48)->format('Y-m-d H:i:s'));
$until = $resume ? $cursor['until'] : now()->addSecond()->format('Y-m-d H:i:s');
$last = $resume ? (int) $cursor['last_id'] : 0;
$generation = $resume ? $state->generation : (string) Str::uuid();
$scanned = $resume ? (int)($cursor['scanned']??0) : 0;
$changed = $resume ? (int)($cursor['changed']??0) : 0;
$base = ['source_key'=>'operations_replica','source_object'=>'rpt.jst_order_express_details',
'target_table'=>'jst_oms_shipping','run_mode'=>'incremental','generation'=>$generation,
'status'=>'running','last_attempted_at'=>now(),'last_error_code'=>null,'updated_at'=>now()];
if (!$targeted) $db->table('business_mirror_table_states')->updateOrInsert(['dataset_key'=>self::DATASET], $base + [
'cursor'=>json_encode(['from'=>$from,'until'=>$until,'last_id'=>$last,'scanned'=>$scanned,'changed'=>$changed]),
'created_at'=>$state->created_at??now()]);
try {
$names = $this->repairMissingCourierNames($generation);
for ($batch=0; $batch<max(1,$maxBatches); $batch++) {
$keys = $targeted ? array_values(array_unique(array_map('intval',$ids))) : $this->keys($last,$from,$until);
$scanned += count($keys);
$existing = $keys === [] ? [] : $db->table('jst_oms_shipping')->whereIn('source_id',$keys)->distinct()->pluck('source_id')->all();
foreach (array_chunk($existing,200) as $part) {
$current = $db->table('jst_oms_shipping')->whereIn('source_id',$part)
->distinct()->get(['source_id','express_no','express_name1'])->groupBy('source_id');
foreach ($this->details($part) as $row) {
$new = UnshippedWaybills::normalize($row['logistic_id']??null);
$name = trim((string)($row['logistic_company_name']??''));
$same = ($current[$row['id']]??collect())->every(fn($r)=>UnshippedWaybills::normalize($r->express_no)===$new
&& ($name==='' || (string)$r->express_name1===$name));
if ($same) continue;
$changed += $this->apply($row, $generation);
}
}
if ($targeted || count($keys)<5000) {
if (!$targeted) $db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update([
'status'=>'succeeded','cursor'=>null,'high_watermark'=>json_encode(['until'=>$until]),'last_succeeded_at'=>now(),'initial_completed_at'=>$state->initial_completed_at??now(),'last_upserted_rows'=>$changed,'updated_at'=>now()]);
return ['status'=>'succeeded','scanned'=>$scanned,'changed'=>$changed,'names'=>$names];
}
$next = (int) end($keys);
if ($next <= $last) throw new RuntimeException('tracking_cursor_not_advanced');
$last=$next;
$db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update([
'cursor'=>json_encode(['from'=>$from,'until'=>$until,'last_id'=>$last,'scanned'=>$scanned,'changed'=>$changed]),'last_upserted_rows'=>$changed,'updated_at'=>now()]);
}
return ['status'=>'running','scanned'=>$scanned,'changed'=>$changed,'names'=>$names];
} catch (\Throwable $e) {
if (!$targeted) $db->table('business_mirror_table_states')->where('dataset_key',self::DATASET)->update(['status'=>'failed','last_error_code'=>$e::class,'updated_at'=>now()]);
throw $e;
}
}
protected function keys(int $last,string $from,string $until): array
{
// 先取窄键,再按明确主键读详情,避免宽行加日期过滤扫描超时。
return array_column($this->queries->forSourceWithTimeout('operations_replica',30)->select(
'SELECT TOP (5000) id FROM rpt.jst_order_express_details WHERE id > CAST(? AS int) AND updatedAt >= CAST(? AS datetime) AND updatedAt < CAST(? AS datetime) ORDER BY id',
[$last,$from,$until]),'id');
}
protected function details(array $ids): array
{
return $this->queries->forSourceWithTimeout('operations_replica',30)->select(
'SELECT id,updatedAt,inner_order_id,so_id,logistic_id,logistic_company_name FROM rpt.jst_order_express_details WHERE id IN ('
.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).') ORDER BY id',$ids);
}
public function apply(array $source, string $generation): int
{
$db=DB::connection('business_mirror');$new=UnshippedWaybills::normalize($source['logistic_id']??null);
if ($new==='' || strcasecmp($new,'OuterWMS')===0) return 0;
return $db->transaction(function() use($db,$source,$new,$generation): int {
$rows=$db->table('jst_oms_shipping')->where('source_id',(int)$source['id'])->lockForUpdate()->get();
if($rows->isEmpty()) return 0;
$old=UnshippedWaybills::normalize($rows->first()->express_no);
$courier=trim((string)($source['logistic_company_name']??''));
$mirror = $this->hasDetailsMirror()
? $db->table('js_jst_order_express_details')->where('id',(int)$source['id'])->first() : null;
$sameMirror = !$mirror || (UnshippedWaybills::normalize($mirror->logistic_id)===$new
&& ($courier==='' || (string)$mirror->logistic_company_name===$courier));
if($sameMirror && $rows->every(fn($r)=>UnshippedWaybills::normalize($r->express_no)===$new
&& ($courier==='' || (string)$r->express_name1===$courier))) return 0;
if(!$rows->every(fn($r)=>(string)$r->trade_no===trim((string)($source['so_id']??'')))) throw new RuntimeException('tracking_order_mismatch');
$this->backup($generation, (string)$source['id'], ['before'=>$rows->all(),'mirror_before'=>$mirror,'source'=>$source]);
$set=['express_no'=>$new];if($courier!=='')$set['express_name1']=$courier;
if($old!=='' && $old!==$new && strcasecmp($old,'OuterWMS')!==0){
$set['front_no']=$old;
self::recordChange((int)$source['id'],$old,(string)$rows->first()->express_name1,$new,$courier,
(string)($source['updatedAt']??now()),(string)$rows->first()->trade_no);
}
$db->table('jst_oms_shipping')->where('source_id',(int)$source['id'])->update($set);
if ($mirror !== null) {
$db->table('js_jst_order_express_details')->where('id',(int)$source['id'])->update([
'logistic_id'=>$new, 'logistic_company_name'=>$courier?:$mirror->logistic_company_name,
]);
}
return 1;
});
}
private function hasDetailsMirror(): bool
{
return $this->hasDetailsMirror ??= DB::connection('business_mirror')->getSchemaBuilder()->hasTable('js_jst_order_express_details');
}
/** 只补已有换单记录中有同源、同旧单号证据的空名称;每轮有界读取。 */
private function repairMissingCourierNames(string $generation): int
{
$db = DB::connection('business_mirror');
if (!$this->hasDetailsMirror()) return 0;
$rows = $db->table('courier_unshipped_waybills')->where('source','replacement')
->whereNull('courier_name')->where('evidence_no','like','shipping:%')->orderBy('id')->limit(500)->get();
$ids = $rows->map(fn($r)=>(int)substr($r->evidence_no,9))->all();
$details = $db->table('js_jst_order_express_details')->whereIn('id',$ids)
->get(['id','logistic_id','logistic_company_name'])->keyBy('id');
$changed = 0;
foreach ($rows as $row) {
$source = $details[(int)substr($row->evidence_no,9)] ?? null;
$name = trim((string)($source->logistic_company_name ?? ''));
if (!$source || $name==='' || UnshippedWaybills::normalize($source->logistic_id)!==$row->waybill_no) continue;
$this->backup($generation, 'name-'.$row->id, ['before'=>$row,'source'=>$source]);
$changed += $db->table('courier_unshipped_waybills')->where('id',$row->id)->whereNull('courier_name')->update(['courier_name'=>$name]);
}
return $changed;
}
private function backup(string $generation, string $key, array $data): void
{
$dir=storage_path('app/private/maintenance/tracking-refresh/'.$generation);
if(!is_dir($dir) && !mkdir($dir,0700,true) && !is_dir($dir)) throw new RuntimeException('tracking_backup_failed');
$payload=json_encode($data,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
$path=$dir.'/'.$key.'-'.bin2hex(random_bytes(4)).'.json';
if(file_put_contents($path,$payload,LOCK_EX)!==strlen($payload)) throw new RuntimeException('tracking_backup_failed');
chmod($path,0600);
}
public static function recordChange(int $sourceId,string $old,string $oldCourier,string $new,string $newCourier,string $time,string $trade): void
{
$old=UnshippedWaybills::normalize($old);$new=UnshippedWaybills::normalize($new);
if($old===''||$new===''||$old===$new||strcasecmp($old,'OuterWMS')===0||strcasecmp($new,'OuterWMS')===0)return;
$db=DB::connection('business_mirror');$order='shipping:'.$sourceId;
$log=['old_waybill'=>$old,'new_waybill'=>$new,'old_courier'=>$oldCourier,'new_courier'=>$newCourier,
'operator'=>'系统同步','remark'=>$oldCourier.':'.$old.'->'.$newCourier.':'.$new];
$db->table('courier_unshipped_order_logs')->updateOrInsert(['order_no'=>$order,'operated_at'=>$time,'old_waybill'=>$old],$log);
if (!$db->table('jst_oms_shipping')->where('source_id','<>',$sourceId)->whereIn('express_no',[$old,'@'.$old])->exists()) {
$db->table('courier_unshipped_waybills')->updateOrInsert(['source'=>'replacement','evidence_no'=>$order,'waybill_no'=>$old],
['courier_name'=>$oldCourier?:null,'new_waybill_no'=>$new,'new_courier_name'=>$newCourier?:null,'trade_no'=>$trade,
'evidence_time'=>$time,'evidence_text'=>'按同一包裹源键核实换单前后信息','operator'=>'系统同步']);
}
$db->table('courier_unshipped_waybills')->where('source','replacement')->where('evidence_no',$order)
->update(['new_waybill_no'=>$new,'new_courier_name'=>$newCourier?:null]);
// A→B→A 时,最终正在使用的号码不再作为未发出旧号。
$db->table('courier_unshipped_waybills')->where('source','replacement')->where('evidence_no',$order)->where('waybill_no',$new)->delete();
$db->table('courier_unshipped_sync')->where('source','replacement')->update([
'row_count'=>$db->table('courier_unshipped_waybills')->where('source','replacement')->count(),
]);
}
}

View File

@ -0,0 +1,136 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
use RuntimeException;
use Throwable;
/** 未发出名单的受控刷新:先完成来源快照,再原子发布,网页不查询上游。 */
class UnshippedSourceSynchronizer
{
public const WAREHOUSE_DATASET = 'derived.courier-unshipped-warehouse';
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries, private readonly UnshippedWaybills $waybills) {}
public function intercept(string $source): int
{
$db = $this->waybills->connection();
$state = $db->table('business_mirror_table_states')->where('dataset_key', ReturnedParcelSynchronizer::DATASET)->first();
if (!$state || $state->status !== 'succeeded' || !$state->last_succeeded_at) throw new RuntimeException('退回件明细尚未完成刷新,保留上次结果。');
$history = $this->waybills->results()->where('source', 'intercept')->where('evidence_no', 'like', 'history:%')->max('evidence_time');
$from = $history ? substr($history, 0, 10) : UnshippedWaybills::START;
if (substr((string)$state->window_started_at, 0, 10) > $from) throw new RuntimeException('退回件来源覆盖不足,保留上次结果。');
$kind = $source === 'intercept_taobao' ? 'taobao' : 'regular';
$generation = (string) Str::uuid(); $missing = 0;
$db->table('courier_unshipped_stage')->where('source', $source)->delete();
$candidates = $db->table(ReturnedParcelSynchronizer::TABLE)->where('source_kind', $kind)
->where('reason', UnshippedWaybills::SOURCES['intercept'])->where('received_at', '>=', $from)
->selectRaw('after_sales_id,order_id,online_order_no,shop,MIN(received_at) AS received_at')
->groupBy('after_sales_id','order_id','online_order_no','shop')->orderBy('after_sales_id');
$candidates->chunk(100, function ($batch) use ($source, $generation, $kind, &$missing): void {
$ids = $batch->pluck('order_id')->filter(fn($id)=>ctype_digit((string)$id) && (int)$id > 0)->unique()->values()->all();
$orders = $ids === [] ? [] : $this->originalOrders($kind, $ids);
$byOrder = [];
foreach ($orders as $order) {
$number = UnshippedWaybills::normalize($order['l_id'] ?? null);
if ($number !== '' && (!isset($byOrder[$order['o_id']]) || strcmp($number,$byOrder[$order['o_id']]['l_id'])<0)) $byOrder[$order['o_id']] = array_replace($order, ['l_id'=>$number]);
}
$rows = [];
foreach ($batch as $refund) {
$order = $byOrder[$refund->order_id] ?? null;
if (!$order) { $missing++; continue; }
$rows[] = ['source'=>$source,'waybill_no'=>UnshippedWaybills::normalize($order['l_id']),
'evidence_no'=>(string)$refund->after_sales_id,'evidence_time'=>$refund->received_at,
'courier_name'=>$order['logistics_company'],'o_id'=>$refund->order_id,'trade_no'=>$refund->online_order_no,
'shop_name'=>$refund->shop,'evidence_text'=>UnshippedWaybills::SOURCES['intercept']];
}
$this->stage($source,$generation,$rows);
});
return $this->waybills->publishStage($source,$generation,$missing);
}
protected function originalOrders(string $kind, array $ids): array
{
$table = $kind === 'taobao' ? 'jst_qmcust_orderlist' : 'jst_Orders';
return $this->queries->forSourceWithTimeout('operations_replica',15)->select(
'SELECT Id,o_id,l_id,logistics_company FROM rpt.'.$table.' WHERE o_id IN ('.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).')',$ids);
}
public function warehouse(int $maxBatches = 0, ?callable $progress = null): array
{
$db=$this->waybills->connection();$state=$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->first();
$cursor=$state?json_decode($state->cursor??'null',true):null;
$resume=$state && in_array($state->status,['running','failed'],true) && is_array($cursor);
$generation=$resume?$state->generation:(string)Str::uuid();$last=$resume?(int)$cursor['last_id']:0;
$high=$resume?(int)$cursor['high_id']:$this->warehouseHighId();$scanned=$resume?(int)$cursor['scanned']:0;
if(!$resume)$db->table('courier_unshipped_stage')->where('source','warehouse')->delete();
$db->table('business_mirror_table_states')->updateOrInsert(['dataset_key'=>self::WAREHOUSE_DATASET],
['source_key'=>'operations_replica','source_object'=>'rpt.jst_workOrderInfo','target_table'=>'courier_unshipped_stage',
'status'=>'running','run_mode'=>'full','generation'=>$generation,'last_attempted_at'=>now(),'updated_at'=>now(),
'created_at'=>$state->created_at??now()]);
$batches=0;
try {
do {
$keys=$this->warehouseKeys($last,$high,5000);
if($keys===[])break;
$ids=[];foreach($keys as $key)if($key['woTypeId']===UnshippedWaybills::WAREHOUSE_WORK_TYPE)$ids[]=$key['Id'];
foreach(array_chunk($ids,100) as $part){
$rows=[];foreach($this->warehouseDetails($part) as $order){
if(substr($order['created'],0,10)<UnshippedWaybills::START || in_array($order['status'],UnshippedWaybills::WAREHOUSE_EXCLUDED_STATUSES,true))continue;
$fields=array_column(json_decode($order['businessFieldList'],true,512,JSON_THROW_ON_ERROR)?:[],'value','fieldId');
$number=UnshippedWaybills::normalize($fields['lIdField']??null);if($number==='')continue;
$rows[]=['source'=>'warehouse','waybill_no'=>$number,'evidence_no'=>$order['woNo'],'evidence_time'=>$order['created'],
'o_id'=>$fields['o_id']??null,'courier_name'=>$fields['logisticsField']??null,'evidence_text'=>trim($order['status'].' '.$order['title'])];
}
$this->stage('warehouse',$generation,$rows);
}
$next=(int)end($keys)['Id'];
if ($next <= $last) throw new RuntimeException('warehouse_cursor_not_advanced');
$last=$next;$scanned+=count($keys);$batches++;
$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update([
'cursor'=>json_encode(['last_id'=>$last,'high_id'=>$high,'scanned'=>$scanned]),'last_upserted_rows'=>$scanned,'updated_at'=>now()]);
$progress && $progress($scanned,$last,$high);
if($maxBatches>0 && $batches>=$maxBatches && $last<$high)return ['status'=>'running','scanned'=>$scanned];
} while($last<$high);
$rows=$this->waybills->publishStage('warehouse',$generation,0);
$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update([
'status'=>'succeeded','cursor'=>null,'initial_completed_at'=>now(),'last_succeeded_at'=>now(),'last_full_succeeded_at'=>now(),
'mirror_row_count'=>$rows,'last_error_code'=>null,'updated_at'=>now()]);
return ['status'=>'succeeded','scanned'=>$scanned,'rows'=>$rows];
}catch(Throwable $e){$db->table('business_mirror_table_states')->where('dataset_key',self::WAREHOUSE_DATASET)->update(['status'=>'failed','last_error_code'=>$e::class,'updated_at'=>now()]);throw $e;}
}
protected function warehouseHighId(): int
{
return (int)$this->queries->forSourceWithTimeout('operations_replica',15)->scalar('SELECT MAX(Id) FROM rpt.jst_workOrderInfo');
}
protected function warehouseKeys(int $last,int $high,int $limit): array
{
return $this->queries->forSourceWithTimeout('operations_replica',15)->select('SELECT TOP ('.$limit.') Id,woTypeId FROM rpt.jst_workOrderInfo WHERE Id > ? AND Id <= ? ORDER BY Id',[$last,$high]);
}
protected function warehouseDetails(array $ids): array
{
return $this->queries->forSourceWithTimeout('operations_replica',15)->select('SELECT Id,woNo,created,status,title,businessFieldList FROM rpt.jst_workOrderInfo WHERE Id IN ('.implode(',',array_fill(0,count($ids),'CAST(? AS int)')).')',$ids);
}
private function stage(string $source,string $generation,array $rows): void
{
if($rows===[])return;
if ($source === 'warehouse') {
$numbers = array_column(array_filter($rows, fn ($row) => empty($row['courier_name'])), 'waybill_no');
$couriers = $numbers === [] ? [] : $this->waybills->connection()->table('jst_oms_shipping')->whereIn('express_no', $numbers)
->orderBy('id')->pluck('express_name1', 'express_no')->all();
foreach ($rows as &$row) $row['courier_name'] = $row['courier_name'] ?: ($couriers[$row['waybill_no']] ?? null);
unset($row);
}
$values=[];foreach($rows as $r)$values[]=$r+['generation'=>$generation,'row_key'=>hash('sha256',$r['evidence_no'].'|'.$r['waybill_no']),
'courier_name'=>null,'trade_no'=>null,'o_id'=>null,'shop_name'=>null,'new_courier_name'=>null,'new_waybill_no'=>null,'operator'=>null,'evidence_text'=>null];
DB::connection('business_mirror')->table('courier_unshipped_stage')->upsert($values,['source','row_key'],array_keys($values[0]));
}
}

View File

@ -2,6 +2,7 @@
namespace App\Support; namespace App\Support;
use App\Support\CourierBills\WaybillMatch;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use RuntimeException; use RuntimeException;
use Throwable; use Throwable;
@ -12,8 +13,8 @@ final class UnshippedWaybills
public const HISTORY_PREFIX = 'history:'; public const HISTORY_PREFIX = 'history:';
public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发']; public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发'];
private const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F'; public const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F';
private const WAREHOUSE_EXCLUDED_STATUSES = [ public const WAREHOUSE_EXCLUDED_STATUSES = [
'REJECT_AUDIT', 'DISABLED', 'REJECTED', 'REFUSED', 'CANCELED', 'CANCELLED', '已拒绝', '已取消', 'REJECT_AUDIT', 'DISABLED', 'REJECTED', 'REFUSED', 'CANCELED', 'CANCELLED', '已拒绝', '已取消',
]; ];
@ -53,6 +54,12 @@ final class UnshippedWaybills
return ltrim(preg_replace('/\s+/u', '', $number ?? '') ?? '', '@'); return ltrim(preg_replace('/\s+/u', '', $number ?? '') ?? '', '@');
} }
private static function isPlaceholder(?string $number): bool
{
// 外部仓占位标记不是运单号,不能作为未发出或换单依据。
return strcasecmp(self::normalize($number), 'OuterWMS') === 0;
}
public static function parseRemark(string $remark): ?array public static function parseRemark(string $remark): ?array
{ {
if (!preg_match('/^\s*([^::]+)[::]([^::]+?)\s*->\s*([^::]+)[::]([^::]+)\s*$/u', $remark, $parts)) { if (!preg_match('/^\s*([^::]+)[::]([^::]+?)\s*->\s*([^::]+)[::]([^::]+)\s*$/u', $remark, $parts)) {
@ -61,7 +68,7 @@ final class UnshippedWaybills
$old = self::normalize($parts[2]); $old = self::normalize($parts[2]);
$new = self::normalize($parts[4]); $new = self::normalize($parts[4]);
foreach ([$old, $new] as $number) { foreach ([$old, $new] as $number) {
if (!preg_match('/^[A-Za-z0-9-]{1,96}$/', $number) || preg_match('/^\d+(?:\.\d+)?e[+-]?\d+$/i', $number)) return null; if (self::isPlaceholder($number) || !preg_match('/^[A-Za-z0-9-]{1,96}$/', $number) || preg_match('/^\d+(?:\.\d+)?e[+-]?\d+$/i', $number)) return null;
} }
return ['old_waybill' => $old, 'new_waybill' => $new, 'old_courier' => trim($parts[1]), 'new_courier' => trim($parts[3])]; return ['old_waybill' => $old, 'new_waybill' => $new, 'old_courier' => trim($parts[1]), 'new_courier' => trim($parts[3])];
@ -75,10 +82,12 @@ final class UnshippedWaybills
public function unshippedSources(array $waybills): array public function unshippedSources(array $waybills): array
{ {
$result = []; $result = [];
foreach (array_chunk(array_unique(array_filter(array_map(self::normalize(...), $waybills))), 500) as $chunk) { $numbers = array_values(array_unique(array_filter(array_map(self::normalize(...), $waybills),
foreach ($this->results()->whereIn('waybill_no', $chunk)->distinct()->get(['waybill_no', 'source']) as $row) { fn ($number) => $number !== '' && !self::isPlaceholder($number))));
foreach (WaybillMatch::find($this->results(), 'waybill_no', $numbers, ['waybill_no', 'source']) as $number => $match) {
foreach ($match['rows'] as $row) {
$label = self::label($row->source); $label = self::label($row->source);
$result[$row->waybill_no][$label] = $label; $result[$number][$label] = $label;
} }
} }
@ -100,7 +109,7 @@ final class UnshippedWaybills
$cutoff = (clone $history)->max('evidence_time'); $cutoff = (clone $history)->max('evidence_time');
if ($cutoff !== null) { if ($cutoff !== null) {
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true); $covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
$rows = array_filter($rows, fn ($row) => substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10) $rows = array_filter($rows, fn ($row) => (str_starts_with($row['evidence_no'], 'shipping:') || substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10))
&& !isset($covered[$row['waybill_no']])); && !isset($covered[$row['waybill_no']]));
} }
$db->transaction(function () use ($db, $source, $rows, $missing): void { $db->transaction(function () use ($db, $source, $rows, $missing): void {
@ -119,7 +128,7 @@ final class UnshippedWaybills
return true; return true;
} catch (Throwable $error) { } catch (Throwable $error) {
if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) { if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '尚无订单操作日志或发货换单记录。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) {
report($error); report($error);
$warning = '读取失败,保留上次同步结果。'; $warning = '读取失败,保留上次同步结果。';
} else { } else {
@ -186,29 +195,104 @@ final class UnshippedWaybills
private function replacements(): array private function replacements(): array
{ {
$logs = $this->connection()->table('courier_unshipped_order_logs')->where('operated_at', '>=', self::START) $logs = $this->connection()->table('courier_unshipped_order_logs')->where('operated_at', '>=', self::START)
->where('operated_at', '<', today())->orderBy('order_no')->orderByDesc('operated_at')->orderByDesc('id')->cursor(); ->where('operated_at', '<=', now())->orderBy('order_no')->orderByDesc('operated_at')->orderByDesc('id')->cursor();
$rows = []; $rows = [];
$currentOrder = null; $currentOrder = null;
$finalNumber = null; $finalNumber = null;
$finalCourier = null;
foreach ($logs as $log) { foreach ($logs as $log) {
if (self::isPlaceholder($log->old_waybill) || self::isPlaceholder($log->new_waybill)) continue;
if ($currentOrder !== $log->order_no) { if ($currentOrder !== $log->order_no) {
$currentOrder = $log->order_no; $currentOrder = $log->order_no;
$finalNumber = $log->new_waybill; $finalNumber = $log->new_waybill;
$finalCourier = $log->new_courier;
} }
if ($log->old_waybill === $finalNumber) continue; if ($log->old_waybill === $finalNumber) continue;
if ($this->connection()->table('jst_oms_shipping')->whereIn('express_no', [$log->old_waybill, '@'.$log->old_waybill])->exists()) continue;
$key = $log->order_no.'|'.$log->old_waybill; $key = $log->order_no.'|'.$log->old_waybill;
$rows[$key] ??= [ $rows[$key] ??= [
'source' => 'replacement', 'waybill_no' => $log->old_waybill, 'courier_name' => $log->old_courier, 'source' => 'replacement', 'waybill_no' => $log->old_waybill, 'courier_name' => $log->old_courier,
'evidence_no' => $log->order_no, 'o_id' => $log->order_no, 'evidence_time' => $log->operated_at, 'evidence_no' => $log->order_no, 'o_id' => $log->order_no, 'evidence_time' => $log->operated_at,
'evidence_text' => $log->remark, 'operator' => $log->operator, 'evidence_text' => $log->remark, 'operator' => $log->operator,
'new_courier_name' => $log->new_courier, 'new_waybill_no' => $log->new_waybill, 'new_courier_name' => $finalCourier, 'new_waybill_no' => $finalNumber,
]; ];
} }
if ($currentOrder === null) throw new RuntimeException('未导入订单操作日志。'); // 发货同步已明确保留的换单前单号也是证据;不是用订单商品或当前单号推断换单。
if ($this->connection()->getSchemaBuilder()->hasColumn('jst_oms_shipping', 'front_no')) {
$ships = $this->connection()->table('jst_oms_shipping')->where('ship_time', '>=', self::START)
->whereNotNull('front_no')->where('front_no', '<>', '')->whereColumn('front_no', '<>', 'express_no')
->select(['id', 'source_id', 'front_no', 'express_no', 'trade_no', 'ship_time', 'express_name1'])->lazyById(500);
foreach ($ships as $ship) {
$old = self::normalize($ship->front_no); $new = self::normalize($ship->express_no);
if ($old === '' || $new === '' || $old === $new || self::isPlaceholder($old) || self::isPlaceholder($new)) continue;
// 旧号码仍是现有发货包裹时,不因另一条换单记录把它排除。
if ($this->connection()->table('jst_oms_shipping')->whereIn('express_no', [$old, '@'.$old])->exists()) continue;
$key = 'shipping:'.$ship->source_id.'|'.$old;
$rows[$key] = [
'source' => 'replacement', 'waybill_no' => $old, 'courier_name' => $rows[$key]['courier_name'] ?? null,
'evidence_no' => 'shipping:'.$ship->source_id, 'trade_no' => $ship->trade_no,
'evidence_time' => $rows[$key]['evidence_time'] ?? $ship->ship_time, 'new_courier_name' => $ship->express_name1,
'new_waybill_no' => $new, 'evidence_text' => $rows[$key]['evidence_text'] ?? '发货镜像明确记录换单前单号;依据时间为发货时间,非换单操作时间',
];
}
}
if ($currentOrder === null && $rows === []) throw new RuntimeException('尚无订单操作日志或发货换单记录。');
// 已核实保存的历史旧名在上游镜像更新后仍需保留。
foreach ($this->results()->where('source','replacement')->whereNotNull('courier_name')
->get(['evidence_no','waybill_no','courier_name']) as $saved) {
$key=$saved->evidence_no.'|'.$saved->waybill_no;
if (isset($rows[$key]) && empty($rows[$key]['courier_name'])) $rows[$key]['courier_name']=$saved->courier_name;
}
// 历史镜像只有仍明确保留同一个旧单号时,才能用它的快递名称补空。
$sourceIds = [];
foreach ($rows as $key => $row) {
if (empty($row['courier_name']) && preg_match('/^shipping:(\d+)$/', $row['evidence_no'], $m)) $sourceIds[$key]=(int)$m[1];
}
if ($sourceIds !== [] && $this->connection()->getSchemaBuilder()->hasTable('js_jst_order_express_details')) {
foreach (array_chunk(array_values(array_unique($sourceIds)),500) as $ids) {
$oldRecords=$this->connection()->table('js_jst_order_express_details')->whereIn('id',$ids)
->get(['id','logistic_id','logistic_company_name'])->keyBy('id');
foreach ($sourceIds as $key=>$id) {
$record=$oldRecords[$id]??null;
if($record && self::normalize($record->logistic_id)===$rows[$key]['waybill_no']) {
$rows[$key]['courier_name']=trim((string)$record->logistic_company_name)?:null;
}
}
}
}
return [$rows, 0]; return [$rows, 0];
} }
/** 完整批次才发布;失败/中断保留上一版及历史导入。 */
public function publishStage(string $source, string $generation, int $missing): int
{
$db = $this->connection();
return $db->transaction(function () use ($db, $source, $generation, $missing): int {
$historySource = in_array($source, ['intercept_regular', 'intercept_taobao'], true) ? 'intercept' : $source;
$history = $this->results()->where('source', $historySource)->where('evidence_no', 'like', self::HISTORY_PREFIX.'%');
$cutoff = (clone $history)->max('evidence_time');
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
$this->results()->where('source', $source)->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->delete();
$count = 0;
$db->table('courier_unshipped_stage')->where('source', $source)->where('generation', $generation)
->orderBy('row_key')->chunkById(300, function ($batch) use ($cutoff, $covered, &$count): void {
$rows = [];
foreach ($batch as $row) {
if ($cutoff !== null && (substr($row->evidence_time, 0, 10) <= substr($cutoff, 0, 10) || isset($covered[$row->waybill_no]))) continue;
$values = (array) $row; unset($values['generation'], $values['row_key']); $rows[] = $values;
}
if ($rows !== []) { $this->results()->insert($rows); $count += count($rows); }
}, 'row_key');
$db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], [
'last_success_at' => now(), 'row_count' => $count, 'missing_count' => $missing, 'warning' => null,
]);
return $count;
});
}
private function warehouse(): array private function warehouse(): array
{ {
$db = $this->connection(); $db = $this->connection();

View File

@ -127,6 +127,14 @@ class SidebarPermissions
$allowed[] = 'process-data/invoice-data'; $allowed[] = 'process-data/invoice-data';
} }
if (in_array('courier-payables/shipping-data', $allowed, true)) {
$allowed[] = 'courier-payables/returned-parcels';
}
if (in_array('supplier-reconciliation/finance-data', $allowed, true)) {
$allowed[] = 'supplier-reconciliation/raw-statements';
}
return array_values(array_unique($allowed)); return array_values(array_unique($allowed));
} }

View File

@ -43,6 +43,7 @@ return [
* existing table, but do not keep querying the upstream source. * existing table, but do not keep querying the upstream source.
*/ */
'datasets' => [ 'datasets' => [
'jiansun.dbo.jst_shipFreight_view' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '发货数据专线核算运费'],
// Small organization and catalog dimensions stay in MariaDB. // Small organization and catalog dimensions stay in MariaDB.
'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'], 'operations_replica.rpt.fys_companyInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '公司资料'],
'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'], 'operations_replica.rpt.fys_shopInfo' => ['role' => 'dimension', 'target_store' => 'mariadb', 'consumer' => '店铺资料/店铺报表'],

View File

@ -813,6 +813,7 @@ $navigation = [
'icon' => 'fact_check', 'icon' => 'fact_check',
'pages' => [ 'pages' => [
['slug' => 'finance-data', 'title' => '财务端数据'], ['slug' => 'finance-data', 'title' => '财务端数据'],
['slug' => 'raw-statements', 'title' => '原始账单'],
['slug' => 'supplier-data', 'title' => '厂家端数据'], ['slug' => 'supplier-data', 'title' => '厂家端数据'],
], ],
], ],

View File

@ -10,6 +10,9 @@ return [
| Entries are appended to an existing section in configuration order. | Entries are appended to an existing section in configuration order.
| |
*/ */
'courier-payables' => [
['slug' => 'returned-parcels', 'title' => '退回件明细', 'icon' => 'assignment_return'],
],
'module_sections' => [ 'module_sections' => [
[ [
'position_after' => 'inventory-management', 'position_after' => 'inventory-management',

View File

@ -2,6 +2,7 @@
return [ return [
'dataset_key' => 'operations_replica.rpt.ding_invoices', 'dataset_key' => 'operations_replica.rpt.ding_invoices',
'first_supported_month' => '2026-10',
'document_types' => [ 'document_types' => [
'公摊日常报销', '公摊日常报销',
'店铺日常报销', '店铺日常报销',

View File

@ -1,11 +1,45 @@
<?php <?php
return [ return [
// 上传入口不设截止时间;系统只在 1-14 日催办未上传厂家,15 日财务出上月终版。 // 系统在 1-14 日催办未上传厂家;15 日 12:00 后已确认厂家不能继续上传或覆盖。
'reminder_end_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_REMINDER_END_DAY', 14))), 'reminder_end_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_REMINDER_END_DAY', 14))),
'final_version_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_FINAL_VERSION_DAY', 15))), 'final_version_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_FINAL_VERSION_DAY', 15))),
'confirmed_upload_lock_day' => max(1, min(28, (int) env('SUPPLIER_CONFIRMED_UPLOAD_LOCK_DAY', 15))),
'confirmed_upload_lock_hour' => max(0, min(23, (int) env('SUPPLIER_CONFIRMED_UPLOAD_LOCK_HOUR', 12))),
'confirmed_upload_lock_timezone' => env('SUPPLIER_CONFIRMED_UPLOAD_LOCK_TIMEZONE', 'Asia/Shanghai'),
'return_confirmation_deadline_day' => max(1, min(28, (int) env('SUPPLIER_RETURN_CONFIRMATION_DEADLINE_DAY', 13))), 'return_confirmation_deadline_day' => max(1, min(28, (int) env('SUPPLIER_RETURN_CONFIRMATION_DEADLINE_DAY', 13))),
// 这些结算方式不依赖月度对账单,不进入未上传统计,也不发送群催办。
'statement_upload_exempt_settlement_methods' => ['订单合同', '现结'],
// 应付汇总镜像尚未覆盖完整,保留已确认的无需上传厂家作为兜底。
'statement_upload_exempt_suppliers' => [
'博曼特',
'常州安裕',
'格林家具',
'公牛电器',
'河北星沐橡胶制品',
'恒菏',
'简尚',
'兰考华兰家具',
'木町工艺品',
'青岛弢森',
'三环',
'三洋木业',
'沐野竹木',
'沭阳简华家具有限公司',
'沭阳勋雅泡沫',
'双爱家私',
'顺兴木业',
'苏州贝格迪派',
'腾云',
'橡润家',
'新奇维木艺',
'优创包装',
'众隆包装',
'帝富尼',
],
'reminder' => [ 'reminder' => [
// 1-14 日每天 10:00、16:00 运行,15 日不得再催办。 // 1-14 日每天 10:00、16:00 运行,15 日不得再催办。
'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'), 'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'),

View File

@ -342,6 +342,17 @@ return [
], ],
'datasets' => [ 'datasets' => [
// 专线页 FreightNew 已按包裹分摊;totalFreight 是组合总额,不能逐包复制。
// 视图没有可靠更新时间,按稳定出库键追加,并每小时全量校准历史改价/反审核。
'jiansun.dbo.jst_shipFreight_view' => [
'source_key' => 'jiansun', 'schema' => 'dbo', 'object' => 'jst_shipFreight_view',
'target' => 'js_jst_ship_freight', 'keys' => ['Id'],
'full_reconcile_hours' => 1,
'minimum_datetime' => ['column' => 'Shiptime', 'value' => '2026-09-01 00:00:00'],
'fixed_filters' => ['ExName' => ['中铁物流', '武进安能', '壹米滴答专线']],
'columns' => ['Id', 'Shiptime', 'ExName', 'Expressno', 'FreightNew', 'totalFreight', 'checksgn', 'status', 'combsgn'],
'indexes' => [['Expressno(64)', 'ExName', 'Shiptime'], ['Id']],
],
// 工作平台供应商管理(简尚版):列表和详情只读共享镜像。 // 工作平台供应商管理(简尚版):列表和详情只读共享镜像。
// 供应商视图含关联资料变化,无可靠视图更新时间,按稳定键追加并周期全量校准。 // 供应商视图含关联资料变化,无可靠视图更新时间,按稳定键追加并周期全量校准。
'jiansun.dbo.js_supplier_View' => [ 'jiansun.dbo.js_supplier_View' => [
@ -544,10 +555,12 @@ return [
// 淘系(天猫/淘宝)订单与售后:聚水潭单独存放在 qmcust 这套表里, // 淘系(天猫/淘宝)订单与售后:聚水潭单独存放在 qmcust 这套表里,
// 与 jst_Orders / jst_OrderItem / jst_returnAndRefundInfo 分开。 // 与 jst_Orders / jst_OrderItem / jst_returnAndRefundInfo 分开。
// 订单售后费用明细等页面需要把两套来源合并展示。 // operations_replica 中的同名对象是无索引报表视图,按更新时间读取会在
// 上游超时;订单和明细改读 jiansun 中带主键/时间索引的实体表。数据集键
// 保留原值,以续用既有镜像状态和目标表。
'operations_replica.rpt.jst_qmcust_orderlist' => [ 'operations_replica.rpt.jst_qmcust_orderlist' => [
'source_key' => 'operations_replica', 'source_key' => 'jiansun',
'schema' => 'rpt', 'schema' => 'dbo',
'object' => 'jst_qmcust_orderlist', 'object' => 'jst_qmcust_orderlist',
'target' => 'ops_jst_qmcust_orders', 'target' => 'ops_jst_qmcust_orders',
'keys' => ['Id'], 'keys' => ['Id'],
@ -560,8 +573,8 @@ return [
], ],
], ],
'operations_replica.rpt.jst_qmcust_orderlist_item' => [ 'operations_replica.rpt.jst_qmcust_orderlist_item' => [
'source_key' => 'operations_replica', 'source_key' => 'jiansun',
'schema' => 'rpt', 'schema' => 'dbo',
'object' => 'jst_qmcust_orderlist_item', 'object' => 'jst_qmcust_orderlist_item',
'target' => 'ops_jst_qmcust_order_items', 'target' => 'ops_jst_qmcust_order_items',
'keys' => ['Id'], 'keys' => ['Id'],
@ -1101,6 +1114,9 @@ return [
['updateTime', 'Id'], ['updateTime', 'Id'],
['express_company', 'createTime', 'Id'], ['express_company', 'createTime', 'Id'],
['transactionNo', 'Id'], ['transactionNo', 'Id'],
['Id'],
['returnExpressNo(191)', 'Id'],
['express_company', 'expressPickupTime', 'Id'],
], ],
], ],
'jiansun.dbo.ekf_ReturnPickupManagement_Item' => [ 'jiansun.dbo.ekf_ReturnPickupManagement_Item' => [

View File

@ -0,0 +1,58 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 快递账单补记账:记账扣过的单,快递后来退回了,在后面的账期把多扣的补回去。
* - courier_bill_rebooks:补记账台账,哪个单号、几月扣的、在哪个账期补了多少;补过的不再补。
* - courier_bill_rebook_reviews:复核记账,这单现在应扣多少(逻辑定下来前由财务每月导入复核结果)。
* - courier_bill_groups.rebook_months:补几个月(空 = 按小汇总识别,0 = 不补,1 = 补上月,2 = 补前两个月)。
*/
return new class extends Migration {
public function up(): void
{
$schema = Schema::connection('business_mirror');
$schema->create('courier_bill_rebooks', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('group_id')->nullable()->index();
$table->string('waybill_no', 96)->index();
$table->char('deduct_month', 7)->comment('扣款账期');
$table->char('refund_month', 7)->index()->comment('补款账期');
$table->decimal('deducted', 14, 2)->nullable()->comment('当时扣的');
$table->decimal('current', 14, 2)->nullable()->comment('补款时应扣的');
$table->decimal('amount', 14, 2)->comment('补款金额');
$table->unsignedBigInteger('statement_id')->nullable()->index()->comment('空 = 历史导入');
$table->string('source', 16)->default('statement');
$table->json('details')->nullable()->comment('确认时的记账明细快照');
$table->dateTime('created_at')->nullable();
$table->unique(['waybill_no', 'deduct_month'], 'courier_bill_rebooks_identity');
});
$schema->create('courier_bill_rebook_reviews', function (Blueprint $table): void {
$table->id();
$table->string('waybill_no', 96);
$table->char('deduct_month', 7);
$table->decimal('current_amount', 14, 2)->comment('复核后现在应扣');
$table->string('source_name', 255)->nullable();
$table->dateTime('updated_at')->nullable();
$table->unique(['waybill_no', 'deduct_month'], 'courier_bill_rebook_reviews_identity');
});
$schema->table('courier_bill_groups', function (Blueprint $table): void {
$table->unsignedTinyInteger('rebook_months')->nullable()->comment('补记账补几个月:空=按小汇总识别,0=不补');
});
}
public function down(): void
{
$schema = Schema::connection('business_mirror');
$schema->table('courier_bill_groups', function (Blueprint $table): void {
$table->dropColumn('rebook_months');
});
$schema->dropIfExists('courier_bill_rebook_reviews');
$schema->dropIfExists('courier_bill_rebooks');
}
};

View File

@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! app()->environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
foreach (['courier_returned_parcels', 'courier_returned_parcels_stage'] as $name) {
if ($schema->hasTable($name)) continue;
$schema->create($name, function (Blueprint $table): void {
$table->unsignedBigInteger('source_id')->primary();
$table->unsignedBigInteger('after_sales_id')->nullable()->index();
$table->unsignedBigInteger('item_id')->nullable();
$table->dateTime('received_at', 6)->index();
$table->string('online_after_sales_no', 255)->nullable();
$table->string('order_id', 64)->nullable();
$table->string('online_order_no', 255)->nullable();
$table->string('waybill', 255)->nullable()->index();
$table->string('courier', 255)->nullable();
$table->string('shop', 255)->nullable();
$table->string('warehouse', 255)->nullable();
$table->string('sku', 255)->nullable()->index();
$table->string('style_code', 255)->nullable();
$table->text('product_name')->nullable();
$table->text('properties')->nullable();
$table->decimal('applied_qty', 20, 4)->nullable();
$table->decimal('returned_qty', 20, 4)->nullable();
$table->decimal('price', 20, 4)->nullable();
$table->decimal('item_amount', 20, 4)->nullable();
$table->decimal('order_refund', 20, 4)->nullable();
$table->string('status', 64)->nullable();
$table->string('type', 64)->nullable();
$table->string('goods_status', 64)->nullable();
$table->text('reason')->nullable();
$table->text('remark')->nullable();
$table->dateTime('source_updated_at', 6)->nullable();
$table->uuid('generation')->index();
$table->dateTime('synced_at', 6);
$table->index(['received_at', 'source_id'], 'returned_parcel_date_id_' . (str_ends_with($table->getTable(), '_stage') ? 'stage' : 'live'));
$table->index(['shop', 'received_at']);
$table->index(['warehouse', 'received_at']);
});
}
}
public function down(): void
{
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
$schema->dropIfExists('courier_returned_parcels_stage');
$schema->dropIfExists('courier_returned_parcels');
}
};

View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (config('system_database.mode', 'bootstrap') === 'bootstrap') return;
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
if (app()->environment('testing') && ! $schema->hasTable('courier_surcharge_settlement_rows')) return;
if (! $schema->hasColumn('courier_surcharge_settlement_rows', 'source_kind')) {
$schema->table('courier_surcharge_settlement_rows', function (Blueprint $table): void {
$table->string('source_kind', 40)->nullable();
$table->string('source_key', 80)->nullable();
$table->dateTime('source_created_at', 6)->nullable();
$table->unique(['rule_id','source_kind','source_key','surcharge_type'], 'surcharge_service_source_unique');
$table->index(['source_kind','rule_id','source_created_at'], 'surcharge_service_window');
});
}
if (! $schema->hasTable('courier_surcharge_service_stage')) {
$schema->create('courier_surcharge_service_stage', function (Blueprint $table): void {
$table->string('dataset_key', 100);
$table->string('generation', 36);
$table->unsignedInteger('rule_id');
$table->string('source_kind', 40);
$table->string('source_key', 80);
$table->dateTime('source_created_at', 6);
$table->string('surcharge_type', 40);
foreach (['courier_name','waybill','platform_product_id','product_code','shop_name','online_order_no','return_waybill_no'] as $key) $table->string($key, 191)->nullable();
$table->unsignedBigInteger('outbound_io_id')->nullable();
foreach (['length','width','height','settlement_weight'] as $key) $table->decimal($key, 12, 2)->nullable();
$table->decimal('volume', 16, 2)->nullable();
$table->string('inspection_type', 60)->nullable();
$table->string('inspection_reason', 120)->nullable();
$table->decimal('settlement_amount', 12, 2);
$table->string('settlement_status', 40);
$table->string('evidence', 500)->nullable();
$table->dateTime('shipped_at')->nullable();
$table->dateTime('pulled_at');
$table->timestamps();
$table->unique(['dataset_key','rule_id','source_key','surcharge_type'], 'surcharge_service_stage_unique');
});
}
}
public function down(): void
{
if (config('system_database.mode', 'bootstrap') === 'bootstrap') return;
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
$schema->dropIfExists('courier_surcharge_service_stage');
$schema->table('courier_surcharge_settlement_rows', function (Blueprint $table): void {
$table->dropUnique('surcharge_service_source_unique');
$table->dropIndex('surcharge_service_window');
$table->dropColumn(['source_kind','source_key','source_created_at']);
});
}
};

View File

@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
$s = Schema::connection('business_mirror');
if (! $s->hasTable('bill_surcharge_matches')) {
$s->create('bill_surcharge_matches', function (Blueprint $t): void {
$t->id(); $t->string('scope', 16); $t->unsignedBigInteger('owner_id');
$t->unsignedBigInteger('file_id'); $t->string('sheet', 100); $t->unsignedInteger('row_no');
$t->string('bill_month', 7); $t->string('waybill_no', 96); $t->string('item', 100);
$t->string('summary_label', 100);
$t->decimal('bill_amount', 16, 4)->nullable(); $t->decimal('self_amount', 16, 2)->nullable();
$t->string('courier_name', 191)->nullable();
foreach (['platform_product_id','product_code','shop_name','online_order_no'] as $k) $t->text($k)->nullable();
$t->string('match_status', 40); $t->text('match_note')->nullable();
$t->text('settlement_ids')->nullable(); $t->timestamp('matched_at')->nullable();
$t->unique(['scope','owner_id','file_id','sheet','row_no'], 'bill_surcharge_source_unique');
$t->index(['scope','owner_id','id'], 'bill_surcharge_owner');
$t->index(['waybill_no','item','bill_month'], 'bill_surcharge_history');
});
}
if (! $s->hasTable('dropship_bill_surcharges')) {
$s->create('dropship_bill_surcharges', function (Blueprint $t): void {
$t->id(); $t->unsignedBigInteger('file_id')->index(); $t->unsignedBigInteger('factory_id');
$t->string('bill_month', 7); $t->string('sheet', 100); $t->unsignedInteger('row_no');
$t->string('waybill_no', 96); $t->string('item', 100); $t->decimal('amount', 16, 4)->nullable();
$t->index(['factory_id','bill_month','id'], 'dropship_surcharge_month');
});
}
}
public function down(): void
{
Schema::connection('business_mirror')->dropIfExists('bill_surcharge_matches');
Schema::connection('business_mirror')->dropIfExists('dropship_bill_surcharges');
}
};

View File

@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private const TABLE = 'js_ekf_return_pickup_management';
private const INDEXES = [
'return_pickup_bill_id' => ['Id'],
'return_pickup_bill_number' => ['returnExpressNo', 'Id'],
'return_pickup_bill_month' => ['express_company', 'expressPickupTime', 'Id'],
];
public function up(): void
{
$schema = Schema::connection('business_mirror');
if (! $schema->hasTable(self::TABLE)) return;
$existing = array_column($schema->getIndexes(self::TABLE), 'columns');
foreach (self::INDEXES as $name => $columns) {
if (! in_array(array_map('strtolower', $columns), array_map(fn ($v) => array_map('strtolower', $v), $existing), true)) {
if ($name === 'return_pickup_bill_number' && $schema->getConnection()->getDriverName() === 'mysql') {
$schema->getConnection()->statement('ALTER TABLE `js_ekf_return_pickup_management` ADD INDEX `return_pickup_bill_number` (`returnExpressNo`(191), `Id`)');
} else {
$schema->table(self::TABLE, fn (Blueprint $table) => $table->index($columns, $name));
}
}
}
}
public function down(): void
{
$schema = Schema::connection('business_mirror');
if (! $schema->hasTable(self::TABLE)) return;
$existing = array_column($schema->getIndexes(self::TABLE), 'name');
foreach (array_keys(self::INDEXES) as $name) {
if (in_array($name, $existing, true)) $schema->table(self::TABLE, fn (Blueprint $table) => $table->dropIndex($name));
}
}
};

View File

@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
if (! app()->environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') return;
if (Schema::connection('business_mirror')->hasTable('courier_unshipped_stage')) return;
Schema::connection('business_mirror')->create('courier_unshipped_stage', function (Blueprint $table): void {
$table->string('source', 32);
$table->char('row_key', 64);
$table->uuid('generation');
$table->string('waybill_no', 96);
$table->string('evidence_no', 96);
$table->dateTime('evidence_time');
foreach (['courier_name', 'trade_no', 'o_id', 'shop_name', 'new_courier_name', 'new_waybill_no', 'operator'] as $field) $table->string($field)->nullable();
$table->text('evidence_text')->nullable();
$table->primary(['source', 'row_key']);
$table->index(['source', 'generation']);
});
}
public function down(): void
{
Schema::connection('business_mirror')->dropIfExists('courier_unshipped_stage');
}
};

View File

@ -0,0 +1,47 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
if (! app()->environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') return;
$schema = Schema::connection('business_mirror');
foreach (['courier_returned_parcels', 'courier_returned_parcels_stage'] as $name) {
if (! $schema->hasTable($name)) continue;
if (! $schema->hasColumn($name, 'source_kind')) {
$schema->table($name, fn (Blueprint $table) => $table->string('source_kind', 16)->default('regular'));
}
$connection = $schema->getConnection();
$primary = collect($schema->getIndexes($name))->firstWhere('primary', true);
if (($primary['columns'] ?? []) !== ['source_kind', 'source_id']) {
if ($connection->getDriverName() === 'sqlite') {
// Laravel 10 does not compile primary-key changes for SQLite.
$manager = $connection->getDoctrineSchemaManager();
$before = $manager->introspectTable($connection->getTablePrefix().$name);
$after = clone $before;
$after->dropPrimaryKey();
$after->getColumn('source_id')->setAutoincrement(false);
$after->setPrimaryKey(['source_kind', 'source_id']);
$manager->alterTable($manager->createComparator()->compareTables($before, $after));
} else {
$schema->table($name, function (Blueprint $table): void {
$table->dropPrimary();
$table->primary(['source_kind', 'source_id']);
});
}
}
$index = 'returned_source_date_'.(str_ends_with($name, '_stage') ? 'stage' : 'live');
if (! collect($schema->getIndexes($name))->contains('name', $index)) {
$schema->table($name, fn (Blueprint $table) => $table->index(['received_at', 'source_kind', 'source_id'], $index));
}
}
}
public function down(): void
{
// 两个来源可能有相同编号,不能回滚成单编号主键并丢弃已同步明细。
}
};

View File

@ -0,0 +1,19 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::connection('business_mirror')->table('dropship_bill_lines', function (Blueprint $table): void {
$table->decimal('bill_weight', 14, 4)->nullable()->comment('厂家账单重量kg,同单多行合计,缺失不填零');
});
}
public function down(): void
{
// 保留已回补的厂家重量,应用版本回退不删除业务数据。
}
};

View File

@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
return new class extends Migration {
public function up(): void
{
$schema = Schema::connection(config('jushuitan.connection', 'jushuitan_local'));
$connection = DB::connection(config('jushuitan.connection', 'jushuitan_local'));
if ($connection->getDriverName() === 'mysql') {
$connection->statement('ALTER TABLE jst_oms_shipping ADD INDEX jst_shipping_warehouse_time (warehouse_name, ship_time), ADD INDEX jst_shipping_front_no (front_no), ALGORITHM=INPLACE, LOCK=NONE');
return;
}
$schema->table('jst_oms_shipping', function (Blueprint $table): void {
$table->index(['warehouse_name', 'ship_time'], 'jst_shipping_warehouse_time');
$table->index('front_no', 'jst_shipping_front_no');
});
}
public function down(): void
{
// 只读查询索引向后兼容,回退应用不重建大表。
}
};

View File

@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
if ($schema->hasTable('courier_returned_parcels') && ! $schema->hasIndex('courier_returned_parcels', 'returned_parcel_order_received')) {
$schema->table('courier_returned_parcels', fn (Blueprint $table) => $table->index(['order_id', 'received_at'], 'returned_parcel_order_received'));
}
}
public function down(): void
{
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
if ($schema->hasTable('courier_returned_parcels') && $schema->hasIndex('courier_returned_parcels', 'returned_parcel_order_received')) {
$schema->table('courier_returned_parcels', fn (Blueprint $table) => $table->dropIndex('returned_parcel_order_received'));
}
}
};

View File

@ -0,0 +1,69 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('kuka_posting_base_imports')) {
return;
}
$schema->table('kuka_posting_base_imports', function (Blueprint $table) use ($schema): void {
if (! $schema->hasColumn('kuka_posting_base_imports', 'posting_target_amount')) {
$table->decimal('posting_target_amount', 18, 2)->nullable();
$table->decimal('posting_selected_amount', 18, 2)->nullable();
$table->decimal('posting_difference_amount', 18, 2)->nullable();
$table->unsignedInteger('posting_selected_rows')->nullable();
$table->unsignedInteger('posting_material_count')->nullable();
$table->unsignedInteger('posting_uncalculable_rows')->nullable();
$table->longText('posting_allocation_json')->nullable();
$table->char('posting_snapshot_hash', 64)->nullable();
$table->unsignedBigInteger('posting_applied_by')->nullable();
$table->timestamp('posting_applied_at')->nullable();
}
});
}
public function down(): void
{
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('kuka_posting_base_imports')) {
return;
}
$schema->table('kuka_posting_base_imports', function (Blueprint $table) use ($schema): void {
$columns = [
'posting_target_amount',
'posting_selected_amount',
'posting_difference_amount',
'posting_selected_rows',
'posting_material_count',
'posting_uncalculable_rows',
'posting_allocation_json',
'posting_snapshot_hash',
'posting_applied_by',
'posting_applied_at',
];
$existing = array_values(array_filter(
$columns,
static fn (string $column): bool => $schema->hasColumn(
'kuka_posting_base_imports',
$column,
),
));
if ($existing !== []) {
$table->dropColumn($existing);
}
});
}
};

View File

@ -233,7 +233,7 @@ CRON_TZ=Asia/Shanghai
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。 # 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1 0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。 # 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1 10 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills >>/opt/caiwuxitong/runtime/unshipped-sync.log 2>&1
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1 30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。 # 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。
50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1 50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1
@ -248,6 +248,8 @@ CRON_TZ=Asia/Shanghai
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1 15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
# 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。 # 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1 0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels --match-surcharges >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
*/15 * * * * root CAIWU_BATCH_LOCK_WAIT=60 /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:refresh-tracking --max-batches=4 >>/opt/caiwuxitong/runtime/tracking-refresh.log 2>&1
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。 # 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1
@ -267,7 +269,8 @@ CRON_TZ=Asia/Shanghai
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1 */15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。 # 科目映射未映射清单:每天检查本月是否已生成,月初只刷新一次;网页手动请求另行排队。
10 6 * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage all --monthly --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
@ -282,6 +285,9 @@ CRON_TZ=Asia/Shanghai
# 补齐晚到的退货进仓与审批变化(超长费按出库日期、退回费/拦截费按查件工单创建时间)。 # 补齐晚到的退货进仓与审批变化(超长费按出库日期、退回费/拦截费按查件工单创建时间)。
30 6 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=7 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=7 --quiet' >/dev/null 2>&1 30 6 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=7 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=7 --quiet' >/dev/null 2>&1
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1 40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
EOF EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots chmod 644 /etc/cron.d/caiwu-jiansun-snapshots

View File

@ -237,7 +237,7 @@ CRON_TZ=Asia/Shanghai
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。 # 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1 0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。 # 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1 10 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills >>/opt/caiwuxitong/runtime/unshipped-sync.log 2>&1
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1 30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。 # 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。
50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1 50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1
@ -252,6 +252,8 @@ CRON_TZ=Asia/Shanghai
15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1 15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1
# 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。 # 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。
0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1 0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1
0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels --match-surcharges >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1
*/15 * * * * root CAIWU_BATCH_LOCK_WAIT=60 /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:refresh-tracking --max-batches=4 >>/opt/caiwuxitong/runtime/tracking-refresh.log 2>&1
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
# 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。 # 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。
*/2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1
@ -271,7 +273,8 @@ CRON_TZ=Asia/Shanghai
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1 */15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。 # 科目映射未映射清单:每天检查本月是否已生成,月初只刷新一次;网页手动请求另行排队。
10 6 * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage all --monthly --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
@ -286,6 +289,9 @@ CRON_TZ=Asia/Shanghai
# 补齐晚到的退货进仓与审批变化(超长费按出库日期、退回费/拦截费按查件工单创建时间)。 # 补齐晚到的退货进仓与审批变化(超长费按出库日期、退回费/拦截费按查件工单创建时间)。
30 6 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=7 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=7 --quiet' >/dev/null 2>&1 30 6 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=7 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=7 --quiet' >/dev/null 2>&1
40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1 40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet' >/dev/null 2>&1
# 客服核实费用按报价生效日校准,覆盖历史工单后补审核与撤销;独立容器保留失败日志。
45 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:pull-customer-service --courier='常州中通快运' >>/opt/caiwuxitong/runtime/surcharge-customer-service-sync.log 2>&1
5 7 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier-surcharge:match-bills --all --existing-only >>/opt/caiwuxitong/runtime/bill-surcharge-matching.log 2>&1
EOF EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots chmod 644 /etc/cron.d/caiwu-jiansun-snapshots

View File

@ -1,5 +1,9 @@
[ [
"dropship-freight:backfill-weights",
"courier-bills:match-reverse",
"courier-bills:refresh-settlement",
"portal-freight:import-pending", "portal-freight:import-pending",
"courier-surcharge:match-bills",
"planting-reimbursement:auto-confirm", "planting-reimbursement:auto-confirm",
"jushuitan:apply-shipping-corrections", "jushuitan:apply-shipping-corrections",
"actual-tax:import", "actual-tax:import",

View File

@ -8,10 +8,10 @@ is_import=0
CAIWU_BATCH_CALLER_DIR="$PWD" CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in case "${1:-}" in
portal-freight:import-pending) is_import=1 ;; portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse|courier-bills:refresh-settlement|dropship-freight:backfill-weights) is_import=1 ;;
planting-reimbursement:auto-confirm) is_import=1 ;; planting-reimbursement:auto-confirm) is_import=1 ;;
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;; jushuitan:refresh-tracking|jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels|courier-surcharge:pull-customer-service) ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
*) echo 'Unsupported finance batch command' >&2; exit 64 ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;;
esac esac
@ -67,6 +67,34 @@ if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = '--pending' ];
fi fi
[ -n "$pending_request" ] || exit 0 [ -n "$pending_request" ] || exit 0
fi fi
if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = 'all' ] && [ "${3:-}" = '--monthly' ]; then
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
[ -n "$storage_root" ] || exit 0
current_month="$(TZ=Asia/Shanghai date +%Y-%m)"
if python3 - "$storage_root" "$current_month" <<'PY'
import glob
import json
import os
import sys
storage_root, current_month = sys.argv[1:3]
paths = glob.glob(os.path.join(storage_root, 'app/account-mapping/coverage-snapshots/all-*.json'))
paths.sort(key=os.path.getmtime, reverse=True)
for path in paths:
try:
snapshot = json.loads(open(path, encoding='utf-8').read())
except (OSError, ValueError, TypeError):
continue
refreshed_at = str(snapshot.get('refreshed_at', ''))
if refreshed_at.startswith(current_month + '-'):
sys.exit(0)
break
sys.exit(1)
PY
then
exit 0
fi
fi
if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
[ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0 [ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0
@ -125,4 +153,15 @@ if [ "$1" = 'account-mapping:refresh-coverage' ]; then
--name "$container_name" batch "$@" --name "$container_name" batch "$@"
exit $? exit $?
fi fi
if [ "$1" = 'jushuitan:refresh-tracking' ] || [ "$1" = 'business-mirror:sync-returned-parcels' ] || [ "$1" = 'courier:sync-unshipped-waybills' ] || [ "$1" = 'courier-surcharge:pull-customer-service' ]; then
container_name="caiwu_returned_parcels_$$"
cleanup_returned_parcels() {
docker rm --force "$container_name" >/dev/null 2>&1 || true
}
trap cleanup_returned_parcels EXIT INT TERM
/usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps \
--name "$container_name" batch "$@"
exit $?
fi
docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@" docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@"

View File

@ -1,5 +1,25 @@
# 上游业务镜像清单 # 上游业务镜像清单
## 发货换单标识校准
`derived.shipping-tracking-refresh` 使用 `operations_replica/rpt.jst_order_express_details` 的稳定包裹键 `id` 和 `updatedAt`,只校准已存在于 `jst_oms_shipping` 的包裹单号、快递名称及同键旧明细镜像,不修改商品、重量、运费或上游数据。先以每批最多 5000 个窄键分页,再为已存在的包裹每 200 个键读取 `id/updatedAt/inner_order_id/so_id/logistic_id/logistic_company_name`。必须同交易单号;空号、OuterWMS 不作为换单。旧号、旧快递、最新号和快递、操作时间写入现有换单记录,多次换单最终指向当前单号。
每 15 分钟通过 `jushuitan:refresh-tracking --max-batches=4` 校准,复用独立批容器、全局互斥锁、1 CPU / 3 GiB 容器及 512 MiB PHP / 1800 秒上限;锁等待最多 60 秒。`business_mirror_table_states` 保存固定时间窗与主键游标,失败继续当前窗口;完成后下一窗口从上次完成边界回看 48 小时,首次回看 48 小时。变更前将原包裹、旧镜像和原换单名称写入私有备份。历史缺名称只按相同源键且旧单号一致的镜像补回,不猜测。可用 `--source-id` 定向最多 500 个已知包裹。
补记账沿用标准化运单号索引查询,补充关联必须同时满足原内部订单号、线上订单号和 SKU,不能把同线上订单的不同补发包裹互抵。按内部订单索引分批读取退回候选,两来源的同数字键均参与,不全表扫描。已确认快递账单沿用确认记录;已确认代发账单从确认快照读取,不随后续换单和退回镜像更新。
## 发货数据专线运费
中铁物流、武进安能、壹米滴答专线的核算运费读取工作平台「专线运费」视图 `jiansun.dbo.jst_shipFreight_view`,镜像为 `js_jst_ship_freight`。只接入这三个快递自 2026-09-01 起的记录;按稳定出库键 `Id` 断点同步,无可靠更新时间,因此每小时全量校准。复用 `business-mirror:sync-tables`、生产批容器及现有同步锁,镜像完成后仅重算这三个快递。首次全量完成前显示待同步。
采用视图逐包分摊后的 `FreightNew`,不把组合总额 `totalFreight` 重复计入每包;0 元保留为有效金额。按快递、运单及出库单/发货时间匹配,同单号重复出库不借用其他批次金额;未匹配、金额为空或匹配不唯一时保留待核对,不回退报价。核算只写 `jst_oms_shipping_freight`,不修改聚水潭原始运费、结算重量或其他快递计费规则。
## 客服核实附加费
`courier-surcharge:pull-customer-service --courier=常州中通快运` 读取现有 `js_jst_work_order_info` 查件工单镜像(类型 `0FE39FBE88E448D396B2E8ED62775284`),不依赖工单标题。费用子表 `TABLEField1413856620250814155027` 逐行取类型、金额和客服审核结果,仅结果为“通过”的行参与对应启用报价。改地址费统一到改地址,工单状态“待确认”不能代替费用行审核结果;商品数量不重复乘费用。
按公司、快递及报价生效日限制范围,每批 300 张工单按 `(created, Id)` 索引游标读取;同工单同类型通过金额合计,保留工单来源键。暂存和断点同事务提交,前后数量核验通过后仅替换该范围的客服核实派生行,失败保留上次结果。生产通过独立批入口、上游全局互斥锁、1 CPU / 3 GiB 容器、512 MiB PHP / 1800 秒上限执行,常州中通快运每天 06:45 校准生效日起记录,以覆盖后补审核和撤销。其他快递或重量条件报价不随此次任务回补。
## 发货线上重量精度 ## 发货线上重量精度
`operations_replica.rpt.jst_qmcust_salesoutbound` 的原始文本重量(含科学计数法)登记为 `ops_jst_precise_outbound`,仅同步 Id、io_id、l_id、io_date、weight、status、local_updated;按 Id 断点全量、local_updated 增量,io_id 索引供发货同步按出库单读取。与两位小数报表的舍入值一致、单号一致且记录有效时,采用原始重量并保留四位小数;未命中不猜重量。 `operations_replica.rpt.jst_qmcust_salesoutbound` 的原始文本重量(含科学计数法)登记为 `ops_jst_precise_outbound`,仅同步 Id、io_id、l_id、io_date、weight、status、local_updated;按 Id 断点全量、local_updated 增量,io_id 索引供发货同步按出库单读取。与两位小数报表的舍入值一致、单号一致且记录有效时,采用原始重量并保留四位小数;未命中不猜重量。
@ -10,7 +30,7 @@
厂家记账核价使用工作平台月度导出的受控镜像,2026年10月账期覆盖5—10月,不借用年份不符或覆盖不足的现有发货来源。`supplier_bookkeeping_shipping_months` 保存月覆盖、摘要、可见代次及断点;`supplier_bookkeeping_shipping_rows` 保存最少核价字段和来源行号;`supplier_bookkeeping_shipping_refs` 保存快递号、换单前单号和订单号索引。原件只读,不接入收件人等个人字段。 厂家记账核价使用工作平台月度导出的受控镜像,2026年10月账期覆盖5—10月,不借用年份不符或覆盖不足的现有发货来源。`supplier_bookkeeping_shipping_months` 保存月覆盖、摘要、可见代次及断点;`supplier_bookkeeping_shipping_rows` 保存最少核价字段和来源行号;`supplier_bookkeeping_shipping_refs` 保存快递号、换单前单号和订单号索引。原件只读,不接入收件人等个人字段。
预处理脚本为 `scripts/prepare-supplier-bookkeeping-shipping.py`,导入命令为受限批入口下的 `supplier-bookkeeping:import-shipments`。完整月导入成功后原子切换代次,失败保留旧版,可续传。运费取“运费”,5月取经用户确认的“系统运费”,不使用“结算运费”。普通商品当前成本读取既有商品资料镜像。规则和验收范围见 [厂家记账金额规则](厂家记账金额规则.md)。 预处理脚本为 `scripts/prepare-supplier-bookkeeping-shipping.py`,导入命令为受限批入口下的 `supplier-bookkeeping:import-shipments`。完整月导入成功后原子切换代次,失败保留旧版,可续传。运费取“运费”,5月取经用户确认的“系统运费”,不使用“结算运费”。普通商品当前成本读取既有商品资料镜像。缺月度文件且工单带明确快递号时,可从现有自动同步表 `jst_oms_shipping` 按索引匹配全部指定包裹,使用商品明细数量及原始 `freight`,不取核算运费或结算运费、不改重量逻辑;无快递号仍要求完整月度文件。规则和验收范围见 [厂家记账金额规则](厂家记账金额规则.md)。
## 结论 ## 结论
@ -20,6 +40,16 @@
## 当前迁移状态 ## 当前迁移状态
“快递应付 → 退回件明细”同时读取 `operations_replica/rpt.jst_returnAndRefundItem`(普通)与 `rpt.jst_qmcust_refundlist_item`(淘系),按 `receive_date`(进仓时间)读取 2026-10-01 起的商品明细,并按 `as_id` 分别关联 `rpt.jst_returnAndRefundInfo`、`rpt.jst_qmcust_refundlist` 的售后、快递、店铺和仓库字段。结果写入共享镜像 `courier_returned_parcels`,`source_kind + source_id` 为稳定键(普通取 `Id`,淘系取 `asi_id`);两来源允许编号相同。分批结果先写 `courier_returned_parcels_stage`,复用 `business_mirror_table_states` 保存来源及游标。分别完整核对两来源计数后在事务内替换指定进仓日期范围,失败保留上次完整结果,相同日期重跑可续传。页面只读此镜像,支持分页、精确筛选和流式 CSV 导出。首次指定 `--from=2026-10-01 --to=2026-12-02`(两端包含),日常从 2026-10-01 校准到当天,以覆盖退货明细无可靠更新时间造成的迟到与历史修订。
生产入口:`sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels`,北京时间每天 10:00、16:00 执行。沿用全局上游锁和独立批容器(1 CPU、3 GiB、PHP 512 MiB),单次容器执行上限 30 分钟、单条上游查询上限 60 秒;每轮先读取至多 5,000 个稳定编号和进仓时间,最多取 2,000 条符合日期的商品,按 500 个编号读取明细、100 个售后号关联主表。命令不会写聚水潭或其他财务台账。
两来源存在重叠:售后号、售后商品明细号、商品编码、进仓时间和实退数量全部相同才视为同一商品行,完整核对各源数量后保留普通来源行,淘系独有行正常发布。可用同命令加 `--deduplicate` 在独立批容器内仅校准现有派生结果,不重读上游;执行前备份镜像。
附加费“已退回”条件读取此镜像的普通、淘系有效进仓记录,并按订单关联、既有两类售后镜像补充历史;进仓日期不受账期限制,仍要求实退数量大于零、进仓日期非空。退回与未发出单号先精确查询,只对剩余单号处理格式和数字 T 前缀差异,多候选不自动归为同票。订单查询使用 `returned_parcel_order_received` 索引。每天 10:00、16:00 同步带 `--match-surcharges`,成功后通过 `courier-surcharge:match-bills --all --existing-only --all-months --refresh-rebooks` 刷新已有未确认账单的附加费和补记账汇总,保留已确认账单、人工金额与暂停自动匹配设置;同步失败不触发重算。补记账也按实际单号查询,不再依赖跨来源重复的行编号游标,进仓日期同样不限账期。
“未发出明细”每日 07:10 通过 `courier:sync-unshipped-waybills` 在同一受限批入口刷新。先完成上述退回件快照,再分别获取普通、淘系现场拦截的原订单发出单号;不因其他全量退款镜像失败而阻断。仓内未发从当前 `operations_replica/rpt.jst_workOrderInfo` 按 `Id` 每批读取 5,000 个类型索引,再按匹配类型的明确 ID 读取业务字段;不恢复退役 `jiansun` 连接。派生暂存 `courier_unshipped_stage` 及数据集 `derived.courier-unshipped-warehouse` 保留断点,完整后才发布,历史导入保留。`--max-batches` 可控制单轮批数,`--source` 可指定来源,刚完成退回件校准时可用 `--skip-returned`。换单除人工操作日志外,还读取发货镜像明确记录的 `front_no`;该依据时间是发货时间,不冒充换单操作时间,也不把国际物流号当旧单号。无历史导入且退回件覆盖不足时拒绝发布拦截结果,避免把不完整范围当全量。
| 状态 | 说明 | | 状态 | 说明 |
| --- | --- | | --- | --- |
| 本次修正 | “发票数据 → 发票明细”继续读取共享镜像 `ding_invoice_flow_mirror` 与 `ding_invoice_record_mirror`。钉钉附件抓取改为增量合并:已确认的台账发票不会被后续 OCR 失败或空附件覆盖,新识别附件只补充来源链接和缺失字段;同销售方同金额但发票号码不同的记录不下沉为同一张。识别支持 PDF 文本、图片 OCR(外部视觉接口或服务器 Tesseract)、XLSX 内嵌图片、ZIP/RAR/7Z 压缩包,XLS 通过 LibreOffice 转为 PDF 后识别。页面手动抓取仍可强制刷新;后台每 15 分钟自动选取最近一个待抓月份,每轮最多处理 20 个流程。 | | 本次修正 | “发票数据 → 发票明细”继续读取共享镜像 `ding_invoice_flow_mirror` 与 `ding_invoice_record_mirror`。钉钉附件抓取改为增量合并:已确认的台账发票不会被后续 OCR 失败或空附件覆盖,新识别附件只补充来源链接和缺失字段;同销售方同金额但发票号码不同的记录不下沉为同一张。识别支持 PDF 文本、图片 OCR(外部视觉接口或服务器 Tesseract)、XLSX 内嵌图片、ZIP/RAR/7Z 压缩包,XLS 通过 LibreOffice 转为 PDF 后识别。页面手动抓取仍可强制刷新;后台每 15 分钟自动选取最近一个待抓月份,每轮最多处理 20 个流程。 |
@ -86,6 +116,7 @@
| 店铺资料 | `rpt.fys_shopInfo` | `ops_fys_shop_info` | | 店铺资料 | `rpt.fys_shopInfo` | `ops_fys_shop_info` |
| 商标资料 | `rpt.fys_TrademarkInfo` | `ops_fys_trademark_info` | | 商标资料 | `rpt.fys_TrademarkInfo` | `ops_fys_trademark_info` |
| 订单 | `rpt.jst_Orders`、`rpt.jst_OrderItem` | `ops_jst_orders`、`ops_jst_order_item` | | 订单 | `rpt.jst_Orders`、`rpt.jst_OrderItem` | `ops_jst_orders`、`ops_jst_order_item` |
| 淘系订单与明细 | `jiansun/dbo.jst_qmcust_orderlist`、`jiansun/dbo.jst_qmcust_orderlist_item` | `ops_jst_qmcust_orders`、`ops_jst_qmcust_order_items`。数据集键沿用历史上的 `operations_replica.rpt.*` 名称以续用镜像状态;实际来源使用原业务库实体表,避免报表库无索引视图超时 |
| 商品与仓库 | `rpt.jst_sku`、`rpt.jst_warehouseInfo`、`rpt.jst_skumap` | `ops_jst_*`(普通商品资料已切换) | | 商品与仓库 | `rpt.jst_sku`、`rpt.jst_warehouseInfo`、`rpt.jst_skumap` | `ops_jst_*`(普通商品资料已切换) |
| 推广费用 | `rpt.ads_itemid_sales_cost_ratio_v2_di` | `ops_item_sales_cost_ratio` | | 推广费用 | `rpt.ads_itemid_sales_cost_ratio_v2_di` | `ops_item_sales_cost_ratio` |
| 退款退货 | `rpt.jst_returnAndRefundInfo`、`rpt.jst_returnAndRefundItem`、`rpt.jst_qmcust_refundlist`、`rpt.jst_qmcust_refundlist_item` | `ops_jst_return_refund_*`、`ops_jst_qmcust_refunds`、`ops_jst_qmcust_refund_items` | | 退款退货 | `rpt.jst_returnAndRefundInfo`、`rpt.jst_returnAndRefundItem`、`rpt.jst_qmcust_refundlist`、`rpt.jst_qmcust_refundlist_item` | `ops_jst_return_refund_*`、`ops_jst_qmcust_refunds`、`ops_jst_qmcust_refund_items` |

View File

@ -7,8 +7,9 @@
1. 对“补偿款项”“记账全款”(兼容“记账全额”),原金额大于0且小于50元,先判断原金额÷商品买家实付合计是否小于40%。命中后金额为0,不扣款,追加备注 `小于50且小于0.4,记账改0`。 1. 对“补偿款项”“记账全款”(兼容“记账全额”),原金额大于0且小于50元,先判断原金额÷商品买家实付合计是否小于40%。命中后金额为0,不扣款,追加备注 `小于50且小于0.4,记账改0`。
2. 未命中的,再用工单 `actual_paid_amount`(页面“实付金额”)作分母,独立判断同样的严格边界。任一轮实付缺失、无效或为0时,只跳过该轮;另一轮仍可正常判断。多商品买家实付缺一项时,不把部分金额当作完整合计。 2. 未命中的,再用工单 `actual_paid_amount`(页面“实付金额”)作分母,独立判断同样的严格边界。任一轮实付缺失、无效或为0时,只跳过该轮;另一轮仍可正常判断。多商品买家实付缺一项时,不把部分金额当作完整合计。
3. 保留厂家记账配置、代发仓发错货限制和多供应商待确认规则。只有已判定可扣款的剩余工单进入核价,不用核价推翻“不扣款”或“待确认”。 3. 保留厂家记账配置、代发仓发错货限制和多供应商待确认规则。只有已判定可扣款的剩余工单进入核价,不用核价推翻“不扣款”或“待确认”。
财务明确指定的不记账工单,按公司设置 `supplier_bookkeeping.excluded_work_orders` 中的完整工单号排除,说明保留确认原因;不据此扩大为所有缺供应商工单不记账。
工单供应商为空时,先按普通商品编码匹配商品资料;完整的 `ZH-/MKH-商品编码-数量-商品编码-数量` 组合编码拆出组件后逐个精确匹配,普通商品精确命中优先。运营组合套装从六个月内原单发货明细拆出实际商品编码,必须覆盖全部指定单号并核对订单;未发出或未完整匹配时不采用部分明细。每个组件都查到商品资料供应商后,才按当前配置、小额归零和核价规则继续处理。保留原编码,展示实际商品编码、逐编码供应商匹配说明;任一组件缺供应商或多供应商判定不一致仍待确认,不使用部分供应商扣款。不覆盖工单已有供应商。 工单供应商为空时,先按普通商品编码匹配商品资料;完整的 `ZH-/MKH-商品编码-数量-商品编码-数量` 组合编码拆出组件后逐个精确匹配,普通商品精确命中优先。运营组合套装从六个月内原单发货明细拆出实际商品编码,必须覆盖全部指定单号并核对订单;未发出或未完整匹配时不采用部分明细。每个组件都查到商品资料供应商后,才按当前配置、小额归零和核价规则继续处理。保留原编码,展示实际商品编码、逐编码供应商匹配说明;任一组件缺供应商或多供应商判定不一致仍待确认,不使用部分供应商扣款。不覆盖工单已有供应商。
4. 补偿、全款按原单商品的实际发货数量乘普通商品资料当前成本单价,再加实际包裹运费,与原金额取较小值。成本按商品编码精确匹配商品资料的当前 `cost_price`,不代表历史月份成本。 4. 补偿、全款按原单商品的实际发货数量乘普通商品资料当前成本单价,再加实际包裹运费,与原金额取较小值;原单运费为空或0时,按对应商品成本×0.2替代,并注明“原单运费缺失或为0,按商品成本×0.2替代运费”。成本按商品编码精确匹配商品资料的当前 `cost_price`,不代表历史月份成本。
5. 运费损耗优先按正数实际运费记账,不受原金额限制;原金额为0也需要匹配。原单包裹运费为空或0时,按对应工单商品的当前成本单价×实际发货数量×0.2替代。多个包裹中只替代缺运费的包裹,其余仍取实际运费。替代需要有效商品成本与逐商品发货数量,缺失或数量含糊时待确认;已有正数实际运费不要求商品成本和数量。 5. 运费损耗优先按正数实际运费记账,不受原金额限制;原金额为0也需要匹配。原单包裹运费为空或0时,按对应工单商品的当前成本单价×实际发货数量×0.2替代。多个包裹中只替代缺运费的包裹,其余仍取实际运费。替代需要有效商品成本与逐商品发货数量,缺失或数量含糊时待确认;已有正数实际运费不要求商品成本和数量。
6. 供应商为「沐野竹木」的工单只记成本价:补偿款项、记账全款、运费损耗均按原单实际发货数量×商品资料当前成本单价记账,不加运费、不与原金额比较,也不要求原单运费;缺发货、数量或成本价时仍待确认。前面的配置、小额归零和代发仓限制照常适用。同一工单同时含沐野竹木和其他供应商时待确认。 6. 供应商为「沐野竹木」的工单只记成本价:补偿款项、记账全款、运费损耗均按原单实际发货数量×商品资料当前成本单价记账,不加运费、不与原金额比较,也不要求原单运费;缺发货、数量或成本价时仍待确认。前面的配置、小额归零和代发仓限制照常适用。同一工单同时含沐野竹木和其他供应商时待确认。
@ -18,14 +19,17 @@
## 发货匹配 ## 发货匹配
- 运费取工作平台月度导出“运费”;5月“系统运费”经用户确认是相同口径。不使用“结算运费”,不借用覆盖不足的现有发货表或其他年份数据。 - 运费取工作平台月度导出“运费”;5月“系统运费”经用户确认是相同口径。不使用“结算运费”,不借用覆盖不足的现有发货表或其他年份数据。
- 查找时间为工单发起月份及前五个月,右端不含下月1日。例如10月工单读取5月1日至11月1日前的发货记录。六个月未完整导入时待确认。 - 查找时间为工单发起月份及前五个月,右端不含下月1日。例如10月工单读取5月1日至11月1日前的发货记录。六个月月度文件完整时保持原导出核价路径;缺文件且工单有明确快递号时,优先只读现有 `jst_oms_shipping` 自动同步明细,所有指定快递号和工单商品都匹配后,按同一金额规则核价,并注明“按系统同步发货明细核价(原快递单号完整匹配)”。
- 缺六个月文件且无原单匹配的补偿/全款,仍先按小于50元且占买家实付或订单实付比例小于0.4归零;未命中时,以完整工单逐商品数量×当前商品成本核价,缺运费按成本×0.2,和原记账金额取小值。完整组合编码中的逐件数量乘工单组合数;多行商品数量逐行对应,重复编码按各行数量相加。缺数量、缺成本、只能匹配部分包裹或已匹配包裹明细不全仍待确认。运费损耗不使用无发货记录的工单回退核价;沐野竹木仍只记成本价。判定说明注明使用工单数量,不将其称为实际发货数量。
- 自动同步来源须有成功同步记录,按现有快递号/订单号索引定点读取,换单前号仅在订单候选内精确核对;不直连上游、不改写发货数据。包裹行数须与 `pkg_count` 一致,沿用未发出名单排除,缺发货、部分单号、缺数量/商品/成本和冲突值仍待确认;自动同步来源不可用不影响文件完整的账期。
- 有物流单号时精确匹配该单号或换单前单号,同时核对工单提供的线上订单号;无物流单号时按线上订单号匹配全部相关包裹。合并订单按拆分后的完整单号建立索引。 - 有物流单号时精确匹配该单号或换单前单号,同时核对工单提供的线上订单号;无物流单号时按线上订单号匹配全部相关包裹。合并订单按拆分后的完整单号建立索引。
- 单号及商品编码匹配前清理前后空白、不可见复制符、单引号、引号、`@` 及其全角形式;保留原始展示值及单号前导0,保留编码内部的 `-`、`+` 等合法内容,不做模糊匹配。 - 单号及商品编码匹配前清理前后空白、不可见复制符、单引号、引号、`@` 及其全角形式;保留原始展示值及单号前导0,保留编码内部的 `-`、`+` 等合法内容,不做模糊匹配。
- 不以平均运费替代原单运费,不借同订单其他快递单的运费;多个单号只匹配部分时待确认。 - 不以平均运费替代原单运费,不借同订单其他快递单的运费;多个单号只匹配部分时待确认。
- “未发出”辅助列按用户确认:`#N/A` 表示未命中未发出名单,可正常匹配;返回单号的整个包裹排除,成本、数量和运费均不累计。按订单匹配时仅核算剩余已发出包裹;原单全部未发出或工单明确列出的单号被部分排除时待确认、不计扣款,保留原金额。其他辅助列错误待确认。 - “未发出”辅助列按用户确认:`#N/A` 表示未命中未发出名单,可正常匹配;返回单号的整个包裹排除,成本、数量和运费均不累计。按订单匹配时仅核算剩余已发出包裹;原单全部未发出明确判“不扣款”,保留原金额作核对;工单明确列出的单号被部分排除时仍待确认、不计部分扣款。其他辅助列错误待确认。缺文件工单回退前同样先核对共享未发出名单。
- 工单商品须全部匹配。一个单元格合并多个商品编码、仅有总数量时,不推测每个商品的数量,标为待确认。 - 工单商品须全部匹配。组合装一个单元格合并多个商品编码、仅有总数量时,沿用财务已确认的各条码1件口径,并注明“组合装按各条码1件计”;沐野竹木只记成本价的特殊规则仍要求逐商品实际数量。
- 包裹运费只取一次;同包裹同商品的重复行不重复累计数量。运费或数量冲突时待确认,不相加、不擅自选值。 - 包裹运费只取一次;同包裹同商品的重复行不重复累计数量。运费或数量冲突时待确认,不相加、不擅自选值。
- 缺发货、有效数量、成本价或运费时待确认,保留原金额,不计扣款合计;运费损耗的空/0运费按第5条替代,判定说明及备注明确记录“按对应商品成本合计×0.2替代运费”,成本与数量列展示替代部分的依据。补偿/全款仍将明确0运费视为有效,空运费待确认。 - 同一快递号对应多个来源发货单时,补偿/全款仅核算含工单商品的来源单,排除同号无关配件单;仍须覆盖全部指定单号和商品,不借用无关来源单运费。工单重复展示同一商品编码时,以实际发货数量核价,不能把重复编码再次乘数量。
- 缺发货、有效数量或成本价时待确认,保留原金额,不计扣款合计;空/0运费按第4、5条替代,成本与数量列展示替代部分的依据,不把缺失运费直接按0记账。
- 原记账金额、匹配成本/运费/数量/快递号/期间供页面核对与导出。 - 原记账金额、匹配成本/运费/数量/快递号/期间供页面核对与导出。
## 月度发货导出镜像 ## 月度发货导出镜像

View File

@ -0,0 +1,35 @@
# 快递联合上传
入口:快递应付(及终版)→ 快递账单对账 → 上传账单 → 联合上传链接。
选择月份、打开页面后复制地址给快递。仍使用统一逐单模板及 30 天签名有效期。
## 范围与归组
- 樵舍:江西新建中通、江西中通快运、樵舍中通、樵舍中通-上楼、山东中通快运、西安圆通、西安中通快运。
- 圆通:常州圆通其他、常州圆通-上楼、小件宿迁圆通、睢宁宿迁圆通、苏北宿迁圆通。
- 睢宁宿迁圆通是苏北宿迁圆通的既有快递名称,圆通共 5 个名称、4 个分组。
- 河北中通与霸州百世:河北中通-江三、河北中通小件-江三、霸州百世快运-雅柏,3 个名称、2 个分组。
- 德邦与顺丰干配:睢宁德邦、崔桥顺丰干配、山东顺丰干配、山东顺丰大件、苏北顺丰干配大件、苏北顺丰干配小件,6 个名称、4 个分组。
- 睢宁德邦归入既有顺德德邦分组;链接只接受列出的 6 个名称,不额外授权顺德德邦名称。
- 不改分组、机器人或既有单家链接。联合权限不继承文件名、机器人共用关系或合并账单配置。
- 优先按系统单号归组;系统查不到快递名称时,使用模板内明确填写的范围内名称。
- 无法归组、范围外名称、同单号不同归属、附加费缺少运费明细时,整份回滚并提示修改。
- 附加费沿用同文件同单号运费的归属。重复文件沿用既有查重规则。
- 签名和任务固定分组快照;排队后配置变化或任一分组确认结算时禁止写入。重读、重新匹配不扩大范围。
- 已存在的 `extra_group_ids` JSON 列保存带 `joint_upload` 键的授权快照;普通文件仍为原数组结构,无迁移。
## 验证
2026-12-04 本地隔离容器,PHP 8.3、SQLite 内存测试库,禁止访问生产数据。
- `CourierJointUploadTest`:签名、别名、匿名上传、排队后配置变化/确认、归组、附加费、回滚、重读、查重、页面入口。
- `PortalFreightBillTest`、`CourierBillReconciliationTest`、`CourierBillPagesTest`:原上传、金额及页面回归。
- 相关回归 47 项,596 个断言通过;容量专项默认跳过,单独运行。
- 容量专项:100,000 行 CSV,3,900,052 字节,交替两家,校验、流式读入、归组及原有完整对账均执行。
- 100,000 行与 123,000 元合计完整,102.78 秒,PHP 峰值 154.5 MiB,数据库查询事件 101,823 次(包含既有逐行匹配更新)。
- 不据此承诺生产 MySQL 耗时;未对生产执行压测或上传测试账单。生产查询时两组尚无已上传文件和当月对账单。
- 河北及德邦/顺丰扩展:生产只读确认原分组、别名及账单为空;49 项回归、625 个断言通过,新增两组整单上传与别名范围校验已覆盖。增加入口显示断言后单独运行页面路径,16 个断言通过。
- 本次扩展沿用同一流式导入及每批 500 行分配,不改变数据量上限、导入命令或频率;未重复执行已通过的 10 万行容量测试。
生产复用已登记的 `portal-freight:import-pending` 独立批处理,每次一份;现有锁、1 CPU、1 GiB 容器、PHP 512 MiB、1 小时超时继续生效。
中断任务标记失败,联系财务核对后重传,不自动重复导入。

View File

@ -0,0 +1,33 @@
# 运费账单确认
代发运费对账的厂家明细页提供厂家切换、费用小汇总、逐单查询、异议处理和推送历史;快递账单对账在对账单内提供同样的对方确认入口。
## 操作顺序
1. 按原有规则完成核对。代发点“核对完成”;自有快递先完成“确认结算”。
2. 点“推送厂家确认”或“推送快递确认”。使用该厂家或对账分组已配置的钉钉机器人。
3. 对方打开免登录链接,查看本版本汇总、费用和逐单明细,也可下载 Excel。可跨页勾选异议并填写原因;未提出异议的单据按本版结果确认。
4. 提交后显示确认状态或逐单异议,同时发送群回执。财务在右侧记录采纳复核结果或不采纳,并填写依据,处理结果回到群内。
5. 需要调整金额时,先修正原有核算来源或费用,再重新推送。新推送生成新版本;旧链接不可再次提交,历史异议保留。
采纳反馈不会直接把对方提出的金额写入财务数据。财务内部的确认结算、台账和原有核算规则保持独立。群消息失败不会丢失确认或异议,财务页提供重发回执入口。
## 数据与权限
- 不新增数据库表或迁移。状态与审计继续使用 `supplier_payable_overrides` 和对应事件表。
- 代发状态 dataset 为 `dropship-freight-confirm`,快递为 `courier-freight-confirm`,record key 均为 `月份|ID`。代发 ID 是厂家 ID,快递 ID 是对账单 ID。
- 逐行版本账单 dataset 为 `<状态dataset>:snapshot:月份|ID:版本`;`meta` 保存汇总和费用,`line:序号` 保存对外明细。批量写入每批 500 行。
- 异议 dataset 为 `dropship-freight-dispute:月份|ID` 或 `courier-freight-dispute:月份|ID`,record key 为 `版本|单号`。保存原始原因、财务决定、依据、复核金额、处理人及时间、回执结果。
- 历史状态 dataset 为 `<状态dataset>:history:月份|ID`,record key 为版本号。
- 外部链接绑定公司、对账单或厂家、账期和版本,有效期 30 天。对外明细只包括单号、发货时间、快递、账单金额、应结金额、分类和说明,不包含内部公式、原始导入列或其他合作方数据。
- 已存在的旧代发链接继续兼容;历史版本未保存逐行快照的页面明确标注当前核算结果,需重新推送后才能固定版本。
## 验证边界
生产只读规模盘点:2026 年 11 月代发账单 15,119 行、最大一家 9,730 行;快递账单 71,650 行、最大一组 24,566 行。性能验证使用隔离 SQLite 和模拟数据,不向真实群发送测试消息,不运行生产压测。
界面每页 50 行对外明细、100 行代发内部明细、20 条财务异议。导出使用现有流式工作簿写入器;版本账单按固定范围分批读取。
2026-12-05 本地 PHP 8.3、2 核/2 GiB、内存 SQLite 验证:相关回归 48 项、767 条断言通过;随后补充大小写规范化、跨页异议提交和并发版本保护,专项 3 项、62 条断言通过。9,730 行代发账单的首页、第二页、筛选合计 1.44 秒,284 次查询累计 241 毫秒;24,566 行快递版本账单保存 1.08 秒,首页/第二页/筛选合计 0.31 秒,导出 1.68 秒,文件 683,504 字节,该专项 254 次查询累计 919 毫秒。整进程峰值 RSS 266.3 MiB,PHP 峰值 195 MiB。包含框架与测试初始化开销;没有在生产压测,也没有实测生产数据库写入耗时。
2026-12-05 发布前补验:合入最新主线后,相关 32 项测试、500 条断言通过。Chrome 已检查真实模板渲染的厂家明细、待确认页、异议表单、填写后自动勾选、刷新保留草稿与清空勾选;修复反馈链接在含 base 地址的页面跳离当前账单的问题,并支持定位到对应异议分页。真实钉钉发送不作为验收动作。手机尺寸及真实设备交互尚未实测。

View File

@ -0,0 +1,18 @@
# 逆向快递账单核算
快递账单对账中的中通快运逆向、常州德邦逆向、申通退货、好省邮快递读取退件取件管理共享镜像。按退货单号和实退单号匹配,原单号已换单时不重复付款;同号多张取件单或一单多个实退单号保留待核实,不重复分配整单运费。普通快递仍按发货数据核对,常州德邦与常州德邦逆向分别处理。
以实际取件时间归属月份;取消、关闭或没有实际取件时间的记录列为未发出。中通、德邦、申通复用逆向报价试算规则。按用户确认口径,同一运单各商品的毛重×退货数量、长×宽×高×退货数量分别合计,整票计费,面单只收一次;基础运费与附加费分别保留。缺少重量、路线、报价或报价尚未生效时不填零价,显示系统未核算。导出保留退件商品、重量、计算公式、报价来源。
好省邮按取件记录的实际承运快递选择报价管理里的好省邮百世、好省邮顺心捷达或好省邮顺丰,复用现有源目省份及城市报价计算器,以取件日选择有效版本。
原始账单、人工处理结果及手工小汇总保留。仅对明确指定且未确认的账单重算,确认后的账单拒绝自动重算。服务器使用独立批处理入口(既有内存、超时和互斥限制):
```sh
sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:match-reverse 12 --company=1
sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:match-reverse 12 --company=1 --apply
```
不带 `--apply` 只预演;实际执行前自动备份该账单的行、未提供明细和小汇总到私有目录。失败后可在核对备份与最新状态后重新运行;不批量处理其他账单。
退件主表约 31 万行、明细约 40 万行、实退单号约 19 万行;查询按单号分批,月份按快递和取件时间索引,关联按取件主键。迁移仅增加共享镜像索引,不写上游业务数据。

View File

@ -0,0 +1,25 @@
# 附加费账单匹配
快递账单和代发账单以账单月份归集附加费。按完整快递单号、规范化费用类型、快递归属匹配 `courier_surcharge_settlement_rows` 中“已计算”的金额;统一匹配包含账单当月在内最近3个自然月,不把账单金额当自算金额。例如11月账单匹配9月1日(含)至12月1日(不含)的数据,跨年同样按自然月计算。发货记录、客服工单和来源结算均受此时间范围限制;无日期记录不自动计费。已计入其他账单的费用仍去重,不因跨月重复结算。
新文件导入时自动匹配,已有账单可用 `courier-surcharge:match-bills --month=2026-11 --statement=11` 或 `--factory=厂家ID` 校准,也可 `--all` 处理当月未确认账单。命令省略月份时取北京时间上月,生产每天 07:05 使用 `--all --existing-only` 更新已经建立匹配的账单;首次历史回补单独确认,部署和定时任务不会自动启用旧账单。命令必须走 `run-finance-batch.sh`,共用上游互斥锁和独立批容器,PHP 512 MiB、容器 1 GiB、最长 3600 秒,失败按同范围重跑。每份账单的更新在事务内;不改已确认快递账单或厂家确认状态,不重算原运费行,手工小汇总优先。
`bill_surcharge_matches` 保存来源文件/工作表/行号、账期、单号、类型、对方金额、自算金额、状态、商品/店铺/订单信息和稳定费用来源标识。`dropship_bill_surcharges` 保存厂家原始附加费行。Excel 使用项目现有流式读取器,每批匹配 300 行,来源按单号索引查询,明细页面 50 行分页,导出逐批写入“附加费核对”子表。类型只使用明确同义词(如改地址费→改地址),不把不明类型猜成其他费用。
同一账期重复提供的单号+费用类型只计一次;同一费用来源已被其他账单计入时不再计入,仅新出现的费用来源可继续计入。同一单号不同费用类型分别核对;匹配不到或快递归属不符时自算金额留空并显示原因。代发还要求发货仓库及快递名称同时属于该厂家,排除自有快递。多个商品信息去重后展示,金额按票汇总,不乘商品数。
查询/校准不会写上游报价或来源费用;删除账单文件时清除其派生匹配结果。真实账单、备份与生产日志保留在 Git 忽略的私有目录。
结算表没有对应结果时,导入及重新匹配会按本票实际快递、报价适用范围和生效日自动核价,并从发货镜像补齐商品、店铺和订单信息。已接入“取发出运费”(按本票全部包裹核算运费合计)、“按尺寸/最长边”及“聚工单客服核实”。账单及客服明细中包含“拦截费”的名称(如“拦截费用”“待拦截费”“包裹拦截费用”,忽略空格)统一对应“拦截费”;“拦截”“拦截退回”“拦截退回运费”也按同一类型处理,同票同类费用仍去重。其他计费方式或尚未接入的附加条件保留空值并显示具体原因,不推测金额。
“取发出运费”的“查件扣单并且买家原因”条件,按同一单号、同一快递、匹配时间范围内的有效查件工单核验原因分类,要求为“扣单/买家-具体原因”,不要求退回进仓。多个扣单工单采用最新有效工单(创建时间、来源ID排序),取消工单不参与;明确非买家原因计0,缺工单或原因不完整保持未匹配。核对说明保留工单号和原始原因,每票发出运费只计一次。
负责人逐票确认的买家原因,复用 `supplier_payable_overrides` 的 `courier-surcharge-buyer-confirmations` 数据集及其事件审计保存,不修改上游工单。确认绑定报价、账单月份、完整单号、工单号及原始原因,并保留确认依据;重新匹配继续使用同一确认。换工单、换报价或原因变更后需重新核实,其他破损单不自动视为买家原因。真实单号和确认记录不得进入 Git。
固定单价自动核价读取报价中的金额(如30元/单、30/单),每票同类费用只计一次,不乘商品数量。空条件或“按单收取”按票计费;“查件扣单”核对同快递有效工单;带“买家原因”的条件核对扣单原因;带“已退回”的条件还要求该工单订单在最近三个自然月有实退数量大于0的进仓记录。退回状态通过已接入售后镜像的订单和售后单索引关联读取,无需全表扫描;缺少进仓依据保持未匹配,不推测已退回。客服通过类条件仍要求同单号、同快递、同费用类型的审核通过明细,金额取报价固定单价,不取客服填写的金额。暂不支持的条件或金额格式保留未匹配原因,不能回退到旧结算金额绕过条件。
固定单价条件“查件扣单并且买家原因或破损”接受扣单原因的“买家-*”“快递-破损”或“破损”,无需退回进仓;仅报价明确采用该条件时适用,不扩大其他报价的范围。改地址固定单价也接受同快递改地址工单中客服结果字段明确为“通过/已通过”,或客服回复字段明确为“通过/已通过/客服回复已通过”;“已联系快递修改”、待跟进及未通过均不是审核通过。
用户要求保留某厂家某月现有金额时,在既有覆盖值表的 `bill-surcharge-auto-match-holds` 数据集记录 `dropship|厂家ID|月份`、`enabled=true` 及原因,并写审计;`--existing-only` 的每日自动重匹配跳过该账期。新账单导入、其他厂家或月份不受影响,后续获授权的指定账期重算仍可正常执行。
客服费用通过现有单号索引读取共享工单,要求同一快递、费用类型一致、逐项审核通过且工单在账单月份结束前创建;按工单归集,不按商品数重复计费。“重量60kg以上”先检查本票已核算计费重量,低于门槛计0;缺重量、缺审核、无报价分别显示原因。原始账单、报价和发货运费均不改写。

View File

@ -63,7 +63,7 @@ class CourierSurchargeSettlementMirrorRepository
} }
/** @return array<string,mixed> */ /** @return array<string,mixed> */
public function state(): array public function state(array $filters = []): array
{ {
if (! $this->available()) { if (! $this->available()) {
return [ return [
@ -75,8 +75,15 @@ class CourierSurchargeSettlementMirrorRepository
} }
try { try {
$lastPulledAt = $this->connection->table(self::TABLE)->max('pulled_at'); $query = $this->filteredQuery($filters);
$rowCount = (int) $this->connection->table(self::TABLE)->count(); $lastPulledAt = (clone $query)->max('pulled_at');
$rowCount = (int) (clone $query)->count();
$serviceState = null;
$courier = trim((string) ($filters['courier_name'] ?? ''));
if ($courier !== '' && $this->connection->getSchemaBuilder()->hasTable('business_mirror_table_states')) {
$serviceState = $this->connection->table('business_mirror_table_states')->where('dataset_key',
\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::dataset((int) company_id(), $courier))->first();
}
} catch (Throwable) { } catch (Throwable) {
return [ return [
'code' => 'pending', 'code' => 'pending',
@ -87,9 +94,9 @@ class CourierSurchargeSettlementMirrorRepository
} }
return [ return [
'code' => $lastPulledAt === null ? 'pending' : 'fresh', 'code' => $serviceState ? ($serviceState->status === 'succeeded' ? 'fresh' : ($serviceState->status === 'failed' ? 'failed' : 'syncing')) : ($lastPulledAt === null ? 'pending' : 'fresh'),
'status' => $lastPulledAt === null ? 'pending' : 'succeeded', 'status' => $serviceState->status ?? ($lastPulledAt === null ? 'pending' : 'succeeded'),
'last_succeeded_at' => $lastPulledAt, 'last_succeeded_at' => $serviceState->last_succeeded_at ?? $lastPulledAt,
'mirror_row_count' => $rowCount, 'mirror_row_count' => $rowCount,
]; ];
} }
@ -141,7 +148,7 @@ class CourierSurchargeSettlementMirrorRepository
$data[] = $mapped; $data[] = $mapped;
} }
$state = $this->state(); $state = $this->state($filters);
return [ return [
'data' => $data, 'data' => $data,
@ -370,6 +377,7 @@ class CourierSurchargeSettlementMirrorRepository
private function normalizeImportType(string $type): string private function normalizeImportType(string $type): string
{ {
$type = trim($type); $type = trim($type);
if (str_contains(preg_replace('/\s+/u', '', $type) ?? '', '拦截费')) return '拦截费';
return [ return [
'退回件' => '退回费', '退回件' => '退回费',
@ -377,6 +385,9 @@ class CourierSurchargeSettlementMirrorRepository
'退货件' => '退回费', '退货件' => '退回费',
'超长' => '超长费', '超长' => '超长费',
'改地址费' => '改地址', '改地址费' => '改地址',
'拦截' => '拦截费',
'拦截退回' => '拦截费',
'拦截退回运费' => '拦截费',
][$type] ?? $type; ][$type] ?? $type;
} }
@ -386,6 +397,18 @@ class CourierSurchargeSettlementMirrorRepository
private function matchImportRow(iterable $rows, string $type, string $courier = ''): ?object private function matchImportRow(iterable $rows, string $type, string $courier = ''): ?object
{ {
$fallback = null; $fallback = null;
$service = [];
foreach ($rows as $row) {
if (($row->source_kind ?? null) === \Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::KIND
&& trim((string) $row->surcharge_type) === $type
&& ($courier === '' || trim((string) $row->courier_name) === $courier)) $service[] = $row;
}
if ($service !== [] && count(array_unique(array_column($service, 'courier_name'))) === 1) {
$sum = clone $service[0];
$sum->settlement_amount = array_sum(array_map(fn ($r) => (float) $r->settlement_amount, $service));
$sum->evidence = implode(';', array_map(fn ($r) => (string) $r->evidence, $service));
return $sum;
}
foreach ($rows as $row) { foreach ($rows as $row) {
if (trim((string) $row->surcharge_type) !== $type) { if (trim((string) $row->surcharge_type) !== $type) {

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