Compare commits

..

483 Commits

Author SHA1 Message Date
ffe97e458a 快递账单重复导入提示与安全重新读取 (#1546) 2026-11-28 12:27:47 +08:00
a7e7b067eb 修复发货包裹商品、数量、体积与换单同步 (#1545) 2026-11-28 12:27:14 +08:00
e6b9775a24 快递账单支持合并导出、原始运费表和四位金额 (#1544)
按 0006、0007、0008 顺序整合;账单相关测试及隔离 MariaDB 迁移验证通过。
2026-11-28 11:31:38 +08:00
6a1e7678fe 中铁客退返货线路报价及吨方取高计费 (#1543) 2026-11-28 10:51:23 +08:00
6b1ff05fee 快递账单上传逐文件按文件名识别分组 (#1542) 2026-11-28 10:48:01 +08:00
801264b4b3 支持合并账单自动拆分和重新匹配 (#1541) 2026-11-28 10:32:48 +08:00
d967420b08 支持对账分组自动生成、导入导出和补归组 (#1540) 2026-11-28 09:38:40 +08:00
52181b41d4 test(发票附件): 覆盖表格原件保存 (#1539) 2026-11-27 22:56:59 +08:00
b601a28e01 快递账单对账第一期与快递应付汇总 (#1538) 2026-11-27 22:08:45 +08:00
3374563c4f feat(发票附件): 保留无法预览的原始文件 (#1537) 2026-11-27 20:18:19 +08:00
79449e4aca fix(发票附件): 按付款月份分目录存储 (#1536) 2026-11-27 20:08:09 +08:00
a8f5e9a188 feat(供应商货款预估): 接入聚水潭采购退货明细 (#1535)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 19:18:52 +08:00
c8dfec5c85 feat: 快递合同管理支持筛选导出清单及签署原件 (#1534) 2026-11-27 18:53:55 +08:00
7e23e42a34 fix(资金余额): 京东钱包新店期初固定按零 (#1533) 2026-11-27 18:43:29 +08:00
ddbd018377 fix(供应商货款预估): 仅对无金额记录补预估 (#1532)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 18:27:25 +08:00
506f1e8784 fix(供应商货款预估): 修正筛选预估汇总并改为万元 (#1531)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 18:17:02 +08:00
684813d03b fix(资金余额): 京东钱包新增店铺期初自动按零计算 (#1530) 2026-11-27 18:15:49 +08:00
79206da614 feat(发票数据): 增加按月原始附件库 (#1529) 2026-11-27 18:00:14 +08:00
a0e4cc4380 feat(供应商货款预估): 增加商品资料成本价兜底
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:48:32 +08:00
e1178f56aa perf(供应商货款预估): 精简汇总扫描列
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:31:17 +08:00
0bb0d895d1 perf(供应商货款预估): 优化兜底取价汇总
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:20:20 +08:00
2912814931 fix(供应商货款预估): 补充当前定价兜底取价
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:05:38 +08:00
5f1348db4b fix(发票预览): 回扫时替换工作簿旧预览 (#1524) 2026-11-27 16:57:03 +08:00
e058927cdd perf(供应商货款预估): 增加代发发货分页索引
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 16:45:32 +08:00
5d6412ac44 fix(发票预览): 安装中文字体并校正 PDF 展示 (#1522) 2026-11-27 16:43:33 +08:00
2d4859f291 保护未发出历史补录并衔接每日同步 (#1521) 2026-11-27 16:35:58 +08:00
c7f011fc93 perf(供应商货款预估): 优化合并明细分页查询
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 16:35:24 +08:00
414d4fd3ee fix(发票数据): 修复表格附件发票预览回填 (#1519) 2026-11-27 16:33:32 +08:00
e0a3b8fd1f 接入已核实的仓内未发工单镜像 (#1518) 2026-11-27 16:20:43 +08:00
773509443d feat(供应商货款预估): 合并代发仓发货明细
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 16:09:20 +08:00
9089d8fb23 未发出明细两列展示及现场拦截分套同步 (#1515) 2026-11-27 16:04:03 +08:00
85c32fbd7d feat: 发货数据支持导入称重重量 (#1514)
替代冲突检测卡住的 #1500。移植 b8536189;发货列表、正常与重复导入、无效重量、计费重量回归及迁移回滚验证通过。生产迁移和部署待独立授权。
2026-11-27 15:44:53 +08:00
66639e19c1 feat(发票数据): 增加发票图片与PDF页内预览 (#1513)
图片和 PDF 发票原件缓存到私有业务存储,页面通过预览弹窗查看;历史附件首次点击时按需缓存。
2026-11-27 15:42:22 +08:00
92f88fb60b 每日汇总快递未发出明细 (#1512) 2026-11-27 15:40:40 +08:00
0a7cc700fb feat: 增加注销账户状态 (#1511) 2026-11-27 15:33:36 +08:00
aa99eb932e fix(部署): 使用可用 Debian 镜像并重试依赖安装
切换腾讯 Debian 镜像并为 apt 依赖安装增加续传重试。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 15:29:19 +08:00
6ca0154a22 fix(发票数据): 继续处理已到期发票积压 (#1509)
OA 同步没有新流程时仍处理已到重试时间的发票;无到期积压时不做增量抓取。
2026-11-27 15:22:17 +08:00
bec7cbdabb feat(发票数据): 合并OA同步并精简发票明细 (#1508)
发票识别并入 OA 流程同步,加入重试退避;发票页移除前置业务列和附件,流程号直达 OA 详情。
2026-11-27 15:19:07 +08:00
dcd12eca7b fix(供应商货款预估): 冻结明细表头
供应商货款预估明细改为局部纵向滚动并固定表头。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 15:16:36 +08:00
e7a73008c7 feat(推广费用): 自动同步聚水潭推广费用到共享镜像 (#1506) 2026-11-27 14:55:30 +08:00
b72b2e12bd feat(发票数据): 展示流程直抓完整发票字段 (#1505)
发票明细按 OA 流程附件直抓口径展示完整字段,打款时间移到最后,并从 2026-10 开始统计。
2026-11-27 14:42:41 +08:00
b6e06e775c fix(供应商货款预估): 补齐月份和供应商商品编码
月份按入库日期年月生成,供应商商品编码按供应商名称和商品编码拼接。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 14:41:23 +08:00
4dfed91c92 feat(资金管理): 新增月度资金余额监控并统一支付宝账户口径
合并月度资金余额监控页、店铺每日余额本页小计标识及全部/店铺支付宝账户名称区分。
2026-11-27 14:33:32 +08:00
e330d94090 fix(供应商应付): 空月份排序放到最后 (#1501)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 14:06:23 +08:00
0513146ef9 feat(供应商应付): 支持退货对账完整批量导入 (#1499)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 13:50:50 +08:00
f5b797070b 凌晨发货同步补拉最近40天 (#1498) 2026-11-27 13:31:17 +08:00
cdbaf45f27 厂家记账按成本价核算沐野竹木 (#1497) 2026-11-27 11:15:22 +08:00
cc204fbb97 feat(发票数据): 自动增量抓取并补入OA发票 (#1496)
自动识别 PDF、图片、XLS/XLSX、ZIP、RAR、7Z 发票附件,每 15 分钟补扫未处理、失败和部分识别流程。
2026-11-27 10:44:37 +08:00
95731bd90b 修复退款待确认读取已退役状态镜像 (#1495) 2026-11-27 10:43:42 +08:00
6cfed8ac51 fix(供应商应付): 货款对账按最新月份和日期排序 (#1494) 2026-11-27 10:38:30 +08:00
6a6c6f94c1 发货数据还原平台和无物流仓库 (#1493) 2026-11-27 10:36:00 +08:00
b2f7a072c8 feat(财务经营分析): 接入快递运费月度店铺汇总 2026-11-27 01:12:19 +08:00
50f5c7bc64 fix(财务经营分析): 排除京东网银钱包 (#1491) 2026-11-26 22:42:16 +08:00
7de0d3370f 发货数据缺少计费重量时留空运费 (#1490) 2026-11-26 21:48:03 +08:00
8df3c3ec36 fix(供应商应付): 终版货款对账按数据库分页 (#1489) 2026-11-26 20:47:47 +08:00
1954e10b5e 发货运费从十月开始核算 (#1488) 2026-11-26 18:37:18 +08:00
56de349bfc fix: 快递共用合同证明和收款账户证明按账号核验 (#1487) 2026-11-26 18:11:18 +08:00
f8efd97115 fix: 修正安装费实际归集月份口径 (#1486) 2026-11-26 18:09:20 +08:00
2f9fd2ac1d fix: 发票数据路由随主路由加载 (#1485)
将发票数据导出、刷新状态和附件路由移入主路由,避免生产 Web 因模块状态缺失路由。
2026-11-26 18:08:09 +08:00
f49d32ca8d fix: 安装费月度对比改用实际金额 (#1484) 2026-11-26 17:58:14 +08:00
24c6b7cb51 fix: 汇总快递应付附加费映射
按交易单号从运费差、其他附加费汇总和退件费页面取数,并对同一单号的多条金额求和。
2026-11-26 17:54:07 +08:00
d112d90ed9 fix: 安装费用改为月度安装公司对比 (#1483) 2026-11-26 17:51:46 +08:00
12bc2f9efd fix: 补开发票数据页面旧权限入口 (#1482)
让已有 OA流程 权限的账号自动获得发票数据菜单和直达权限。
2026-11-26 17:45:04 +08:00
8b27e3e7aa perf(货款预估): 优化筛选汇总取价 (#1481)
筛选汇总改为批量取最新变价后聚合,减少重复回查。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 17:42:57 +08:00
832fe6399a fix: 安装费用趋势改按安装公司区分 (#1479) 2026-11-26 17:40:28 +08:00
4539031eb1 fix: 补充平提家具店铺期初余额 (#1477)
增加淘宝-平提家具源头工厂零期初余额,并补充生产数据修正迁移。
2026-11-26 17:31:25 +08:00
2ec2e7410f fix: 修复证件粘贴预览并定位签署表单错误 (#1476) 2026-11-26 17:30:28 +08:00
e1efa6812a feat(货款预估): 增加筛选金额汇总 (#1475)
筛选后展示数量、最新价金额和预估金额×0.8合计。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 17:26:11 +08:00
c333497e0b fix(快递应付): 移除停用的运费对账模块 (#1474) 2026-11-26 17:25:10 +08:00
e471e2b057 fix: 补充索菲亚常州店期初余额 (#1473)
增加天猫-索菲亚常州专卖店零期初余额,并补充生产数据修正迁移。
2026-11-26 17:14:10 +08:00
cb4fc5af0d fix: 补充华斯旗舰店期初余额 (#1472)
增加天猫-华斯旗舰店零期初余额,并补充生产数据修正迁移。
2026-11-26 16:58:13 +08:00
8a6e51e031 fix(货款预估): 保证秒级时间筛选完整显示 (#1471)
窄窗口改为响应式两列筛选布局,完整显示日期和秒数。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 16:53:55 +08:00
ea0680913e fix: 快递公司主体变更取消银行卡上传 (#1470) 2026-11-26 16:48:23 +08:00
83ab4d4479 feat: 增加 OA 发票数据页面与抓取链路 (#1469) 2026-11-26 16:46:27 +08:00
73679c55e3 feat(货款预估): 支持秒级筛选和筛选结果导出 (#1468)
支持入库时间精确到秒筛选,并导出当前筛选全集。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 16:42:28 +08:00
95f7734845 feat: 增加安装费平台与切换影响分析 (#1467) 2026-11-26 16:10:07 +08:00
828b5d4412 feat: 支持江南农商行账单导入 (#1466) 2026-11-26 15:58:51 +08:00
9edbc0a158 fix: 分段排版大报价签署 PDF 降低内存占用 (#1465) 2026-11-26 15:48:18 +08:00
063f5f1a67 feat: 安装费汇总增加每月平均费用 (#1464) 2026-11-26 15:41:46 +08:00
b4767adb86 fix(协议签署): 优化任务列表和筛选布局 (#1463) 2026-11-26 15:39:35 +08:00
f0df43e2f2 fix(对账单): 修复 Excel 空行导致上传卡死
自闭合空行现在会正确推进 XMLReader,避免同一空行无限重复读取。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 15:31:21 +08:00
1e823e299b fix: 统一江南农商行账户分类 (#1461) 2026-11-26 15:28:52 +08:00
5a2f4586f7 fix: 修正森屿家栖淘系微信六月期末余额 (#1460)
修正淘宝-欧意朗森屿家栖企业店 2026-06-30 淘系微信期末余额,并新增生产数据修正迁移。
2026-11-26 15:16:52 +08:00
e24b6b8de7 perf: 优化安装使用趋势查询 (#1459) 2026-11-26 15:02:09 +08:00
732e6ecd8f fix: 安装使用趋势按发货月份统计 (#1458) 2026-11-26 14:52:35 +08:00
593ba3f62c fix: 清理安装费汇总旧独立标签 (#1457)
自动移除安装费汇总历史独立顶栏标签。
2026-11-26 14:34:21 +08:00
89bfb24e26 fix(报价导出): 新增省份按原价格表列追加
跳过未报价的省份占位行,保留后续价格及新增省份的原表头列对齐。回归 72 断言及两份现有变价单 60 断言通过。
2026-11-26 14:28:43 +08:00
29d19aaa34 fix(权限): 供应商登录使用钉钉当前组织
供应商登录使用钉钉当前组织部门,HR 副本保留为兼容回退。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 14:20:37 +08:00
64c50ba414 fix(协议签署): 公司主体变更按E签宝账号核验签署人 (#1453) 2026-11-26 13:53:14 +08:00
939a4e597c fix(供应商对账): 修复厂家操作表单上下文丢失
四个厂家端写操作统一携带当前厂家;展示所有校验错误;上传增加提交中状态并防止重复提交。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 13:52:42 +08:00
cb6e10d3b9 fix: 将安装费趋势改为安装明细子页 (#1452)
移除安装费汇总独立菜单,改为安装明细下的子页,并兼容旧地址。
2026-11-26 13:44:01 +08:00
b1015c7cfb fix: 修正斯福恩淘系微信六月期末余额 (#1451)
修正天猫-斯福恩旗舰店 2026-06-30 淘系微信期末余额,并新增生产数据修正迁移。
2026-11-26 13:40:04 +08:00
5959ed1311 fix: 完整同步账户简称变更 (#1450) 2026-11-26 13:39:49 +08:00
30e6e6f995 fix(供应商对账): 按月度入库数据每日催办
上传入口不设截止时间;系统仅在每月 1-14 日 10:00 提醒未上传厂家,15 日财务出上月终版。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 13:26:16 +08:00
3ce42d564e feat: 业绩明细更新后自动重算商品成本 (#1448) 2026-11-26 13:06:50 +08:00
523b6c2db2 fix(供应商对账): 安装催办宿主机定时任务 (#1447)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 12:06:27 +08:00
37b9a17b65 修复原始账单更新后自动重算业绩明细
京东、京喜、抖音原始账单导入后自动排队重算业绩明细;补齐 10 月最新数据。
2026-11-26 11:53:47 +08:00
671b6b81a8 feat(供应商对账): 月度催办未上传对账单厂家 (#1445)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 11:44:34 +08:00
a65b0b41ff feat(退款待确认): 增加申请时间下钻明细 (#1444)
按退款月份数量查看申请日期分布,再点击具体日期加载待确认明细。
2026-11-26 10:45:48 +08:00
2386c92a15 fix(协议签署): 支持报价更正重签和人工确认归档 (#1441) 2026-11-26 10:45:11 +08:00
aa5950e0c9 fix(财务台账): 内部转账余额沿用银行余额口径
内部转账账户选择器直接使用银行余额页当前余额,非银行账户保留原余额回退。
2026-11-26 10:24:03 +08:00
79c9b2c3a6 feat: 新增安装费使用趋势汇总 (#1442)
新增安装费汇总页、安装公司使用趋势、切换判断和权限继承。
2026-11-26 10:12:24 +08:00
cd85ad0f63 fix: 快递报价和合作合同强制乙方正文签章 (#1440) 2026-11-25 21:01:27 +08:00
0eb439b1e9 报价表底部直接新增省份行 (#1439) 2026-11-25 20:34:48 +08:00
365368d032 完善快递资料主表编辑并限定授权人员 (#1438) 2026-11-25 18:48:37 +08:00
c663a59cf0 feat: 增加华夏个人卡和农业银行账单导入 (#1437) 2026-11-25 18:25:05 +08:00
a026cdc1f0 修复报价变价新增省份入口不显示 (#1436) 2026-11-25 18:06:08 +08:00
696327fb38 fix: 防止临时银行账单文件进入镜像 (#1435) 2026-11-25 18:00:23 +08:00
35c1048880 fix: 电子签自由签位置不发送必签参数 (#1434) 2026-11-25 17:58:29 +08:00
832d245c8b 报价变更支持新增省份 (#1433) 2026-11-25 17:48:29 +08:00
bd07ef1b9a fix: 合作合同统一甲方电话并使用已有签署身份 (#1432) 2026-11-25 17:44:37 +08:00
0991391fd7 feat(财务台账): 支持工商银行PDF账单导入 (#1431) 2026-11-25 17:34:25 +08:00
212f4aa9e6 feat: 合作合同使用手机号并先乙方后甲方签署 (#1430) 2026-11-25 17:34:09 +08:00
db78e87ea5 feat(财务台账): 增加中国银行非直连账单模板 (#1429) 2026-11-25 17:11:34 +08:00
b9665b6393 feat(财务台账): 支持银行账单多文件批量导入 (#1428) 2026-11-25 16:50:49 +08:00
24d0bf0a22 fix(抖音账户): 按店铺最新月末快照滚动期初余额 (#1427) 2026-11-25 16:42:02 +08:00
9ab3d85a3a feat(财务台账): 增加华夏非直连账单模板 (#1426) 2026-11-25 16:30:19 +08:00
0c26491633 fix: 退出已停用上游的定时同步与开发机依赖 (#1425) 2026-11-25 16:26:50 +08:00
1a44a73150 fix(财务台账): 非直连阶段账单联动余额 (#1424) 2026-11-25 16:16:58 +08:00
96f0fceab7 fix(权限): 受限账号直达单页终版目录
修复受限账号进入单页终版目录时显示空目录总览。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-25 16:10:29 +08:00
9875ced91b fix(安装明细): 定期全量校准审核状态 (#1422) 2026-11-25 16:07:29 +08:00
31f14cd210 fix: 停用开发机生产中继安装入口 (#1421) 2026-11-25 16:00:52 +08:00
67ce756594 fix(财务台账): 日流水缺失时从账户期初补算余额
动账明细优先使用当天日流水期初,缺少时从最近账户期初滚动计算。
2026-11-25 16:00:09 +08:00
a597285e29 fix(权限): 允许受限账号进入单页目录
修复受限钉钉账号进入单页目录时误返回 403。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-25 15:54:45 +08:00
02b685bca9 feat(财务台账): 区分银企直连与非直连账单导入 (#1418) 2026-11-25 15:46:44 +08:00
337bee9da1 fix(财务台账): 手动招商账户显示滚动余额 (#1417) 2026-11-25 15:44:55 +08:00
3f11a171b3 fix(供应商应付终版): 冻结表格表头
供应商应付(终版)表格使用局部纵向滚动并冻结表头。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-25 15:43:48 +08:00
ac31ca56ea fix(财务台账): 补齐非直连动账余额展示 (#1415) 2026-11-25 15:40:23 +08:00
267d62ee43 feat(财务台账): 发布动账筛选与店铺默认公户 (#1414) 2026-11-25 15:27:20 +08:00
6a46a277cb fix: 降低 Windows 本地前端监听的空闲 CPU 占用 (#1413) 2026-11-25 15:26:41 +08:00
35a98063eb feat(财务台账): 增加银行账单模板导入 (#1412) 2026-11-25 14:58:01 +08:00
a19836d3f3 fix(抖音账户): 补齐索菲亚易开点七月期初 (#1411)
按聚水潭平台资金账户余额将索菲亚易开点家具专卖店 2026 年 7 月期初余额固定为 0,并覆盖逐月滚动至 10 月期末的回归测试。
2026-11-25 14:54:45 +08:00
daf50db507 fix: 修复扬灵梦汐协议签署首次访问被拒绝 (#1410) 2026-11-25 14:53:26 +08:00
b6e984ad30 feat(权限): 支持受限钉钉账号单页授权 (#1409)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-25 14:45:00 +08:00
d0dc453139 fix(财务台账): 新期初后动账未定价时拒绝旧余额 (#1408) 2026-11-25 14:17:21 +08:00
091cbee965 fix(财务台账): 无交易月份沿用真实期初 (#1407) 2026-11-25 14:11:12 +08:00
c026f72604 fix(财务台账): 直连无流水时期末回退锁定期初 (#1406) 2026-11-25 13:54:04 +08:00
0b5a90456d fix(财务台账): 无真实期初不生成零基流水 (#1405) 2026-11-25 13:44:40 +08:00
cda29213a1 fix(财务台账): 严格锁定期初并保护手工余额 (#1410) 2026-11-25 13:33:58 +08:00
b0319e1cd1 fix(财务台账): 期初禁止按次月余额倒推 (#1403) 2026-11-25 13:21:52 +08:00
fa38374246 feat(财务经营分析): 接入安装费月度汇总 (#1402) 2026-11-25 13:05:21 +08:00
b1b7710315 feat: 导出供应商合作合同和签署原件 (#1401) 2026-11-25 12:08:43 +08:00
a14c0d44ca fix(财务台账): 锁定月度期初不让动账改写 (#1400) 2026-11-25 12:03:11 +08:00
1114349ac7 feat(财务台账): 增加银行余额页与直连余额滚动 (#1399)
资金台账新增银行余额页、直连余额滚动、日期筛选、列设置和页内余额校正。
2026-11-25 12:01:46 +08:00
41080477b8 feat(财务台账): 增加余额更新时间 (#1398) 2026-11-25 11:06:36 +08:00
864f4fe9e8 feat: 增加供应商合作合同到期提醒 (#1397) 2026-11-25 10:43:43 +08:00
99e94f7939 fix(财务台账): 招商银行邮件失败由服务器提醒 (#1396) 2026-11-25 10:39:17 +08:00
abe8376f20 fix(财务台账): 调整招商银行邮件抓取时间 (#1395)
招商银行邮件任务改为每天 07:00,失败后重试一次。
2026-11-25 10:21:15 +08:00
f0bee2dc22 fix(财务台账): 修正招商银行邮件安装路径 (#1393)
修正邮箱配置来源路径。
2026-11-25 10:14:56 +08:00
39769abd26 feat(财务台账): 接入招商银行邮件账单 (#1392)
接入招商银行邮件账单下载、整目录导入和余额同步。
2026-11-25 10:11:08 +08:00
04aab012b9 fix: 供应商合作合同正文及附件乙方盖章设为必签 (#1391) 2026-11-25 10:04:25 +08:00
e8ca07dfd6 fix(协议签署): 按归档时间倒序显示已归档任务 (#1390) 2026-11-25 09:51:25 +08:00
6156245335 fix: 协议签署删除权限绑定指定账号 (#1388) 2026-11-25 09:35:16 +08:00
4fa23a63e3 fix: 协议签署三类任务删除仅限李斯人参苏木 (#1387) 2026-11-25 09:22:05 +08:00
871793ff29 fix: 报价重复推送显示原因并支持版本筛选 (#1386) 2026-11-25 09:15:51 +08:00
e76e87e4db feat(财务台账): 发布银行账单与账户资金管理 (#1385)
发布银行账单、账户资金管理、公司规划分布与余额联动。
2026-11-25 09:14:24 +08:00
11637818b9 fix: 处理商品成本合单循环 (#1384) 2026-11-24 22:06:43 +08:00
40ac376760 修复协议签署管理主体点击无反馈 (#1383) 2026-11-24 18:52:04 +08:00
c670272aa2 fix: 有限等待私有存储检测文件删除状态一致 (#1382) 2026-11-24 18:46:01 +08:00
cd8c0511f2 feat: 协议签署归档列表按合作方类型筛选 2026-11-24 18:38:29 +08:00
f75481633d fix: 协议签署删除按钮放在操作栏最后 (#1378) 2026-11-24 18:21:14 +08:00
820de98c29 feat: 合作合同仅由合作方签署并在归档状态旁显示删除 (#1377) 2026-11-24 18:15:09 +08:00
9e933fa787 fix: 合作合同空变量显示下划线并开放定向协议签署权限 (#1376) 2026-11-24 17:41:01 +08:00
f053ed8fd0 feat: 报价统一初审复审并支持每阶段任一人通过 (#1375) 2026-11-24 17:00:17 +08:00
8bf3acece5 fix: 刷新业绩明细店铺筛选项缓存 2026-11-24 15:36:19 +08:00
1a592c82a0 feat(得物支付宝账户): 增加店铺与商户号映射列 (#1373)
新增支付宝账户、得物店铺和商户号映射列。
2026-11-24 14:41:21 +08:00
6d9a4d2ddd fix: 业绩明细按原始店铺拆分主体 2026-11-24 14:06:47 +08:00
1aed8762b6 fix(得物支付宝账户): 修正玖阔账户名称后缀 (#1371)
修正玖阔账户后缀并补充账户范围测试。
2026-11-24 13:47:06 +08:00
23b0beda61 fix: 保留已发货母单的商品成本 (#1370) 2026-11-24 13:03:05 +08:00
cfde5d06c7 feat(得物支付宝账户): 新增聚水潭支付宝账单页签 (#1369)
新增得物支付宝账户页签,限定 8 个主体并默认展示聚水潭 2026 年 10 月淘系支付宝账单。
2026-11-24 12:09:24 +08:00
d2d58276fb feat(财务台账): 增加银行账单页与余额联动
新增银行账单独立页面与银行原始账单存储,账户总览余额可联动到对应账号账单。
2026-11-24 11:30:22 +08:00
1e02737f92 fix(日志统计): 排除已离职林冲的漏写扣分 (#1367) 2026-11-23 19:22:47 +08:00
6e092547c0 feat(pdd-balance): automate store-month opening balances
Maintain store-month openings, pending tasks, and balance cache invalidation.
2026-11-23 18:58:16 +08:00
d42bc76404 feat(账户总览): 直连余额叠加次日起动账
次日导入前一天最终余额后,仅叠加次日起全部动账;前一天流水不重复计算。
2026-11-23 17:20:47 +08:00
0e1bac07c0 fix(账户总览): 银企直连账户使用最新直连余额
银企直连账户的当前余额、可用金额和不可用金额统一优先使用最新直连快照。
2026-11-23 16:57:17 +08:00
75f96d8ee4 refactor(财务台账): 账户总览取代账户资金汇总入口
账户总览成为财务台账默认入口,账户资金汇总从主导航下线。
2026-11-23 16:25:30 +08:00
fc6aadc7ff fix(账户总览): 筛选浮层自适应弹窗可视区域
筛选浮层不再被弹窗裁切,并在下方空间不足时向上展开。
2026-11-23 15:31:31 +08:00
24f11ed0ae fix(账户总览): 银行明细列筛选保持银行范围
列筛选候选与全选/清除只作用于当前银行明细范围。
2026-11-23 15:23:02 +08:00
765c85af0c fix(账户总览): 银行明细按当前行实时筛选
银行数字展开时实时读取当前明细行并过滤,避免显示其他银行账户。
2026-11-23 15:12:07 +08:00
841eae6d39 fix: 修复供应商货款预估筛选与供应商列
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-23 15:07:11 +08:00
c6aeb823ed feat(账户总览): 明细表增加独立列设置
数字展开明细表增加独立列设置并保存本地显示偏好。
2026-11-23 14:42:44 +08:00
ffd31af3e1 fix(账户总览): 保持弹窗内筛选不跳页
弹窗内全量明细筛选和排序改为客户端处理,避免页面重载后退出弹窗。
2026-11-23 14:26:32 +08:00
add4c912b8 fix: 增加OA流程API每日调用硬限额 (#1356) 2026-11-23 10:19:22 +08:00
34dfd46e22 fix: 限制OA审批同步API调用频率 (#1355) 2026-11-23 09:57:37 +08:00
f0f5b35071 fix(期末余额双源核对): 按完整账户名称精确匹配店铺 (#1354)
避免阿里巴巴与支付宝开头的独立账户被规范化后错误合并。
2026-11-21 17:25:29 +08:00
bfb668f5db feat(顾家对账): 增加灵珊对账单打印页 (#1353)
新增灵珊对账单表二格式预览和A4横向自动打印页,按料号透视数据生成明细、地址分组、合计与盖章区。
2026-11-21 17:09:19 +08:00
e9d5163ca0 revert: 撤销唯品会结算月每日余额调整 (#1352)
撤销 PR #1351,恢复唯品会原有每日余额口径。
2026-11-21 17:03:18 +08:00
7b61be1ed0 fix: 统一唯品会结算月每日余额口径 (#1351)
唯品会 MP/JX 按结算月份计入每日余额。
2026-11-21 17:00:17 +08:00
1340d24ced fix(供应商货款预估): 修正采购入库长字段索引 (#1350)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-21 16:50:44 +08:00
17da14981d feat: 发票额度支持按筛选导出 CSV (#1349) 2026-11-21 16:30:13 +08:00
bb0e83da80 feat(顾家对账): 按料号透视灵珊虚拟过账 (#1348)
灵珊虚拟过账按顾家料号透视,ERP商品导入、开票模板和库存模板读取同一批透视行,销售金额按料号汇总计算。
2026-11-21 16:13:37 +08:00
205cdfe50e feat(供应商货款预估): 接入采购入库与变价价格 (#1347)
接入聚水潭采购入库明细、固定剔除规则和工作平台最新变价后采购价。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-21 15:59:27 +08:00
d664680aec feat(顾家对账): 按虚拟过账生成库存模板 (#1345)
按灵珊虚拟过账逐行生成库存管理模板,固定欧伯娜供应商资料,并仅填写指定库存字段。
2026-11-21 15:18:07 +08:00
3e3cb199f7 feat(顾家对账): 增加开票模板汇总卡片 (#1344)
去掉开票填写模板表格上方的标题说明栏,增加开票数量和开票金额汇总卡片,表格字段及明细保持不变。
2026-11-21 14:57:58 +08:00
7d3c2e9605 feat(供应商货款预估): 新增三个子页面 (#1343)
新增货款明细、退货明细和汇总三个页内子页面。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-21 14:12:50 +08:00
5bdee2bd8f fix(商品月加权平均单价): 排除指定商品编码 (#1342) 2026-11-21 13:43:08 +08:00
4041e7351d feat(账单同步): 联动业绩明细重算并增加窗口审计 2026-11-21 12:09:41 +08:00
703940b7b2 fix(商品月加权平均单价): 排除配件仓 (#1340) 2026-11-21 11:58:05 +08:00
2eadd534f9 feat(顾家对账): 按灵珊虚拟过账生成开票模板 (#1339)
按灵珊虚拟过账生成开票填写模板,数量与销售金额逐行对应,单据号、备注、规格型号留空。
2026-11-21 11:48:48 +08:00
31dc6b7651 fix(顾家对账): 统一ERP与虚拟过账金额口径 (#1338) 2026-11-21 11:36:05 +08:00
ba26a130ae feat(顾家对账): 增加ERP商品导入汇总卡片 (#1337) 2026-11-21 11:23:54 +08:00
b32c7ebf67 fix(顾家对账): 登记ERP收货人池批处理导入 (#1336) 2026-11-21 11:10:36 +08:00
eba8d5e796 feat(顾家对账): 按灵珊虚拟过账生成ERP导入 (#1335) 2026-11-21 11:06:02 +08:00
fe19763ffd feat(顾家对账): 增加灵珊销售金额尾差调整 (#1334) 2026-11-21 09:14:13 +08:00
5a27e64aaa fix(供应商对账): 将全部确认操作移至退货标题区 (#1332)
将全部确认操作移至退货标题区并强化主操作样式。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-20 18:33:22 +08:00
8543953752 fix(顾家对账): 统一单价金额两位小数展示 (#1331) 2026-11-20 18:02:32 +08:00
03dfc70da7 fix(供应商对账): 突出对账单必填规则 (#1330)
明确厂家对账单必填规则,并升级上传区域提示样式。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-20 17:52:25 +08:00
da35e00eec fix(顾家对账): 按总额计算灵珊销售金额 (#1329) 2026-11-20 17:42:07 +08:00
606077c0b7 种菜报销增加订单收入核对与追回汇总 (#1321) 2026-11-20 17:25:07 +08:00
6d85f64d84 feat(顾家对账): 增加灵珊虚拟过账汇总卡片 (#1328) 2026-11-20 17:23:55 +08:00
c713db6fe5 fix(供应商对账): 同步后台厂家端页面新界面 (#1327)
后台厂家端数据页面复用厂家门户工作区,保留上传、筛选、导出、确认/异议和厂家切换。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-20 17:15:54 +08:00
15d34c0de0 fix: 修复易签宝中文企业实名查询签名 (#1326) 2026-11-20 17:14:20 +08:00
f594adbba4 fix: 优化账户余额总览每日汇总性能 (#1325)
数据库端按日期和店铺聚合每日余额,并统一单飞缓存。
2026-11-20 16:55:04 +08:00
082c7f7f38 feat: 报价确认单自动带入企业并按账号核验实名 (#1324) 2026-11-20 16:38:51 +08:00
6518018b9f fix: 优化期末余额双源核对页面加载卡顿 (#1323)
分页明细、默认收起核查原因并增加冷查询单飞缓存。
2026-11-20 16:27:14 +08:00
23fc36c74c 财务经营分析表接入推广费
从聚水潭平台费用(新)→ 推广费(店铺)按账期和店铺汇总推广费支出,写入财务经营分析表推广费用-有票及汇总、CSV导出。
2026-11-20 16:12:22 +08:00
97b5824aee fix: 得物账单页面读取权威导入数据
得物账户账单页切换为聚胜算权威完整账单,并补充未就绪兜底与委托测试。
2026-11-20 15:54:27 +08:00
9821736dba fix(顾家对账): 暂不填写灵珊虚拟过账末三列 (#1319) 2026-11-20 15:49:06 +08:00
837e01b164 feat(供应商对账): 优化厂家端对账页面 (#1318)
厂家端对账页面改为三步骤流程,补齐账期和截止时间、筛选查询、导出、确认异议及响应式黑金视觉。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-20 15:48:47 +08:00
b0693163a6 fix(顾家对账): 恢复灵珊虚拟过账原表头 (#1317) 2026-11-20 15:39:59 +08:00
efba0711f6 fix: 兼容日常费用报销单据类型
兼容 OA 日常费用/借支费用标题,避免归入其他,同时保留旧标题兼容。
2026-11-20 15:33:59 +08:00
a43d358680 feat(顾家对账): 按规则生成灵珊虚拟过账 (#1315)
灵珊虚拟过账仅取过账标签为是的发货行,固定供应商信息并生成日期顺序淘宝单号。
2026-11-20 15:24:32 +08:00
5303994ac3 fix: 报价确认单按真实签署主体传递实名信息 (#1314) 2026-11-20 15:21:33 +08:00
f66cb9fd8f fix: 定向同步补齐OA明细抬头
按审批编号定向同步时强制读取钉钉官方详情,补齐已完成流程的开票抬头和出纳打款抬头。
2026-11-20 14:42:40 +08:00
cedd6638a1 fix(财务台账): 按实际付款日期同步钉钉动账
钉钉动账改为从实际付款事实反查审批,取消按流程发起时间限制。
2026-11-20 14:00:33 +08:00
9de660ae55 feat: 费用明细增加税务类型和公司主体 (#1311) 2026-11-20 13:49:18 +08:00
27a025a33d feat(顾家对账): 增加TOC订单发货数量汇总卡片 (#1310)
移除 TOC订单顶部说明区,增加发货数量汇总卡片。
2026-11-20 13:45:49 +08:00
dddea5b8eb 调整财务经营分析表列宽间距
为财务经营分析表设置固定列宽体系,增加文本列、金额列和单元格内边距,保持横向滚动时清晰可读。
2026-11-20 13:42:42 +08:00
2466c41ba0 feat(顾家对账): TOC订单仅取过账标签为是的数据 (#1307)
TOC订单按过账标签筛选,并填充订单号、物料编号、型号和发货数量。
2026-11-20 13:30:23 +08:00
8cbd56a4cb fix: 精简期末余额双源核对快捷时间按钮 (#1306)
移除快捷时间按钮及其无用逻辑,保留手动日期筛选与查询。
2026-11-20 11:29:00 +08:00
eed9678abe feat(顾家对账): 增加过账汇总卡片和全量导出 (#1305)
移除过账页冗余汇总和表头区,增加采购数量、供应商金额卡片及全量 CSV 导出。
2026-11-20 11:21:11 +08:00
9d6e2a85d2 财务经营分析表增加税务类型
在财务经营分析表的公司类型后新增税务类型列,并同步页面、行数据和 CSV 导出。
2026-11-20 11:20:40 +08:00
7219b4d143 fix: 恢复待付款单数表二下钻 (#1303) 2026-11-20 11:18:02 +08:00
d5af967e51 fix(财务台账): 拦截早于账户期初日期的动账
手工新增或编辑动账时校验账户自身期初日期,避免早于期初的明细未进入账户总览。
2026-11-20 11:10:11 +08:00
c11f363d1a fix(顾家对账): 统一数量和金额显示精度 (#1301)
顾家对账数量使用自然数字格式,单价和金额固定两位小数。
2026-11-20 11:03:30 +08:00
2a37724b8e 完善财务经营分析表列
按附件表头将财务经营分析表扩展为 20 列,并同步页面、汇总、CSV 导出、公司类型映射和自动化测试。
2026-11-20 11:02:12 +08:00
3dbb09c5d2 fix: 保留OA审批汇总表一并追加表二 (#1299) 2026-11-20 10:43:49 +08:00
556535d643 feat(账户总览): 合并银行直连汇总并拆分个人卡 (#1288) 2026-11-20 10:35:40 +08:00
b5ba81add3 fix(顾家对账): 铺满顾家过账数据表格宽度 (#1298)
顾家过账表按固定比例列宽铺满容器,消除末尾空白。
2026-11-20 10:33:28 +08:00
02275d064c fix: 保留OA审批汇总表一显示 (#1297) 2026-11-20 10:30:11 +08:00
e02d896ad5 feat(顾家对账): 调整顾家过账数据列间距 (#1296)
顾家过账数据使用宽间距列布局,其他对账页签保持不变。
2026-11-20 10:16:22 +08:00
00942162ae feat(顾家对账): 按过账标签汇总顾家过账数据 (#1294)
顾家过账数据仅汇总过账标签为“是”的发货明细,其他页签口径保持不变。
2026-11-20 10:00:32 +08:00
7f989314ed fix: 将负数预警预估页改为可见子页签
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-20 09:58:34 +08:00
c82b758763 feat: 将OA表二调整到审批汇总 (#1292) 2026-11-20 09:50:52 +08:00
2d53ddc943 feat(账户余额): 扩展总览页面宽屏布局 (#1291) 2026-11-20 09:37:30 +08:00
5f24bf4fcf feat: 新增负数预警预估子页面
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-19 20:59:53 +08:00
10626f0e55 fix(账户余额): 失效每日余额旧版本缓存 (#1289) 2026-11-19 18:53:02 +08:00
e6ce84759e fix(账户余额): 修复非镜像平台每日余额查询 (#1287) 2026-11-19 18:40:47 +08:00
3240342fa4 fix(actual-tax): widen ratio columns to preserve source values 2026-11-19 17:58:04 +08:00
58506f45a7 feat(账户总览): 接入银企直联期末余额 (#1285)
按银行账号接入银企直联可用余额快照,并用于账户总览期末余额。
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-11-19 17:47:43 +08:00
da503915b3 fix(种菜报销): 保留导出确认的工单完成状态 (#1284) 2026-11-19 17:36:32 +08:00
381c0e0d03 fix(账户余额): 刷新每日余额旧缓存 (#1283) 2026-11-19 17:34:50 +08:00
557017b178 feat: 账户档案返回时打开保留账户汇总 (#1282)
账户档案返回账户总览后自动打开保留账户资金总览,并清理临时查询参数。
2026-11-19 17:31:08 +08:00
160618526e feat(????): ???????????? 2026-11-19 17:28:52 +08:00
2ea6326bdf fix(顾家对账): 修复数字订单号收货匹配索引失效 (#1279)
数字订单号保持字符串绑定,避免 varchar 索引隐式数值转换;补充回归测试。
2026-11-19 17:20:57 +08:00
039a366717 fix(账户余额): 修复非镜像平台每日余额读取 (#1280)
修复唯品会MP、唯品会JX和小红书每日余额接口的空方向查询类型错误。
2026-11-19 17:20:35 +08:00
824e1b0d92 feat(顾家对账): 按规则生成各子菜单过账数据 (#1278)
按规则生成六个对账子菜单的数据,支持分页、金额倒算和收货信息补全。`n`n验证:数据生成单测 1 个、38 条断言;页面集成 3 个、58 条断言。
2026-11-19 17:09:43 +08:00
0282fea3fd feat(内部流转): 增加精选供应链标签三 2026-11-19 16:46:58 +08:00
8b46486b87 feat(顾家对账): 按工作簿子表补充各页签表头 (#1276)
按工作簿4子表名补充顾家对账各页签表头;无对应工作表的两个对账单页签保持占位。`n`n验证:页面测试 2 个、49 条断言通过。
2026-11-19 16:25:14 +08:00
4de11d6d95 perf(账户余额): 按平台分页加载店铺每日余额 (#1275)
拆分平台与店铺每日余额接口,店铺数据按平台、搜索和页码懒加载,降低首屏响应体积。
2026-11-19 16:08:14 +08:00
0188ad18f8 fix: 保留财务确认的逐单种菜报销金额 (#1274) 2026-11-19 15:59:05 +08:00
119f52c442 feat(账户余额): 增加平台与店铺每日余额视图 (#1273)
每日余额明细支持汇总、平台和店铺维度,增加真实每日余额接口、店铺筛选分页及点击日期查看当日四项明细。
2026-11-19 15:40:23 +08:00
30c4b8cd99 fix: 移除OA测试中的真实收款信息 (#1272) 2026-11-19 15:34:07 +08:00
a1783bf0eb feat(顾家过账): 支持按整表物料源修正发货明细 (#1271)
整表物料源逐行修正有效物料、成本和发货金额,#N/A 行保持原样,页面优先使用修正物料。

验证:导入器 5 个测试、53 条断言;页面 9 个测试、112 条断言;生产审计 8,837 行有效、5,112 行 #N/A。
2026-11-19 15:32:05 +08:00
805fc38cf9 feat: OA流程补充收款人银行账号 (#1270) 2026-11-19 15:26:33 +08:00
3afbf6320f feat(顾家过账): 同步修正异常物料成本和金额 (#1269)
异常物料修正同步使用生效报价单含税价计算成本和发货金额,页面使用同一逻辑展示。

验证:定向修正器 4 个测试、39 条断言;页面 9 个测试、111 条断言;15 个物料编号均有唯一生效报价。
2026-11-19 13:37:21 +08:00
de6a7fbc37 fix(账户余额): 恢复余额总览页面标题 (#1268)
将红框中的页签和页面内标题改回账户余额总览,趋势看板内容保持不变。
2026-11-19 13:18:30 +08:00
2fc587d2fa feat(店铺余额): 新增余额趋势看板 (#1267)
将账户余额总览切换为店铺余额趋势看板,新增 7/30 天联动趋势图、悬停明细、每日滚动余额表和固定种子演示数据校验。
2026-11-19 12:25:41 +08:00
5b95620d54 feat(顾家过账): 修正异常发货明细物料信息 (#1266)
根据异常清单和完整物料表定向修正发货明细物料编号与描述;只允许修正标记行使用存储物料,其他行逻辑不变。

验证:定向修正器 4 个测试、39 条断言;页面 9 个测试、109 条断言;生产只读审计 221 行精确匹配。
2026-11-19 12:07:45 +08:00
5611491d02 feat: 展示整月每日余额核对趋势 2026-11-19 12:00:30 +08:00
bd76d99457 feat: 支持聚水潭店铺余额多日期导入 2026-11-19 11:52:20 +08:00
6248d74450 feat: 优化种菜报销工作台展示与明细交互 (#1263) 2026-11-19 11:45:45 +08:00
92c7450f8f feat: 待付款汇总支持同页审批人明细 (#1262) 2026-11-19 11:30:25 +08:00
09a30cd980 fix: 表头筛选回车直接筛选匹配项 (#1261) 2026-11-19 11:21:36 +08:00
018b719257 fix: 新增账户后停留在当前页面 (#1260) 2026-11-19 11:10:40 +08:00
5baf7a40fb perf: 避免淘系支付宝期初余额全量窗口排序 2026-11-19 11:06:22 +08:00
b0074bbfa7 perf: 优化淘系支付宝期初余额查询 2026-11-19 10:44:27 +08:00
691a80e0c3 feat: 账户档案筛选覆盖全部账户 (#1257) 2026-11-19 10:42:53 +08:00
d69d2af66e feat: 快递资料展示工作平台属性并免扣工厂快递配件运费 (#1256) 2026-11-19 10:07:15 +08:00
33d088797f fix: 优化期末余额双源核对加载速度 2026-11-19 10:06:53 +08:00
3ad61407f0 fix: 离职人员常仪不再计算日志扣分 (#1254) 2026-11-18 18:39:59 +08:00
c1c98f756b fix: 修复手工动账导入审计字段超长 (#1253)
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-11-18 18:34:28 +08:00
e4eca2d9af fix: 统一报价签章栏与乙方签约主体 (#1252) 2026-11-18 18:29:42 +08:00
8277d066e8 fix: 报价签署使用真实合同主体并支持个人签署 (#1251) 2026-11-18 18:24:40 +08:00
301caa112d fix: 兼容 PowerShell 5.1 并安全传递中文简称 (#1250) 2026-11-18 18:01:23 +08:00
19763659d1 fix: 精确填写支付宝加密密码框 (#1249) 2026-11-18 17:56:01 +08:00
81410eef8d fix: 稳定支付宝商家平台登录会话 (#1248) 2026-11-18 17:50:10 +08:00
7149bdad1c fix: 等待支付宝登录验证后再保存会话 (#1247) 2026-11-18 17:48:13 +08:00
a3a391236f fix: 修正部署认证脚本中文编码 (#1246) 2026-11-18 17:44:30 +08:00
04900e6987 fix: 修正支付宝设置脚本中文编码 (#1245) 2026-11-18 17:38:15 +08:00
cdd08d6357 feat: 增加朱俊祥支付宝安全自动登录配置 (#1244) 2026-11-18 17:34:49 +08:00
7a4249d753 fix: 去除完整报价导出中的重复历史备注 (#1243) 2026-11-18 17:19:59 +08:00
941b1acd19 feat: 精简财务台账来源与同步频率 (#1242) 2026-11-18 17:09:22 +08:00
48cb5c956a fix: 导出完整变价后报价并统一备注执行日期 (#1241) 2026-11-18 17:07:09 +08:00
29e2779c7e fix: 发票额度预警使用精确支撑天数 (#1240)
使用未舍入的可支撑天数判断 5 天阈值,并以两位小数展示。
2026-11-18 16:52:10 +08:00
5cf63f793a feat: 发票额度增加整月预测和5天预警 (#1239)
删除店铺范围和开票额度列,按当月日均推算整月开票,并在可用额度不足 5 天时预警。
2026-11-18 16:48:32 +08:00
26b9f9432b feat: 钉钉付款明细五分钟同步到动账账户 (#1238) 2026-11-18 16:39:55 +08:00
71c2e0e278 fix: 移除保留账户旧网银钱包并统一返回入口 (#1237) 2026-11-18 16:09:25 +08:00
f2181e586c fix: 防止临时报价截止日期手输时被清空 (#1236) 2026-11-18 16:07:45 +08:00
1cf6f020c5 fix: 支持明确跳过数据库迁移发布 (#1235) 2026-11-18 15:55:37 +08:00
8135bd53c8 feat: 上线账户总览与账户建档联动 (#1234) 2026-11-18 15:48:57 +08:00
69ffa43d43 feat: 发票额度读取票聚销方可用额度 (#1233)
发票额度改为读取票聚销方管理的最新可用额度,并每 15 分钟同步共享镜像。
2026-11-18 15:35:10 +08:00
33aa492f7b feat: 完善动账明细修改和删除操作 (#1232)
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-11-18 15:06:46 +08:00
a2fbc66fb7 fix: 部门负责人只取店铺账号资料 (#1231) 2026-11-18 14:52:04 +08:00
627216f43e feat: 美化内部转账并增加账户模糊筛选 (#1230)
内部转账弹窗采用统一黑金布局,转入转出账户支持模糊筛选与余额提示。
2026-11-18 14:36:44 +08:00
3a298ae3b4 fix: 移除公司成本安排侧栏入口 (#1229) 2026-11-18 14:13:08 +08:00
f106ef988d feat(发货数据): 按报价管理的报价核算运费,结果显示在发货数据页面 (#1228)
从 2026-11-01 起,按发货日在报价管理里生效的报价版本(与报价管理「当前生效」同一判断:未作废、
已审核/签署生效、执行期间覆盖发货日,取执行日期最新)逐包裹核算运费,写入 jst_oms_shipping_freight。
- 结算重量:实称>线上>重量;按各快递计泡系数取 max(重量, 长×宽×高÷系数);免抛仓(含「配件」仓)不计泡、不收多件费;
  超长费计入,其他附加费不计;城市单独报价、整省「X元/公斤」、洞洞板 9000、个别版本系数等按 10 月逐单核对的口径;
- 计算引擎移植自 10 月离线核算脚本,10 月 29.5 万个包裹逐单比对结果一致(仅 x.xx5 边界按正确四舍五入进位);
- 发货数据同步完成后核算该窗口;报价版本新增/作废/签署归档后按该快递从执行日期起自动重算;
- 新命令 jushuitan:calc-freight --from --to [--carrier];
- 发货数据页面/导出新增「报价核算」列:核算运费、核算-聚水潭运费、报价版本、结算重量依据、核算结算重量、
  计费重量、首重、续重/费率、面单、一口价、多件/超长加收、核算公式、核算状态(合并口径每包裹一行,明细只在第一行)。

同时修复发货数据同步 11 月起频繁失败:副本库查发货视图超时后报 20047 DBPROCESS is dead,
原重试只识别 20003/dbnextrow,整次同步失败(11-17 只同步到 62%)。现把 20047 视为可重连重试,
发货视图每批出库单由 300 降到 100。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhry6eiuwf

> 开工时标题使用 `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` 并清理任务分支
- [ ] 如涉及生产迁移、数据修复、删除、覆盖配置或部署,已另行取得对应高风险授权

Reviewed-on: #1228
2026-11-18 14:03:04 +08:00
957504ac1e fix: 修复内部转账审计字段超长 (#1227)
修复内部转账审计类型超过 `fin_ledger_edit_events.entity_type` 20 字符限制导致的事务回滚和 Server Error。

将类型缩短为 `internal_xfer_create` / `internal_xfer_delete`,并补充审计落库测试。

验证:内部转账创建、删除测试 2 项通过,38 个断言。
2026-11-18 13:51:26 +08:00
ceac04e1e0 feat: 动账明细支持手工导入并拆分行操作列 (#1226)
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-11-18 10:44:20 +08:00
bd3532e140 feat: 新增发票额度页面 (#1225)
新增票务管理发票额度页面、最新期间额度汇总、主体筛选与额度风险状态。
2026-11-17 17:51:12 +08:00
991d7350b9 fix: 精简商品成本主体字段 (#1224) 2026-11-17 15:05:25 +08:00
30316cdbc9 feat: 商品成本按主体期间匹配公司盘点 (#1223) 2026-11-17 11:50:07 +08:00
6cecd87e05 feat: 增加OA发票及出纳打款抬头 (#1222) 2026-11-17 10:47:03 +08:00
7d9f3d7bd1 fix: 兼容供应商汇总金额前导加号公式 (#1221) 2026-11-17 10:24:12 +08:00
1dbcc7794d fix: 日志统计包含当前未截止日期 (#1220) 2026-11-17 10:12:19 +08:00
264423c63f fix(顾家过账): 兼容历史索引字段旧值 (#1219)
身份校验以业务源字段为准,历史搜索索引旧值不再阻断标签导入。

验证:单元测试 5 个、47 条断言通过;生产 13,949 行业务源身份差异 0。
2026-11-17 10:11:02 +08:00
a570da3f78 feat: 钉钉审批回填发货资料并统一网点代码 (#1218) 2026-11-17 10:04:58 +08:00
03e5f78d91 feat: 增加待付款流程审批人汇总 (#1217) 2026-11-17 10:03:25 +08:00
4f694f7333 feat(顾家过账): 支持按月导入过账标签 (#1216)
按源表行序定向更新过账标签,逐行校验订单身份,仅修改过账标签与 row_hash。

验证:新增单元测试 4 个、41 条断言通过;真实 13,949 行隔离导入通过。
2026-11-17 09:57:10 +08:00
b4512c76f2 fix: 双休日加班打卡不计日志扣分 (#1215) 2026-11-17 00:06:24 +08:00
8a62fdea39 feat: 增加财务台账内部转账 (#1214)
支持一次填写生成转出和转入两条动账明细,并整组删除恢复余额。
2026-11-16 19:55:20 +08:00
424d7379df fix: 完善财务台账银行归类规则 (#1213)
补齐平安、交通、光大银行简称识别,兼容账户简称末尾数字,并增加杭州环客精确例外。
2026-11-16 19:44:39 +08:00
bf2247640e fix: 小额打款主体列兼容店铺字段 (#1212) 2026-11-16 19:38:54 +08:00
c639b351d8 fix: 修复小额打款日期翻月并补充主体税务类型
修复小额打款日历翻月,新增当前主体与税务类型列。

31 项测试、367 个断言通过。
2026-11-16 19:23:19 +08:00
ea6c7c380b fix: 完善华夏银行账户别名识别 (#1210)
补充“华夏”作为华夏银行简称,确保两字公司名的账户能通过银行和公司关键字匹配。

测试:运行中付款明细与账户匹配测试通过。
2026-11-16 19:10:10 +08:00
a7b3e051b5 feat: 接入钉钉运行中付款明细 (#1209)
运行中审批完成付款填写后进入动账明细,按账户简称、科目编码和关键字匹配账户。
2026-11-16 18:51:19 +08:00
f5371c24f3 fix: 移除账户详情页汇总卡片 (#1208) 2026-11-16 18:44:18 +08:00
81fd0465e4 feat: 精简其他账户信息并纳入独立账户 (#1207) 2026-11-16 18:32:43 +08:00
c4157ed7d5 fix: 删除银行分类余额列 (#1206) 2026-11-16 18:00:15 +08:00
125c6cb003 fix: 待办页返回账户汇总
## 变更

- 不保留账户处理待办的返回按钮改为“返回账户汇总”,目标为账户资金汇总的账户汇总页。
- 账户异常待办使用相同返回文案和目标。

## 验证

- FinanceLedgerAccountKeepTodoTest 全量通过。
- FinanceLedgerAccountStatusTest 全量通过。
- 本地实际页面验证两个按钮文案和点击跳转。
2026-11-16 17:43:34 +08:00
a03405e932 fix: 业绩明细仅展示当前主体和税务类型
业绩明细仅展示当前存续主体和税务类型,移除历史期间及公司状态等多余列。

34 项测试、369 个断言通过。
2026-11-16 17:38:14 +08:00
4be7631ae3 fix: 网商邮箱账单来源显示为邮箱 (#1203)
将网商邮箱账单内部来源代码显示为邮箱,保留原来源键用于同步和去重。
2026-11-16 17:31:02 +08:00
28e69e32ed feat(顾家过账): 增加货号品牌货号回退 (#1202)
品牌货号先按款式编码匹配,未命中再按原始货号回退;物料编号始终按原始货号匹配。
2026-11-16 17:25:26 +08:00
01ef6181d9 feat: 优化账户资金概览与待办进度
## 变更

- 将账户汇总收敛为账户数、资金概览和待办处理进度。
- 本期资金与当前余额合并到一个弹窗,展示银行余额条形图和四列明细。
- 银行明细按所属银行、当前余额、可用金额、不可用金额展示,并在表尾合计。
- 不保留账户和不可用金额账户分别使用独立进度与左右页签,不在汇总页展开待处理明细。

## 验证

- FinanceLedgerBankCategoryDialogTest:6 项通过,74 个断言。
- FinanceLedgerAccountKeepTodoTest:10 项通过,144 个断言。
- FinanceLedgerAccountStatusTest:19 项通过,338 个断言。
- FinanceLedgerFlowSummarySpreadsheetTest:6 项通过,73 个断言。
- 本地真实页面验证 1,144 个账户下的布局、页签切换和资金概览弹窗。
2026-11-16 17:23:54 +08:00
0a2646561a feat: 业绩明细按发生日期匹配主体
业绩明细按发生日期匹配店铺维度报表主体,并用公司盘点补充主体资料。

39 项测试、417 个断言通过。
2026-11-16 17:23:08 +08:00
65d37c8093 feat: 接入网商银行邮件账单自动导入 (#1199)
独立邮箱机器人读取网商银行加密账单,解密并导入财务台账。
2026-11-16 16:41:07 +08:00
8cdec97df6 style(财务台账): 紧凑账户汇总列宽与行高 (#1198)
收窄账户汇总数据来源列,并降低表格行高、下拉框和行内编辑按钮高度。
2026-11-16 16:38:27 +08:00
92554baf0f feat(财务台账): 增加数据来源未填写筛选 (#1197)
账户资金汇总数据来源筛选新增未填写选项,并准确区分空白与已维护数据。
2026-11-16 16:09:46 +08:00
c43574a92a fix(财务台账): 收窄账户汇总数据来源列 (#1196)
将账户资金汇总各页签共用的数据来源列收窄至 8rem,并让下拉框随列宽自适应。
2026-11-16 16:00:48 +08:00
6dff7620b6 feat(顾家过账): 按款式编码匹配品牌货号 (#1195)
品牌货号改为按款式编码匹配,物料编号继续按聚水潭原始货号匹配;同一款式下多个货号共享品牌货号。
2026-11-16 15:30:20 +08:00
b662a340e1 fix: 应付金额排除不涉及付款流程
应付金额只汇总待付款和已付款,不涉及付款仍可查看但不计入。

41 项测试、342 个断言通过。
2026-11-16 13:16:51 +08:00
61cfa8a3ff fix(顾家过账): 发货日期移至首列 (#1193) 2026-11-16 11:47:08 +08:00
db72543cc6 feat(顾家过账): 发货明细仅展示指定字段 (#1192)
发货明细仅渲染指定 15 个业务字段,并移除序号列;原始数据、筛选、物料和金额口径保持不变。
2026-11-16 11:36:18 +08:00
861bc4db71 fix(顾家过账): 品牌货号缺失时匹配档案货号 (#1191)
商品编码优先匹配品牌货号;缺失时按供应商档案条码回退货号;两级都缺失时保留聚水潭原货号。
2026-11-16 11:16:38 +08:00
5cf5a9bd5b feat(顾家过账): 品牌货号匹配增加货号回退 (#1190) 2026-11-16 10:48:15 +08:00
921ba9d6a3 fix: 报价执行日期统一、签署价格两位小数及变价备注编辑 (#1189) 2026-11-16 10:22:31 +08:00
bd276126c5 feat: OA审批汇总增加提交人并按等待时间排序
OA审批汇总增加提交人,并按已等待时长从短到长排列。

41 项测试、338 个断言通过。
2026-11-16 10:04:03 +08:00
395b29aaef feat(顾家过账): 按商品编码显示品牌货号 (#1187)
按商品编码匹配最新非空品牌货号,未命中保留原货号;物料编号和成本口径不变。
2026-11-16 09:43:44 +08:00
494f468b9c fix: 修正OA审批汇总图标字体资源路径 (#1186)
修正图标字体资源路径,确保审批汇总子页面不再显示英文图标名。
2026-11-16 09:41:19 +08:00
256d0ff0f2 fix: 修复OA审批汇总子页面图标与返回位置 (#1185)
审批汇总子页面加载本地图标字体,消除英文图标名,并将返回按钮移至右侧。
2026-11-16 09:31:40 +08:00
167211490b fix: 报价签署原件仅展示横向新价格并修复缺失字形 (#1184) 2026-11-16 09:31:03 +08:00
e12c9c20ec fix(部署): 聚水潭发货数据定时同步失败自动重试并留日志,晚上补拉一次 (#1183)
每晚 01:28 只跑一次 jushuitan:sync-shipping --days=3,输出丢到 /dev/null;
副本库偶发超时时整次同步失败且无记录,最近几天大量漏单(如 11-06 只同步到 43%、11-08 68%)。
- run-finance-batch.sh:发货数据同步输出含"同步失败"时自动重试(默认 3 次、间隔 5 分钟),
  每次输出写 /opt/caiwuxitong/jst-sync-shipping.log(超 5MB 轮转);只有警告不重试;
- cron 增加 21:28 再拉最近 3 天,补齐凌晨商品明细未到齐/超时漏掉的包裹。

注:BusinessMirrorScheduleTest 在 main 上已有 2 个与本改动无关的失败(compose.jiangling.yml 的
config_db 内存参数、app 服务配置断言),本次未改动。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhry6eiuwf

> 开工时标题使用 `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` 并清理任务分支
- [ ] 如涉及生产迁移、数据修复、删除、覆盖配置或部署,已另行取得对应高风险授权

Reviewed-on: #1183
2026-11-15 14:07:08 +08:00
d3532bf0da fix: 祥和中通和柏卡顺丰干配配件补发免扣款 (#1182) 2026-11-15 13:32:46 +08:00
e60095e64d feat: 临时变价支持多段执行区间并在空档恢复原报价 (#1181) 2026-11-15 11:55:50 +08:00
770ddea8a9 feat(供应商对账): 增加免登录送货确认链接 (#1180)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-15 11:36:27 +08:00
c658bbed99 feat: 增加未定价账期汇总与导出 (#1179)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-15 11:28:34 +08:00
cad98ba3e9 fix: 开放历史未定价批次命令入口 (#1178)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-15 10:56:25 +08:00
632e661c8b fix: 报价签署自动带出快递账号并免填经办人姓名 (#1177) 2026-11-15 10:50:43 +08:00
baed64ec3d feat: 增加历史未定价当月定价批次页面 (#1176)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-15 10:44:58 +08:00
ee871dafc1 feat(供应商对账): 钉钉卡片一键确认回传财务端 (#1175)
厂家可在钉钉 AI 卡片内直接确认月度货款,确认结果签名回传并在财务端实时展示。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-15 10:01:31 +08:00
68b7e927b1 feat: 指定变价审核与撤回重提并导出横向明细 (#1174) 2026-11-15 09:44:15 +08:00
90fdf33968 feat: 未定价明细增加件数与预估金额汇总 (#1173)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-15 09:35:08 +08:00
16b6c20f73 feat: 未定价明细沿用原始表头并保留重复行 (#1172)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-14 20:58:00 +08:00
6c5088e91b fix: 修正厂家对账快递单号匹配 (#1171)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-14 17:32:51 +08:00
3ef2f4d00b fix: 提高报价变价表单参数上限 (#1170) 2026-11-14 11:23:39 +08:00
9c75c8faad fix: 报价变价按地区与重量区间横向编辑 (#1169) 2026-11-14 09:37:05 +08:00
cb6e65a6bf fix: 排班同步失败时保留成功快照 (#1168) 2026-11-13 23:03:51 +08:00
9dbabead87 feat: 快递变价指定发起和审核人员 (#1167) 2026-11-13 19:36:07 +08:00
d2b3dc3f60 fix: 支付宝表格仅保留导入表字段 (#1166)
支付宝基本信息表仅展示导入表对应字段。
2026-11-13 18:56:05 +08:00
3aab35ac22 fix(财务台账): 网商银行表格仅保留导入表字段 (#1165) 2026-11-13 18:49:22 +08:00
10fd8bfdb4 feat: 支持支付宝基本信息导入 (#1164)
支持支付宝基本信息表格合并导入,并保存法人、账户类型、商户号和店铺字段。
2026-11-13 18:38:20 +08:00
4ca8685324 feat(财务台账): 重做网商银行基本信息页并支持表格导入 (#1163) 2026-11-13 18:20:47 +08:00
c21a622a16 fix: unify reconciliation table amount units
Move 万元 units into the table headers and show numeric cells without repeated unit suffixes.
2026-11-13 17:51:52 +08:00
5645021f89 fix: 完善期末余额核对筛选与趋势展示
Improve filter feedback, review-state counts, time-scaled trend dates, and page heading hierarchy.
2026-11-13 17:37:23 +08:00
097525a6ca fix(财务台账): 修正银行分类余额排序脚本 (#1160) 2026-11-13 15:47:20 +08:00
fa2cfe32e1 fix(财务台账): 银行分类表格居中并支持余额排序 (#1159)
- 表格居中对齐\n- 余额列支持排序
2026-11-13 15:36:07 +08:00
8b9349282f fix(财务台账): 对齐银行分类数量表格 (#1158)
- 表头和数据统一对齐\n- 增加固定列宽和纵向辅助线
2026-11-13 15:25:27 +08:00
e9302ee420 feat: OA流程筛选选择后自动查询
筛选下拉和当前审批人选择后自动查询。
2026-11-13 15:03:39 +08:00
90a0466220 feat(财务台账): 增加银行分类数量弹窗和账户来源维护 (#1156)
- 增加银行分类数量弹窗与保留状态统计\n- 账户分类页增加是否保留列\n- 数据来源统一为手动/银企直连
2026-11-13 14:43:58 +08:00
4592ad5b74 fix: 报价确认单甲方跟随签署主体并补齐表头字形 (#1155) 2026-11-13 14:21:56 +08:00
efa4193fbd feat: OA流程付款状态直接筛选已付款
移除包含已付款审批开关,付款状态直接筛选待付款和已付款。
2026-11-13 14:04:52 +08:00
f71fa8f669 fix: 已付清审批按付款合计排除 2026-11-13 13:23:33 +08:00
6fc87fbf24 feat: OA 审批汇总增加进入时间 2026-11-13 12:08:57 +08:00
31ef152cc9 fix: 精简财务台账账户视图与旧网银钱包表头 (#1151)
移除动账明细重复账户导航,并增加旧网银钱包专用空表表头。
2026-11-13 11:24:11 +08:00
f78149e630 feat(种菜报销): 接入钉钉群机器人(取消通知 @ 发起人、每天 10:25 推送汇总),看板职级为空改为取消 (#1150)
- 工作台新增「钉钉机器人设置」:Webhook、加签密钥加密存公司设置,页面不回显;支持自定义关键词、汇总单独发群、@ 报销人花名
- 核对后点「发取消通知到钉钉群」:按发起人一人一条,按钉钉花名册(花名 → userid)@ 发起人;同一批已发过的不重复发,可勾选重发
- 新增 planting-reimbursement:daily-digest,每天 10:25(宿主机 cron)生成当天批次,把待核对条数/金额、可报销合计、取消/待复查数、自检结果和工作台链接推到群里;数据停更或看板未上传会提醒
- 种菜监控看板提示「职级为空」的单改为取消工单,群通知原因写「职级为空」(2026-11-13 报销人确认)
- 没上传花名册时,收款人在职改按钉钉花名册在职真名判断;两边都取不到时不做该项校验并提示,避免误判
涉及:只读聚工单镜像与钉钉花名册副本;钉钉群机器人发消息;不涉及迁移,不写聚工单。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
2026-11-13 11:15:04 +08:00
2a2c009453 fix: 财务台账网银钱包更名为旧网银钱包 (#1149)
将财务台账账户基本信息中的网银钱包统一更名为旧网银钱包。
2026-11-13 11:02:43 +08:00
c330f35b13 fix: OA 待处理页面默认排除已付款审批 2026-11-13 11:00:03 +08:00
81ef31a657 fix: 独立账户页只展示所选账户类型 (#1147)
独立账户页移除账户类型切换栏,只展示通过卡片进入时所选的账户类型。
2026-11-13 10:23:55 +08:00
45dade3c26 feat: 账户基本信息类型卡片改为独立页面 (#1146)
将五类账户基本信息的详情入口改为独立页面,复用现有账户筛选和编辑能力。
2026-11-13 10:12:52 +08:00
b4783ae528 fix: 缺少发起身份时拒绝按错误主体推送易签宝 (#1145) 2026-11-13 09:57:51 +08:00
8fb8d9487b fix: 隐藏财务台账账户总表主标签 (#1144)
隐藏账户总表主标签,默认进入账户资金汇总,并保留账户资料入口与表头功能。
2026-11-13 09:41:17 +08:00
16e45407b2 feat: 供应商负数预警调整情况说明并增加公司承担金额 (#1143)
将供应商负数预警中的负数原因显示改为情况说明,并在其后增加公司承担金额字段。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-13 09:36:58 +08:00
b66ccf1c43 fix: 统一 OA 主页面应付与实际付款口径 2026-11-13 09:28:59 +08:00
4c3d382633 fix: 将账户基本信息移入账户资金汇总 (#1141)
将账户基本信息卡片索引迁入账户资金汇总,并移除账户总表中的入口。
2026-11-12 19:09:54 +08:00
951e553fae feat(种菜报销): 新增种菜报销工作台,逐单校验并生成打款明细与钉钉流程明细 (#1140)
- 种菜数据汇总新增「种菜报销工作台」:按聚工单锁单口径取单(待处理 WAIT_CONFIRM、付款 D-7~D-1、ERP订单状态非取消/删除/空、售后单号为空;可切换处理中 CONFIRMING 和付款起始日),逐单校验重复报销、金额公式、佣金资格、收款人在职、以旧换新买家实付(取买家实付/看板订单实付中最低,查不到标签的待复查)、看板超额(同日按付款先后报到日限额)与看板未匹配
- 导出前须勾选「已在聚工单核对条数和金额一致」;页面给出应核对的条数/金额、各口径合计自检,聚工单镜像停更超过 20 分钟时提示先别报销
- 页面给出可报销合计(三大天猫/其他)、钉钉「种菜报销流程」明细行、按发起人的发群通知与取消清单
- 导出种菜对账、种菜报销明细(打款卡号明细表)、聚工单种菜任务工单导入模版,格式对齐手工文件
- 财务可上传种菜监控看板、报销佣金人员、花名册在职、店铺信息;名单存 storage 持久卷 JSON,花名册只存姓名
- 聚工单镜像读取补充 ERP订单标签、待报销工单和已报销订单查询
涉及:只读聚工单镜像;不涉及迁移、上游写入、钉钉和聚工单写操作。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
2026-11-12 18:54:21 +08:00
9831df1ef5 feat: add account type cards and unified account tabs
Adds the account basic information card index, five account type cards, and unified account navigation pages.
2026-11-12 18:31:12 +08:00
bd0b1dd6f4 fix: 同一人每日日志只计一条 (#1138) 2026-11-12 17:59:35 +08:00
76407ae5e5 fix: 每人每天只关联一条超时补交日志 (#1137) 2026-11-12 17:32:07 +08:00
e875656c66 fix: 隐藏供应商应付表打款明细列 (#1136)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-12 15:44:30 +08:00
eb983ecf76 fix: 抵消对账明细同采购单同条码假差异 (#1135)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-12 11:12:29 +08:00
6b40bb3e36 fix: period balance reconciliation blank page
Fix undefined signedWan template method and add regression coverage.
2026-11-12 10:30:50 +08:00
f9f92ec65c fix: 未定价差异按条码汇总展示
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-12 09:55:27 +08:00
52ff4999d1 fix: 支持快递差异与未定价批量推送
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-12 09:34:59 +08:00
474866b5f8 fix: 区分 OA 审批应付金额与实际付款 2026-11-12 09:25:52 +08:00
ad6ce5ddf4 fix: 最晚出账时间改取供应商不合作流程 (#1130)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-12 09:07:03 +08:00
7aca023c63 fix: 仅将 OA 审批单数入口改为汇总子页面 2026-11-11 23:28:30 +08:00
87845baa01 fix: 最晚出账时间改为按供应商简称匹配 (#1128)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-11 21:15:59 +08:00
eb078cf4ee fix: 修正负数预警最晚出账时间匹配 (#1127)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-11 21:07:58 +08:00
8563a3f635 fix: 允许多个货号共用物料编号 (#1126)
增加品牌SKU到报价单物料编号的回退匹配,同一物料编号可被多个货号共用。
2026-11-11 20:52:48 +08:00
886f66293b perf: extend reconciliation cache ttl
Extend summary and trend cache lifetime to thirty minutes.
2026-11-11 20:51:43 +08:00
b1e4eb3c72 perf: cache period balance reconciliation
Cache summary and trend responses for five minutes by company and date.
2026-11-11 20:41:12 +08:00
a1498e6134 feat: 负数预警增加最晚出账单时间 (#1123)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-11 20:39:09 +08:00
c41681284a fix: 修复 OA 审批汇总页路由缓存 500 2026-11-11 20:31:13 +08:00
2ef723e38d fix: 修正数据来源审计类型长度 (#1121)
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-11-11 20:23:25 +08:00
b38d3e5b30 fix: 超时日志排除请假免提交日期 (#1120) 2026-11-11 20:22:38 +08:00
2d5da83780 fix: preserve reconciliation financial summary
Restore the existing financial overview totals while keeping lazy trend loading.
2026-11-11 20:21:00 +08:00
45b88d1528 feat: distinguish duplicate financial account short names
Shows duplicate account short names with stable numeric suffixes in the account directory and account flow summary.
2026-11-11 20:11:15 +08:00
27021ce55a feat: 顾家发货明细补齐物料与成本 (#1117)
按货号同步唯一物料编号,并从顾家报价单带出物料描述和含税成本,按实发数量计算发货金额。
2026-11-11 20:08:21 +08:00
59485b99f2 fix: period balance reconciliation performance
Separate trend loading, aggregate summary from store balances, and cap trend queries to five representative dates.
2026-11-11 19:57:36 +08:00
f4f0d5d7b1 feat: 同步账户资金汇总并新增数据来源 (#1114)
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-11-11 19:50:50 +08:00
c34175c3d1 fix: 发货明细型号表头改为物料描述 (#1115)
物料描述作为型号字段的显示表头,数据来源与顺序保持不变。
2026-11-11 19:50:09 +08:00
0f65cb124b feat: 供应商负数预警支持导出和未回传筛选 (#1113)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-11 19:49:44 +08:00
d88d318e6c 完善服务公司店铺配置与合同附件 (#1112) 2026-11-11 19:46:45 +08:00
be1eabfd16 feat: add Wangshang bank to account flow summary
Adds a separate Wangshang bank view to account flow summary and excludes Wangshang accounts from the bank-account view.
2026-11-11 19:36:25 +08:00
739fff215a feat: period balance reconciliation
Add the period balance reconciliation page, permissions, financial closing balances, Jushuitan snapshots for Taobao Alipay, Pinduoduo and Douyin, and explicit unavailable states.
2026-11-11 19:33:39 +08:00
ecf5b36217 feat: 顾家发货明细增加过账标签 (#1109)
在款式编码后增加过账标签,并更新列偏好版本与相关测试。
2026-11-11 19:29:42 +08:00
31d66ff89f feat: split Alipay and Wangshang account tabs (#1108) 2026-11-11 19:24:13 +08:00
1e69ca883d feat: 日志统计增加超时日志数量 (#1107) 2026-11-11 19:16:11 +08:00
daca32926d feat: 调整顾家发货明细新增表头 (#1106)
feat: 调整顾家发货明细新增表头 (#1106)
2026-11-11 19:14:44 +08:00
d6fe74ad1e fix: 日志统计固定使用中国时区 (#1105)
合并 PR #1105:日志统计统一使用 Asia/Shanghai,修复页面扣分日期滞后。
2026-11-11 18:56:53 +08:00
4743506504 feat: 顾家发货明细支持列宽调整 (#1104)
顾家发货明细增加默认列宽、拖拽调整和用户宽度记忆。
2026-11-11 18:49:16 +08:00
edb0e6c721 fix: 自动重试钉钉日志接口瞬时失败 (#1103)
合并 PR #1103:钉钉日志系统繁忙和远程超时自动退避重试。
2026-11-11 18:41:53 +08:00
aa44afe52a feat: 按聚水潭导出表头展示顾家基础数据 (#1102)
顾家基础数据按聚水潭导出表头展示,并跳过订单状态已取消。
2026-11-11 18:33:08 +08:00
7363d01cb2 fix: 比例展示去掉无意义尾零
比例页面显示为 1.5%。
2026-11-11 18:08:56 +08:00
83ffec8d57 fix: 自动分配严格按主体维度报表收入
自动分配改用主体报表口径并支持错误来源校正。
2026-11-11 18:02:44 +08:00
27b8610ef2 fix: 钉钉差异推送展示采购单明细
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-11 17:59:09 +08:00
6a722a98c6 fix: 登记客服公司映射批处理导入
登记客服公司映射导入命令到批处理白名单。
2026-11-11 17:57:54 +08:00
9bd3778c8f fix: 优化服务公司名称首列布局 (#1097)
修复公司名称竖向换行和行高异常。
2026-11-11 17:51:35 +08:00
00728c5212 feat: 固定客服公司映射并自动平衡未分配店铺 (#1096)
固定已有映射,收入店铺自动平衡后锁定。
2026-11-11 17:45:18 +08:00
65a7da66f0 feat: 接入客服公司店铺映射与主体报表收入 (#1095)
导入客服公司店铺映射,主体报表收入字段改名并默认隐藏。
2026-11-11 17:39:54 +08:00
9a162b3f0a fix: 余额总览排除支付宝前缀店铺
账户余额总览排除淘系支付宝中以支付宝开头的店铺,并保持明细口径一致。
2026-11-11 17:33:51 +08:00
fd07bbba7e fix: 压缩服务公司列表首列宽度 (#1093)
公司名称首列收紧至 190px,减少前端空白。
2026-11-11 17:30:15 +08:00
c93cb2db96 fix: 显示供应商对账差异来源采购单
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-11 17:29:04 +08:00
65c774a836 fix: 服务公司总览展示结算比例并收紧首列 (#1091)
总览改为百分比展示并压缩公司名称列宽。
2026-11-11 17:25:42 +08:00
a5c536f9dd feat: 固定客服服务公司结算比例 (#1090)
客服服务公司结算比例固定为 1.5%,后端同步校验。
2026-11-11 17:22:14 +08:00
11c506af89 feat: 汇总 OA 流程审批并增加详情页 2026-11-11 17:18:04 +08:00
c750f3c09b fix: 对齐服务公司对账字段名称 (#1088)
服务公司对账列名对齐公司盘点字段。
2026-11-11 17:11:23 +08:00
89a7ee4d3a feat: 服务公司对账自动同步公司盘点 (#1087) 2026-11-11 17:05:58 +08:00
868a1ec403 fix: 展示全部收款平台名称
账户余额总览说明中列出全部 8 个收款平台。
2026-11-11 16:56:50 +08:00
59a9d5bf58 feat: 落地服务公司对账配置与月度预览 (#1085) 2026-11-11 16:34:26 +08:00
e5faacd2bf fix: 删除月度期末余额汇总卡片
删除账户余额总览中的月度汇总卡片、切换、接口及关联代码。
2026-11-11 16:09:08 +08:00
dde4531ff4 feat: show bank affiliation in account directory (#1083) 2026-11-11 15:53:40 +08:00
178bf2840f feat: 主体报表接入公司盘点税务工商类型 2026-11-11 15:36:16 +08:00
11db14c758 feat: 更名服务公司对账并补充配置方案 (#1081) 2026-11-11 15:28:53 +08:00
1f2ac85ab4 fix: remove next action column from account directory (#1080) 2026-11-11 15:16:50 +08:00
0fbbae4b97 feat: 经营报表新增独立公司对账入口 (#1079) 2026-11-11 14:54:56 +08:00
c5a525695b feat: 新增顾家对账菜单 (#1078)
在顾家过账下新增顾家对账页面,并提供八个横向本地页签。
2026-11-11 14:51:48 +08:00
afd6d1ab69 fix: 精简账户总表冗余提额列 (#1077) 2026-11-11 14:50:26 +08:00
bad13f90c5 feat: 账户总表增加银行账户与非店铺账户视图 (#1076) 2026-11-11 14:30:35 +08:00
d512e5d9ba feat: 主体报表接入上月店铺结算收入 (#1075)
新增动态上月店铺结算收入列。
金额取业绩明细收入金额,按店铺日汇总和主体期间拆分后汇总。

验证:36 项测试、277 个断言通过。
2026-11-11 14:21:33 +08:00
6a1a718e89 fix: 精简顾家报价单页面重复信息 (#1074)
移除顾家报价单红框内的来源信息、标题说明和只读镜像提示,保留筛选、表格和分页。
2026-11-11 14:16:19 +08:00
e5e11a25cb fix: 月度期末余额按发生时间仅展示单月
移除 7-9 月历史列和环比列,按发生时间结束日期所在月份读取平台及店铺汇总。
2026-11-11 14:11:58 +08:00
394a6838d3 feat: 拆分银行账户与非店铺账户汇总视图 (#1072)
账户资金汇总新增银行账户和非店铺账户视图;支付宝类账户归入非店铺账户,其余账户归入银行账户,并对各视图独立汇总与编辑。
2026-11-11 14:08:41 +08:00
4e76f76b71 fix: 供应商对账识别未定价行 (#1067)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-11 13:24:09 +08:00
c32dbe57b2 feat: 接入顾家报价单导入 (#1070)
feat: 接入顾家报价单导入 (#1070)
2026-11-11 13:20:51 +08:00
6cf43d10ae feat: 按天保留系统化待办操作记录 (#1069) 2026-11-11 11:03:39 +08:00
fcfc401eff fix: 财务系统仅允许钉钉账号登录 (#1068)
登录页仅保留钉钉入口;停用密码、找回密码、重置密码和邀请注册登录;旧密码会话立即失效。
2026-11-11 11:02:49 +08:00
0754045003 feat: 为系统化待办增加晨曦删除权限 (#1066) 2026-11-11 09:50:25 +08:00
80aa79ddc4 feat: 增加系统化待办逾期待办弹窗 (#1057) 2026-11-11 09:30:37 +08:00
78f3bbb2a1 feat: 支持账户资金汇总新增行和列 (#1064)
账户资金汇总支持新增账户行和自定义列;自定义列可逐账户填写、自动保存、左右插入和删除,并使用独立镜像表持久化。
2026-11-10 22:00:41 +08:00
b959cef955 feat: 支持账户资金汇总直接编辑每日流水 (#1063)
账户资金汇总新增逐行编辑入口,可直接选择日期打开每日流水编辑;目标日期无流水时创建手动流水,并统一回算账户余额、每日流水及期间汇总。
2026-11-10 20:24:54 +08:00
1dd1985de2 feat: 支持独立账单 Excel 式插入行和列 (#1062) 2026-11-10 19:48:59 +08:00
0c92a3c567 fix: 优化灵珊店铺业绩月份查询 (#1061)
fix: 优化灵珊店铺业绩月份查询 (#1061)
2026-11-10 19:24:07 +08:00
814f9a4520 feat: 汇总灵珊店铺月度收入 (#1060)
feat: 汇总灵珊店铺月度收入 (#1060)
2026-11-10 19:19:34 +08:00
87292e7959 feat: 开放独立账单明细完整编辑 (#1059) 2026-11-10 19:17:04 +08:00
6e6e3038a1 fix: 精简顾家过账发货明细页面 (#1058)
fix: 精简顾家过账发货明细页面 (#1058)
2026-11-10 19:00:14 +08:00
1c58ba0684 fix: 修复OA流程导出被通用页签路由拦截 (#1057) 2026-11-10 18:23:26 +08:00
0f4b7d2977 feat: 增加顾家过账基础数据子菜单 (#1056)
feat: 增加顾家过账基础数据子菜单 (#1056)
2026-11-10 18:00:37 +08:00
d803d97c19 feat: 限制系统化待办删除权限 (#1055) 2026-11-10 17:47:13 +08:00
14adc83014 fix: 使用规范店铺键匹配乐简期初 (#1054) 2026-11-10 17:26:12 +08:00
157ceadcad feat: 发票基础信息同步、店铺明细与筛选合计 (#1053) 2026-11-10 17:22:07 +08:00
e0c57cfafd fix: 快递入驻按自动分支发起并支持已开通失败单补发 (#1051) 2026-11-10 17:19:35 +08:00
c9f84ccea9 fix: 系统化待办创建时间按上海时区显示 (#1052) 2026-11-10 17:18:23 +08:00
778 changed files with 129703 additions and 8324 deletions

View File

@ -10,6 +10,7 @@ runtime
*.md
JetBrainsMono-字体
node_modules
outputs
**/__pycache__
vendor
bootstrap/cache/*
@ -27,6 +28,7 @@ storage/framework/testing
storage/logs/*
tests
test-data
tmp
docs
scripts
npm-debug.log

1
.gitignore vendored
View File

@ -109,6 +109,7 @@ modules/*
# 本地私有配置、账号密码和敏感信息文档;禁止使用 git add -f 强制提交。
/runtime/private/敏感信息.md
/runtime/
/tmp/
/.caiwu-build/
.workbuddy/
runtime/.env

View File

@ -57,13 +57,14 @@
## 6. 数据、上游与敏感信息
- 生产网页、后台任务、数据同步和上游网络通道必须运行在服务器或公司管理的固定网络设施上,禁止依赖个人开发机的常驻进程、登录状态或开机状态。生产服务器无法直连上游时,先修复网络或使用公司固定网关,不得在开发机安装生产中继。
- 密码、Token、SSH 私钥、数据库连接串、真实财务数据和生产日志不得进入 Git、PR 或公开文档。
- 需要长期保存的敏感信息写入被 Git 忽略的 `runtime/private/敏感信息.md`;写入前用 `git check-ignore` 确认。负责人明确要求时,可在当前一对一对话提供指定范围的敏感信息,但不得扩大传播。
- 本任务所需的上游只读排查、数据字典刷新、数据集登记和启用、共享镜像建表及索引迁移、首次全量、增量、历史回补和镜像校准,由开发者的 Codex 自主完成,无需负责人逐次授权或代执行。Codex 自行核对来源与范围、备份受影响的配置/镜像及同步状态,使用生产同步节点和现有互斥锁分批执行,并核对源数据、完成状态与真实页面;不把这些工作转交给新人。可从上游重建的镜像修复属于此范围;上游写入、原始业务/财务数据修改、无关数据删除、凭据轮换和覆盖生产连接配置仍需单独授权。
- `caiwu_system_config` 保存用户、权限、设置、连接资料、数据字典和同步状态;`caiwu_business_mirror` 保存项目已正式接入的上游业务数据。二者不是 SQL Server 网络代理。
- 上游数据库统一按只读黑盒处理。业务查询使用固定、参数化的 Repository/查询执行器,禁止把用户输入拼成 SQL 或执行写操作。
- 正式页面优先读取共享业务镜像;尚未迁移的旧页面可继续使用现有快照兼容层。接入新数据时沿用现有镜像数据集、稳定游标、断点同步和同步状态模式,不另造一套链路。
- 两个现有来源固定为:`jiansun` 对应 `JianSun` 旧业务库;`operations_replica` 对应 `JSReportReplica` 的 `rpt` 只读视图。不得交换来源或写回历史临时库名。
- 当前使用 `operations_replica` 对应 `JSReportReplica` 的 `rpt` 只读视图。`jiansun`(`JianSun` 旧业务库)和 `js_data_middle_platform` 已退役,保留已有镜像与历史标识,不再自动开启连接或恢复其专属同步。新增来源不得复用退役标识或交换来源含义。
- 只有涉及上游接入、镜像同步、数据字典或生产刷新时,才读取 `docs/开发与部署SOP.md` 第 8 节及 `docs/上游业务镜像清单.md`。
## 7. 新人本地开发

View File

@ -1,6 +1,10 @@
# CaiWuXiTong 本地测试环境
本说明用于开发者在自己的电脑上启动项目。项目使用 Docker,默认访问地址为:
本说明用于开发者在自己的电脑上启动项目。项目使用 Docker。
本地环境只用于开发、测试、构建和发布。生产取数和后台任务不得依赖本机常驻服务;上游网络问题应在生产服务器或公司固定网络设施解决,不安装开发机中继。
默认访问地址为:
```text
http://127.0.0.1:18088
@ -54,6 +58,8 @@ bash deploy/local-init.sh
这个账号只存在于本机临时数据库中。系统数据库切换完成后,请使用系统数据库里属于自己的账号登录,不要继续把临时账号当作团队共享账号。
`local-init.sh` 会在本机 `runtime/.env` 写入 `AUTH_PASSWORD_LOGIN_ENABLED=true`,仅用于私有开发库和自动登录助手。代码默认关闭这一开关,并且配置层只允许 `APP_ENV=local` 时生效;正式环境始终只开放钉钉登录。已有开发机拉取本次代码后需重新执行一次 `bash deploy/local-init.sh`。
初始化中断后,Codex 直接重新执行 `bash deploy/local-init.sh`。脚本会根据 Dockerfile、依赖锁文件、前端源码和静态资源生成镜像指纹:输入未变化时复用镜像,发生变化或缺少必要静态资源时自动重建,并从数据库初始化阶段继续。`--build` 只用于强制重建;`--skip-build` 仅允许镜像指纹和静态资源均已通过校验时使用。
拉取新代码后再次运行该脚本时,本机临时引导库会自动更新;连接团队共享系统数据库后,这项自动更新会安全跳过。普通开发者任何时候都不需要执行 `php artisan migrate`,也不得对团队共享系统数据库自行迁移。
@ -135,10 +141,10 @@ docker compose -f docker-compose.local.yml exec -u www-data app php artisan app:
docker compose -f docker-compose.local.yml exec -u www-data app php artisan test --do-not-cache-result
# 停止容器,但保留本地数据
docker compose -f docker-compose.local.yml stop
docker compose -f docker-compose.local.yml --profile dev stop
# 再次启动
docker compose -f docker-compose.local.yml start
docker compose -f docker-compose.local.yml up -d app mysql
```
不要执行 `docker compose down -v`、删除数据库卷或强制迁移。确需重置本地临时库时,先确认不会影响当前系统数据库配置并找负责人或 Codex处理。
@ -147,7 +153,7 @@ docker compose -f docker-compose.local.yml start
- PHP、配置、模块、页面模板和路由目录已经挂载到容器;开发环境关闭 PHP OPcache 和 Blade 编译缓存,刷新浏览器即可加载最新源码,无需重启 PHP 服务;
- 开发环境启动时只执行 `optimize:clear`,不会生成 Laravel 的配置、路由或视图缓存;生产环境仍保留原有缓存构建机制;
- 本地 Compose 会同时启动 `frontend` watcher。修改 `resources/assets` 下的 Vue、JavaScript 或 SCSS 后,Laravel Mix 会通过轮询自动重新编译,Apache 使用共享静态资源卷提供最新文件;浏览器刷新即可看到结果。
- 普通初始化只启动 PHP 和 MySQL,前端自动编译通过 `dev` profile 按需启动,见下一节。
- 如果 watcher 构建失败,查看 `docker compose -f docker-compose.local.yml logs -f frontend`;修复源码后它会继续监听并重新编译。
- Composer 依赖、前端依赖、Dockerfile 或构建资源发生变化时,重新执行 `bash deploy/local-init.sh`,脚本会自动重建;
- 修改 `runtime/.env` 后,执行:
@ -157,7 +163,31 @@ docker compose -f docker-compose.local.yml restart app
docker compose -f docker-compose.local.yml exec -u www-data app php artisan optimize:clear
```
停止本地环境时,`app`、`frontend` 和 `mysql` 会一起停止;再次运行初始化脚本会恢复 PHP 服务和前端 watcher。
停止本地环境时保留数据卷;再次运行初始化脚本会恢复 PHP 和 MySQL,并停止已有的前端 watcher。
## 前端自动编译与空闲 CPU
使用 Docker Compose 2.32 或更新版本。源码仍在 Windows 的项目目录编辑,Compose Watch 使用宿主机文件事件,将 `resources/assets`、`resources/views` 和 `resources/lang` 的变更同步到前端容器的 Linux 文件系统。Laravel Mix 在容器内使用 inotify;`node_modules` 留在镜像中,`public` 和 `storage` 保持现有 named volume。Webpack 不监听依赖、产物、存储和 vendor 目录。
```powershell
# 网页开发:初始化并启动 PHP/MySQL,不启动前端 watcher
bash deploy/local-init.sh
# 需要自动编译 Vue、JS、CSS 或模板中的 Tailwind 类名时,前台运行
docker compose -f docker-compose.local.yml --profile dev up --watch frontend
# 结束前端开发:在上述终端按 Ctrl+C;也可以显式停止 watcher
docker compose -f docker-compose.local.yml stop frontend
# 停止本地网页与 watcher,保留 MySQL 运行和全部数据卷
docker compose -f docker-compose.local.yml stop app frontend
```
首次启动会编译一次,之后只有源码变更才重新构建;Apache 通过共享的 `jiangling_public` 卷提供新产物,刷新浏览器即可使用。`frontend` 的重启策略是 `no`,不会随 Docker 重启自动运行。普通 `docker compose up -d` 不会启动 `dev` profile;初始化也不会留下旧的轮询 watcher。
Windows bind mount 经过 Docker Desktop/WSL2 的 9P 文件共享。高频 poll 会反复请求文件元数据,即使没有编辑也会使宿主机 `dllhost.exe` 中的 `vp9fs.dll` 和 `vmmemWSL` 持续占用 CPU。默认 watcher 因此不再使用 poll;手动兼容命令 `npm run watch-poll` 保留为 5 秒间隔,不作为 Windows 的日常开发入口。
变更依赖、Webpack/Tailwind 配置或切换分支后,结束 watch 会话并运行 `bash deploy/local-init.sh`,再启动前端自动编译。原生监听与同步只用于本地开发,不改变生产 Compose 或正式构建流程。
## 相关文档

View File

@ -19,6 +19,8 @@ Codex 的接入验收不能只回答“成功”或“失败”,必须逐个
完整步骤和排错说明见 [LOCAL_DEPLOY.md](LOCAL_DEPLOY.md)。需要在另一台电脑继续开发时,按 [新电脑开发接续指南](docs/新电脑开发接续指南.md) 操作;所有 Markdown 文档的入口见 [文档索引](docs/README.md)。
前端自动编译按需运行 `docker compose -f docker-compose.local.yml --profile dev up --watch frontend`。Windows 源码通过文件事件同步到容器内的 Linux 文件系统,再由 Laravel Mix 原生监听;不要对 Windows bind mount 目录开启高频轮询,它会持续扫描 9P 文件共享并占用宿主机 CPU。日常仅启动网页时不运行 watcher,具体启停命令见 [本地开发说明](LOCAL_DEPLOY.md#前端自动编译与空闲-cpu)。
## 数据库边界
- 本机 MySQL 只负责第一次启动和临时登录,不是团队业务数据源。

View File

@ -0,0 +1,28 @@
<?php
namespace App\Business\ActualTax;
use Illuminate\Http\Request;
class ActualTaxPageData
{
public function page(Request $request): array
{
$columns = array_values((array) config('actual_tax.columns', []));
$groups = [];
foreach ($columns as $column) {
$label = (string) ($column['group'] ?? '其他');
$groups[$label] ??= ['label' => $label, 'columns' => []];
$groups[$label]['columns'][] = $column;
}
return [
'view' => 'business.pages.company-management.actual-tax',
'actualTax' => app(ActualTaxRepository::class)->page($request),
'actualTaxColumns' => $columns,
'actualTaxGroups' => array_values($groups),
'actualTaxSource' => (array) config('actual_tax.source', []),
];
}
}

View File

@ -0,0 +1,234 @@
<?php
namespace App\Business\ActualTax;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Support\Facades\Schema;
class ActualTaxRepository
{
public const TABLE = ActualTaxWorkbookImporter::TABLE;
public const PER_PAGE = 50;
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $databases)
{
$this->connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
public function ready(): bool
{
return Schema::connection($this->connection->getName())->hasTable(self::TABLE);
}
/**
* @return array{
* rows:LengthAwarePaginator,
* filters:array<string,string>,
* options:array<string,array<int,mixed>>,
* summary:array<string,int|float|null>,
* imported_at:mixed,
* source_file:?string,
* ready:bool
* }
*/
public function page(Request $request): array
{
$filters = $this->filters($request);
if (! $this->ready()) {
return [
'rows' => new Paginator([], 0, self::PER_PAGE, 1, [
'path' => $request->url(),
'query' => $request->query(),
]),
'filters' => $filters,
'options' => $this->emptyOptions(),
'summary' => $this->emptySummary(),
'imported_at' => null,
'source_file' => null,
'ready' => false,
];
}
$query = $this->filteredQuery($filters);
$summary = $this->summary($query);
$sortable = array_values(array_map(
static fn (array $column): string => (string) $column['field'],
array_filter(
(array) config('actual_tax.columns', []),
static fn (array $column): bool => ($column['sortable'] ?? true) !== false,
),
));
$sort = (string) $request->query('sort', '');
$sort = in_array($sort, $sortable, true) ? $sort : '';
$direction = strtolower((string) $request->query('direction', 'asc')) === 'desc' ? 'desc' : 'asc';
if ($sort !== '') {
$query->orderBy($sort, $direction);
} else {
$query->orderByDesc('period')->orderBy('sort_order');
}
$query->orderBy('id');
$rows = $query->paginate(
self::PER_PAGE,
['*'],
'page',
max((int) $request->query('page', 1), 1),
)->withQueryString();
$latest = $this->connection->table(self::TABLE)
->orderByDesc('imported_at')
->first(['imported_at', 'source_file']);
return [
'rows' => $rows,
'filters' => $filters,
'options' => $this->filterOptions(),
'summary' => $summary,
'imported_at' => $latest?->imported_at,
'source_file' => $latest?->source_file,
'ready' => true,
];
}
/**
* @return array<string,string>
*/
private function filters(Request $request): array
{
$period = trim((string) $request->query('period', ''));
if (preg_match('/^\d{6}$/', $period) !== 1) {
$period = '';
}
return [
'period' => $period,
'type' => $this->filterText($request->query('type'), 16),
'region' => $this->filterText($request->query('region'), 16),
'taxpayer_type' => $this->filterText($request->query('taxpayer_type'), 32),
'accounting_company' => $this->filterText($request->query('accounting_company'), 191),
'contact_person' => $this->filterText($request->query('contact_person'), 64),
'company_name' => $this->filterText($request->query('company_name'), 191),
];
}
/**
* @param array<string,string> $filters
*/
private function filteredQuery(array $filters): Builder
{
$query = $this->connection->table(self::TABLE);
foreach (['period', 'type', 'region', 'taxpayer_type', 'accounting_company', 'contact_person'] as $field) {
if (($filters[$field] ?? '') !== '') {
$query->where($field, $filters[$field]);
}
}
if (($filters['company_name'] ?? '') !== '') {
$query->where(
'company_name',
'like',
'%' . addcslashes($filters['company_name'], '%_\\') . '%',
);
}
return $query;
}
/**
* @return array<string,int|float|null>
*/
private function summary(Builder $query): array
{
$aggregate = (clone $query)
->selectRaw('COUNT(*) AS records')
->selectRaw('COUNT(DISTINCT company_name) AS companies')
->selectRaw('COALESCE(SUM(total_revenue), 0) AS total_revenue')
->selectRaw('COALESCE(SUM(total_tax_paid), 0) AS total_tax_paid')
->first();
$revenue = round((float) ($aggregate->total_revenue ?? 0), 2);
$tax = round((float) ($aggregate->total_tax_paid ?? 0), 2);
return [
'records' => (int) ($aggregate->records ?? 0),
'companies' => (int) ($aggregate->companies ?? 0),
'total_revenue' => $revenue,
'total_tax_paid' => $tax,
'tax_burden_rate' => $revenue > 0 ? $tax / $revenue : null,
];
}
/**
* @return array<string,array<int,mixed>>
*/
private function filterOptions(): array
{
$options = [];
foreach ([
'period',
'type',
'region',
'taxpayer_type',
'accounting_company',
'contact_person',
] as $field) {
$direction = $field === 'period' ? 'desc' : 'asc';
$options[$field] = $this->connection->table(self::TABLE)
->whereNotNull($field)
->where($field, '<>', '')
->distinct()
->orderBy($field, $direction)
->pluck($field)
->all();
}
return $options;
}
/**
* @return array<string,array<int,mixed>>
*/
private function emptyOptions(): array
{
return [
'period' => [],
'type' => [],
'region' => [],
'taxpayer_type' => [],
'accounting_company' => [],
'contact_person' => [],
];
}
/**
* @return array<string,int|float|null>
*/
private function emptySummary(): array
{
return [
'records' => 0,
'companies' => 0,
'total_revenue' => 0.0,
'total_tax_paid' => 0.0,
'tax_burden_rate' => null,
];
}
private function filterText(mixed $value, int $limit): string
{
return mb_substr(trim((string) $value), 0, $limit);
}
}

View File

@ -0,0 +1,733 @@
<?php
namespace App\Business\ActualTax;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use RuntimeException;
use XMLReader;
class ActualTaxWorkbookImporter
{
public const TABLE = 'business_actual_tax_records';
private const HEADER_ROWS = 3;
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $databases)
{
$this->connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
public function ready(): bool
{
return Schema::connection($this->connection->getName())->hasTable(self::TABLE);
}
/**
* @return array{imported:int,skipped:int,source_file:string}
*/
public function import(string $path, ?string $sourceName = null): array
{
$realPath = realpath($path);
if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) {
throw new RuntimeException('实际税金表文件不存在或不可读:' . $path);
}
if (! $this->ready()) {
throw new RuntimeException('实际税金数据表尚未创建,请先执行数据库迁移。');
}
[$rows, $skipped] = $this->readRows($realPath);
if ($rows === []) {
throw new RuntimeException('文件内没有可导入的实际税金数据。');
}
$this->assertUniqueRows($rows);
$now = Carbon::now();
$sourceFile = basename($sourceName ?: $realPath);
$this->connection->transaction(function () use ($rows, $now, $sourceFile): void {
// 链接中的“代办对接表”是完整台账,每次成功导入后整份替换。
$this->connection->table(self::TABLE)->delete();
foreach (array_chunk($rows, 200) as $chunk) {
$this->connection->table(self::TABLE)->insert(array_map(
static fn (array $row): array => $row + [
'source_file' => $sourceFile,
'imported_at' => $now,
'created_at' => $now,
'updated_at' => $now,
],
$chunk,
));
}
});
return [
'imported' => count($rows),
'skipped' => $skipped,
'source_file' => $sourceFile,
];
}
/**
* @return array{0:list<array<string,mixed>>,1:int}
*/
private function readRows(string $path): array
{
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
return match ($extension) {
'csv' => $this->readCsv($path),
'xlsx' => $this->readXlsxStreaming($path),
default => $this->readSpreadsheet($path),
};
}
/**
* @return array{0:list<array<string,mixed>>,1:int}
*/
private function readCsv(string $path): array
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('无法读取实际税金 CSV 文件。');
}
try {
$header = fgetcsv($handle);
if ($header === false) {
throw new RuntimeException('实际税金 CSV 文件没有表头。');
}
foreach ($header as $index => $heading) {
$heading = trim((string) preg_replace('/^\xEF\xBB\xBF/', '', (string) $heading));
if (str_starts_with($heading, '"') && str_ends_with($heading, '"')) {
$heading = substr($heading, 1, -1);
}
$header[$index] = $heading;
}
$columnMap = $this->flatColumnMap($header);
$rows = [];
$skipped = 0;
$line = 1;
while (($lineValues = fgetcsv($handle)) !== false) {
$line++;
$row = $this->normalizeFlatRow($lineValues, $columnMap, $line, $rows);
if ($row === null) {
$skipped++;
} elseif ($row !== []) {
$rows[] = $row;
}
}
return [$rows, $skipped];
} finally {
fclose($handle);
}
}
/**
* XLSX 使用 XMLReader 按行读取,避免把整份宽表同时装入内存。
*
* @return array{0:list<array<string,mixed>>,1:int}
*/
private function readXlsxStreaming(string $path): array
{
$zip = new \ZipArchive();
if ($zip->open($path) !== true) {
throw new RuntimeException('无法打开实际税金 XLSX 文件。');
}
$sheetTemp = null;
try {
$sheetPath = $this->resolveXlsxSheetPath($zip);
$sharedStrings = $this->readXlsxSharedStrings($zip);
$sheetTemp = $this->extractZipEntry($zip, $sheetPath);
$reader = new XMLReader();
if (! $reader->open($sheetTemp, null, LIBXML_NONET | LIBXML_COMPACT)) {
throw new RuntimeException('无法读取实际税金 XLSX 工作表。');
}
$columns = (array) config('actual_tax.columns', []);
$headerRows = [];
$rows = [];
$skipped = 0;
$lastRowNumber = 0;
$headerValidated = false;
try {
while ($reader->read()) {
if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') {
continue;
}
$rowNumber = (int) ($reader->getAttribute('r') ?: ($lastRowNumber + 1));
$lastRowNumber = $rowNumber;
$line = $this->parseXlsxRow($reader->readOuterXml(), $sharedStrings);
if ($rowNumber <= self::HEADER_ROWS) {
$headerRows[$rowNumber] = $line;
continue;
}
if (! $headerValidated) {
$this->validateStreamingHeader($headerRows);
$headerValidated = true;
}
$values = [];
foreach ($columns as $column) {
$sourceIndex = (int) ($column['source_index'] ?? -1);
if ($sourceIndex < 0) {
continue;
}
$values[(string) $column['field']] = $this->normalizeValue(
$line[$sourceIndex] ?? null,
(string) ($column['type'] ?? 'text'),
(string) ($column['label'] ?? $column['field']),
$rowNumber,
);
}
$row = $this->finalizeRow($values, $rowNumber, count($rows) + 1);
if ($row === null) {
$skipped++;
} else {
$rows[] = $row;
}
}
} finally {
$reader->close();
}
if (! $headerValidated) {
$this->validateStreamingHeader($headerRows);
}
return [$rows, $skipped];
} finally {
if ($sheetTemp !== null && is_file($sheetTemp)) {
@unlink($sheetTemp);
}
$zip->close();
}
}
/**
* @return list<string>
*/
private function readXlsxSharedStrings(\ZipArchive $zip): array
{
$entry = 'xl/sharedStrings.xml';
if ($zip->locateName($entry) === false) {
return [];
}
$temp = $this->extractZipEntry($zip, $entry);
$reader = new XMLReader();
if (! $reader->open($temp, null, LIBXML_NONET | LIBXML_COMPACT)) {
@unlink($temp);
throw new RuntimeException('无法读取实际税金 XLSX 共享字符串。');
}
$strings = [];
try {
while ($reader->read()) {
if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'si') {
continue;
}
$node = simplexml_load_string(
$reader->readOuterXml(),
\SimpleXMLElement::class,
LIBXML_NONET | LIBXML_COMPACT,
);
if ($node === false) {
continue;
}
$texts = $node->xpath('.//*[local-name()="t" and not(ancestor::*[local-name()="rPh"])]') ?: [];
$strings[] = implode('', array_map(
static fn (\SimpleXMLElement $text): string => (string) $text,
$texts,
));
}
} finally {
$reader->close();
@unlink($temp);
}
return $strings;
}
/**
* @param list<string> $sharedStrings
* @return list<string|null>
*/
private function parseXlsxRow(string $rowXml, array $sharedStrings): array
{
$line = array_fill(0, 79, null);
$row = simplexml_load_string(
$rowXml,
\SimpleXMLElement::class,
LIBXML_NONET | LIBXML_COMPACT,
);
if ($row === false) {
return $line;
}
$cells = $row->xpath('./*[local-name()="c"]') ?: [];
$nextColumn = 0;
foreach ($cells as $cell) {
$reference = (string) ($cell['r'] ?? '');
$columnIndex = $nextColumn;
if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) === 1) {
$columnIndex = Coordinate::columnIndexFromString(strtoupper($matches[1])) - 1;
}
$nextColumn = $columnIndex + 1;
if ($columnIndex >= count($line)) {
continue;
}
$type = (string) ($cell['t'] ?? '');
$value = '';
if ($type === 'inlineStr') {
$texts = $cell->xpath('.//*[local-name()="t" and not(ancestor::*[local-name()="rPh"])]') ?: [];
$value = implode('', array_map(
static fn (\SimpleXMLElement $text): string => (string) $text,
$texts,
));
} else {
$values = $cell->xpath('./*[local-name()="v"]') ?: [];
$value = isset($values[0]) ? (string) $values[0] : '';
}
if ($type === 's') {
$value = $sharedStrings[(int) $value] ?? '';
}
$line[$columnIndex] = $value === '' ? null : $value;
}
return $line;
}
private function resolveXlsxSheetPath(\ZipArchive $zip): string
{
$workbookXml = $zip->getFromName('xl/workbook.xml');
if ($workbookXml === false) {
throw new RuntimeException('实际税金 XLSX 缺少 workbook.xml。');
}
$workbook = simplexml_load_string(
$workbookXml,
\SimpleXMLElement::class,
LIBXML_NONET | LIBXML_COMPACT,
);
if ($workbook === false) {
throw new RuntimeException('实际税金 XLSX 工作簿结构无法解析。');
}
$configuredSheet = (string) config('actual_tax.source.sheet', '代办对接表');
$sheetNode = null;
foreach ($workbook->xpath('//*[local-name()="sheet"]') ?: [] as $candidate) {
if ((string) ($candidate['name'] ?? '') === $configuredSheet) {
$sheetNode = $candidate;
break;
}
}
if (! $sheetNode instanceof \SimpleXMLElement) {
throw new RuntimeException('工作簿中未找到“' . $configuredSheet . '”工作表。');
}
$relationshipNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
$relationshipId = (string) ($sheetNode->attributes($relationshipNamespace)['id'] ?? '');
$relationshipsXml = $zip->getFromName('xl/_rels/workbook.xml.rels');
if ($relationshipId === '' || $relationshipsXml === false) {
throw new RuntimeException('实际税金 XLSX 缺少工作表关系信息。');
}
$relationships = simplexml_load_string(
$relationshipsXml,
\SimpleXMLElement::class,
LIBXML_NONET | LIBXML_COMPACT,
);
if ($relationships === false) {
throw new RuntimeException('实际税金 XLSX 工作表关系无法解析。');
}
foreach ($relationships->xpath('//*[local-name()="Relationship"]') ?: [] as $relationship) {
if ((string) ($relationship['Id'] ?? '') !== $relationshipId) {
continue;
}
$target = ltrim((string) ($relationship['Target'] ?? ''), '/');
if ($target === '') {
break;
}
return str_starts_with($target, 'xl/') ? $target : 'xl/' . $target;
}
throw new RuntimeException('未找到实际税金 XLSX 工作表文件。');
}
private function extractZipEntry(\ZipArchive $zip, string $entry): string
{
$source = $zip->getStream($entry);
if ($source === false) {
throw new RuntimeException('无法读取实际税金 XLSX 文件中的 ' . $entry . '。');
}
$temp = tempnam(sys_get_temp_dir(), 'actual-tax-xlsx-');
if ($temp === false) {
fclose($source);
throw new RuntimeException('无法创建实际税金 XLSX 临时文件。');
}
$destination = fopen($temp, 'wb');
if ($destination === false) {
fclose($source);
@unlink($temp);
throw new RuntimeException('无法写入实际税金 XLSX 临时文件。');
}
stream_copy_to_stream($source, $destination);
fclose($source);
fclose($destination);
return $temp;
}
/**
* @param array<int,list<string|null>> $headerRows
*/
private function validateStreamingHeader(array $headerRows): void
{
$required = [
0 => '期间',
4 => '公司名称',
7 => '真实业绩(含税)',
24 => '合计收入',
45 => '税金合计',
78 => '备注',
];
foreach ($required as $index => $label) {
if ($this->normalizeHeader($headerRows[1][$index] ?? '') !== $this->normalizeHeader($label)) {
throw new RuntimeException('实际税金 XLSX 表头与“代办对接表”契约不一致。');
}
}
}
/**
* @return array{0:list<array<string,mixed>>,1:int}
*/
private function readSpreadsheet(string $path): array
{
$spreadsheet = IOFactory::load($path);
$configuredSheet = (string) config('actual_tax.source.sheet', '代办对接表');
$sheet = $spreadsheet->getSheetByName($configuredSheet);
if (! $sheet instanceof Worksheet) {
throw new RuntimeException('工作簿中未找到“' . $configuredSheet . '”工作表。');
}
$grid = $sheet->toArray(null, true, false, false);
if ($grid === []) {
throw new RuntimeException('“' . $configuredSheet . '”工作表为空。');
}
if ($this->hasThreeRowHeader($grid)) {
return $this->readThreeRowHeader($grid);
}
$columnMap = $this->flatColumnMap($grid[0] ?? []);
$rows = [];
$skipped = 0;
foreach (array_slice($grid, 1, null, true) as $index => $lineValues) {
$row = $this->normalizeFlatRow($lineValues, $columnMap, (int) $index + 1, $rows);
if ($row === null) {
$skipped++;
} elseif ($row !== []) {
$rows[] = $row;
}
}
return [$rows, $skipped];
}
/**
* @param list<list<mixed>> $grid
* @return array{0:list<array<string,mixed>>,1:int}
*/
private function readThreeRowHeader(array $grid): array
{
$columns = (array) config('actual_tax.columns', []);
$rows = [];
$skipped = 0;
foreach (array_slice($grid, self::HEADER_ROWS, null, true) as $index => $lineValues) {
$sourceRow = (int) $index + 1;
$values = [];
foreach ($columns as $column) {
$sourceIndex = (int) ($column['source_index'] ?? -1);
if ($sourceIndex < 0) {
continue;
}
$values[(string) $column['field']] = $this->normalizeValue(
$lineValues[$sourceIndex] ?? null,
(string) ($column['type'] ?? 'text'),
(string) ($column['label'] ?? $column['field']),
$sourceRow,
);
}
$row = $this->finalizeRow($values, $sourceRow, count($rows) + 1);
if ($row === null) {
$skipped++;
} else {
$rows[] = $row;
}
}
return [$rows, $skipped];
}
/**
* @param list<mixed> $values
* @param array<int,array<string,mixed>> $columnMap
* @param list<array<string,mixed>> $rows
* @return array<string,mixed>|null
*/
private function normalizeFlatRow(
array $values,
array $columnMap,
int $sourceRow,
array $rows,
): ?array {
$normalized = [];
foreach ($columnMap as $index => $column) {
$normalized[(string) $column['field']] = $this->normalizeValue(
$values[$index] ?? null,
(string) ($column['type'] ?? 'text'),
(string) ($column['label'] ?? $column['field']),
$sourceRow,
);
}
return $this->finalizeRow($normalized, $sourceRow, count($rows) + 1);
}
/**
* @param array<string,mixed> $values
* @return array<string,mixed>|null
*/
private function finalizeRow(array $values, int $sourceRow, int $sortOrder): ?array
{
if (collect($values)->every(static fn ($value): bool => $value === null || $value === '')) {
return null;
}
$period = trim((string) ($values['period'] ?? ''));
$type = trim((string) ($values['type'] ?? ''));
$companyName = trim((string) ($values['company_name'] ?? ''));
if (preg_match('/^\d{6}$/', $period) !== 1) {
throw new RuntimeException("第 {$sourceRow} 行期间无效,应为 YYYYMM。");
}
if ($companyName === '') {
throw new RuntimeException("第 {$sourceRow} 行缺少公司名称。");
}
$values['period'] = $period;
$values['type'] = $type;
$values['company_name'] = $companyName;
$values['source_key'] = hash('sha256', implode('|', [$period, $type, $companyName]));
$values['source_row'] = $sourceRow;
$values['sort_order'] = $sortOrder;
return $values;
}
/**
* @param list<array<string,mixed>> $rows
*/
private function assertUniqueRows(array $rows): void
{
$seen = [];
foreach ($rows as $row) {
$key = (string) $row['source_key'];
if (isset($seen[$key])) {
throw new RuntimeException(sprintf(
'第 %d 行与第 %d 行的期间、类型、公司名称重复。',
$seen[$key],
(int) $row['source_row'],
));
}
$seen[$key] = (int) $row['source_row'];
}
}
/**
* @param list<mixed> $header
* @return array<int,array<string,mixed>>
*/
private function flatColumnMap(array $header): array
{
$lookup = [];
foreach ((array) config('actual_tax.columns', []) as $column) {
$lookup[$this->normalizeHeader($column['field'] ?? '')] = $column;
$lookup[$this->normalizeHeader($column['label'] ?? '')] = $column;
}
$map = [];
foreach ($header as $index => $heading) {
$field = $lookup[$this->normalizeHeader($heading)] ?? null;
if ($field !== null) {
$map[$index] = $field;
}
}
$required = ['period', 'type', 'company_name'];
$mappedFields = array_column($map, 'field');
$missing = array_values(array_diff($required, $mappedFields));
if ($missing !== []) {
throw new RuntimeException('文件表头缺少字段:' . implode('、', $missing) . '。');
}
return $map;
}
/**
* @param list<list<mixed>> $grid
*/
private function hasThreeRowHeader(array $grid): bool
{
if (count($grid) < self::HEADER_ROWS + 1) {
return false;
}
$required = [
0 => '期间',
4 => '公司名称',
7 => '真实业绩(含税)',
24 => '合计收入',
45 => '税金合计',
78 => '备注',
];
foreach ($required as $index => $label) {
if ($this->normalizeHeader($grid[0][$index] ?? '') !== $this->normalizeHeader($label)) {
return false;
}
}
return count($grid[0] ?? []) >= 79;
}
private function normalizeValue(
mixed $value,
string $type,
string $label,
int $sourceRow,
): mixed {
if ($value === null || (is_string($value) && trim($value) === '')) {
return null;
}
// WPS/Excel 错误值通过内部负数错误码返回,例如 #DIV/0!、#VALUE!。
$errorCandidate = is_int($value) || is_float($value)
? (float) $value
: (is_numeric(str_replace([',', ',', ' '], '', (string) $value))
? (float) str_replace([',', ',', ' '], '', (string) $value)
: null);
if ($errorCandidate !== null
&& $errorCandidate <= -2146820000
&& $errorCandidate >= -2146830000) {
return null;
}
if (in_array($type, ['text', 'status', 'mixed_amount'], true)) {
if (is_float($value) && floor($value) === $value) {
return (string) (int) $value;
}
return trim((string) $value);
}
if (is_int($value) || is_float($value)) {
return $this->decimal((float) $value, $type === 'ratio' ? 8 : 2);
}
$text = trim((string) $value);
if ($text === '' || in_array($text, ['/', '—', '-', 'N/A'], true) || str_starts_with($text, '#')) {
return null;
}
$isPercent = str_contains($text, '%');
$normalized = str_replace([',', ',', '¥', '¥', '%', ' '], '', $text);
if (! is_numeric($normalized)) {
throw new RuntimeException("第 {$sourceRow} 行“{$label}”不是有效数字:{$text}");
}
$number = (float) $normalized;
if ($type === 'ratio') {
if ($isPercent) {
$number /= 100;
}
return $this->decimal($number, 8);
}
return $this->decimal($number, $type === 'decimal' ? 2 : 2);
}
private function decimal(float $value, int $precision): string
{
$formatted = rtrim(rtrim(number_format($value, $precision, '.', ''), '0'), '.');
return $formatted === '' || $formatted === '-' ? '0' : $formatted;
}
private function normalizeHeader(mixed $value): string
{
if ($value === null || is_bool($value) || is_array($value)) {
return '';
}
return mb_strtolower(str_replace(
['(', ')', ' ', ' ', '_', '-', "\n", "\r"],
['(', ')', '', '', '', '', '', ''],
trim((string) $value),
));
}
}

View File

@ -281,6 +281,50 @@ SQL);
return $statement->fetchAll();
}
/** @return list<array<string,mixed>> */
public function allSubjectReferences(int $companyId): array
{
$statement = $this->pdo()->prepare(
'SELECT company_name, company_type, taxpayer_type, business_registration_type, company_status '
. 'FROM company_plan_rows '
. 'WHERE company_id = :company_id ORDER BY id'
);
$statement->execute([':company_id' => $companyId]);
return $statement->fetchAll();
}
/**
* 服务公司对账从公司盘点读取类型包含“服务公司”的主体。
*
* @return list<array<string,mixed>>
*/
public function serviceCompanyRows(int $companyId): array
{
$statement = $this->pdo()->prepare(<<<'SQL'
SELECT
id,
company_name,
company_type,
taxpayer_type,
business_registration_type,
unified_social_credit_code,
company_status,
sequence_no
FROM company_plan_rows
WHERE company_id = :company_id
AND company_type IS NOT NULL
AND TRIM(company_type) LIKE '%服务公司%'
ORDER BY
CASE WHEN sequence_no IS NULL THEN 1 ELSE 0 END,
sequence_no,
id
SQL);
$statement->execute([':company_id' => $companyId]);
return $statement->fetchAll();
}
public function findForCompany(int $companyId, int $id): ?array
{
$statement = $this->pdo()->prepare(

View File

@ -395,6 +395,18 @@ SQL);
];
}
/** @return list<array<string,mixed>> */
public function allShopReferences(int $companyId): array
{
$statement = $this->pdo()->prepare(
'SELECT shop_name, company_name, successor '
. 'FROM company_plan_shops WHERE company_id = :company_id ORDER BY id'
);
$statement->execute([':company_id' => $companyId]);
return $statement->fetchAll();
}
/**
* 每个主体下的未完结店铺数量,用于主表徽章与跳转。
*

View File

@ -7,6 +7,7 @@ use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\LazyCollection;
use Throwable;
/** Read the signed snapshot directly: no duplicate contracts, attachment copies or archive backfill. */
@ -22,18 +23,9 @@ class CourierContractPageData
'unknown' => '期限待核对',
];
public function page(bool $includeRows = true): array
public function page(bool $includeRows = true, string $partnerType = 'courier'): array
{
$search = mb_substr(trim((string) request()->query('contract_search', '')), 0, 255);
$status = (string) request()->query('contract_status', '');
$status = array_key_exists($status, self::STATUSES) ? $status : '';
$from = $this->date(request()->query('contract_end_from'));
$to = $this->date(request()->query('contract_end_to'));
if ($from && $to && $from > $to) {
[$from, $to] = [$to, $from];
}
$filters = ['contract_search' => $search, 'contract_status' => $status,
'contract_end_from' => $from ?? '', 'contract_end_to' => $to ?? ''];
$filters = $this->filters();
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
$page = max((int) request()->query('page', 1), 1);
$options = ['path' => request()->url(), 'query' => request()->except('page')];
@ -52,39 +44,14 @@ class CourierContractPageData
}
$matched = [];
$today = Carbon::today(config('app.timezone'));
// Dates and partner types are encrypted. Stream bounded chunks instead of SQL JSON queries
// or persisting a second, potentially stale copy of the signed business snapshot.
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
->select(['id', 'company_id', 'business_no', 'courier_name', 'payload', 'document_type', 'status',
'signed_pdf_path', 'certificate_path', 'archived_at', 'created_by', 'created_at'])
->lazyById(250);
foreach ($signatures as $signature) {
$payload = $signature->archivedCourierContractPayload();
if ($payload === null) {
try {
$signature->payload;
} catch (Throwable) {
$data['courierContractUnreadable']++;
}
continue;
}
$row = $this->snapshot($signature, $payload, $today);
$recordUnreadable = static function () use (&$data): void {
$data['courierContractUnreadable']++;
};
foreach ($this->contractRows($partnerType, $recordUnreadable) as $row) {
$data['courierContractCounts'][$row['status']]++;
if (! $includeRows || ($status !== '' && $status !== $row['status'])) {
continue;
if ($includeRows && $this->matchesFilters($row, $filters)) {
$matched[] = $row;
}
if (($from && (! $row['end_date'] || $row['end_date'] < $from))
|| ($to && (! $row['end_date'] || $row['end_date'] > $to))) {
continue;
}
if ($search !== '' && ! str_contains(mb_strtolower(implode(' ', [
$row['courier_name'], $row['number'], $row['business_no'], $row['party_a'], $row['party_b'],
])), mb_strtolower($search))) {
continue;
}
$matched[] = $row;
}
if ($includeRows) {
$priority = ['due' => 0, 'expired' => 1, 'unknown' => 2, 'active' => 3, 'upcoming' => 4];
@ -113,6 +80,77 @@ class CourierContractPageData
return $data;
}
public function exportRows(string $partnerType): iterable
{
$filters = $this->filters();
$rows = LazyCollection::make(fn () => $this->contractRows($partnerType))
->filter(fn (array $row): bool => $this->matchesFilters($row, $filters));
foreach ($rows->chunk(250) as $chunk) {
$owners = $partnerType === 'courier'
? user_model_class()::query()->whereIn('id', $chunk->pluck('created_by')->filter()->unique()->all())->pluck('name', 'id')
: [];
foreach ($chunk as $row) {
$row['creator'] = $owners[$row['created_by']] ?? '未记录';
yield $row;
}
}
}
private function filters(): array
{
$search = request()->query('contract_search');
$search = is_string($search) ? mb_substr(trim($search), 0, 255) : '';
$status = request()->query('contract_status');
$status = is_string($status) && array_key_exists($status, self::STATUSES) ? $status : '';
$from = $this->date(request()->query('contract_end_from'));
$to = $this->date(request()->query('contract_end_to'));
if ($from && $to && $from > $to) {
[$from, $to] = [$to, $from];
}
return ['contract_search' => $search, 'contract_status' => $status,
'contract_end_from' => $from ?? '', 'contract_end_to' => $to ?? ''];
}
private function matchesFilters(array $row, array $filters): bool
{
$status = $filters['contract_status'];
$from = $filters['contract_end_from'];
$to = $filters['contract_end_to'];
if (($status !== '' && $status !== $row['status'])
|| ($from !== '' && (! $row['end_date'] || $row['end_date'] < $from))
|| ($to !== '' && (! $row['end_date'] || $row['end_date'] > $to))) {
return false;
}
$search = $filters['contract_search'];
return $search === '' || str_contains(mb_strtolower(implode(' ', [
$row['courier_name'], $row['number'], $row['business_no'], $row['party_a'], $row['party_b'],
])), mb_strtolower($search));
}
private function contractRows(string $partnerType, ?callable $recordUnreadable = null): iterable
{
$today = Carbon::today(config('app.timezone'));
// The dates and partner type live in encrypted snapshots.
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
->select(['id', 'company_id', 'business_no', 'courier_name', 'payload', 'document_type', 'status',
'signed_pdf_path', 'certificate_path', 'archived_at', 'created_by', 'created_at'])
->lazyById(250);
foreach ($signatures as $signature) {
$payload = $signature->archivedContractPayload($partnerType);
if ($payload !== null) {
yield $this->snapshot($signature, $payload, $today);
} elseif ($recordUnreadable !== null) {
try {
$signature->payload;
} catch (Throwable) {
$recordUnreadable();
}
}
}
}
private function snapshot(CourierAgreementSignature $signature, array $payload, Carbon $today): array
{
$start = $this->date($payload['cooperation_start_date'] ?? null);

View File

@ -0,0 +1,196 @@
<?php
namespace App\Business;
use Illuminate\Database\DatabaseManager;
/**
* 财务经营分析表 › 快递运费按月、按店铺汇总。
*
* 每一行快递运费由「结算运费 + 其他附加费汇总 + 退件费」组成:
* 结算运费 = 提供成本运费 + 运费差;三份快递应付快照都按交易单号匹配。
* 同一交易单号的多条快照金额全部相加;基础运费多行也全部相加,
* 但同一月份、同一交易单号的附加费用只挂一次,避免一条订单拆成多行后重复计入。
*/
class CourierFreightFinancialSummary
{
public function __construct(
private readonly DatabaseManager $databases,
private readonly CourierPayableSummaryMap $summaries,
) {}
public function version(int $companyId): int
{
return (int) cache()->get('courier-freight-financial-version:' . $companyId, 0);
}
/**
* 返回仅包含有快递运费来源的月份。调用方据此区分「本月无数据」和「金额为 0」。
*
* @param list<string> $reportMonths YYYY-MM
* @return array<string,array<string,float>> 月份 => [店铺 => 快递运费]
*/
public function monthlyStoreTotals(array $reportMonths, int $companyId): array
{
$reportMonths = array_values(array_unique(array_filter(
$reportMonths,
static fn (string $month): bool => preg_match('/^\d{4}-\d{2}$/', $month) === 1,
)));
$wantedMonths = array_fill_keys($reportMonths, true);
if ($wantedMonths === []) {
return [];
}
$cacheKey = 'courier-freight-financial-monthly:v1:'
. $companyId . ':' . $this->version($companyId) . ':' . hash('sha256', implode(',', $reportMonths));
return cache()->remember($cacheKey, now()->addHour(), function () use (
$companyId,
$wantedMonths,
$reportMonths,
): array {
// 先利用 (company_id, source) 索引找出目标月份对应的来源,
// 避免在 100 万级明细上直接分组,也避免没有当月来源时仍扫描全表。
$sources = $this->databases->connection()->table('courier_freight_rows')
->where('company_id', $companyId)
->whereNull('deleted_at')
->distinct()
->orderBy('source')
->pluck('source')
->map(static fn ($source): string => trim((string) $source))
->filter()
->values()
->all();
$matchingSources = [];
foreach ($sources as $source) {
$month = $this->sourceMonth($source, $reportMonths);
if ($month !== null && isset($wantedMonths[$month])) {
$matchingSources[$source] = true;
}
}
if ($matchingSources === []) {
return [];
}
return $this->buildMonthlyStoreTotals($companyId, array_keys($wantedMonths), array_keys($matchingSources));
});
}
/**
* @param list<string> $reportMonths
* @param list<string> $sources
* @return array<string,array<string,float>>
*/
private function buildMonthlyStoreTotals(int $companyId, array $reportMonths, array $sources): array
{
$differences = $this->summaries->mapByMonth(
$companyId,
CourierPayableSummaryMap::PAGE_FREIGHT_DIFFERENCE,
);
$surcharges = $this->summaries->mapByMonth(
$companyId,
CourierPayableSummaryMap::PAGE_OTHER_SURCHARGE,
);
$returnFees = $this->summaries->mapByMonth(
$companyId,
CourierPayableSummaryMap::PAGE_RETURN_FEE,
);
$totals = [];
$feeApplied = [];
$rows = $this->databases->connection()->table('courier_freight_rows')
->where('company_id', $companyId)
->whereNull('deleted_at')
->whereIn('source', $sources)
->select(['source', 'shop_name', 'transaction_no'])
->selectRaw('SUM(COALESCE(freight_amount, 0)) AS freight_amount')
->groupBy('source', 'shop_name', 'transaction_no')
->orderBy('source')
->orderBy('shop_name')
->orderBy('transaction_no')
->cursor();
foreach ($rows as $row) {
$month = $this->sourceMonth(
(string) $row->source,
$reportMonths,
);
if ($month === null || ! in_array($month, $reportMonths, true)) {
continue;
}
// 即使店铺为空也保留月份,表示该月已有快递成本来源。
$totals[$month] ??= [];
$storeName = trim((string) $row->shop_name);
if ($storeName === '') {
continue;
}
$transactionNo = trim((string) $row->transaction_no);
$amount = (float) $row->freight_amount;
$feeKey = $month . "\0" . $transactionNo;
if ($transactionNo !== '' && ! isset($feeApplied[$feeKey])) {
$amount += $this->numeric($differences[$month][$transactionNo] ?? null);
$amount += $this->numeric($surcharges[$month][$transactionNo] ?? null);
$amount += $this->numeric($returnFees[$month][$transactionNo] ?? null);
$feeApplied[$feeKey] = true;
}
$totals[$month][$storeName] = round(
($totals[$month][$storeName] ?? 0.0) + $amount,
2,
);
}
return $totals;
}
/**
* 来源通常为「提供成本9月汇总」。优先取来源里的年份;没有年份时,
* 用当前报表年份补齐。若来源是「5-7月」范围,取最后月份作为该汇总的账期。
*
* @param list<string> $reportMonths
*/
private function sourceMonth(string $source, array $reportMonths): ?string
{
$source = trim($source);
if ($source === '') {
return null;
}
if (preg_match(
'/(?<!\d)((?:19|20)\d{2})\D{0,4}(1[0-2]|0?[1-9])(?!\d)/u',
$source,
$matches,
) === 1) {
return $matches[1] . '-' . str_pad((string) (int) $matches[2], 2, '0', STR_PAD_LEFT);
}
if (preg_match(
'/(?:1[0-2]|0?[1-9])\s*[-~至]\s*(1[0-2]|0?[1-9])\s*月/u',
$source,
$range,
) === 1) {
$month = (int) $range[1];
} elseif (preg_match('/(1[0-2]|0?[1-9])\s*月/u', $source, $single) === 1) {
$month = (int) $single[1];
} else {
return null;
}
$year = $reportMonths !== [] ? substr($reportMonths[0], 0, 4) : null;
return $year === null
? null
: $year . '-' . str_pad((string) $month, 2, '0', STR_PAD_LEFT);
}
private function numeric(mixed $value): float
{
if ($value === null || $value === '') {
return 0.0;
}
return is_numeric($value) ? (float) $value : 0.0;
}
}

View File

@ -3,6 +3,7 @@
namespace App\Business;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use RuntimeException;
@ -110,6 +111,7 @@ class CourierFreightImporter
$flush();
arsort($sources);
Cache::increment('courier-freight-financial-version:' . $companyId);
return [
'file' => basename($path),

View File

@ -7,7 +7,7 @@ use Illuminate\Support\Facades\Storage;
use Throwable;
/**
* 快递应付的两个汇总页 → 「交易单号 ⇒ 金额类取值」映射。
* 快递应付的三个汇总页 → 「交易单号 ⇒ 金额类取值」映射。
*
* 这些数据都是财务在「应付款项 › 快递应付 › 运费差 / 其他附加费汇总 / 退件费」页面上传的汇总快照
* (JSON 文件,不是数据库表),快递运费页面按交易单号把对应金额带出来展示。
@ -37,6 +37,7 @@ class CourierPayableSummaryMap
];
private const CACHE_MINUTES = 10;
private const AMOUNT_SCALE = 10;
public function __construct(private readonly CourierPayableSummaryStore $store) {}
@ -57,7 +58,7 @@ class CourierPayableSummaryMap
}
// 文件时间戳进缓存键:财务重新导入运费差后不用等缓存过期。
$key = sprintf('courier-payable-summary-map:v1:%s:%d:%d', $page, $companyId, (int) $disk->lastModified($path));
$key = sprintf('courier-payable-summary-map:v3:%s:%d:%d', $page, $companyId, (int) $disk->lastModified($path));
return Cache::remember($key, now()->addMinutes(self::CACHE_MINUTES), function () use ($companyId, $page): array {
try {
@ -70,6 +71,43 @@ class CourierPayableSummaryMap
});
}
/**
* 汇总快照按原始日期拆成月份,供财务经营分析表按月匹配。
*
* 同一交易单号在同一月份可以出现多行,所有金额都累加,不做去重。
*
* @return array<string,array<string,string>> 月份 => [交易单号 => 金额]
*/
public function mapByMonth(int $companyId, string $page): array
{
if (! isset(self::PAGES[$page])) {
return [];
}
$disk = Storage::disk('uploads');
$path = $this->store->path($companyId, $page);
if (! $disk->exists($path)) {
return [];
}
$key = sprintf(
'courier-payable-summary-month-map:v1:%s:%d:%d',
$page,
$companyId,
(int) $disk->lastModified($path),
);
return Cache::remember($key, now()->addMinutes(self::CACHE_MINUTES), function () use ($companyId, $page): array {
try {
return $this->buildByMonth($companyId, $page);
} catch (Throwable $exception) {
report($exception);
return [];
}
});
}
/** @return array<string,string> */
private function build(int $companyId, string $page): array
{
@ -86,7 +124,8 @@ class CourierPayableSummaryMap
return [];
}
$map = [];
$totals = [];
$fallbacks = [];
foreach ((array) $snapshot['rows'] as $row) {
$orderNos = trim((string) ($row[$orderColumn] ?? ''));
if ($orderNos === '') {
@ -99,17 +138,123 @@ class CourierPayableSummaryMap
}
// 源表一个格子可能放多个交易单号(逗号分隔),逐个挂到同一个金额上。
foreach (explode(',', $orderNos) as $orderNo) {
foreach (preg_split('/[,,]/u', $orderNos) ?: [] as $orderNo) {
$orderNo = trim($orderNo);
if ($orderNo !== '' && ! isset($map[$orderNo])) {
$map[$orderNo] = $value;
if ($orderNo === '') {
continue;
}
// 同一交易单号可能拆成多条运费差、附加费或退件费,按单号汇总,
// 避免页面只取第一条而漏计同一订单的后续金额。
$numericValue = $this->numericDecimal($value);
if ($numericValue !== null && function_exists('bcadd')) {
$totals[$orderNo] = bcadd(
$totals[$orderNo] ?? '0',
$numericValue,
self::AMOUNT_SCALE,
);
} else {
$fallbacks[$orderNo] ??= $value;
}
}
}
$map = [];
foreach ($totals as $orderNo => $total) {
$map[$orderNo] = $this->decimalString($total);
}
foreach ($fallbacks as $orderNo => $value) {
if (! isset($map[$orderNo])) {
$map[$orderNo] = $value;
}
}
return $map;
}
/** @return array<string,array<string,string>> */
private function buildByMonth(int $companyId, string $page): array
{
$snapshot = $this->store->snapshot($companyId, $page);
if ($snapshot === null) {
return [];
}
[$orderHeaders, $valueHeaders] = self::PAGES[$page];
$headers = array_map(static fn ($value): string => trim((string) $value), (array) $snapshot['headers']);
$orderColumn = $this->columnIndex($headers, $orderHeaders);
$valueColumn = $this->columnIndex($headers, $valueHeaders);
$dateColumn = $this->columnIndex($headers, ['日期', '结算月份', '结算月', '月份']);
if ($orderColumn === null || $valueColumn === null || $dateColumn === null) {
return [];
}
$totals = [];
foreach ((array) $snapshot['rows'] as $row) {
$month = $this->month((string) ($row[$dateColumn] ?? ''));
$orderNos = trim((string) ($row[$orderColumn] ?? ''));
$value = trim((string) ($row[$valueColumn] ?? ''));
$numericValue = $this->numericDecimal($value);
if ($month === null || $orderNos === '' || $numericValue === null) {
continue;
}
$totals[$month] ??= [];
foreach (preg_split('/[,,]/u', $orderNos) ?: [] as $orderNo) {
$orderNo = trim($orderNo);
if ($orderNo === '') {
continue;
}
$totals[$month][$orderNo] = function_exists('bcadd')
? bcadd($totals[$month][$orderNo] ?? '0', $numericValue, self::AMOUNT_SCALE)
: (string) ((float) ($totals[$month][$orderNo] ?? 0) + (float) $numericValue);
}
}
$map = [];
foreach ($totals as $month => $orders) {
foreach ($orders as $orderNo => $total) {
$map[$month][$orderNo] = $this->decimalString($total);
}
}
return $map;
}
private function month(string $value): ?string
{
if (preg_match(
'/(?<!\d)((?:19|20)\d{2})\D{0,4}(1[0-2]|0?[1-9])(?!\d)/u',
trim($value),
$matches,
) !== 1) {
return null;
}
return $matches[1] . '-' . str_pad((string) (int) $matches[2], 2, '0', STR_PAD_LEFT);
}
private function numericDecimal(string $value): ?string
{
if (! is_numeric($value)) {
return null;
}
if (stripos($value, 'e') === false) {
return $value;
}
return sprintf('%.' . self::AMOUNT_SCALE . 'F', (float) $value);
}
private function decimalString(string $value): string
{
$value = rtrim(rtrim($value, '0'), '.');
return $value === '' || $value === '-0' ? '0' : $value;
}
/**
* 按表头名定位:候选顺序优先,每个候选先找完全相等的表头,再退化成包含匹配
* (例如「差异(结算运费-提供成本运费)」只能靠包含匹配)。

View File

@ -9,6 +9,7 @@ use App\Models\Business\CourierProfile;
use App\Models\Business\CourierProfileEvent;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
@ -33,7 +34,7 @@ final class CourierProfileData
/** 把覆盖值盖到快递资料行上,`_overridden` 记下改过的字段。 */
public function apply(object $row, array $overrides): object
{
$row = clone $row;
$row = $this->fillFromOnboarding(clone $row);
$changed = [];
foreach ($overrides as $field => $value) {
if (array_key_exists($field, CourierProfile::EDITABLE)) {
@ -155,11 +156,16 @@ final class CourierProfileData
/** 工作平台的行:扣款方式没填时用入驻里我方填的。 */
public function fillFromOnboarding(object $row): object
{
$row = clone $row;
$onboarding = $row->_info['onboarding'] ?? null;
if ($onboarding !== null && blank($row->undefined3 ?? null) && filled($onboarding->deduction_method)) {
$row = clone $row;
$row->undefined3 = $onboarding->deduction_method;
}
foreach (['entity_type', 'company_full_name', ...self::APPENDED_PROFILE_FIELDS] as $field) {
if (! property_exists($row, $field)) {
$row->{$field} = $onboarding?->{$field};
}
}
return $row;
}
@ -187,36 +193,38 @@ final class CourierProfileData
/** 保存编辑:只记和当前显示值不同的字段,并写一条操作日志。 */
public function update(string $expcode, ?string $courierName, object $current, array $values, int $userId): int
{
$profile = CourierProfile::query()->firstOrNew(['company_id' => company_id(), 'expcode' => $expcode]);
$overrides = (array) ($profile->overrides ?? []);
$changes = [];
foreach (CourierProfile::EDITABLE as $field => $label) {
if (! array_key_exists($field, $values)) {
continue;
return DB::transaction(function () use ($expcode, $courierName, $current, $values, $userId): int {
$profile = CourierProfile::query()->firstOrNew(['company_id' => company_id(), 'expcode' => $expcode]);
$overrides = (array) ($profile->overrides ?? []);
$changes = [];
foreach (CourierProfile::EDITABLE as $field => $label) {
if (! array_key_exists($field, $values)) {
continue;
}
$new = $this->normalize($field, $values[$field]);
$old = $this->normalize($field, $current->{$field} ?? null);
if ($new === $old) {
continue;
}
$overrides[$field] = $new;
$changes[$field] = ['label' => $label, 'old' => $old, 'new' => $new];
}
$new = $this->normalize($field, $values[$field]);
$old = $this->normalize($field, $current->{$field} ?? null);
if ($new === $old) {
continue;
if ($changes === []) {
return 0;
}
$overrides[$field] = $new;
$changes[$field] = ['label' => $label, 'old' => $old, 'new' => $new];
}
if ($changes === []) {
return 0;
}
$profile->fill([
'courier_name' => $courierName ?: $profile->courier_name,
'overrides' => $overrides,
'updated_by' => $userId,
]);
$profile->created_by ??= $userId;
$profile->save();
$profile->fill([
'courier_name' => $courierName ?: $profile->courier_name,
'overrides' => $overrides,
'updated_by' => $userId,
]);
$profile->created_by ??= $userId;
$profile->save();
$this->log($expcode, 'edit', '修改 ' . implode('、', array_column($changes, 'label')), $changes, $userId);
$this->log($expcode, 'edit', '修改 ' . implode('、', array_column($changes, 'label')), $changes, $userId);
return count($changes);
return count($changes);
});
}
public function log(string $expcode, string $action, string $summary, ?array $changes, int $userId): void

View File

@ -0,0 +1,378 @@
<?php
namespace App\Business;
use App\Business\Piaoju\PiaojuSellerQuotaRepository;
use App\Models\Business\InvoiceBasic;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Throwable;
class InvoiceQuotaPageData
{
private const PER_PAGE = 50;
private const QUOTA_WARNING_DAYS = 5;
public function __construct(
private readonly PiaojuSellerQuotaRepository $piaojuQuotas,
) {
}
public function page(): array
{
try {
$data = $this->buildData();
} catch (Throwable $exception) {
report($exception);
return $this->errorPayload();
}
$rows = $data['allRows'];
$total = $rows->count();
$lastPage = max(1, (int) ceil($total / self::PER_PAGE));
$currentPage = min(max((int) request()->query('page', 1), 1), $lastPage);
$pageRows = $rows
->slice(($currentPage - 1) * self::PER_PAGE, self::PER_PAGE)
->values();
$paginator = new LengthAwarePaginator(
$pageRows,
$total,
self::PER_PAGE,
$currentPage,
[
'path' => request()->url(),
'query' => request()->query(),
]
);
return [
'view' => 'business.pages.invoice_quota',
'title' => '发票额度',
'period' => $data['period'],
'periodOptions' => $data['periodOptions'],
'sellerEntity' => $data['sellerEntity'],
'rows' => $paginator,
'summary' => $data['summary'],
'loadError' => null,
];
}
/**
* 返回当前筛选条件下的全部行,供 CSV 导出使用。
*
* @return array{period:string, sellerEntity:string, allRows:Collection, summary:array}
*/
public function exportData(): array
{
return $this->buildData();
}
private function buildData(): array
{
$periodOptions = InvoiceBasic::query()
->select('period')
->whereNotNull('period')
->where('period', '<>', '')
->distinct()
->orderByDesc('period')
->pluck('period')
->map(static fn ($period): string => trim((string) $period))
->filter(fn (string $period): bool => $this->normalizePeriod($period) !== null)
->unique()
->values();
$requestedPeriod = $this->normalizePeriod(
trim((string) request()->query('period', ''))
);
$period = $requestedPeriod ?? $periodOptions->first() ?? '';
$forecastContext = $this->forecastContext($period);
$sellerEntity = mb_substr(
trim((string) request()->query('seller_entity', '')),
0,
100
);
$query = InvoiceBasic::query()->select([
'id',
'store_entity',
'invoice_issuer',
'output_amount',
'period',
]);
if ($period !== '') {
$query->where('period', $period);
} else {
$query->where(function ($query): void {
$query->whereNull('period')->orWhere('period', '');
});
}
if ($sellerEntity !== '') {
$needle = '%' . addcslashes($sellerEntity, '%_\\') . '%';
$query->where('store_entity', 'like', $needle);
}
$snapshots = $this->piaojuQuotas->byNormalizedName();
$rows = $query
->orderBy('store_entity')
->orderByDesc('id')
->get()
->map(fn (InvoiceBasic $row): object => $this->presentRow(
$row,
$snapshots->get(PiaojuSellerQuotaRepository::normalizeName((string) $row->store_entity)),
$forecastContext,
))
->sortBy(static fn (object $row): string => sprintf(
'%02d|%s',
$row->status_rank,
(string) $row->store_entity
))
->values();
$total = $rows->count();
$usedAmount = $rows->sum(static fn (object $row): float => (float) $row->output_amount);
$usedTotal = round($usedAmount, 2);
$forecastTotal = (int) ($forecastContext['elapsed_days'] ?? 0) > 0
? round(
$usedAmount
* (int) ($forecastContext['days_in_month'] ?? 0)
/ (int) $forecastContext['elapsed_days'],
2
)
: 0.0;
$availableRows = $rows->filter(
static fn (object $row): bool => $row->available_amount !== null
);
$availableTotal = round($availableRows->sum(
static fn (object $row): float => (float) $row->available_amount
), 2);
$matchedCount = $rows->where('snapshot_matched', true)->count();
$unmatchedCount = $rows->where('snapshot_matched', false)->count();
$unavailableCount = $rows->where('snapshot_unavailable', true)->count();
$insufficientCount = $rows->where('insufficient', true)->count();
$warningCount = $rows->where('quota_warning', true)->count();
return [
'period' => $period,
'periodOptions' => $periodOptions,
'sellerEntity' => $sellerEntity,
'allRows' => $rows,
'summary' => [
'record_count' => $total,
'used_total' => $usedTotal,
'forecast_total' => $forecastTotal,
'available_total' => $availableTotal,
'matched_count' => $matchedCount,
'unmatched_count' => $unmatchedCount,
'unavailable_count' => $unavailableCount,
'insufficient_count' => $insufficientCount,
'warning_count' => $warningCount,
'forecast_elapsed_days' => $forecastContext['elapsed_days'],
'forecast_days_in_month' => $forecastContext['days_in_month'],
'forecast_is_current' => $forecastContext['is_current'],
'latest_quota_updated_at' => $this->latestDateTime(
$rows->pluck('quota_updated_at')
),
'latest_source_fetched_at' => $this->latestDateTime(
$rows->pluck('source_fetched_at')
),
],
];
}
private function presentRow(
InvoiceBasic $row,
?object $snapshot,
array $forecastContext,
): object
{
$outputAmount = round((float) $row->output_amount, 2);
$availableAmount = $snapshot !== null && is_numeric($snapshot->invoice_limit)
? round((float) $snapshot->invoice_limit, 2)
: null;
$authStatus = strtoupper(trim((string) ($snapshot->auth_status ?? '')));
$elapsedDays = (int) ($forecastContext['elapsed_days'] ?? 0);
$daysInMonth = (int) ($forecastContext['days_in_month'] ?? 0);
$dailyAverageRaw = $elapsedDays > 0
? $outputAmount / $elapsedDays
: null;
$dailyAverage = $dailyAverageRaw !== null ? round($dailyAverageRaw, 2) : null;
$forecastMonthly = $dailyAverageRaw !== null && $daysInMonth > 0
? round($outputAmount * $daysInMonth / $elapsedDays, 2)
: null;
$coverageDaysRaw = $dailyAverageRaw !== null && $dailyAverageRaw > 0 && $availableAmount !== null
? max($availableAmount, 0) / $dailyAverageRaw
: null;
$coverageDays = $coverageDaysRaw !== null ? round($coverageDaysRaw, 2) : null;
$quotaWarning = (bool) ($forecastContext['is_current'] ?? false)
&& $authStatus === 'AUTHENTICATED'
&& $availableAmount !== null
&& $availableAmount > 0
&& $coverageDaysRaw !== null
&& $coverageDaysRaw < self::QUOTA_WARNING_DAYS;
if ($snapshot === null) {
$status = '未匹配';
$statusTone = 'muted';
$statusIcon = 'link_off';
$statusRank = 0;
} elseif ($authStatus === 'AUTHENTICATED_EXPIRED') {
$status = '授权过期';
$statusTone = 'warning';
$statusIcon = 'schedule';
$statusRank = 1;
} elseif ($authStatus !== 'AUTHENTICATED') {
$status = '不可查看';
$statusTone = 'muted';
$statusIcon = 'visibility_off';
$statusRank = 1;
} elseif ($availableAmount === null) {
$status = '未获取额度';
$statusTone = 'muted';
$statusIcon = 'cloud_off';
$statusRank = 1;
} elseif ($availableAmount <= 0) {
$status = '额度不足';
$statusTone = 'danger';
$statusIcon = 'error';
$statusRank = 2;
} elseif ($quotaWarning) {
$status = '5天内预警';
$statusTone = 'danger';
$statusIcon = 'notification_important';
$statusRank = 2;
} else {
$status = '正常';
$statusTone = 'success';
$statusIcon = 'check_circle_outline';
$statusRank = 3;
}
return (object) [
'id' => $row->id,
'store_entity' => $row->store_entity,
'invoice_issuer' => $row->invoice_issuer,
'output_amount' => $outputAmount,
'daily_average' => $dailyAverage,
'forecast_monthly' => $forecastMonthly,
'available_amount' => $availableAmount,
'coverage_days' => $coverageDays,
'quota_updated_at' => $this->formatDateTime($snapshot->invoice_limit_updated_at ?? null),
'source_fetched_at' => $this->formatDateTime($snapshot->source_fetched_at ?? null),
'snapshot_matched' => $snapshot !== null,
'snapshot_unavailable' => $snapshot !== null
&& ($authStatus !== 'AUTHENTICATED' || $availableAmount === null),
'insufficient' => $snapshot !== null
&& $authStatus === 'AUTHENTICATED'
&& $availableAmount !== null
&& $availableAmount <= 0,
'quota_warning' => $quotaWarning,
'status' => $status,
'status_tone' => $statusTone,
'status_icon' => $statusIcon,
'status_rank' => $statusRank,
'period' => $row->period,
];
}
private function formatDateTime(mixed $value): ?string
{
$text = trim((string) ($value ?? ''));
if ($text === '') {
return null;
}
try {
return Carbon::parse($text, 'Asia/Shanghai')->format('Y-m-d H:i');
} catch (Throwable) {
return null;
}
}
private function latestDateTime(Collection $values): ?string
{
return $values
->filter(static fn (mixed $value): bool => trim((string) $value) !== '')
->sortDesc()
->first();
}
private function normalizePeriod(string $period): ?string
{
return preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1
? $period
: null;
}
/**
* @return array{elapsed_days:int,days_in_month:int,is_current:bool}
*/
private function forecastContext(string $period): array
{
if ($period === '') {
return ['elapsed_days' => 0, 'days_in_month' => 0, 'is_current' => false];
}
try {
$month = Carbon::createFromFormat('!Y-m-d', $period . '-01', 'Asia/Shanghai');
$today = Carbon::now('Asia/Shanghai')->startOfDay();
} catch (Throwable) {
return ['elapsed_days' => 0, 'days_in_month' => 0, 'is_current' => false];
}
$daysInMonth = $month->daysInMonth;
if ($month->format('Y-m') === $today->format('Y-m')) {
return [
'elapsed_days' => min($today->day, $daysInMonth),
'days_in_month' => $daysInMonth,
'is_current' => true,
];
}
if ($month->lt($today->copy()->startOfMonth())) {
return [
'elapsed_days' => $daysInMonth,
'days_in_month' => $daysInMonth,
'is_current' => false,
];
}
return ['elapsed_days' => 0, 'days_in_month' => $daysInMonth, 'is_current' => false];
}
private function errorPayload(): array
{
return [
'view' => 'business.pages.invoice_quota',
'title' => '发票额度',
'period' => '',
'periodOptions' => collect(),
'sellerEntity' => '',
'rows' => new LengthAwarePaginator([], 0, self::PER_PAGE, 1, [
'path' => request()->url(),
'query' => request()->query(),
]),
'summary' => [
'record_count' => 0,
'used_total' => 0.0,
'forecast_total' => 0.0,
'available_total' => 0.0,
'matched_count' => 0,
'unmatched_count' => 0,
'unavailable_count' => 0,
'insufficient_count' => 0,
'warning_count' => 0,
'forecast_elapsed_days' => 0,
'forecast_days_in_month' => 0,
'forecast_is_current' => false,
'latest_quota_updated_at' => null,
'latest_source_fetched_at' => null,
],
'loadError' => '发票额度数据暂时无法读取,请稍后重试。',
];
}
}

View File

@ -0,0 +1,198 @@
<?php
namespace App\Business;
use App\Models\Business\InputInvoiceReport;
use App\Models\Business\OutputInvoiceReport;
use Illuminate\Support\Collection;
use Throwable;
/**
* 发票数据报表:发票情况汇总在前,进项/销项明细在后。
*
* 汇总按公司名称合并进项报表与销项报表,金额均使用两张报表的合计口径;
* 差额 = 销项 − 进项,正数表示销项大于进项。
*/
class InvoiceReportsPageData
{
private const TABS = ['summary', 'input', 'output'];
public function page(?string $tab): array
{
$tab = in_array($tab, self::TABS, true) ? $tab : 'summary';
$inputRows = $this->reportRows(InputInvoiceReport::class);
$outputRows = $this->reportRows(OutputInvoiceReport::class);
if ($tab === 'summary') {
$allRows = $this->summaryRows($inputRows, $outputRows);
$filters = $this->summaryFilters();
$summaryRows = $this->filterSummaryRows($allRows, $filters);
return [
'view' => 'business.pages.invoice_reports',
'summaryRows' => $summaryRows,
'summaryTotals' => $this->summaryTotals($summaryRows),
'summaryFilters' => $filters,
'companyOptions' => $allRows->pluck('company_name')
->filter(static fn ($name): bool => (string) $name !== '')
->unique()
->sort()
->values(),
'taxpayerTypeOptions' => $allRows->pluck('taxpayer_type')
->filter(static fn ($type): bool => (string) $type !== '' && (string) $type !== '—')
->unique()
->sort()
->values(),
];
}
return [
'view' => 'business.pages.invoice_reports',
'items' => $tab === 'output' ? $outputRows : $inputRows,
];
}
/**
* 报表表在部分老环境可能尚未迁移,缺失时保持页面可用并展示空表。
*
* @param class-string $model
*/
private function reportRows(string $model): Collection
{
try {
return $model::query()
->orderBy('company_name')
->orderBy('id')
->get();
} catch (Throwable $exception) {
report($exception);
return collect();
}
}
private function summaryRows(Collection $inputRows, Collection $outputRows): Collection
{
$inputs = $inputRows->groupBy(fn ($row): string => trim((string) $row->company_name));
$outputs = $outputRows->groupBy(fn ($row): string => trim((string) $row->company_name));
$companyNames = $inputs->keys()
->merge($outputs->keys())
->filter(static fn ($name): bool => $name !== '')
->unique()
->sort()
->values();
$taxpayerTypes = $this->taxpayerTypes($companyNames);
return $companyNames->map(function (string $companyName) use ($inputs, $outputs, $taxpayerTypes): object {
$inputRows = $inputs->get($companyName, collect());
$outputRows = $outputs->get($companyName, collect());
$inputAmount = $this->sumField($inputRows, 'input_total_amount');
$inputTax = $this->sumField($inputRows, 'input_total_tax');
$outputAmount = $this->sumField($outputRows, 'output_total_amount');
$outputTax = $this->sumField($outputRows, 'output_total_tax');
$ratio = $outputAmount > 0 ? $inputAmount / $outputAmount : null;
return (object) [
'company_name' => $companyName,
'taxpayer_type' => $taxpayerTypes->get($companyName, '—'),
'input_total_amount' => $inputAmount,
'input_total_tax' => $inputTax,
'output_total_amount' => $outputAmount,
'output_total_tax' => $outputTax,
'input_output_ratio' => $ratio,
'is_warning' => $ratio !== null && $ratio < 0.8,
];
});
}
private function summaryTotals(Collection $rows): object
{
return (object) [
'input_total_amount' => round((float) $rows->sum('input_total_amount'), 2),
'input_total_tax' => round((float) $rows->sum('input_total_tax'), 2),
'output_total_amount' => round((float) $rows->sum('output_total_amount'), 2),
'output_total_tax' => round((float) $rows->sum('output_total_tax'), 2),
];
}
/**
* @return array{company:string,taxpayer_type:string,warning:string}
*/
private function summaryFilters(): array
{
$warning = strtolower(trim((string) request()->query('warning', '')));
return [
'company' => trim((string) request()->query('company', '')),
'taxpayer_type' => trim((string) request()->query('taxpayer_type', '')),
'warning' => in_array($warning, ['yes', 'no'], true) ? $warning : '',
];
}
/**
* @param array{company:string,taxpayer_type:string,warning:string} $filters
*/
private function filterSummaryRows(Collection $rows, array $filters): Collection
{
return $rows->filter(function (object $row) use ($filters): bool {
if ($filters['company'] !== '' && $row->company_name !== $filters['company']) {
return false;
}
if ($filters['taxpayer_type'] !== '' && $row->taxpayer_type !== $filters['taxpayer_type']) {
return false;
}
if ($filters['warning'] === 'yes' && ! $row->is_warning) {
return false;
}
if ($filters['warning'] === 'no' && $row->is_warning) {
return false;
}
return true;
})->values();
}
/**
* 纳税人类型取公司基础信息共享镜像;镜像未就绪或公司未登记时显示「—」。
*/
private function taxpayerTypes(Collection $companyNames): Collection
{
$names = $companyNames
->map(static fn ($name): string => trim((string) $name))
->filter(static fn (string $name): bool => $name !== '')
->unique()
->values()
->all();
if ($names === []) {
return collect();
}
try {
$rows = app(\Modules\EcommerceFinance\Repositories\BusinessInformationMirrorRepository::class)
->allCompaniesForClassification(['_company_names' => $names]);
return collect($rows)
->mapWithKeys(static fn (array $row): array => [
trim((string) ($row['company_name'] ?? '')) => trim((string) ($row['taxpayer_category'] ?? '')),
])
->filter(static fn ($value, $key): bool => $key !== '' && (string) $value !== '');
} catch (Throwable $exception) {
report($exception);
return collect();
}
}
private function sumField(Collection $rows, string $field): float
{
return round($rows->sum(static fn ($row): float => (float) $row->{$field}), 2);
}
}

View File

@ -30,6 +30,7 @@ class KukaPostingBaseImporter
* store_count: int,
* order_count: int,
* skipped_store_rows: int,
* skipped_cancelled_rows: int,
* file_sha256: string
* }
*/
@ -59,12 +60,18 @@ class KukaPostingBaseImporter
throw new RuntimeException('顾家过账基础数据字段或店铺范围未配置。');
}
$sourceColumns = array_values(array_filter(array_map(
static fn (array $field): string => trim((string) ($field['source'] ?? '')),
$fields,
)));
if (count($sourceColumns) !== count($fields)) {
throw new RuntimeException('顾家过账基础数据字段配置不完整。');
$requiredSourceColumns = [];
$optionalSourceColumns = [];
foreach ($fields as $field) {
$source = trim((string) ($field['source'] ?? ''));
if ($source === '') {
throw new RuntimeException('顾家过账基础数据字段配置不完整。');
}
if (($field['optional'] ?? false) === true) {
$optionalSourceColumns[] = $source;
} else {
$requiredSourceColumns[] = $source;
}
}
$sheetName = trim((string) ($sheetName ?: config('kuka_posting.source_sheet', '发货明细表')));
@ -77,6 +84,7 @@ class KukaPostingBaseImporter
$orders = [];
$rowCount = 0;
$skippedStoreRows = 0;
$skippedCancelledRows = 0;
$sourceRowNumber = 1;
$now = now();
@ -87,12 +95,14 @@ class KukaPostingBaseImporter
$sheetName,
$companyId,
$fields,
$sourceColumns,
$requiredSourceColumns,
$optionalSourceColumns,
$allowedStores,
&$storeCounts,
&$orders,
&$rowCount,
&$skippedStoreRows,
&$skippedCancelledRows,
&$sourceRowNumber,
$fileHash,
$now,
@ -114,7 +124,12 @@ class KukaPostingBaseImporter
$batch = [];
};
foreach ($this->reader->rows($path, $sourceColumns, [], $sheetName) as $sourceValues) {
foreach ($this->reader->rows(
$path,
$requiredSourceColumns,
$optionalSourceColumns,
$sheetName,
) as $sourceValues) {
$sourceRowNumber++;
$storeName = trim((string) ($sourceValues['店铺'] ?? ''));
if ($storeName === '' || ! in_array($storeName, $allowedStores, true)) {
@ -122,6 +137,11 @@ class KukaPostingBaseImporter
continue;
}
if (trim((string) ($sourceValues['订单状态'] ?? '')) === '已取消') {
$skippedCancelledRows++;
continue;
}
$payload = [];
foreach ($fields as $field) {
@ -231,6 +251,7 @@ class KukaPostingBaseImporter
'store_count' => count(array_filter($storeCounts)),
'order_count' => count($orders),
'skipped_store_rows' => $skippedStoreRows,
'skipped_cancelled_rows' => $skippedCancelledRows,
'file_sha256' => strtolower($fileHash),
];
}

View File

@ -28,7 +28,15 @@ class KukaPostingBasePageData
public function build(Request $request, int $companyId): array
{
$stores = array_values((array) config('kuka_posting.stores', []));
$fields = array_values((array) config('kuka_posting.fields', []));
$fieldDefinitions = collect((array) config('kuka_posting.fields', []))->keyBy('name');
$displayFieldNames = array_values((array) config('kuka_posting.shipment_display_fields', []));
$fields = $displayFieldNames === []
? $fieldDefinitions->values()->all()
: collect($displayFieldNames)
->map(static fn (string $name): ?array => $fieldDefinitions->get($name))
->filter()
->values()
->all();
$available = $this->repository->available();
$periods = $available ? $this->repository->periods($companyId) : [];
$latest = $available ? $this->repository->latestImport($companyId) : null;
@ -67,13 +75,98 @@ class KukaPostingBasePageData
'path' => $request->url(),
'query' => $request->query(),
]);
$rows->setCollection($rows->getCollection()->map(function (object $row): object {
$decodedRows = $rows->getCollection()->map(function (object $row): array {
$values = json_decode((string) $row->source_values, true);
if (! is_array($values)) {
$values = [];
}
$values['_row_id'] = $row->id;
return [
'item_number' => trim((string) ($values['货号'] ?? '')),
'style_code' => trim((string) ($values['款式编码'] ?? '')),
'values' => $values,
];
});
$maps = $this->repository->materialMaps(
$companyId,
$decodedRows->pluck('item_number')->filter()->unique()->values()->all(),
);
$brandItems = $this->repository->brandItemMaps(
$companyId,
$decodedRows->pluck('style_code')->filter()->unique()->values()->all(),
);
$itemBrandItems = $this->repository->itemBrandItemMaps(
$companyId,
$decodedRows->pluck('item_number')->filter()->unique()->values()->all(),
);
$repairedMaterialNumbers = $decodedRows
->filter(static fn (array $row): bool => trim((string) (
$row['values']['物料信息修正'] ?? ''
)) === '是')
->map(static fn (array $row): string => trim((string) (
$row['values']['物料编号'] ?? ''
)))
->filter();
$quotations = $this->repository->effectiveQuotations(
$companyId,
collect($maps)
->pluck('material_number')
->filter()
->merge($repairedMaterialNumbers)
->unique()
->values()
->all(),
);
$rows->setCollection($decodedRows->map(function (array $row) use ($maps, $brandItems, $itemBrandItems, $quotations): object {
$values = $row['values'];
$usesRepairedMaterial = trim((string) ($values['物料信息修正'] ?? '')) === '是';
$storedMaterialNumber = trim((string) ($values['物料编号'] ?? ''));
$storedMaterialDescription = trim((string) ($values['型号'] ?? ''));
if (in_array($storedMaterialNumber, ['', '—', '-'], true)) {
$storedMaterialNumber = '';
}
if (in_array($storedMaterialDescription, ['', '—', '-'], true)) {
$storedMaterialDescription = '';
}
$mappedMaterialNumber = trim((string) ($maps[$row['item_number']]->material_number ?? ''));
$materialNumber = $usesRepairedMaterial && $storedMaterialNumber !== ''
? $storedMaterialNumber
: $mappedMaterialNumber;
$quotation = $materialNumber === '' ? null : ($quotations[$materialNumber] ?? null);
$brandItemNumber = trim((string) (
$brandItems[$row['style_code']]->brand_item_number ?? ''
));
if ($brandItemNumber === '') {
$brandItemNumber = trim((string) (
$itemBrandItems[$row['item_number']]->brand_item_number ?? ''
));
}
if ($brandItemNumber !== '') {
$values['货号'] = $brandItemNumber;
}
$values['物料编号'] = '';
$values['型号'] = '';
$values['成本'] = '';
$values['发货金额'] = '';
if ($quotation !== null) {
$cost = $this->decimal($quotation->price_including_tax);
$quantity = $this->decimal($values['实发数量'] ?? null);
$values['物料编号'] = $materialNumber;
$values['型号'] = (string) ($quotation->material_desc ?? '');
$values['成本'] = $cost ?? '';
$values['发货金额'] = $cost !== null && $quantity !== null
? $this->multiplyDecimal($cost, $quantity)
: '';
} elseif ($mappedMaterialNumber === '' && $usesRepairedMaterial) {
$values['物料编号'] = $storedMaterialNumber;
$values['型号'] = $storedMaterialDescription;
}
return (object) $values;
}));
$statuses = $available ? $this->repository->statuses($companyId, $period) : [];
@ -128,4 +221,20 @@ class KukaPostingBasePageData
'error' => $error,
];
}
private function decimal(mixed $value): ?string
{
$normalized = str_replace(',', '', trim((string) $value));
return $normalized !== '' && is_numeric($normalized) ? $normalized : null;
}
private function multiplyDecimal(string $cost, string $quantity): string
{
if (function_exists('bcmul')) {
return bcmul($cost, $quantity, 4);
}
return number_format((float) $cost * (float) $quantity, 4, '.', '');
}
}

View File

@ -87,6 +87,107 @@ class KukaPostingBaseRepository
->all();
}
/**
* @param list<string> $itemNumbers
* @return array<string,object>
*/
public function materialMaps(int $companyId, array $itemNumbers): array
{
$itemNumbers = array_values(array_unique(array_filter(array_map(
static fn (mixed $value): string => trim((string) $value),
$itemNumbers,
))));
if ($itemNumbers === []
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_material_map_rows')) {
return [];
}
return $this->connection()
->table('kuka_posting_material_map_rows')
->where('company_id', $companyId)
->where('match_status', 'matched')
->whereIn('item_number', $itemNumbers)
->get(['item_number', 'material_number'])
->filter(static fn (object $row): bool => trim((string) $row->material_number) !== '')
->keyBy(static fn (object $row): string => (string) $row->item_number)
->all();
}
/**
* @param list<string> $lookupCodes
* @return array<string,object>
*/
public function brandItemMaps(int $companyId, array $lookupCodes): array
{
$lookupCodes = array_values(array_unique(array_filter(array_map(
static fn (mixed $value): string => trim((string) $value),
$lookupCodes,
))));
if ($lookupCodes === []
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_brand_item_map_rows')) {
return [];
}
return $this->connection()
->table('kuka_posting_brand_item_map_rows')
->where('company_id', $companyId)
->whereIn('product_code', $lookupCodes)
->get(['product_code', 'brand_item_number'])
->filter(static fn (object $row): bool => trim((string) $row->brand_item_number) !== '')
->keyBy(static fn (object $row): string => (string) $row->product_code)
->all();
}
/**
* @param list<string> $itemNumbers
* @return array<string,object>
*/
public function itemBrandItemMaps(int $companyId, array $itemNumbers): array
{
$itemNumbers = array_values(array_unique(array_filter(array_map(
static fn (mixed $value): string => trim((string) $value),
$itemNumbers,
))));
if ($itemNumbers === []
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_item_brand_item_map_rows')) {
return [];
}
return $this->connection()
->table('kuka_posting_item_brand_item_map_rows')
->where('company_id', $companyId)
->whereIn('item_number', $itemNumbers)
->get(['item_number', 'brand_item_number'])
->filter(static fn (object $row): bool => trim((string) $row->brand_item_number) !== '')
->keyBy(static fn (object $row): string => (string) $row->item_number)
->all();
}
/**
* @param list<string> $materialNumbers
* @return array<string,object>
*/
public function effectiveQuotations(int $companyId, array $materialNumbers): array
{
$materialNumbers = array_values(array_unique(array_filter(array_map(
static fn (mixed $value): string => trim((string) $value),
$materialNumbers,
))));
if ($materialNumbers === []
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) {
return [];
}
return $this->connection()
->table('kuka_posting_quotation_rows')
->where('company_id', $companyId)
->where('record_status', '生效')
->whereIn('material_number', $materialNumbers)
->get(['material_number', 'material_desc', 'price_including_tax'])
->keyBy(static fn (object $row): string => (string) $row->material_number)
->all();
}
public function paginate(
int $companyId,
string $period,

View File

@ -0,0 +1,434 @@
<?php
namespace App\Business\KukaPostingBase;
use App\Business\XlsxSheetReader;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
use InvalidArgumentException;
use RuntimeException;
class KukaPostingLabelImporter
{
private const LABEL_FIELD = '过账标签';
private const ALLOWED_LABELS = [
'是',
'补单(订单四组)',
];
private const IDENTITY_FIELDS = [
'店铺',
'内部订单号',
'线上订单号',
'商品编码',
'原始线上订单号',
];
private const UPDATE_CHUNK = 500;
public function __construct(
private readonly DatabaseManager $databases,
private readonly XlsxSheetReader $reader,
) {
}
/**
* @return array{
* period: string,
* dry_run: bool,
* label_column: string,
* rows: int,
* stores: array<string, int>,
* store_count: int,
* labels: array<string, int>,
* updated: int,
* unchanged: int,
* file_sha256: string
* }
*/
public function import(
string $path,
string $period,
?string $sheetName = null,
?string $labelColumn = null,
int $companyId = 1,
bool $dryRun = false,
): array {
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
}
if (! is_file($path) || ! is_readable($path)) {
throw new InvalidArgumentException('月度过账标签文件不存在或不可读。');
}
$connection = $this->connection();
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) {
throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。');
}
$allowedStores = array_values(array_filter(array_map(
static fn (mixed $store): string => trim((string) $store),
(array) config('kuka_posting.stores', []),
)));
if ($allowedStores === []) {
throw new RuntimeException('顾家过账基础数据店铺范围未配置。');
}
$labelColumn = trim((string) ($labelColumn ?? ''));
if ($labelColumn === '') {
$labelColumn = CarbonImmutable::createFromFormat('!Y-m', $period)
->format('Y年n月过账');
}
$sheetName = trim((string) ($sheetName ?? ''));
if ($sheetName === '') {
$sheetName = 'Sheet1';
}
$fileHash = hash_file('sha256', $path);
if (! is_string($fileHash)) {
throw new RuntimeException('无法计算月度过账标签文件摘要。');
}
$records = $this->readRecords(
$path,
$sheetName,
$labelColumn,
$allowedStores,
);
if ($dryRun) {
return $this->validateRows(
$connection,
$records,
$period,
$labelColumn,
$companyId,
false,
) + [
'dry_run' => true,
'file_sha256' => strtolower($fileHash),
];
}
$result = [];
$connection->transaction(function () use (
&$result,
$connection,
$records,
$period,
$labelColumn,
$companyId,
): void {
$result = $this->validateRows(
$connection,
$records,
$period,
$labelColumn,
$companyId,
true,
);
$this->applyLabels($connection, $records, $period, $companyId);
});
return $result + [
'dry_run' => false,
'file_sha256' => strtolower($fileHash),
];
}
/**
* @param list<string> $allowedStores
* @return list<array{excel_row_number: int, label: string, identity: array<string, string>}>
*/
private function readRecords(
string $path,
string $sheetName,
string $labelColumn,
array $allowedStores,
): array {
$records = [];
$excelRowNumber = 1;
foreach ($this->reader->rows(
$path,
array_merge([$labelColumn], self::IDENTITY_FIELDS),
[],
$sheetName,
) as $values) {
$excelRowNumber++;
$label = trim((string) ($values[$labelColumn] ?? ''));
if (! in_array($label, self::ALLOWED_LABELS, true)) {
throw new RuntimeException(sprintf(
'Excel 第 %d 行的“%s”只能为“%s”,当前值为“%s”。',
$excelRowNumber,
$labelColumn,
implode('”或“', self::ALLOWED_LABELS),
$label,
));
}
$identity = [];
foreach (self::IDENTITY_FIELDS as $field) {
$identity[$field] = trim((string) ($values[$field] ?? ''));
}
if (! in_array($identity['店铺'], $allowedStores, true)) {
throw new RuntimeException(sprintf(
'Excel 第 %d 行的店铺“%s”不在顾家过账基础数据范围内。',
$excelRowNumber,
$identity['店铺'],
));
}
$records[] = [
'excel_row_number' => $excelRowNumber,
'label' => $label,
'identity' => $identity,
];
}
if ($records === []) {
throw new RuntimeException('月度过账标签文件没有数据行。');
}
return $records;
}
/**
* @param list<array{excel_row_number: int, label: string, identity: array<string, string>}> $records
* @return array{
* period: string,
* label_column: string,
* rows: int,
* stores: array<string, int>,
* store_count: int,
* labels: array<string, int>,
* updated: int,
* unchanged: int
* }
*/
private function validateRows(
ConnectionInterface $connection,
array $records,
string $period,
string $labelColumn,
int $companyId,
bool $lockRows,
): array {
$expectedRows = count($records);
$databaseRows = $this->baseRowsQuery($connection, $period, $companyId)
->count();
if ($databaseRows !== $expectedRows) {
throw new RuntimeException(sprintf(
'月度过账标签文件有 %s 行,但共享镜像 %s 有 %s 行,行数不一致,未写入任何标签。',
number_format($expectedRows),
$period,
number_format($databaseRows),
));
}
$labels = array_fill_keys(self::ALLOWED_LABELS, 0);
$stores = [];
$updated = 0;
$unchanged = 0;
$index = 0;
$query = $this->baseRowsQuery($connection, $period, $companyId)
->orderBy('source_row_number');
if ($lockRows) {
$query->lockForUpdate();
}
foreach ($query->cursor() as $row) {
$record = $records[$index] ?? null;
if ($record === null) {
throw new RuntimeException('共享镜像行数多于月度过账标签文件,未写入任何标签。');
}
$sourceValues = $this->decodeSourceValues($row);
$this->assertIdentity($row, $sourceValues, $record);
$label = $record['label'];
$labels[$label]++;
$store = $record['identity']['店铺'];
$stores[$store] = ($stores[$store] ?? 0) + 1;
if (trim((string) ($sourceValues[self::LABEL_FIELD] ?? '')) === $label) {
$unchanged++;
} else {
$updated++;
}
$index++;
}
if ($index !== $expectedRows) {
throw new RuntimeException('共享镜像行数少于月度过账标签文件,未写入任何标签。');
}
ksort($stores);
return [
'period' => $period,
'label_column' => $labelColumn,
'rows' => $expectedRows,
'stores' => $stores,
'store_count' => count($stores),
'labels' => $labels,
'updated' => $updated,
'unchanged' => $unchanged,
];
}
/**
* @param list<array{excel_row_number: int, label: string, identity: array<string, string>}> $records
*/
private function applyLabels(
ConnectionInterface $connection,
array $records,
string $period,
int $companyId,
): void {
$index = 0;
$batch = [];
$flush = static function () use (&$batch, $connection): void {
if ($batch === []) {
return;
}
$connection->table('kuka_posting_base_rows')->upsert(
$batch,
['company_id', 'period', 'source_row_number'],
['source_values', 'row_hash'],
);
$batch = [];
};
foreach ($this->baseRowsQuery($connection, $period, $companyId)
->orderBy('source_row_number')
->cursor() as $row) {
$record = $records[$index] ?? null;
if ($record === null) {
throw new RuntimeException('共享镜像行数多于月度过账标签文件,标签写入已回滚。');
}
$sourceValues = $this->decodeSourceValues($row);
$this->assertIdentity($row, $sourceValues, $record);
$index++;
if (trim((string) ($sourceValues[self::LABEL_FIELD] ?? '')) === $record['label']) {
continue;
}
$sourceValues[self::LABEL_FIELD] = $record['label'];
$encoded = json_encode(
$sourceValues,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
);
$batch[] = [
'company_id' => $companyId,
'period' => $period,
'source_row_number' => (int) $row->source_row_number,
'store_name' => $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,
];
if (count($batch) >= self::UPDATE_CHUNK) {
$flush();
}
}
if ($index !== count($records)) {
throw new RuntimeException('共享镜像行数少于月度过账标签文件,标签写入已回滚。');
}
$flush();
}
/**
* @return array<string, mixed>
*/
private function decodeSourceValues(object $row): array
{
$values = json_decode(
(string) $row->source_values,
true,
512,
JSON_THROW_ON_ERROR,
);
if (! is_array($values)) {
throw new RuntimeException(sprintf(
'共享镜像 source_row_number=%d 的源数据不是有效对象。',
(int) $row->source_row_number,
));
}
return $values;
}
/**
* @param array<string, mixed> $sourceValues
* @param array{excel_row_number: int, label: string, identity: array<string, string>} $record
*/
private function assertIdentity(object $row, array $sourceValues, array $record): void
{
$databaseIdentity = [
'店铺' => trim((string) ($sourceValues['店铺'] ?? '')),
'内部订单号' => trim((string) ($sourceValues['内部订单号'] ?? '')),
'线上订单号' => trim((string) ($sourceValues['线上订单号'] ?? '')),
'商品编码' => trim((string) ($sourceValues['商品编码'] ?? '')),
'原始线上订单号' => trim((string) ($sourceValues['原始线上订单号'] ?? '')),
];
foreach ($databaseIdentity as $field => $value) {
if ($value !== $record['identity'][$field]) {
throw new RuntimeException(sprintf(
'Excel 第 %d 行与共享镜像 source_row_number=%d 的“%s”不一致,未写入任何标签。',
$record['excel_row_number'],
(int) $row->source_row_number,
$field,
));
}
}
// 顶层订单字段是页面搜索用的冗余索引,历史数据可能保留旧值。
// 行身份以 source_values 中的业务源字段为准,本命令不会改动这些索引字段。
}
private function baseRowsQuery(
ConnectionInterface $connection,
string $period,
int $companyId,
) {
return $connection->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->select([
'id',
'source_row_number',
'store_name',
'internal_order_no',
'online_order_no',
'product_code',
'source_values',
'imported_at',
]);
}
private function connection(): ConnectionInterface
{
return $this->databases->connection($this->connectionName());
}
private function connectionName(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
}

View File

@ -0,0 +1,505 @@
<?php
namespace App\Business\KukaPostingBase;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
use RuntimeException;
use Throwable;
class KukaPostingMaterialMapSynchronizer
{
public const SOURCE_KEY = 'furniture3d';
public const DATASET_KEY = 'furniture3d.kuka-material-map';
private const INSERT_CHUNK = 500;
private const SOURCE_ITEM_CHUNK = 200;
public function __construct(
private readonly DatabaseManager $databases,
private readonly UpstreamReadOnlyQueryFactory $queries,
) {
}
/**
* @return array{
* dry_run: bool,
* items: int,
* matched: int,
* unmatched: int,
* ambiguous: int,
* direct: int,
* archive: int,
* brand_sku: int,
* brand_item_mappings: int,
* brand_sku_mappings: int,
* item_brand_mappings: int
* }
*/
public function sync(int $companyId = 1, ?string $period = null, bool $dryRun = false): array
{
$connection = $this->connection();
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_material_map_rows')
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_brand_item_map_rows')
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_item_brand_item_map_rows')
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) {
throw new RuntimeException('顾家物料匹配所需的数据表尚未建立,请先执行数据库迁移。');
}
$started = microtime(true);
$this->markState('running', 0, null, $started);
try {
$identifiers = $this->sourceIdentifiers($connection, $companyId, $period);
$items = $identifiers['items'];
if ($items === []) {
throw new RuntimeException('当前账期没有可用于匹配的货号。');
}
$quotations = $this->activeQuotations($connection, $companyId);
[$direct, $archive, $brandSku] = $this->sourceCandidates($items);
$rows = $this->resolveRows($companyId, $items, $quotations, $direct, $archive, $brandSku);
$stats = $this->stats($rows);
$displayItemResult = $this->displayItemRows(
$companyId,
$identifiers['style_codes'],
$items,
);
if (! $dryRun) {
$connection->transaction(function () use ($connection, $companyId, $rows, $displayItemResult): void {
$connection->table('kuka_posting_material_map_rows')
->where('company_id', $companyId)
->delete();
$connection->table('kuka_posting_brand_item_map_rows')
->where('company_id', $companyId)
->delete();
$connection->table('kuka_posting_item_brand_item_map_rows')
->where('company_id', $companyId)
->delete();
foreach (array_chunk($rows, self::INSERT_CHUNK) as $chunk) {
$connection->table('kuka_posting_material_map_rows')->insert($chunk);
}
foreach (array_chunk($displayItemResult['style_rows'], self::INSERT_CHUNK) as $chunk) {
$connection->table('kuka_posting_brand_item_map_rows')->insert($chunk);
}
foreach (array_chunk($displayItemResult['item_rows'], self::INSERT_CHUNK) as $chunk) {
$connection->table('kuka_posting_item_brand_item_map_rows')->insert($chunk);
}
});
$this->markState('succeeded', count($rows), null, $started);
}
return ['dry_run' => $dryRun] + $stats + [
'brand_item_mappings' => count($displayItemResult['style_rows'])
+ count($displayItemResult['item_rows']),
'brand_sku_mappings' => count($displayItemResult['style_rows']),
'item_brand_mappings' => count($displayItemResult['item_rows']),
];
} catch (Throwable $exception) {
if (! $dryRun) {
$this->markState('failed', 0, $exception::class, $started);
}
throw $exception;
}
}
/** @return array{items:list<string>,style_codes:list<string>} */
private function sourceIdentifiers(ConnectionInterface $connection, int $companyId, ?string $period): array
{
$items = [];
$styleCodes = [];
$query = $connection->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->when($period !== null, fn ($builder) => $builder->where('period', $period));
$query->select(['id', 'source_values'])
->orderBy('id')
->chunkById(1000, function ($rows) use (&$items, &$styleCodes): void {
foreach ($rows as $row) {
$values = json_decode((string) $row->source_values, true);
if (! is_array($values)) {
continue;
}
$itemNumber = trim((string) ($values['货号'] ?? ''));
if ($itemNumber !== '') {
$items[$itemNumber] = true;
}
$styleCode = trim((string) ($values['款式编码'] ?? ''));
if ($styleCode !== '') {
$styleCodes[$styleCode] = true;
}
}
});
$items = array_keys($items);
sort($items, SORT_STRING);
$styleCodes = array_keys($styleCodes);
sort($styleCodes, SORT_STRING);
return ['items' => $items, 'style_codes' => $styleCodes];
}
/**
* @param list<string> $styleCodes
* @param list<string> $itemNumbers
* @return array{
* style_rows:list<array<string,mixed>>,
* item_rows:list<array<string,mixed>>
* }
*/
private function displayItemRows(int $companyId, array $styleCodes, array $itemNumbers): array
{
$query = $this->queries->forSourceWithTimeout(self::SOURCE_KEY, 15);
$styleRows = [];
$itemRows = [];
$now = now();
foreach (array_chunk($styleCodes, self::SOURCE_ITEM_CHUNK) as $chunk) {
foreach ($query->select($this->brandItemSql(count($chunk)), $chunk) as $sourceRow) {
$styleCode = trim((string) ($sourceRow['lookup_code'] ?? ''));
$brandItemNumber = trim((string) ($sourceRow['brand_item_number'] ?? ''));
if ($styleCode === '' || $brandItemNumber === '') {
continue;
}
$sourceImportedAt = trim((string) ($sourceRow['source_imported_at'] ?? ''));
$styleRows[] = [
'company_id' => $companyId,
'product_code' => $styleCode,
'brand_item_number' => $brandItemNumber,
'source_imported_at' => $sourceImportedAt === '' ? null : $sourceImportedAt,
'synced_at' => $now,
];
}
}
foreach (array_chunk($itemNumbers, self::SOURCE_ITEM_CHUNK) as $chunk) {
foreach ($query->select($this->brandItemSql(count($chunk)), $chunk) as $sourceRow) {
$itemNumber = trim((string) ($sourceRow['lookup_code'] ?? ''));
$brandItemNumber = trim((string) ($sourceRow['brand_item_number'] ?? ''));
if ($itemNumber === '' || $brandItemNumber === '') {
continue;
}
$sourceImportedAt = trim((string) ($sourceRow['source_imported_at'] ?? ''));
$itemRows[] = [
'company_id' => $companyId,
'item_number' => $itemNumber,
'brand_item_number' => $brandItemNumber,
'source_imported_at' => $sourceImportedAt === '' ? null : $sourceImportedAt,
'synced_at' => $now,
];
}
}
return [
'style_rows' => $styleRows,
'item_rows' => $itemRows,
];
}
/** @return array<string,string> */
private function activeQuotations(ConnectionInterface $connection, int $companyId): array
{
return $connection->table('kuka_posting_quotation_rows')
->where('company_id', $companyId)
->where('record_status', '生效')
->get(['material_number', 'material_desc'])
->mapWithKeys(static function (object $row): array {
$materialNumber = trim((string) $row->material_number);
return $materialNumber === ''
? []
: [$materialNumber => trim((string) $row->material_desc)];
})
->all();
}
/**
* @param list<string> $items
* @return array{
* 0:array<string,array<string,true>>,
* 1:array<string,array<string,true>>,
* 2:array<string,array<string,true>>
* }
*/
private function sourceCandidates(array $items): array
{
$direct = [];
$archive = [];
$brandSku = [];
$query = $this->queries->forSourceWithTimeout(self::SOURCE_KEY, 15);
foreach (array_chunk($items, self::SOURCE_ITEM_CHUNK) as $chunk) {
$directRows = $query->select($this->directSql(count($chunk)), $chunk);
$this->collectCandidates(
$direct,
$directRows,
);
$this->collectCandidates($brandSku, $directRows, 'brand_sku');
$this->collectCandidates(
$archive,
$query->select($this->archiveSql(count($chunk)), $chunk),
);
}
return [$direct, $archive, $brandSku];
}
/**
* @param array<string,array<string,true>> $target
* @param list<array<string,mixed>> $rows
*/
private function collectCandidates(
array &$target,
array $rows,
string $materialField = 'material_number',
): void
{
foreach ($rows as $row) {
$itemNumber = trim((string) ($row['item_number'] ?? ''));
$materialNumber = trim((string) ($row[$materialField] ?? ''));
if ($itemNumber === '' || $materialNumber === '') {
continue;
}
$target[$itemNumber][$materialNumber] = true;
}
}
private function directSql(int $count): string
{
$placeholders = implode(', ', array_fill(0, $count, '?'));
return 'SELECT "normalizedSku" AS item_number, '
. 'TRIM(updates->>\'materialNo\') AS material_number, '
. 'TRIM(updates->>\'brandSkuCode\') AS brand_sku '
. 'FROM public."BarcodePrintImportRecord" '
. 'WHERE "normalizedSku" IN (' . $placeholders . ') '
. 'AND (COALESCE(updates->>\'materialNo\', \'\') <> \'\' '
. 'OR COALESCE(updates->>\'brandSkuCode\', \'\') <> \'\') '
. 'GROUP BY "normalizedSku", updates->>\'materialNo\', updates->>\'brandSkuCode\' '
. 'LIMIT 5000';
}
private function archiveSql(int $count): string
{
$placeholders = implode(', ', array_fill(0, $count, '?'));
return 'SELECT TRIM(sku) AS item_number, TRIM(barcode) AS material_number '
. 'FROM public."SupplyChainProductArchive" '
. 'WHERE sku IN (' . $placeholders . ') '
. 'AND COALESCE(TRIM(barcode), \'\') <> \'\' '
. 'GROUP BY sku, barcode '
. 'LIMIT 5000';
}
private function brandItemSql(int $count): string
{
$placeholders = implode(', ', array_fill(0, $count, '?'));
return 'SELECT DISTINCT ON ("normalizedSku") '
. '"normalizedSku" AS lookup_code, '
. 'TRIM(updates->>\'brandSkuCode\') AS brand_item_number, '
. '"importedAt" AS source_imported_at '
. 'FROM public."BarcodePrintImportRecord" '
. 'WHERE "normalizedSku" IN (' . $placeholders . ') '
. 'AND COALESCE(TRIM(updates->>\'brandSkuCode\'), \'\') <> \'\' '
. 'ORDER BY "normalizedSku", "importedAt" DESC NULLS LAST, id DESC '
. 'LIMIT 5000';
}
/**
* @param list<string> $items
* @param array<string,true> $quoteMaterials
* @param array<string,array<string,true>> $direct
* @param array<string,array<string,true>> $archive
* @param array<string,array<string,true>> $brandSku
* @return list<array<string,mixed>>
*/
private function resolveRows(
int $companyId,
array $items,
array $quotations,
array $direct,
array $archive,
array $brandSku,
): array {
$quoteKeys = array_keys($quotations);
$brandMaterials = $this->quoteBrandMaterials($quotations);
$rows = [];
$now = now();
foreach ($items as $itemNumber) {
$directMatches = array_values(array_unique(array_intersect(
array_keys($direct[$itemNumber] ?? []),
$quoteKeys,
)));
$archiveMatches = array_values(array_unique(array_intersect(
array_keys($archive[$itemNumber] ?? []),
$quoteKeys,
)));
$brandMatches = [];
foreach (array_keys($brandSku[$itemNumber] ?? []) as $brand) {
foreach (array_keys($brandMaterials[$brand] ?? []) as $materialNumber) {
$brandMatches[] = $materialNumber;
}
}
$brandMatches = array_values(array_unique($brandMatches));
$matches = array_values(array_unique(array_merge(
$directMatches,
$archiveMatches,
$brandMatches,
)));
$materialNumber = null;
$matchSource = null;
if (count($directMatches) === 1) {
$materialNumber = $directMatches[0];
$matchSource = 'barcode_material_no';
} elseif ($directMatches === [] && count($archiveMatches) === 1) {
$materialNumber = $archiveMatches[0];
$matchSource = 'archive_barcode';
} elseif ($directMatches === [] && $archiveMatches === [] && count($brandMatches) === 1) {
$materialNumber = $brandMatches[0];
$matchSource = 'brand_sku';
}
$status = match (true) {
$materialNumber !== null => 'matched',
count($matches) > 1 => 'ambiguous',
default => 'unmatched',
};
$rows[] = [
'company_id' => $companyId,
'item_number' => $itemNumber,
'material_number' => $materialNumber,
'match_status' => $status,
'match_source' => $matchSource,
'candidate_count' => count($matches),
'candidate_materials' => json_encode(
$matches,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
),
'synced_at' => $now,
];
}
return $rows;
}
/**
* @param array<string,string> $quotations
* @return array<string,array<string,true>>
*/
private function quoteBrandMaterials(array $quotations): array
{
$materials = [];
foreach ($quotations as $materialNumber => $description) {
$brand = trim(explode('~', $description, 2)[0]);
if ($brand !== '') {
$materials[$brand][$materialNumber] = true;
}
}
return $materials;
}
/** @param list<array<string,mixed>> $rows */
private function stats(array $rows): array
{
$counts = ['matched' => 0, 'unmatched' => 0, 'ambiguous' => 0];
$sources = ['barcode_material_no' => 0, 'archive_barcode' => 0, 'brand_sku' => 0];
foreach ($rows as $row) {
$counts[$row['match_status']]++;
if ($row['match_source'] !== null) {
$sources[$row['match_source']]++;
}
}
return [
'items' => count($rows),
'matched' => $counts['matched'],
'unmatched' => $counts['unmatched'],
'ambiguous' => $counts['ambiguous'],
'direct' => $sources['barcode_material_no'],
'archive' => $sources['archive_barcode'],
'brand_sku' => $sources['brand_sku'],
];
}
private function markState(
string $status,
int $rowCount,
?string $errorCode,
float $started,
): void {
if (! Schema::connection($this->connectionName())->hasTable('business_mirror_table_states')) {
return;
}
$connection = $this->connection();
$now = now();
$existing = $connection->table('business_mirror_table_states')
->where('dataset_key', self::DATASET_KEY)
->first();
$values = [
'source_key' => self::SOURCE_KEY,
'source_object' => 'public.SupplyChainProductArchive + public.BarcodePrintImportRecord',
'target_table' => 'kuka_posting_material_map_rows',
'status' => $status,
'run_mode' => 'targeted',
'last_attempted_at' => $now,
'last_error_code' => $errorCode === null ? null : mb_substr($errorCode, 0, 120),
'updated_at' => $now,
];
if ($status === 'succeeded') {
$values += [
'initial_completed_at' => $existing?->initial_completed_at ?? $now,
'last_succeeded_at' => $now,
'last_upserted_rows' => $rowCount,
'mirror_row_count' => $rowCount,
];
if (Schema::connection($this->connectionName())
->hasColumn('business_mirror_table_states', 'mirror_row_count_is_exact')) {
$values['mirror_row_count_is_exact'] = true;
}
}
if ($existing !== null) {
$connection->table('business_mirror_table_states')
->where('dataset_key', self::DATASET_KEY)
->update($values);
return;
}
$connection->table('business_mirror_table_states')->insert($values + [
'dataset_key' => self::DATASET_KEY,
'created_at' => $now,
]);
}
private function connection(): ConnectionInterface
{
return $this->databases->connection($this->connectionName());
}
private function connectionName(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,314 @@
<?php
namespace App\Business\KukaPostingPerformance;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Throwable;
class KukaPostingPerformancePageData
{
private const EXCLUDED_PLATFORMS = ['京东网银钱包'];
private const INCOME_SQL = 'COALESCE(income_amount, 0)'
. ' + COALESCE(discount_amount, 0)'
. ' + COALESCE(offset_amount, 0)'
. ' + COALESCE(refund_amount, 0)'
. ' + COALESCE(default_compensation_amount, 0)';
/**
* 业绩明细的 12 家店铺月度收入汇总。
*
* 收入口径:账单收入 + 优惠金额 + 冲减金额 + 退款金额 + 违约赔付(冲减收入)。
*
* @return array<string,mixed>
*/
public function build(Request $request): array
{
$stores = array_values(array_unique(array_filter(array_map(
static fn (mixed $store): string => trim((string) $store),
(array) config('kuka_posting.stores', []),
))));
if ($stores === []) {
return $this->emptyResult($stores, '尚未配置灵珊店铺业绩的店铺范围。');
}
try {
$months = $this->availableMonths();
$month = $this->selectedMonth((string) $request->query('month', ''), $months);
if ($month === null) {
return $this->emptyResult($stores, '业绩明细暂时没有可汇总的月份。');
}
$storeRows = cache()->remember(
$this->cacheKey('stores', $month, $stores),
now()->addMinutes(10),
fn (): array => $this->storeRows($month, $stores),
);
$monthlyTotals = cache()->remember(
$this->cacheKey('months', implode('|', $months), $stores),
now()->addMinutes(10),
fn (): array => $this->monthlyTotals($months, $stores),
);
$summary = $this->summary($storeRows);
return [
'stores' => $storeRows,
'months' => $months,
'month' => $month,
'month_label' => $this->monthLabel($month),
'summary' => $summary,
'monthly_totals' => $monthlyTotals,
'error' => null,
];
} catch (Throwable $exception) {
report($exception);
return $this->emptyResult(
$stores,
'灵珊店铺业绩暂时无法读取,请稍后重试;这不代表该月收入为 0。',
);
}
}
/**
* @return list<string>
*/
private function availableMonths(): array
{
return cache()->remember(
$this->cacheKey('available-months'),
now()->addMinutes(10),
function (): array {
$range = $this->connection()
->table('store_receipt_order_match_rows')
->whereNotIn('platform', self::EXCLUDED_PLATFORMS)
->whereNotNull('report_month')
->selectRaw('MIN(report_month) as min_month, MAX(report_month) as max_month')
->first();
if (($range->min_month ?? null) === null || ($range->max_month ?? null) === null) {
return [];
}
$end = CarbonImmutable::parse((string) $range->max_month)->startOfMonth();
$start = CarbonImmutable::parse((string) $range->min_month)->startOfMonth();
$earliest = now()->startOfMonth()->subMonthsNoOverflow(11);
if ($start->lt($earliest)) {
$start = $earliest;
}
$months = [];
for ($cursor = $end; $cursor->gte($start); $cursor = $cursor->subMonthNoOverflow()) {
$months[] = $cursor->format('Y-m');
}
return $months;
},
);
}
/**
* @param list<string> $months
*/
private function selectedMonth(string $requested, array $months): ?string
{
if (preg_match('/^\d{4}-\d{2}$/', $requested) === 1 && in_array($requested, $months, true)) {
return $requested;
}
$previousMonth = now()->subMonthNoOverflow()->format('Y-m');
return in_array($previousMonth, $months, true) ? $previousMonth : ($months[0] ?? null);
}
/**
* @param list<string> $stores
* @return list<array<string,mixed>>
*/
private function storeRows(string $month, array $stores): array
{
$aggregates = $this->connection()
->table('store_receipt_order_match_rows')
->where('report_month', $month . '-01')
->whereIn('store_name', $stores)
->whereNotIn('platform', self::EXCLUDED_PLATFORMS)
->selectRaw(
'store_name,
COUNT(*) as row_count,
SUM(COALESCE(income_amount, 0)) as income_amount,
SUM(COALESCE(discount_amount, 0)) as discount_amount,
SUM(COALESCE(offset_amount, 0)) as offset_amount,
SUM(COALESCE(refund_amount, 0)) as refund_amount,
SUM(COALESCE(default_compensation_amount, 0)) as default_compensation_amount,
SUM(' . self::INCOME_SQL . ') as total_income,
MAX(imported_at) as imported_at'
)
->groupBy('store_name')
->get()
->keyBy('store_name');
return array_map(static function (string $store) use ($aggregates): array {
$row = $aggregates->get($store);
return [
'store_name' => $store,
'row_count' => (int) ($row->row_count ?? 0),
'income_amount' => round((float) ($row->income_amount ?? 0), 2),
'discount_amount' => round((float) ($row->discount_amount ?? 0), 2),
'offset_amount' => round((float) ($row->offset_amount ?? 0), 2),
'refund_amount' => round((float) ($row->refund_amount ?? 0), 2),
'default_compensation_amount' => round((float) ($row->default_compensation_amount ?? 0), 2),
'total_income' => round((float) ($row->total_income ?? 0), 2),
'imported_at' => $row->imported_at ?? null,
'has_data' => $row !== null,
];
}, $stores);
}
/**
* @param list<string> $months
* @param list<string> $stores
* @return list<array{month:string,label:string,total_income:float,row_count:int}>
*/
private function monthlyTotals(array $months, array $stores): array
{
$totals = [];
foreach ($months as $month) {
$row = $this->connection()
->table('store_receipt_order_match_rows')
->where('report_month', $month . '-01')
->whereIn('store_name', $stores)
->whereNotIn('platform', self::EXCLUDED_PLATFORMS)
->selectRaw(
'COUNT(*) as row_count,
SUM(' . self::INCOME_SQL . ') as total_income'
)
->first();
$totals[] = [
'month' => $month,
'label' => $this->monthLabel($month),
'total_income' => round((float) ($row->total_income ?? 0), 2),
'row_count' => (int) ($row->row_count ?? 0),
];
}
return $totals;
}
/**
* @param list<array<string,mixed>> $rows
* @return array<string,mixed>
*/
private function summary(array $rows): array
{
$summary = [
'row_count' => 0,
'stores_with_data' => 0,
'income_amount' => 0.0,
'discount_amount' => 0.0,
'offset_amount' => 0.0,
'refund_amount' => 0.0,
'default_compensation_amount' => 0.0,
'total_income' => 0.0,
'imported_at' => null,
];
foreach ($rows as $row) {
$summary['row_count'] += (int) $row['row_count'];
$summary['stores_with_data'] += $row['has_data'] ? 1 : 0;
foreach ([
'income_amount',
'discount_amount',
'offset_amount',
'refund_amount',
'default_compensation_amount',
'total_income',
] as $field) {
$summary[$field] += (float) $row[$field];
}
if ($row['imported_at'] !== null
&& ($summary['imported_at'] === null || $row['imported_at'] > $summary['imported_at'])) {
$summary['imported_at'] = $row['imported_at'];
}
}
foreach ([
'income_amount',
'discount_amount',
'offset_amount',
'refund_amount',
'default_compensation_amount',
'total_income',
] as $field) {
$summary[$field] = round((float) $summary[$field], 2);
}
return $summary;
}
/**
* @param list<string> $stores
* @return array<string,mixed>
*/
private function emptyResult(array $stores, string $error): array
{
return [
'stores' => array_map(static fn (string $store): array => [
'store_name' => $store,
'row_count' => 0,
'income_amount' => 0.0,
'discount_amount' => 0.0,
'offset_amount' => 0.0,
'refund_amount' => 0.0,
'default_compensation_amount' => 0.0,
'total_income' => 0.0,
'imported_at' => null,
'has_data' => false,
], $stores),
'months' => [],
'month' => null,
'month_label' => '—',
'summary' => [
'row_count' => 0,
'stores_with_data' => 0,
'income_amount' => 0.0,
'discount_amount' => 0.0,
'offset_amount' => 0.0,
'refund_amount' => 0.0,
'default_compensation_amount' => 0.0,
'total_income' => 0.0,
'imported_at' => null,
],
'monthly_totals' => [],
'error' => $error,
];
}
private function connection()
{
return DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
}
private function monthLabel(string $month): string
{
return substr($month, 0, 4) . '年' . (int) substr($month, 5, 2) . '月';
}
/**
* @param list<string> $stores
*/
private function cacheKey(string $scope, string $period = '', array $stores = []): string
{
return 'kuka-posting-performance-v1:' . $scope . ':' . md5(json_encode([
$period,
$stores,
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
}

View File

@ -0,0 +1,251 @@
<?php
namespace App\Business\KukaPostingQuotation;
use App\Business\XlsxSheetReader;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
class KukaPostingQuotationImporter
{
private const INSERT_CHUNK = 500;
public function __construct(
private readonly DatabaseManager $databases,
private readonly XlsxSheetReader $reader,
) {
}
/**
* @return array{
* dry_run: bool,
* rows: int,
* material_count: int,
* status_counts: array<string, int>,
* file_sha256: string
* }
*/
public function import(
string $path,
?string $sheetName = null,
int $companyId = 1,
bool $dryRun = false,
): array {
if (! is_file($path) || ! is_readable($path)) {
throw new InvalidArgumentException('顾家报价单文件不存在或不可读。');
}
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_imports')
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) {
throw new RuntimeException('顾家报价单表尚未建立,请先执行数据库迁移。');
}
$fields = (array) config('kuka_posting.quotation_fields', []);
$sourceColumns = array_values(array_filter(array_map(
static fn (array $field): string => trim((string) ($field['source'] ?? '')),
$fields,
)));
if ($fields === [] || count($sourceColumns) !== count($fields)) {
throw new RuntimeException('顾家报价单字段配置不完整。');
}
$keyField = (string) config('kuka_posting.quotation_key_field', 'MaterialNumber');
$statusField = (string) config('kuka_posting.quotation_status_field', 'RecordStatus');
if (! in_array($keyField, $sourceColumns, true) || ! in_array($statusField, $sourceColumns, true)) {
throw new RuntimeException('顾家报价单缺少物料编码或状态字段配置。');
}
$sheetName = trim((string) ($sheetName ?: config('kuka_posting.quotation_source_sheet', 'Sheet1')));
$fileHash = hash_file('sha256', $path);
if (! is_string($fileHash)) {
throw new RuntimeException('无法计算顾家报价单文件摘要。');
}
$connection = $this->connection();
$rows = [];
$materials = [];
$statusCounts = [];
$sourceRowNumber = 1;
$now = now();
foreach ($this->reader->rows($path, $sourceColumns, [], $sheetName) as $sourceValues) {
$sourceRowNumber++;
// 前两行分别是系统字段名和中文表名,真实报价记录从第 3 行开始。
if ($sourceRowNumber < 3) {
continue;
}
if (count(array_filter(
$sourceValues,
static fn (mixed $value): bool => trim((string) $value) !== '',
)) === 0) {
continue;
}
$payload = [];
foreach ($fields as $field) {
$source = (string) $field['source'];
$value = trim((string) ($sourceValues[$source] ?? ''));
if (($field['kind'] ?? null) === 'date' && $value !== '') {
$value = $this->normalizeDate($value);
}
$payload[(string) $field['name']] = $value;
}
$materialNumber = trim((string) ($payload['material_number'] ?? ''));
if ($materialNumber === '') {
throw new RuntimeException('顾家报价单第 ' . $sourceRowNumber . ' 行缺少物料编码。');
}
if (isset($materials[$materialNumber])) {
throw new RuntimeException('顾家报价单存在重复物料编码:' . $materialNumber);
}
$materials[$materialNumber] = true;
$status = trim((string) ($payload['record_status'] ?? ''));
if ($status !== '') {
$statusCounts[$status] = ($statusCounts[$status] ?? 0) + 1;
}
$rows[] = [
'company_id' => $companyId,
'material_number' => $materialNumber,
'material_desc' => $this->limit((string) ($payload['material_desc'] ?? ''), 500),
'supplier_account' => $this->limit((string) ($payload['supplier_account'] ?? ''), 191),
'supplier_name' => $this->limit((string) ($payload['supplier_name'] ?? ''), 500),
'record_status' => $this->limit($status, 64),
'price_including_tax' => $this->decimal((string) ($payload['price_including_tax'] ?? '')),
'price_excluding_tax' => $this->decimal((string) ($payload['price_excluding_tax'] ?? '')),
'price_valid_date' => $this->nullableValue((string) ($payload['price_valid_date'] ?? '')),
'price_expiry_date' => $this->nullableValue((string) ($payload['price_expiry_date'] ?? '')),
'row_hash' => hash(
'sha256',
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
),
'source_values' => json_encode(
$payload,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
),
'source_row_number' => $sourceRowNumber,
'imported_at' => $now,
];
}
if ($rows === []) {
throw new RuntimeException('顾家报价单中没有可导入的报价记录。');
}
ksort($statusCounts);
$write = function () use (
$connection,
$companyId,
&$rows,
$statusCounts,
$sheetName,
$path,
$fileHash,
$now,
$dryRun,
): void {
if ($dryRun) {
return;
}
$connection->table('kuka_posting_quotation_rows')
->where('company_id', $companyId)
->delete();
foreach (array_chunk($rows, self::INSERT_CHUNK) as $chunk) {
$connection->table('kuka_posting_quotation_rows')->insert($chunk);
}
$connection->table('kuka_posting_quotation_imports')->upsert(
[[
'company_id' => $companyId,
'row_count' => count($rows),
'material_count' => count($rows),
'status_counts' => json_encode($statusCounts, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'file_name' => basename($path),
'file_sha256' => strtolower($fileHash),
'source_sheet' => $sheetName,
'completed_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]],
['company_id'],
[
'row_count',
'material_count',
'status_counts',
'file_name',
'file_sha256',
'source_sheet',
'completed_at',
'updated_at',
],
);
};
if ($dryRun) {
$write();
} else {
$connection->transaction($write);
}
return [
'dry_run' => $dryRun,
'rows' => count($rows),
'material_count' => count($materials),
'status_counts' => $statusCounts,
'file_sha256' => strtolower($fileHash),
];
}
private function connection(): ConnectionInterface
{
return $this->databases->connection($this->connectionName());
}
private function connectionName(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
private function normalizeDate(string $value): string
{
if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) {
return gmdate('Y-m-d H:i:s', (int) round(((float) $value - 25569) * 86400));
}
try {
return CarbonImmutable::parse($value, 'Asia/Shanghai')->format('Y-m-d H:i:s');
} catch (Throwable) {
throw new InvalidArgumentException('顾家报价单日期格式无法识别:' . $value);
}
}
private function decimal(string $value): ?string
{
$value = str_replace(',', '', trim($value));
return $value !== '' && is_numeric($value) ? $value : null;
}
private function nullableValue(string $value): ?string
{
return $value === '' ? null : $value;
}
private function limit(string $value, int $length): ?string
{
$value = trim($value);
return $value === '' ? null : mb_substr($value, 0, $length);
}
}

View File

@ -0,0 +1,178 @@
<?php
namespace App\Business\KukaPostingQuotation;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;
class KukaPostingQuotationPageData
{
/**
* @return array<string,mixed>
*/
public function build(Request $request, int $companyId): array
{
$fields = array_values((array) config('kuka_posting.quotation_fields', []));
$perPage = (int) $request->integer('per_page', 50);
if (! in_array($perPage, [50, 100, 200], true)) {
$perPage = 50;
}
$page = max(1, (int) $request->integer('page', 1));
$keyword = mb_substr(trim((string) $request->query('keyword', '')), 0, 120);
$status = mb_substr(trim((string) $request->query('status', '')), 0, 64);
$empty = new LengthAwarePaginator([], 0, $perPage, $page, [
'path' => $request->url(),
'query' => $request->query(),
]);
if ($fields === []) {
return $this->result($empty, [], $keyword, $status, $perPage, '顾家报价单字段配置不完整。');
}
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
$schema = Schema::connection($connectionName);
if (! $schema->hasTable('kuka_posting_quotation_rows')
|| ! $schema->hasTable('kuka_posting_quotation_imports')) {
return $this->result($empty, $fields, $keyword, $status, $perPage, '顾家报价单镜像尚未建立,请先执行数据库迁移和报价单导入。');
}
try {
$connection = DB::connection($connectionName);
$import = $connection->table('kuka_posting_quotation_imports')
->where('company_id', $companyId)
->first();
$statuses = $connection->table('kuka_posting_quotation_rows')
->where('company_id', $companyId)
->whereNotNull('record_status')
->where('record_status', '!=', '')
->distinct()
->orderBy('record_status')
->pluck('record_status')
->map(static fn (mixed $value): string => (string) $value)
->all();
if ($status !== '' && ! in_array($status, $statuses, true)) {
$status = '';
}
$query = $connection->table('kuka_posting_quotation_rows')
->where('company_id', $companyId);
if ($keyword !== '') {
$like = '%' . addcslashes($keyword, '\\%_') . '%';
$query->where(static function ($nested) use ($like): void {
$nested->where('material_number', 'like', $like)
->orWhere('material_desc', 'like', $like)
->orWhere('supplier_account', 'like', $like)
->orWhere('supplier_name', 'like', $like);
});
}
if ($status !== '') {
$query->where('record_status', $status);
}
$rows = $query
->orderBy('material_number')
->paginate($perPage, ['*'], 'page', $page)
->withQueryString();
$rows->setCollection($rows->getCollection()->map(static function (object $row): object {
$values = json_decode((string) $row->source_values, true);
return (object) (is_array($values) ? $values : []);
}));
$range = $connection->table('kuka_posting_quotation_rows')
->where('company_id', $companyId)
->selectRaw('MIN(price_valid_date) as min_valid, MAX(price_expiry_date) as max_expiry')
->first();
$statusCounts = json_decode((string) ($import->status_counts ?? ''), true);
return $this->result(
$rows,
$fields,
$keyword,
$status,
$perPage,
null,
[
'rows' => (int) ($import->row_count ?? 0),
'materials' => (int) ($import->material_count ?? 0),
'statuses' => is_array($statusCounts) ? $statusCounts : [],
'valid_from' => $range->min_valid ?? null,
'valid_to' => $range->max_expiry ?? null,
'file_name' => (string) ($import->file_name ?? ''),
'file_sha256' => (string) ($import->file_sha256 ?? ''),
'source_sheet' => (string) ($import->source_sheet ?? ''),
'completed_at' => (string) ($import->completed_at ?? ''),
],
$statuses,
);
} catch (Throwable $exception) {
report($exception);
return $this->result(
$empty,
$fields,
$keyword,
$status,
$perPage,
'顾家报价单暂时无法读取,请稍后重试;这不代表报价数据为 0。',
);
}
}
/**
* @param list<array<string,mixed>> $fields
* @param list<string> $statuses
* @param array<string,mixed> $import
* @return array<string,mixed>
*/
private function result(
LengthAwarePaginator $rows,
array $fields,
string $keyword,
string $status,
int $perPage,
?string $error,
array $import = [],
array $statuses = [],
): array {
$directoryFields = array_map(static fn (array $field): array => [
'name' => (string) $field['name'],
'source' => (string) $field['name'],
'label' => (string) $field['label'],
'kind' => (string) ($field['kind'] ?? 'text'),
'tones' => (array) ($field['tones'] ?? []),
], $fields);
return [
'directory' => [
'title' => '顾家报价单 · 价格明细',
'icon' => 'request_quote',
'status' => '顾家报价单',
'description' => '顾家 SRM 报价数据原始字段;当前数据集共 '
. number_format((int) ($import['rows'] ?? 0)) . ' 条,物料编码唯一。',
'empty' => '顾家报价单尚未导入。',
'fields' => $directoryFields,
],
'rows' => $rows,
'filters' => [
'keyword' => $keyword,
'status' => $status,
'per_page' => $perPage,
],
'statuses' => $statuses,
'import' => $import,
'summary' => [
'filtered_rows' => $rows->total(),
'rows' => (int) ($import['rows'] ?? 0),
'materials' => (int) ($import['materials'] ?? 0),
'valid_from' => $import['valid_from'] ?? null,
'valid_to' => $import['valid_to'] ?? null,
'completed_at' => $import['completed_at'] ?? null,
],
'error' => $error,
];
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,170 @@
<?php
namespace App\Business\Piaoju;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class PiaojuSellerQuotaClient
{
/**
* @return list<array<string,mixed>>
*/
public function fetchAll(): array
{
$this->prepare();
$rows = [];
$total = null;
$pageSize = max((int) config('piaoju.page_size', 100), 1);
$maxPages = max((int) config('piaoju.max_pages', 20), 1);
for ($page = 1; $page <= $maxPages; $page++) {
[$batch, $pageTotal] = $this->fetchPage($page, $pageSize);
$total ??= $pageTotal;
foreach ($batch as $row) {
if (! is_array($row)) {
continue;
}
$key = trim((string) ($row['id'] ?? $row['sellerCode'] ?? ''));
if ($key === '') {
throw new RuntimeException('piaoju_seller_key_missing');
}
$rows[$key] = $row;
}
if ($batch === []
|| ($total !== null && count($rows) >= $total)
|| ($total === null && count($batch) < $pageSize)) {
break;
}
}
if ($total !== null && count($rows) !== $total) {
throw new RuntimeException('piaoju_seller_count_mismatch');
}
return array_values($rows);
}
/**
* @return array{0:list<array<string,mixed>>,1:?int}
*/
private function fetchPage(int $page, int $pageSize): array
{
$response = Http::acceptJson()
->withHeaders([
'Cookie' => $this->cookieHeader(),
'Origin' => 'https://fp.erp321.com',
'Referer' => 'https://fp.erp321.com/setting/companyBodyManage',
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
. '(KHTML, like Gecko) Chrome/157.0.0.0 Safari/537.36 Edg/157.0.0.0',
])
->connectTimeout(10)
->timeout(max((int) config('piaoju.timeout_seconds', 30), 1))
->retry(2, 300, throw: false)
->post(
rtrim((string) config('piaoju.api_base_url'), '/') . '/fp/fms/company/seller/page',
[
'data' => [
'coid' => (string) config('piaoju.coid'),
'uid' => (string) config('piaoju.uid'),
'ssProjectType' => (string) config('piaoju.project_type'),
'sellerNames' => [],
'status' => null,
'authStatus' => null,
],
'page' => [
'pageNum' => $page,
'pageSize' => $pageSize,
],
]
);
return $this->parseResponse($response);
}
/**
* @return array{0:list<array<string,mixed>>,1:?int}
*/
private function parseResponse(Response $response): array
{
if (! $response->successful()) {
throw new RuntimeException('piaoju_api_http_error');
}
$payload = $response->json();
if (! is_array($payload)) {
throw new RuntimeException('piaoju_api_invalid_response');
}
$code = $payload['code'] ?? null;
if ($code !== null && ! in_array((string) $code, ['0', '0000', '200'], true)) {
throw new RuntimeException(
in_array((string) $code, ['-1', '1006', '403'], true)
? 'piaoju_api_auth_failed'
: 'piaoju_api_error'
);
}
if (($payload['success'] ?? null) === false) {
throw new RuntimeException('piaoju_api_error');
}
$data = $payload['data'] ?? null;
$rows = null;
$total = null;
if (is_array($data)) {
if (array_is_list($data)) {
$rows = $data;
$total = isset($payload['total']) ? (int) $payload['total'] : null;
} else {
$rows = $data['list'] ?? $data['records'] ?? null;
$total = $data['total'] ?? $payload['total'] ?? null;
}
}
if (! is_array($rows)) {
throw new RuntimeException('piaoju_api_invalid_response');
}
return [
array_values(array_filter($rows, 'is_array')),
$total === null ? null : max((int) $total, 0),
];
}
private function prepare(): void
{
$this->cookieHeader();
if (trim((string) config('piaoju.coid')) === ''
|| trim((string) config('piaoju.uid')) === '') {
throw new RuntimeException('piaoju_api_context_missing');
}
}
private function cookieHeader(): string
{
$cookie = trim((string) config('piaoju.cookie', ''));
if ($cookie !== '') {
return $cookie;
}
$path = trim((string) config('piaoju.cookie_file', ''));
if ($path === '' || ! is_file($path)) {
throw new RuntimeException('piaoju_cookie_not_configured');
}
$cookie = trim((string) file_get_contents($path));
if ($cookie === '' || preg_match('/[\r\n]/', $cookie) === 1) {
throw new RuntimeException('piaoju_cookie_invalid');
}
return $cookie;
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace App\Business\Piaoju;
use DateTimeInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
class PiaojuSellerQuotaImporter
{
public const TABLE = 'piaoju_seller_quota_snapshots';
/**
* @param list<array<string,mixed>> $rows
*/
public function replace(array $rows, ?DateTimeInterface $fetchedAt = null): int
{
$values = $this->values($rows, $fetchedAt);
if ($values === []) {
throw new RuntimeException('piaoju_seller_rows_empty');
}
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$connection->beginTransaction();
try {
foreach (array_chunk($values, 200) as $chunk) {
$connection->table(self::TABLE)->upsert(
$chunk,
['seller_key'],
[
'seller_name',
'tax_number',
'seller_status',
'auth_status',
'auth_status_desc',
'invoice_limit',
'invoice_limit_updated_at',
'source_fetched_at',
'synced_at',
'updated_at',
],
);
}
$connection->table(self::TABLE)
->whereNotIn('seller_key', array_column($values, 'seller_key'))
->delete();
$connection->commit();
} catch (Throwable $exception) {
$connection->rollBack();
throw $exception;
}
return count($values);
}
/**
* @param list<array<string,mixed>> $rows
* @return list<array<string,mixed>>
*/
public function values(array $rows, ?DateTimeInterface $fetchedAt = null): array
{
$fetchedAt ??= now();
$sourceFetchedAt = Carbon::instance($fetchedAt)
->setTimezone('Asia/Shanghai')
->format('Y-m-d H:i:s');
$values = [];
foreach ($rows as $row) {
$taxNumber = $this->text($row['taxNumber'] ?? null, 64);
$sellerKey = $taxNumber
?? trim((string) ($row['id'] ?? $row['sellerCode'] ?? ''));
$sellerName = trim((string) ($row['sellerName'] ?? ''));
if ($sellerKey === '' || $sellerName === '') {
throw new RuntimeException('piaoju_seller_row_invalid');
}
if (isset($values[$sellerKey])) {
throw new RuntimeException('piaoju_seller_key_duplicated');
}
$values[$sellerKey] = [
'seller_key' => mb_substr($sellerKey, 0, 64),
'seller_name' => mb_substr($sellerName, 0, 191),
'tax_number' => $taxNumber,
'seller_status' => $row['status'] === null ? null : (bool) $row['status'],
'auth_status' => $this->text($row['authStatus'] ?? null, 32),
'auth_status_desc' => $this->text($row['authStatusDesc'] ?? null, 64),
'invoice_limit' => $this->decimal($row['invoiceLimit'] ?? null),
'invoice_limit_updated_at' => $this->dateTime($row['invoiceLimitUpdated'] ?? null),
'source_fetched_at' => $sourceFetchedAt,
'synced_at' => now(),
'created_at' => now(),
'updated_at' => now(),
];
}
return array_values($values);
}
private function text(mixed $value, int $length): ?string
{
$text = trim((string) ($value ?? ''));
return $text === '' ? null : mb_substr($text, 0, $length);
}
private function decimal(mixed $value): ?float
{
return is_numeric($value) ? round((float) $value, 2) : null;
}
private function dateTime(mixed $value): ?string
{
$text = trim((string) ($value ?? ''));
if ($text === '') {
return null;
}
try {
return Carbon::parse($text, 'Asia/Shanghai')->format('Y-m-d H:i:s');
} catch (Throwable) {
return null;
}
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Business\Piaoju;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;
class PiaojuSellerQuotaRepository
{
/**
* @return Collection<string,object>
*/
public function byNormalizedName(): Collection
{
try {
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
if (! Schema::connection($connectionName)->hasTable(PiaojuSellerQuotaImporter::TABLE)) {
return collect();
}
$rows = DB::connection($connectionName)
->table(PiaojuSellerQuotaImporter::TABLE)
->select([
'seller_key',
'seller_name',
'tax_number',
'seller_status',
'auth_status',
'auth_status_desc',
'invoice_limit',
'invoice_limit_updated_at',
'source_fetched_at',
'synced_at',
])
->get();
return $rows
->groupBy(fn (object $row): string => self::normalizeName((string) $row->seller_name))
->filter(fn (Collection $group): bool => $group->count() === 1)
->map(static fn (Collection $group): object => $group->first());
} catch (Throwable $exception) {
report($exception);
return collect();
}
}
public static function normalizeName(string $name): string
{
$name = str_replace(['(', ')'], ['(', ')'], trim($name));
$name = preg_replace('/\s+/u', '', $name) ?? $name;
return mb_strtoupper($name);
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace App\Business\ServiceCompanyReconciliation;
use App\Business\XlsxSheetReader;
use RuntimeException;
class CustomerServiceMappingWorkbookImporter
{
public function __construct(private readonly XlsxSheetReader $reader) {}
/**
* @return array{
* rows:list<array{service_company_name:string,store_company_name:string,fee_rate:float,source_row:int}>,
* total_rows:int,
* assigned_rows:int,
* unassigned_rows:int,
* unassigned:list<array{store_company_name:string,fee_rate:float,source_row:int}>,
* invalid_rows:list<string>
* }
*/
public function rows(string $path): array
{
if (! is_file($path)) {
throw new RuntimeException('客服公司映射文件不存在:' . $path);
}
$result = [
'rows' => [],
'total_rows' => 0,
'assigned_rows' => 0,
'unassigned_rows' => 0,
'unassigned' => [],
'invalid_rows' => [],
];
foreach ($this->reader->rows(
$path,
['公司名称', '结算比例', '对应客服公司'],
sheetName: '公司盘点',
) as $row) {
$result['total_rows']++;
$sourceRow = $result['total_rows'] + 1;
$storeName = trim((string) ($row['公司名称'] ?? ''));
$serviceName = trim((string) ($row['对应客服公司'] ?? ''));
if ($storeName === '') {
continue;
}
$feeRate = $this->feeRate((string) ($row['结算比例'] ?? ''));
if ($feeRate === null) {
$result['invalid_rows'][] = "第 {$sourceRow} 行结算比例无效。";
continue;
}
if ($serviceName === '') {
$result['unassigned_rows']++;
$result['unassigned'][] = [
'store_company_name' => $storeName,
'fee_rate' => $feeRate,
'source_row' => $sourceRow,
];
continue;
}
$result['rows'][] = [
'service_company_name' => $serviceName,
'store_company_name' => $storeName,
'fee_rate' => $feeRate,
'source_row' => $sourceRow,
];
$result['assigned_rows']++;
}
return $result;
}
private function feeRate(string $value): ?float
{
$normalized = trim(str_replace(['%', ',', ','], ['', '', ''], $value));
if ($normalized === '' || ! is_numeric($normalized)) {
return null;
}
$rate = (float) $normalized;
if ($rate > 1) {
$rate /= 100;
}
return $rate > 0 && $rate <= 1 ? round($rate, 6) : null;
}
}

View File

@ -466,7 +466,7 @@ class SupplierSummaryInboundImporter
if (
preg_match(
'/^=?\s*\$?([A-Z]{1,3})\$?(\d+)\s*\*\s*\$?([A-Z]{1,3})\$?(\d+)\s*$/i',
'/^[=+]?\s*\$?([A-Z]{1,3})\$?(\d+)\s*\*\s*\$?([A-Z]{1,3})\$?(\d+)\s*$/i',
$formula,
$matches,
) !== 1

View File

@ -17,7 +17,7 @@ class SystemizationTodoAuditLogger
public const ACTION_LABELS = [
'create' => '新增',
'update' => '修改',
'update' => '改动',
'delete' => '删除',
'import' => '导入',
];
@ -149,18 +149,6 @@ class SystemizationTodoAuditLogger
}
DB::table(self::TABLE)->insert($rows);
$companyIds = array_values(array_unique(array_column($rows, 'company_id')));
foreach ($companyIds as $companyId) {
$maxId = (int) DB::table(self::TABLE)
->where('company_id', $companyId)
->max('id');
if ($maxId > self::HISTORY_LIMIT) {
DB::table(self::TABLE)
->where('company_id', $companyId)
->where('id', '<=', $maxId - self::HISTORY_LIMIT)
->delete();
}
}
}
/**
@ -170,6 +158,7 @@ class SystemizationTodoAuditLogger
int $companyId,
int $limit = self::HISTORY_LIMIT,
?string $from = null,
?string $date = null,
): array
{
if (! $this->tableReady()) {
@ -179,6 +168,10 @@ class SystemizationTodoAuditLogger
return DB::table(self::TABLE)
->where('company_id', $companyId)
->when($from !== null && $from !== '', fn ($query) => $query->where('at', '>=', $from))
->when($date !== null && $date !== '', function ($query) use ($date): void {
$query->where('at', '>=', $date . ' 00:00:00')
->where('at', '<', Carbon::parse($date)->addDay()->toDateString() . ' 00:00:00');
})
->orderByDesc('id')
->limit(max(1, min($limit, self::HISTORY_LIMIT)))
->get()

View File

@ -275,25 +275,14 @@ class UpstreamBusinessInformation
}
$references ??= $this->companyPlanClassificationReferences($rows);
$byCreditCode = [];
$byCompanyName = [];
foreach ($references as $reference) {
$creditCode = $this->normalizeCreditCode($reference['unified_social_credit_code'] ?? null);
if ($creditCode !== '' && ! isset($byCreditCode[$creditCode])) {
$byCreditCode[$creditCode] = $reference;
}
$companyName = $this->normalizeCompanyName($reference['company_name'] ?? null);
if ($companyName !== '' && ! isset($byCompanyName[$companyName])) {
$byCompanyName[$companyName] = $reference;
}
}
$index = $this->companyPlanClassificationIndex($references);
foreach ($rows as &$row) {
$creditCode = $this->normalizeCreditCode($row['unified_social_credit_code'] ?? null);
$companyName = $this->normalizeCompanyName($row['company_name'] ?? null);
$reference = $byCreditCode[$creditCode] ?? $byCompanyName[$companyName] ?? null;
$reference = $this->matchedCompanyPlanClassification(
$index,
$row['company_name'] ?? null,
[$row],
);
$planTaxType = trim((string) ($reference['taxpayer_type'] ?? ''));
$row['taxpayer_category'] = $this->normalizeTaxType(
@ -319,6 +308,10 @@ class UpstreamBusinessInformation
*/
private function companyPlanClassificationReferences(array $rows = [], bool $all = false): array
{
if ($this->companyPlans === null) {
return [];
}
try {
$companyId = (int) (company_id() ?: 1);
if ($all) {
@ -337,6 +330,61 @@ class UpstreamBusinessInformation
}
}
/**
* @param list<array<string,mixed>> $references
* @return array{
* by_credit_code:array<string,array<string,mixed>>,
* by_company_name:array<string,array<string,mixed>>
* }
*/
private function companyPlanClassificationIndex(array $references): array
{
$byCreditCode = [];
$byCompanyName = [];
foreach ($references as $reference) {
$creditCode = $this->normalizeCreditCode($reference['unified_social_credit_code'] ?? null);
if ($creditCode !== '' && ! isset($byCreditCode[$creditCode])) {
$byCreditCode[$creditCode] = $reference;
}
$companyName = $this->normalizeCompanyName($reference['company_name'] ?? null);
if ($companyName !== '' && ! isset($byCompanyName[$companyName])) {
$byCompanyName[$companyName] = $reference;
}
}
return [
'by_credit_code' => $byCreditCode,
'by_company_name' => $byCompanyName,
];
}
/**
* @param array{
* by_credit_code:array<string,array<string,mixed>>,
* by_company_name:array<string,array<string,mixed>>
* } $index
* @param list<array<string,mixed>> $companyRows
* @return array<string,mixed>|null
*/
private function matchedCompanyPlanClassification(
array $index,
mixed $companyName,
array $companyRows = [],
): ?array {
foreach ($companyRows as $companyRow) {
$creditCode = $this->normalizeCreditCode($companyRow['unified_social_credit_code'] ?? null);
if ($creditCode !== '' && isset($index['by_credit_code'][$creditCode])) {
return $index['by_credit_code'][$creditCode];
}
}
$normalizedCompanyName = $this->normalizeCompanyName($companyName);
return $index['by_company_name'][$normalizedCompanyName] ?? null;
}
/**
* @param array<string,string|list<string>> $filters
*/
@ -481,7 +529,7 @@ SQL);
}
/**
* 店铺基础信息页每次读取时把负责人字段覆盖为店铺账号镜像中的值。
* 店铺基础信息页从店铺账号镜像关联负责人;部门负责人不使用旧档案兜底。
* 账号店铺名与 ERP 店铺名只差下划线/空格,因此统一归一后关联。
*
* @param list<array<string,mixed>> $rows
@ -494,16 +542,16 @@ SQL);
$key = StoreAccountMirrorRepository::storeNameKey($row['erp_store_name'] ?? '');
$match = $ownership[$key] ?? null;
if ($match === null) {
// 部门负责人只认店铺账号密码镜像,不能沿用可能属于其他口径的旧档案值。
$row['department_manager'] = null;
continue;
}
foreach ([
'store_manager' => $match['operation_owner'],
'department_manager' => $match['operation_department_head'],
] as $field => $value) {
if ($value !== '') {
$row[$field] = $value;
}
if ($match['operation_owner'] !== '') {
$row['store_manager'] = $match['operation_owner'];
}
$departmentManager = trim((string) $match['operation_department_head']);
$row['department_manager'] = $departmentManager !== '' ? $departmentManager : null;
}
unset($row);
@ -789,6 +837,7 @@ SQL);
'entity' => $entity,
'company_type' => $row['company_type'] ?? null,
'rolling_12m_income' => null,
'previous_month_settlement_income' => null,
'can_change_entity' => null,
'plan' => null,
'new_entity' => null,
@ -799,6 +848,11 @@ SQL);
}
$this->sumNullable($entities[$entity], 'rolling_12m_income', $row['rolling_12m_income'] ?? null);
$this->sumNullable(
$entities[$entity],
'previous_month_settlement_income',
$row['previous_month_settlement_income'] ?? null,
);
for ($month = 1; $month <= 12; $month++) {
$key = sprintf('income_%02d', $month);
$entities[$entity][$key] ??= null;
@ -813,15 +867,29 @@ SQL);
} catch (Throwable) {
$classifications = [];
}
$planClassifications = $this->companyPlanClassificationIndex(
$this->companyPlanClassificationReferences(all: true),
);
foreach ($rows as &$row) {
$row['company_details'] = $details[$row['entity']] ?? [];
$row['city'] = $this->cityFromDetails($row['company_details']);
$row['company_status'] = $row['company_details'][0]['company_status'] ?? null;
$classification = $classifications[$row['entity']] ?? [];
$taxType = $classification['tax_type']
$planClassification = $this->matchedCompanyPlanClassification(
$planClassifications,
$row['entity'],
$row['company_details'],
);
$planTaxType = trim((string) ($planClassification['taxpayer_type'] ?? ''));
$planBusinessType = trim((string) ($planClassification['business_registration_type'] ?? ''));
$taxType = $planTaxType !== ''
? $planTaxType
: $classification['tax_type']
?? $row['company_details'][0]['taxpayer_category']
?? null;
$businessType = $classification['business_registration_type']
$businessType = $planBusinessType !== ''
? $planBusinessType
: $classification['business_registration_type']
?? $row['company_details'][0]['business_registration_type']
?? null;
$classificationStatus = trim((string) ($classification['status'] ?? ''));
@ -833,16 +901,19 @@ SQL);
$row['tax_type'] = $this->normalizeTaxType($taxType) ?? '/';
$businessType = trim((string) $businessType);
$row['business_registration_type'] = $retained
&& in_array($businessType, ['核定', '个人独资企业'], true)
&& ($planBusinessType !== '' || in_array($businessType, ['核定', '个人独资企业'], true))
? $businessType
: '/';
}
unset($row);
// 整列为空的月份默认隐藏;金额 0 仍视为有账单,不隐藏。
// 服务公司结算收入列按业务要求默认隐藏;整列为空的月份也默认隐藏,金额 0 仍视为有账单。
request()->attributes->set(
'subject-operating-report.default_hidden_columns',
$this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true),
array_values(array_unique([
'previous_month_settlement_income',
...$this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true),
])),
);
$rows = array_values(array_filter($rows, fn (array $row): bool => $this->subjectMatchesFilters($row, $filters)));
@ -1049,7 +1120,7 @@ SQL);
}
}
foreach (['rolling_12m_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
foreach (['rolling_12m_income', 'previous_month_settlement_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
$needle = str_replace(',', '', trim((string) ($filters[$key] ?? '')));
if ($needle !== '' && (! is_numeric($needle) || ! is_numeric($row[$key] ?? null)
|| abs((float) $row[$key] - (float) $needle) > 0.000001)) {
@ -1067,6 +1138,7 @@ SQL);
$key = (string) ($filters['_sort'] ?? 'entity');
$allowed = [
'city', 'entity', 'company_type', 'tax_type', 'business_registration_type', 'rolling_12m_income',
'previous_month_settlement_income',
...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12)),
'can_change_entity', 'plan', 'new_entity',
];

View File

@ -0,0 +1,169 @@
<?php
namespace App\Console\Commands;
use App\Utilities\FinanceLedgerAccountShouldKeep;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Throwable;
class AssignFinanceLedgerCompanyPlans extends Command
{
private const PRESERVED_ACCOUNT_TYPES = ['支付宝', '网商银行'];
protected $signature = 'finance-ledger:assign-company-plans
{path : 公司保留名单 XLSX/XLS 文件}
{--dry-run : 只核对公司和账户数量,不写入数据}';
protected $description = '按公司保留名单设置账户公司规划与是否保留';
public function handle(): int
{
try {
$companies = $this->companyNames((string) $this->argument('path'));
if ($companies === []) {
throw new \RuntimeException('公司保留名单中没有可识别的公司名称。');
}
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$accounts = $connection->table('fin_accounts')
->orderBy('id')
->get(['id', 'company_name', 'account_type']);
$retainedIds = [];
$temporaryIds = [];
$preservedIds = [];
$matchedKeys = [];
foreach ($accounts as $account) {
$key = $this->normalizeCompanyName((string) ($account->company_name ?? ''));
$accountId = (int) $account->id;
if ($key !== '' && isset($companies[$key])) {
$matchedKeys[$key] = true;
}
if (in_array(trim((string) ($account->account_type ?? '')), self::PRESERVED_ACCOUNT_TYPES, true)) {
$preservedIds[] = $accountId;
} elseif ($key !== '' && isset($companies[$key])) {
$retainedIds[] = $accountId;
} else {
$temporaryIds[] = $accountId;
}
}
$unmatchedCompanies = array_values(array_diff_key($companies, $matchedKeys));
$this->table(
['名单公司', '匹配名单公司', '账户总数', '更新为保留', '更新为暂时保留', '保持原状'],
[[
count($companies),
count($matchedKeys),
$accounts->count(),
count($retainedIds),
count($temporaryIds),
count($preservedIds),
]],
);
if ($unmatchedCompanies !== []) {
$this->warn('以下名单公司没有匹配到账户:' . implode('、', $unmatchedCompanies));
}
if ((bool) $this->option('dry-run')) {
$this->info('核对完成,未写入数据。');
return self::SUCCESS;
}
$now = now();
$connection->transaction(function () use (
$connection,
$retainedIds,
$temporaryIds,
$now,
): void {
foreach (array_chunk($retainedIds, 500) as $ids) {
$connection->table('fin_accounts')
->whereIn('id', $ids)
->update([
'company_plan' => '保留',
'account_should_keep' => '是',
'updated_at' => $now,
]);
}
foreach (array_chunk($temporaryIds, 500) as $ids) {
$connection->table('fin_accounts')
->whereIn('id', $ids)
->update([
'company_plan' => '不保留',
'account_should_keep' => FinanceLedgerAccountShouldKeep::TEMPORARY,
'updated_at' => $now,
]);
}
});
$this->info(sprintf(
'已更新 %d 个账户:保留 %d 个,暂时保留 %d 个;另有 %d 个支付宝或网商银行账户保持原状。',
count($retainedIds) + count($temporaryIds),
count($retainedIds),
count($temporaryIds),
count($preservedIds),
));
return self::SUCCESS;
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
/**
* @return array<string,string>
*/
private function companyNames(string $path): array
{
if (! is_file($path)) {
throw new \RuntimeException('公司保留名单文件不存在:' . $path);
}
$worksheet = IOFactory::load($path)->getActiveSheet();
$rows = $worksheet->toArray(null, true, true, false);
if ($rows === []) {
return [];
}
$header = array_map(
fn (mixed $value): string => $this->normalizeCompanyName((string) $value),
$rows[0],
);
$column = array_search('公司名称', $header, true);
if ($column === false) {
$column = 0;
} else {
array_shift($rows);
}
$companies = [];
foreach ($rows as $row) {
$name = trim((string) ($row[$column] ?? ''));
$key = $this->normalizeCompanyName($name);
if ($key !== '') {
$companies[$key] = $name;
}
}
return $companies;
}
private function normalizeCompanyName(string $name): string
{
$name = str_replace(
['(', ')', '【', '】', ' '],
['(', ')', '[', ']', ' '],
trim($name),
);
$name = (string) preg_replace('/\s+/u', '', $name);
return mb_strtolower($name, 'UTF-8');
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace App\Console\Commands;
use DateTimeImmutable;
use Illuminate\Console\Command;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\BillSyncWindowAuditor;
class AuditBillSyncWindow extends Command
{
protected $signature = 'bill-sync:audit-window
{--from= : 开始日期 YYYY-MM-DD;默认以前一自然日结束的最近 7 天}
{--to= : 结束日期 YYYY-MM-DD;默认前一自然日}
{--days=7 : 未指定 --from 时回看的自然日数,最大 93}
{--json : 输出 JSON,供每日账单自动化读取}';
protected $description = '核对最近账单窗口的日期、行数、店铺数和收支,识别漏日及异常低量';
public function handle(BillSyncWindowAuditor $auditor): int
{
try {
[$from, $to] = $this->window();
} catch (InvalidArgumentException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$result = $auditor->audit($from, $to);
if ((bool) $this->option('json')) {
$this->line(json_encode(
$result,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
));
} else {
$this->renderText($result);
}
return $result['has_gaps'] || $result['has_anomalies']
? self::FAILURE
: self::SUCCESS;
}
/** @return array{0:string,1:string} */
private function window(): array
{
$to = trim((string) $this->option('to'));
$to = $to !== ''
? $this->date($to, '--to')
: now('Asia/Shanghai')->subDay()->toDateString();
$from = trim((string) $this->option('from'));
if ($from !== '') {
$from = $this->date($from, '--from');
} else {
$days = max(1, (int) $this->option('days'));
if ($days > 93) {
throw new InvalidArgumentException('--days 最大为 93。');
}
$from = (new DateTimeImmutable($to))->modify('-' . ($days - 1) . ' days')->format('Y-m-d');
}
if ($from > $to) {
throw new InvalidArgumentException('开始日期不能晚于结束日期。');
}
return [$from, $to];
}
private function date(string $value, string $option): string
{
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if (! $parsed || $parsed->format('Y-m-d') !== $value) {
throw new InvalidArgumentException("{$option} 日期格式必须为 YYYY-MM-DD。");
}
return $value;
}
/** @param array<string,mixed> $result */
private function renderText(array $result): void
{
$this->line("账单窗口:{$result['window']['from']} 至 {$result['window']['to']}");
foreach ($result['platforms'] as $platform) {
if (($platform['status'] ?? '') === 'failed') {
$this->line("{$platform['label']} | FAILED | {$platform['error']}");
continue;
}
$missing = $platform['missing_dates'] !== [] ? implode(',', $platform['missing_dates']) : '-';
$suspicious = $platform['suspicious_dates'] !== [] ? implode(',', $platform['suspicious_dates']) : '-';
$this->line(
"{$platform['label']} | {$platform['status']} | missing={$missing} | suspicious={$suspicious}"
);
}
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Console\Commands\Concerns;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
use Throwable;
trait QueuesBillPerformanceResync
{
protected function queueBillPerformanceResync(
BillPerformanceResyncDispatcher $dispatcher,
string $platform,
array $result,
bool $periodEndExclusive = false,
): bool {
try {
$periodEnd = (string) ($result['period_end'] ?? '');
if ($periodEndExclusive && $periodEnd !== '') {
$periodEnd = Carbon::parse($periodEnd)->subDay()->toDateString();
}
$queued = $dispatcher->dispatch(
$platform,
(string) ($result['period_start'] ?? ''),
$periodEnd,
);
} catch (Throwable $exception) {
report($exception);
$this->error('账单已导入,但业绩明细重算任务排队失败;请重新执行本导入命令以重试排队。');
return false;
}
$this->line(
'业绩明细重算已排队:'
. implode('、', $queued['months'])
. '(新增 ' . $queued['jobs'] . ' 个任务)'
);
return true;
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\FinanceLedgerAccountEditor;
use RuntimeException;
use Throwable;
class ImportAccountShortRenames extends Command
{
protected $signature = 'finance-ledger:import-account-short-renames
{path : 账户简称批量修改 JSON 文件}
{--apply : 实际写入;未指定时只校验}';
protected $description = '按账户 ID 批量修改账户简称,并同步所有关联数据';
public function handle(FinanceLedgerAccountEditor $editor): int
{
try {
$path = (string) $this->argument('path');
if (! is_file($path) || ! is_readable($path)) {
throw new RuntimeException('账户简称批量修改文件不存在或不可读取。');
}
if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'json') {
throw new RuntimeException('账户简称批量修改文件必须为 JSON。');
}
if (filesize($path) > 10 * 1024 * 1024) {
throw new RuntimeException('账户简称批量修改文件不能超过 10 MB。');
}
$content = file_get_contents($path);
if (! is_string($content)) {
throw new RuntimeException('无法读取账户简称批量修改文件。');
}
$mappings = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
if (! is_array($mappings) || ! array_is_list($mappings)) {
throw new RuntimeException('账户简称批量修改文件必须是 JSON 数组。');
}
$apply = (bool) $this->option('apply');
$result = $editor->renameShorts($mappings, $apply);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'%s账户简称:共 %d 户,计划修改 %d 户,未变化 %d 户。',
$result['dry_run'] ? '校验完成,' : '已完成',
$result['requested'],
$result['changed'],
$result['unchanged'],
));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Console\Commands;
use App\Business\ActualTax\ActualTaxWorkbookImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportActualTax extends Command
{
protected $signature = 'actual-tax:import
{path : 实际税金表工作簿或 CSV 路径}';
protected $description = '导入实际税金表,整份替换共享业务镜像中的上一版数据';
public function handle(ActualTaxWorkbookImporter $importer): int
{
try {
$result = $importer->import((string) $this->argument('path'));
} catch (Throwable $exception) {
report($exception);
$this->error('实际税金表导入失败:' . $exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'实际税金表导入完成:%s 条,跳过空行 %s 条,来源文件 %s。',
number_format($result['imported']),
number_format($result['skipped']),
$result['source_file'],
));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BankBillHeaderImporter;
use Throwable;
class ImportBankBillHeaders extends Command
{
protected $signature = 'finance-ledger:import-bank-bill-headers
{path : 银行批量明细 XLSX/XLS 文件}
{--bank= : 招商银行或华夏银行}
{--dry-run : 只检查,不写入表头配置}';
protected $description = '导入银行原始账单表头并生成银行账单列配置';
public function handle(BankBillHeaderImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('bank'),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'%s%s:%d 列。',
$result['dry_run'] ? '校验完成,' : '表头已导入,',
$result['bank'],
$result['columns'],
));
$this->line(implode(' | ', $result['labels']));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BankBillStatementImporter;
use Throwable;
class ImportBankBills extends Command
{
protected $signature = 'finance-ledger:import-bank-bills
{path : 银行批量账单 XLSX/XLS/CSV 文件}
{--bank= : 账单所属银行模板}
{--scope=direct : direct(银企直连)或 non_direct(非银企直连)}
{--dry-run : 只校验,不写入账单数据}
{--replace : 先清空该银行旧账单,再导入本次文件}';
protected $description = '按已导入的银行表头导入原始账单明细';
public function handle(BankBillStatementImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('bank'),
(bool) $this->option('dry-run'),
(bool) $this->option('replace'),
true,
(string) $this->option('scope'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'%s%s:%d 条,新增 %d 条,更新 %d 条,跳过 %d 条;涉及 %d 个账户。',
$result['dry_run'] ? '校验完成,' : '账单已导入,',
$result['bank'],
$result['rows'],
$result['inserted'],
$result['updated'],
$result['skipped'],
$result['accounts'],
));
$this->line(sprintf(
'账务日期:%s 至 %s。',
$result['first_date'] ?? '无',
$result['last_date'] ?? '无',
));
$this->line(sprintf(
'已同步 %d 个账户的当前余额。',
$result['synced_accounts'],
));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BankBillStatementDirectoryImporter;
use Throwable;
class ImportBankBillsDirectory extends Command
{
protected $signature = 'finance-ledger:import-bank-bills-directory
{path : 已解压的银行账单目录}
{--bank= : 招商银行、华夏银行或网商银行}
{--dry-run : 只校验,不写入账单数据}';
protected $description = '一次导入目录中的多份银行账单,并统一同步余额';
public function handle(BankBillStatementDirectoryImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('bank'),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'%s%s:%d 个文件,成功 %d 个,失败 %d 个,共 %d 条;新增 %d 条,更新 %d 条,跳过 %d 条。',
$result['dry_run'] ? '校验完成,' : '账单已导入,',
$result['bank'],
$result['files'],
$result['imported_files'],
$result['failed_files'],
$result['rows'],
$result['inserted'],
$result['updated'],
$result['skipped'],
));
$this->line(sprintf(
'账务日期:%s 至 %s;涉及 %d 个账户,已同步 %d 个账户余额。',
$result['first_date'] ?? '无',
$result['last_date'] ?? '无',
$result['accounts'],
$result['synced_accounts'],
));
foreach ($result['failures'] as $failure) {
$this->error($failure);
}
return $result['failed_files'] === 0 ? self::SUCCESS : self::FAILURE;
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BankDirectBalanceWorkbookImporter;
use Throwable;
class ImportBankDirectBalances extends Command
{
protected $signature = 'finance-ledger:import-bank-direct-balances
{path : 银企直联余额 XLSX/XLS 文件}
{--balance-date= : 指定余额日期,格式 YYYY-MM-DD}
{--dry-run : 只校验和统计,不写入共享业务库}';
protected $description = '导入银企直联账户可用余额及期末余额快照';
public function handle(BankDirectBalanceWorkbookImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
$this->option('balance-date') === null
? null
: (string) $this->option('balance-date'),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '值'], [
['余额日期', $result['balance_date']],
['账户数', $result['total']],
['银行数', $result['bank_count']],
['可用余额合计', number_format($result['available_total'], 2, '.', '')],
['替换原快照', $result['replaced']],
['模式', $result['dry_run'] ? '校验' : '写入'],
]);
$this->info($result['dry_run']
? '银企直联余额校验完成,未写入共享业务库。'
: '银企直联余额导入完成,期末余额已接入账户总览。');
return self::SUCCESS;
}
}

View File

@ -2,13 +2,17 @@
namespace App\Console\Commands;
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
use Modules\EcommerceFinance\Services\DewuSettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportDewuSettlementBills extends Command
{
use QueuesBillPerformanceResync;
protected $signature = 'dewu-bills:import-authoritative
{path : 聚胜算导出的得物完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
@ -20,7 +24,10 @@ class ImportDewuSettlementBills extends Command
protected $description = '导入并核验聚胜算得物完整账单(保留全部渠道)';
public function handle(DewuSettlementBillImporter $importer): int
public function handle(
DewuSettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -67,6 +74,10 @@ class ImportDewuSettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->queueBillPerformanceResync($performanceResync, 'dewu', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -2,12 +2,16 @@
namespace App\Console\Commands;
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
use Modules\EcommerceFinance\Services\DouyinAuthoritativeBillImporter;
use Throwable;
class ImportDouyinAuthoritativeBills extends Command
{
use QueuesBillPerformanceResync;
protected $signature = 'business-mirror:import-douyin-authoritative
{path : 胜算原始明细 UTF-8 CSV} {month : 所属月份 YYYY-MM}
{--count= : 核对笔数} {--income= : 核对收入合计} {--expense= : 核对支出合计}
@ -15,7 +19,10 @@ class ImportDouyinAuthoritativeBills extends Command
protected $description = '校验并原子启用指定月份或月初至截止日的胜算抖音明细,保留旧版本用于回滚';
public function handle(DouyinAuthoritativeBillImporter $importer): int
public function handle(
DouyinAuthoritativeBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
{
try {
$result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'),
@ -25,6 +32,10 @@ class ImportDouyinAuthoritativeBills extends Command
return self::FAILURE;
}
$this->info('胜算抖音明细已启用,范围:[' . $result['period_start'] . ', ' . $result['period_end'] . '),笔数:' . $result['row_count']);
if (! $this->queueBillPerformanceResync($performanceResync, 'douyin', $result, true)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

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

View File

@ -4,6 +4,7 @@ namespace App\Console\Commands;
use App\Business\WithdrawalBalanceAlertSynchronizer;
use App\Models\Business\StoreReceivingAccount;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\FinanceBillShopBalanceFallback;
use Modules\EcommerceFinance\Services\JushuitanShopBalanceImporter;
@ -14,6 +15,7 @@ class ImportJushuitanShopBalances extends Command
protected $signature = 'business:import-jushuitan-shop-balances
{path : 聚水潭店铺余额接口 JSON 或 XLSX/XLS 导出文件}
{--balance-date= : 导入日期,格式 YYYY-MM-DD;多日期导出必须指定}
{--date-range= : 连续日期范围 YYYY-MM-DD:YYYY-MM-DD;一次导入多天余额}
{--scope=all : 来源范围,同一日期同一范围会被原子替换}
{--dry-run : 只校验和统计,不写入共享业务库}';
@ -25,13 +27,31 @@ class ImportJushuitanShopBalances extends Command
FinanceBillShopBalanceFallback $financeFallback,
): int
{
$dateRange = trim((string) ($this->option('date-range') ?? ''));
$balanceDate = $this->option('balance-date');
$allDates = $dateRange !== '';
if ($allDates && $balanceDate !== null) {
$this->error('--date-range 与 --balance-date 不能同时使用。');
return self::FAILURE;
}
try {
$result = $importer->import(
(string) $this->argument('path'),
$this->option('balance-date') === null ? null : (string) $this->option('balance-date'),
(string) $this->option('scope'),
(bool) $this->option('dry-run'),
);
if ($allDates) {
$result = $importer->importMany(
(string) $this->argument('path'),
$this->rangeDates($dateRange),
(string) $this->option('scope'),
(bool) $this->option('dry-run'),
);
} else {
$result = $importer->import(
(string) $this->argument('path'),
$balanceDate === null ? null : (string) $balanceDate,
(string) $this->option('scope'),
(bool) $this->option('dry-run'),
);
}
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
@ -39,38 +59,54 @@ class ImportJushuitanShopBalances extends Command
return self::FAILURE;
}
$this->info(sprintf(
'%s:%s 共 %d 条,替换原有 %d 条。',
$result['dry_run'] ? '校验完成' : '导入完成',
$result['balance_date'],
$result['total'],
$result['replaced'],
));
$financeFallbackFailed = false;
try {
$fallback = $financeFallback->fillMissing(
$result['balance_date'],
(string) $this->option('scope'),
(bool) $result['dry_run'],
);
if (! $fallback['supported']) {
$this->warn('账单余额回填:当前来源的店铺收款账户账单没有累计账户余额字段,跳过回填。');
} elseif ($fallback['missing'] === 0) {
$this->info('账单余额回填:聚水潭余额没有缺失店铺。');
} else {
if ($allDates) {
foreach ($result['dates'] as $daily) {
$this->info(sprintf(
'账单余额回填:缺失 %d 家,匹配 %d 家,写入 %d 条,仍有 %d 家待补。',
$fallback['missing'],
$fallback['resolved'],
$fallback['filled'],
$fallback['unresolved'],
'%s:%s 共 %d 条,替换原有 %d 条。',
$daily['dry_run'] ? '校验完成' : '导入完成',
$daily['balance_date'],
$daily['total'],
$daily['replaced'],
));
}
} catch (Throwable $exception) {
report($exception);
$this->error('财务系统店铺收款账户账单余额回填失败,聚水潭余额已保留,财务回填未覆盖。');
$financeFallbackFailed = true;
} else {
$this->info(sprintf(
'%s:%s 共 %d 条,替换原有 %d 条。',
$result['dry_run'] ? '校验完成' : '导入完成',
$result['balance_date'],
$result['total'],
$result['replaced'],
));
}
$financeFallbackFailed = false;
if ($allDates) {
$this->warn('多日期历史导入未执行财务账单回填,聚水潭原始快照已按日期写入。');
} else {
try {
$fallback = $financeFallback->fillMissing(
$result['balance_date'],
(string) $this->option('scope'),
(bool) $result['dry_run'],
);
if (! $fallback['supported']) {
$this->warn('账单余额回填:当前来源的店铺收款账户账单没有累计账户余额字段,跳过回填。');
} elseif ($fallback['missing'] === 0) {
$this->info('账单余额回填:聚水潭余额没有缺失店铺。');
} else {
$this->info(sprintf(
'账单余额回填:缺失 %d 家,匹配 %d 家,写入 %d 条,仍有 %d 家待补。',
$fallback['missing'],
$fallback['resolved'],
$fallback['filled'],
$fallback['unresolved'],
));
}
} catch (Throwable $exception) {
report($exception);
$this->error('财务系统店铺收款账户账单余额回填失败,聚水潭余额已保留,财务回填未覆盖。');
$financeFallbackFailed = true;
}
}
if (! $result['dry_run']) {
@ -103,4 +139,33 @@ class ImportJushuitanShopBalances extends Command
return $financeFallbackFailed ? self::FAILURE : self::SUCCESS;
}
/** @return list<string> */
private function rangeDates(string $range): array
{
$parts = explode(':', $range);
if (count($parts) !== 2) {
throw new \InvalidArgumentException('日期范围格式应为 YYYY-MM-DD:YYYY-MM-DD。');
}
$start = CarbonImmutable::createFromFormat('!Y-m-d', trim($parts[0]), 'Asia/Shanghai');
$end = CarbonImmutable::createFromFormat('!Y-m-d', trim($parts[1]), 'Asia/Shanghai');
if (! $start instanceof CarbonImmutable
|| $start->format('Y-m-d') !== trim($parts[0])
|| ! $end instanceof CarbonImmutable
|| $end->format('Y-m-d') !== trim($parts[1])
|| $end->lt($start)) {
throw new \InvalidArgumentException('日期范围格式应为 YYYY-MM-DD:YYYY-MM-DD,且结束日期不能早于开始日期。');
}
if ($start->diffInDays($end) > 366) {
throw new \InvalidArgumentException('单次多日期导入不能超过 366 天。');
}
$dates = [];
for ($date = $start; $date->lte($end); $date = $date->addDay()) {
$dates[] = $date->format('Y-m-d');
}
return $dates;
}
}

View File

@ -0,0 +1,164 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
use Throwable;
class ImportKukaErpRecipients extends Command
{
protected $signature = 'kuka-posting:import-erp-recipients
{file : 工作簿5.xlsx 路径}
{--company=1 : 公司 ID}
{--sheet=Sheet1 : 工作表名称}';
protected $description = '导入顾家ERP商品导入使用的收货人池';
public function handle(): int
{
try {
$path = (string) $this->argument('file');
if (! is_file($path)) {
throw new RuntimeException('导入文件不存在。');
}
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
if (! Schema::connection($connectionName)->hasTable('kuka_posting_erp_recipient_rows')) {
throw new RuntimeException('ERP收货人池表尚未建立。');
}
$rows = $this->readRows($path, (string) $this->option('sheet'));
if ($rows === []) {
throw new RuntimeException('工作簿中没有可导入的收货人数据。');
}
$companyId = max(1, (int) $this->option('company'));
$now = now();
DB::connection($connectionName)->transaction(function () use ($connectionName, $companyId, $now, $rows): void {
$connection = DB::connection($connectionName);
$connection->table('kuka_posting_erp_recipient_rows')
->where('company_id', $companyId)
->delete();
$connection->table('kuka_posting_erp_recipient_rows')->insert(array_map(
fn (array $row, int $index): array => $row + [
'company_id' => $companyId,
'sort_order' => $index + 1,
'imported_at' => $now,
'created_at' => $now,
'updated_at' => $now,
],
$rows,
array_keys($rows),
));
});
$this->info('已导入 ERP 收货人池:'.count($rows).' 条。');
return self::SUCCESS;
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
/**
* @return list<array{receiver_name:string,receiver_mobile:string,receiver_state:string,receiver_city:string,receiver_district:string,receiver_address:string,buyer_nick:string,source_row_number:int,row_hash:string}>
*/
private function readRows(string $path, string $sheetName): array
{
$spreadsheet = IOFactory::load($path);
$sheet = $sheetName === ''
? $spreadsheet->getActiveSheet()
: $spreadsheet->getSheetByName($sheetName);
if ($sheet === null) {
throw new RuntimeException('工作簿中没有指定工作表:'.$sheetName);
}
$data = $sheet->toArray(null, false, false, false);
$headers = [
'收货人(必填)',
'收货人手机(必填)',
'收货人的所在省份(必填)',
'收货人的所在城市(必填)',
'收货人的所在区(县)(必填)',
'收货地址(必填)',
'买家昵称(必填)',
];
$headerIndex = null;
$columns = [];
foreach (array_slice($data, 0, 20, true) as $rowIndex => $row) {
$candidate = [];
foreach ($row as $columnIndex => $value) {
$label = trim((string) $value);
if (in_array($label, $headers, true)) {
$candidate[$label] = $columnIndex;
}
}
if (count($candidate) === count($headers)) {
$headerIndex = (int) $rowIndex;
$columns = $candidate;
break;
}
}
if ($headerIndex === null) {
throw new RuntimeException('未找到工作簿5的标准表头。');
}
$rows = [];
foreach (array_slice($data, $headerIndex + 1, null, true) as $rowIndex => $row) {
$values = [];
foreach ($headers as $header) {
$values[$header] = trim((string) ($row[$columns[$header]] ?? ''));
}
if ($values['收货人(必填)'] === 'clientName'
|| $values['收货人手机(必填)'] === 'clientMobile') {
continue;
}
foreach ($headers as $header) {
if ($values[$header] === '') {
throw new RuntimeException('第 '.($rowIndex + 1).' 行存在必填字段为空。');
}
}
$mobile = $this->normalizeMobile($values['收货人手机(必填)']);
if ($mobile === '') {
throw new RuntimeException('第 '.($rowIndex + 1).' 行收货人手机无效。');
}
$normalized = [
'receiver_name' => $values['收货人(必填)'],
'receiver_mobile' => $mobile,
'receiver_state' => $values['收货人的所在省份(必填)'],
'receiver_city' => $values['收货人的所在城市(必填)'],
'receiver_district' => $values['收货人的所在区(县)(必填)'],
'receiver_address' => $values['收货地址(必填)'],
'buyer_nick' => $values['买家昵称(必填)'],
'source_row_number' => (int) $rowIndex + 1,
];
$normalized['row_hash'] = hash('sha256', json_encode(
$normalized,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
));
$rows[] = $normalized;
}
return $rows;
}
private function normalizeMobile(mixed $value): string
{
$mobile = trim((string) $value);
if ($mobile === '') {
return '';
}
if (is_numeric($mobile) && preg_match('/^\d+(?:\.0+)?$/', $mobile) === 1) {
return number_format((float) $mobile, 0, '', '');
}
return preg_replace('/\s+/u', '', $mobile) ?? '';
}
}

View File

@ -52,6 +52,7 @@ class ImportKukaPostingBase extends Command
['店铺数', number_format($result['store_count'])],
['订单数', number_format($result['order_count'])],
['非指定店铺跳过', number_format($result['skipped_store_rows'])],
['已取消状态跳过', number_format($result['skipped_cancelled_rows'])],
['文件 SHA-256', $result['file_sha256']],
]);
$this->table(['店铺', '行数'], $storeRows);

View File

@ -0,0 +1,71 @@
<?php
namespace App\Console\Commands;
use App\Business\KukaPostingBase\KukaPostingLabelImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportKukaPostingLabels extends Command
{
protected $signature = 'business-mirror:import-kuka-posting-labels
{path : 带月度过账标签列的 XLSX 文件}
{--month= : 账期 YYYY-MM}
{--sheet=Sheet1 : 工作表名称}
{--column= : 标签列名,默认按账期生成“YYYY年M月过账”}
{--company=1 : 公司 ID}
{--dry-run : 只校验文件和共享镜像,不写入过账标签}';
protected $description = '按源表行序更新顾家过账基础数据的过账标签';
public function handle(KukaPostingLabelImporter $importer): int
{
$period = trim((string) $this->option('month'));
if ($period === '') {
$this->error('必须指定 --month=YYYY-MM。');
return self::FAILURE;
}
try {
$result = $importer->import(
(string) $this->argument('path'),
$period,
(string) ($this->option('sheet') ?: 'Sheet1'),
$this->option('column') ? (string) $this->option('column') : null,
max(1, (int) $this->option('company')),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('顾家过账标签未导入,原有数据未改变。' . $exception->getMessage());
return self::FAILURE;
}
$labelRows = [];
foreach ($result['labels'] as $label => $count) {
$labelRows[] = [$label, number_format($count)];
}
$storeRows = [];
foreach ($result['stores'] as $store => $count) {
$storeRows[] = [$store, number_format($count)];
}
$this->table(['项目', '值'], [
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['账期', $result['period']],
['标签列', $result['label_column']],
['数据行数', number_format($result['rows'])],
['店铺数', number_format($result['store_count'])],
['需要更新', number_format($result['updated'])],
['已一致', number_format($result['unchanged'])],
['文件 SHA-256', $result['file_sha256']],
]);
$this->table(['过账标签', '行数'], $labelRows);
$this->table(['店铺', '行数'], $storeRows);
$this->info($result['dry_run'] ? '顾家过账标签校验完成。' : '顾家过账标签已更新。');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace App\Console\Commands;
use App\Business\KukaPostingBase\KukaPostingMaterialRepairImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportKukaPostingMaterialRepair extends Command
{
protected $signature = 'business-mirror:import-kuka-posting-material-repair
{abnormalPath : 表一,缺少物料信息的异常数据 XLSX 文件}
{mappingPath : 表二,包含完整物料信息的发货明细 XLSX 文件}
{--month= : 账期 YYYY-MM}
{--sheet=Sheet1 : 两个工作表共用的工作表名称}
{--company=1 : 公司 ID}
{--dry-run : 只校验异常清单、表二和生产镜像,不写入}';
protected $description = '仅修正顾家过账异常发货明细行的物料编号和物料描述';
public function handle(KukaPostingMaterialRepairImporter $importer): int
{
$period = trim((string) $this->option('month'));
if ($period === '') {
$this->error('必须指定 --month=YYYY-MM。');
return self::FAILURE;
}
try {
$result = $importer->import(
(string) $this->argument('abnormalPath'),
(string) $this->argument('mappingPath'),
$period,
(string) ($this->option('sheet') ?: 'Sheet1'),
max(1, (int) $this->option('company')),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('顾家过账物料修正未导入,原有数据未改变。' . $exception->getMessage());
return self::FAILURE;
}
$storeRows = [];
foreach ($result['stores'] as $store => $count) {
$storeRows[] = [$store, number_format($count)];
}
$this->table(['项目', '值'], [
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['账期', $result['period']],
['异常数据行数', number_format($result['rows'])],
['业务记录数', number_format($result['identities'])],
['物料组合数', number_format($result['material_pairs'])],
['需要更新', number_format($result['updated'])],
['已一致', number_format($result['unchanged'])],
['表一 SHA-256', $result['abnormal_file_sha256']],
['表二 SHA-256', $result['mapping_file_sha256']],
]);
$this->table(['店铺', '异常行数'], $storeRows);
$this->info($result['dry_run'] ? '顾家过账异常物料校验完成。' : '顾家过账异常物料已修正。');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Business\KukaPostingBase\KukaPostingMaterialRepairImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportKukaPostingMaterialSource extends Command
{
protected $signature = 'business-mirror:import-kuka-posting-material-source
{path : 包含完整发货明细和物料信息的 XLSX 文件}
{--month= : 账期 YYYY-MM}
{--sheet=Sheet1 : 工作表名称}
{--company=1 : 公司 ID}
{--dry-run : 只校验文件、物料报价和共享镜像,不写入}';
protected $description = '按整表物料源文件修正顾家过账发货明细的物料、成本和金额';
public function handle(KukaPostingMaterialRepairImporter $importer): int
{
$period = trim((string) $this->option('month'));
if ($period === '') {
$this->error('必须指定 --month=YYYY-MM。');
return self::FAILURE;
}
try {
$result = $importer->importSource(
(string) $this->argument('path'),
$period,
(string) ($this->option('sheet') ?: 'Sheet1'),
max(1, (int) $this->option('company')),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('顾家过账物料源修正未导入,原有数据未改变。' . $exception->getMessage());
return self::FAILURE;
}
$storeRows = [];
foreach ($result['stores'] as $store => $count) {
$storeRows[] = [$store, number_format($count)];
}
$this->table(['项目', '值'], [
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['账期', $result['period']],
['源文件行数', number_format($result['rows'])],
['有效物料行数', number_format($result['valid_rows'])],
['#N/A 等跳过行数', number_format($result['skipped_unmapped_rows'])],
['物料编号数', number_format($result['materials'])],
['需要更新', number_format($result['updated'])],
['已一致', number_format($result['unchanged'])],
['文件 SHA-256', $result['file_sha256']],
]);
$this->table(['店铺', '有效物料行数'], $storeRows);
$this->info($result['dry_run'] ? '顾家过账整表物料校验完成。' : '顾家过账整表物料已修正。');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace App\Console\Commands;
use App\Business\KukaPostingQuotation\KukaPostingQuotationImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportKukaPostingQuotation extends Command
{
protected $signature = 'business-mirror:import-kuka-posting-quotation
{path : 顾家报价单 XLSX 文件}
{--sheet= : 工作表名称,默认 Sheet1}
{--company=1 : 公司 ID}
{--dry-run : 只校验文件、字段和物料编码,不写入共享镜像}';
protected $description = '导入顾家过账报价单';
public function handle(KukaPostingQuotationImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
$this->option('sheet') ?: null,
max(1, (int) $this->option('company')),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('顾家报价单未导入,原有数据未改变。' . $exception->getMessage());
return self::FAILURE;
}
$statuses = [];
foreach ($result['status_counts'] as $status => $count) {
$statuses[] = [$status, number_format($count)];
}
$this->table(['项目', '值'], [
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['报价记录', number_format($result['rows'])],
['唯一物料', number_format($result['material_count'])],
['文件 SHA-256', $result['file_sha256']],
]);
if ($statuses !== []) {
$this->table(['状态', '记录数'], $statuses);
}
$this->info($result['dry_run'] ? '顾家报价单校验完成。' : '顾家报价单已导入共享镜像。');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,118 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\UploadedFile;
use Modules\EcommerceFinance\Services\PayablesFinalImportRunner;
use Modules\EcommerceFinance\Services\PayablesFinalRegistry;
use Throwable;
class ImportPayablesFinal extends Command
{
protected $signature = 'payables:final-import
{--directory= : 已解压 CSV 文件目录}
{--section=supplier-payables-final : 终版目录}
{--dataset=payment-reconciliation : 数据集页面}
{--company=1 : 公司 ID}
{--user= : 操作人 ID}';
protected $description = '将终版页面的 CSV 文件分片导入业务数据库';
public function handle(
PayablesFinalRegistry $registry,
PayablesFinalImportRunner $runner,
): int {
$directory = trim((string) $this->option('directory'));
$section = trim((string) $this->option('section'));
$dataset = trim((string) $this->option('dataset'));
$companyId = max(1, (int) $this->option('company'));
$userId = $this->option('user') === null ? null : max(1, (int) $this->option('user'));
if ($directory === '' || ! is_dir($directory)) {
$this->error('导入目录不存在。');
return self::FAILURE;
}
if (! $registry->supports($section, $dataset)) {
$this->error('不支持的终版页面。');
return self::FAILURE;
}
$files = glob(rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*.csv') ?: [];
sort($files, SORT_NATURAL);
if ($files === []) {
$this->error('导入目录中没有 CSV 文件。');
return self::FAILURE;
}
$fields = $registry->fields($section, $dataset);
$storeDataset = 'final:'
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
. ':'
. $dataset;
$totalCreated = 0;
$totalUpdated = 0;
$totalRows = 0;
try {
foreach ($files as $index => $path) {
$file = new UploadedFile(
$path,
basename($path),
'text/csv',
null,
true,
);
$prepared = $runner->prepare(
$file,
$fields,
$storeDataset,
$companyId,
$userId,
);
$token = $prepared['token'];
$offset = 0;
$created = 0;
$updated = 0;
do {
$progress = $runner->process($token, $offset, null, $companyId);
$offset = $progress['offset'];
$created = $progress['created'];
$updated = $progress['updated'];
} while (! $progress['done']);
$totalCreated += $created;
$totalUpdated += $updated;
$totalRows += (int) $prepared['total'];
$this->line(sprintf(
'[%d/%d] %s:%s 行,新增 %s,更新 %s',
$index + 1,
count($files),
basename($path),
number_format((int) $prepared['total']),
number_format($created),
number_format($updated),
));
}
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'导入完成:文件 %s 个,读取 %s 行,新增 %s,更新 %s。',
number_format(count($files)),
number_format($totalRows),
number_format($totalCreated),
number_format($totalUpdated),
));
return self::SUCCESS;
}
}

View File

@ -11,16 +11,19 @@ use Throwable;
class ImportPinduoduoPlatformBalances extends Command
{
protected $signature = 'business-mirror:import-pdd-platform-balances
{path : 拼多多平台实际期末余额 XLSX/XLS/CSV}
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD}';
{path : 聚水潭平台资金账户余额 XLSX/XLS/CSV}
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD;文件名含 YYYY-MM 时可省略}';
protected $description = '导入拼多多平台实际期末余额,作为后续月份期初余额的滚动基准';
protected $description = '导入拼多多“期初余额”和“平台实际期末余额”,并自动维护待补期初队列';
public function handle(PinduoduoPlatformBalanceImporter $importer): int
{
$periodEnd = trim((string) $this->option('period-end'));
if ($periodEnd === '') {
$this->error('缺少 --period-end。');
$periodEnd = $this->periodEndFromFilename((string) $this->argument('path'));
}
if ($periodEnd === '') {
$this->error('无法从文件名识别账期,请使用 --period-end=YYYY-MM-DD 指定月末。');
return self::FAILURE;
}
@ -38,9 +41,11 @@ class ImportPinduoduoPlatformBalances extends Command
return self::FAILURE;
}
$this->table(['截止日期', '店铺数', '余额合计', '替换旧行数', '来源文件'], [[
$this->table(['截止日期', '店铺数', '期初行数', '期初合计', '期末余额合计', '替换旧行数', '来源文件'], [[
$result['period_end'],
$result['total'],
$result['opening_total'],
$result['opening_balance_total'],
$result['balance_total'],
$result['replaced'],
$result['source_filename'],
@ -48,4 +53,23 @@ class ImportPinduoduoPlatformBalances extends Command
return self::SUCCESS;
}
private function periodEndFromFilename(string $path): string
{
$filename = basename($path);
if (preg_match('/(20\d{2})[-_年](\d{1,2})/u', $filename, $matches) !== 1) {
return '';
}
$month = (int) $matches[2];
if ($month < 1 || $month > 12) {
return '';
}
$date = \DateTimeImmutable::createFromFormat(
'!Y-n-j',
sprintf('%d-%d-1', (int) $matches[1], $month),
);
return $date === false ? '' : $date->format('Y-m-t');
}
}

View File

@ -2,13 +2,17 @@
namespace App\Console\Commands;
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
use Modules\EcommerceFinance\Services\PinduoduoSettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportPinduoduoSettlementBills extends Command
{
use QueuesBillPerformanceResync;
protected $signature = 'pinduoduo-bills:import-authoritative
{path : 聚胜算导出的拼多多完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
@ -20,7 +24,10 @@ class ImportPinduoduoSettlementBills extends Command
protected $description = '导入并核验聚胜算拼多多完整账单(保留全部账户类型)';
public function handle(PinduoduoSettlementBillImporter $importer): int
public function handle(
PinduoduoSettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -67,6 +74,10 @@ class ImportPinduoduoSettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->queueBillPerformanceResync($performanceResync, 'pinduoduo', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -0,0 +1,111 @@
<?php
namespace App\Console\Commands;
use App\Business\ServiceCompanyReconciliation\CustomerServiceMappingWorkbookImporter;
use App\Business\ServiceCompanyReconciliation\ServiceCompanyReconciliationRepository;
use Illuminate\Console\Command;
class ImportServiceCompanyCustomerMapping extends Command
{
protected $signature = 'service-company:import-customer-mapping
{file : 客服公司映射 Excel 路径}
{--company-id=1 : 租户公司 ID}
{--effective-from=2026-10-01 : 结算关系生效日期}
{--auto-assign-period= : 未分配店铺按该月收入自动平衡,默认上一个完整月}
{--deactivate-empty-auto : 校正错误自动分配,停用报表当前月份无收入的自动来源关系}
{--actor=客服公司映射导入 : 导入操作人}
{--dry-run : 只解析和校验,不写入数据库}';
protected $description = '导入客服公司与店铺公司的配置映射';
public function handle(
CustomerServiceMappingWorkbookImporter $importer,
ServiceCompanyReconciliationRepository $repository,
): int {
$companyId = (int) $this->option('company-id');
$effectiveFrom = trim((string) $this->option('effective-from'));
$autoAssignPeriod = trim((string) $this->option('auto-assign-period'));
if ($autoAssignPeriod === '') {
$autoAssignPeriod = now()->startOfMonth()->subMonthNoOverflow()->format('Y-m');
}
try {
$parsed = $importer->rows((string) $this->argument('file'));
} catch (\Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->table(['指标', '数量'], [
['店铺公司行数', $parsed['total_rows']],
['已分配客服公司', $parsed['assigned_rows']],
['暂不分配', $parsed['unassigned_rows']],
['无效行', count($parsed['invalid_rows'])],
]);
if ($parsed['invalid_rows'] !== []) {
$this->error(implode(PHP_EOL, $parsed['invalid_rows']));
return self::FAILURE;
}
if ((bool) $this->option('dry-run')) {
$this->info('校验通过,未写入数据库。');
return self::SUCCESS;
}
$result = $repository->syncCustomerServiceMappings(
$companyId,
$parsed['rows'],
$effectiveFrom,
trim((string) $this->option('actor')) ?: '客服公司映射导入',
$parsed['unassigned'],
$autoAssignPeriod,
);
if ($result['errors'] !== []) {
$this->error(implode(PHP_EOL, $result['errors']));
return self::FAILURE;
}
$this->table(['结果', '数量'], [
['新增', $result['created']],
['更新', $result['updated']],
['无变化', $result['unchanged']],
['停用', $result['inactive']],
['自动补分配', $result['auto_assigned']],
['有收入但无法分配', count($result['auto_errors'])],
]);
if ($result['auto_totals'] !== []) {
$this->table(
['客服公司', '自动补分配后收入'],
collect($result['auto_totals'])
->map(static fn (float $amount, string $name): array => [$name, number_format($amount, 2, '.', '')])
->values()
->all(),
);
}
if ($result['auto_errors'] !== []) {
$this->warn(implode(PHP_EOL, $result['auto_errors']));
}
if ((bool) $this->option('deactivate-empty-auto')) {
$cleanup = $repository->deactivateAutoMappingsWithoutReportIncome(
$companyId,
$autoAssignPeriod,
trim((string) $this->option('actor')) ?: '客服公司映射导入',
);
if ($cleanup['errors'] !== []) {
$this->error(implode(PHP_EOL, $cleanup['errors']));
return self::FAILURE;
}
$this->table(['自动分配校正', '数量'], [
['停用无收入关系', $cleanup['deactivated']],
['保留有收入关系', $cleanup['kept']],
]);
}
$this->info("客服公司映射已同步,生效日期:{$effectiveFrom}");
return self::SUCCESS;
}
}

View File

@ -2,13 +2,17 @@
namespace App\Console\Commands;
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
use Modules\EcommerceFinance\Services\TaobaoAlipaySettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportTaobaoAlipaySettlementBills extends Command
{
use QueuesBillPerformanceResync;
protected $signature = 'taobao-alipay-bills:import-authoritative
{path : 聚胜算导出的淘系支付宝完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
@ -20,7 +24,10 @@ class ImportTaobaoAlipaySettlementBills extends Command
protected $description = '导入并核验聚胜算淘系支付宝完整账单';
public function handle(TaobaoAlipaySettlementBillImporter $importer): int
public function handle(
TaobaoAlipaySettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -66,6 +73,10 @@ class ImportTaobaoAlipaySettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->queueBillPerformanceResync($performanceResync, 'taobao-alipay', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -2,13 +2,17 @@
namespace App\Console\Commands;
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
use Modules\EcommerceFinance\Services\TaobaoWechatSettlementBillImporter;
use RuntimeException;
use Throwable;
class ImportTaobaoWechatSettlementBills extends Command
{
use QueuesBillPerformanceResync;
protected $signature = 'taobao-wechat-bills:import-authoritative
{path : 聚胜算导出的淘系微信完整账单 XLSX}
{--from= : 账期开始日期,格式 YYYY-MM-DD}
@ -20,7 +24,10 @@ class ImportTaobaoWechatSettlementBills extends Command
protected $description = '导入并核验聚胜算淘系微信完整账单';
public function handle(TaobaoWechatSettlementBillImporter $importer): int
public function handle(
TaobaoWechatSettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -67,6 +74,10 @@ class ImportTaobaoWechatSettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->queueBillPerformanceResync($performanceResync, 'taobao-wechat', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -13,7 +13,7 @@ class ImportWangshangBankBills extends Command
{--date= : 账单日期 YYYY-MM-DD,默认前一天}
{--dry-run : 只校验,不写入财务台账}';
protected $description = '批量导入网商银行交易明细到财务台账动账明细';
protected $description = '批量导入网商银行影刀账单到银行账单';
public function handle(WangshangBankBillImporter $importer): int
{
@ -26,7 +26,7 @@ class ImportWangshangBankBills extends Command
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('网商银行账单未导入,保留原有动账明细。' . $exception->getMessage());
$this->error('网商银行影刀账单未导入,保留原有银行账单。' . $exception->getMessage());
return self::FAILURE;
}
@ -45,12 +45,16 @@ class ImportWangshangBankBills extends Command
$this->info(sprintf(
'%s网商银行账单:%d 个账户,%d 笔,收入 %.2f,支出 %.2f。',
$result['dry_run'] ? '校验完成,' : '已接入财务台账动账明细,',
$result['dry_run'] ? '校验完成,' : '已写入银行账单,',
count($result['accounts']),
$result['rows'],
$result['income'],
$result['expense'],
));
$this->line(sprintf(
'已同步 %d 个账户的当前余额。',
$result['synced_accounts'],
));
return self::SUCCESS;
}

View File

@ -0,0 +1,384 @@
<?php
namespace App\Console\Commands;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use RuntimeException;
class LockFinanceLedgerMonthlyOpening extends Command
{
protected $signature = 'finance-ledger:lock-monthly-opening
{date? : 锁定日期,必须为每月 1 日;默认当月}
{--apply : 正式写入;不传时只预览}
{--json : 以 JSON 输出结果}';
protected $description = '按上月末最后一笔真实银行余额锁定账户月度期初';
public function handle(): int
{
try {
$date = $this->date();
$previousEnd = $date->subDay();
$nextMonth = $date->addMonthNoOverflow();
$result = $this->lock($date, $previousEnd, $nextMonth, (bool) $this->option('apply'));
if ((bool) $this->option('json')) {
$this->line(json_encode(
$result,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
));
} else {
$this->line(($result['applied'] ? '已锁定' : '预览') . ' ' . $result['opening_date'] . ' 月度期初');
$this->line(
'可锁定账户:' . $result['eligible_accounts']
. ';写入账户:' . $result['unique_account_shorts']
. ';新增:' . $result['created']
. ';更新:' . $result['updated']
. ';无变化:' . $result['unchanged']
. ';保留手工期初:' . $result['preserved_existing']
);
$this->line(
'跳过:无真实余额 ' . $result['skipped_no_basis']
. ';同名账户余额冲突 ' . $result['skipped_conflicts']
);
}
return self::SUCCESS;
} catch (\Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
private function date(): CarbonImmutable
{
$value = trim((string) ($this->argument('date') ?: now('Asia/Shanghai')->toDateString()));
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
if (! $date instanceof CarbonImmutable
|| $date->format('Y-m-d') !== $value
|| $date->day !== 1) {
throw new RuntimeException('锁定日期必须使用 YYYY-MM-01 格式。');
}
return $date;
}
/**
* @return array<string,mixed>
*/
private function lock(
CarbonImmutable $date,
CarbonImmutable $previousEnd,
CarbonImmutable $nextMonth,
bool $apply,
): array {
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$accounts = $connection->table('fin_accounts')
->whereNotNull('account_short')
->where('account_short', '<>', '')
->orderBy('account_short')
->orderBy('account_no')
->get(['id', 'account_short', 'account_no']);
$bankStatementBefore = [];
foreach ($connection->table('fin_transactions')
->where('source', 'bank_statement')
->whereNotNull('balance')
->orderBy('txn_date')
->orderBy('id')
->get(['txn_date', 'source_value', 'income', 'expense', 'balance']) as $row) {
$accountNo = $this->accountNo($row->source_value);
if ($accountNo === '') {
continue;
}
if ($row->txn_date <= $previousEnd->toDateString()) {
$bankStatementBefore[$accountNo] = $row;
}
}
$bankBillBefore = [];
foreach ($connection->table('fin_bank_direct_bills')
->whereNotNull('balance')
->orderBy('txn_date')
->orderBy('txn_at')
->orderBy('id')
->get(['account_no', 'txn_date', 'income', 'expense', 'balance']) as $row) {
$accountNo = $this->accountNo($row->account_no);
if ($accountNo === '') {
continue;
}
if ($row->txn_date <= $previousEnd->toDateString()) {
$bankBillBefore[$accountNo] = $row;
}
}
$snapshotBefore = [];
foreach ($connection->table('fin_bank_direct_balance_snapshots')
->where('balance_date', '<=', $previousEnd->toDateString())
->orderBy('balance_date')
->orderBy('balance_at')
->orderBy('id')
->get(['account_no', 'account_balance', 'available_balance']) as $row) {
$accountNo = $this->accountNo($row->account_no);
if ($accountNo !== '') {
$snapshotBefore[$accountNo] = $row;
}
}
$openingBefore = $connection->table('fin_account_opening')
->where('opening_date', '<', $date->toDateString())
->orderBy('opening_date')
->orderBy('id')
->get(['account_short', 'opening_date', 'opening_balance'])
->keyBy('account_short');
$latestTransactionByShort = [];
$latestTransactionByAccountNo = [];
foreach ($connection->table('fin_transactions')
->whereNull('deleted_at')
->where('txn_date', '<=', $previousEnd->toDateString())
->cursor() as $row) {
$transactionDate = substr((string) $row->txn_date, 0, 10);
$short = trim((string) ($row->account_short ?? ''));
if ($short !== ''
&& ($latestTransactionByShort[$short] ?? '') < $transactionDate) {
$latestTransactionByShort[$short] = $transactionDate;
}
$accountNo = $this->accountNo($row->source_value ?? null);
if ($accountNo !== ''
&& ($latestTransactionByAccountNo[$accountNo] ?? '') < $transactionDate) {
$latestTransactionByAccountNo[$accountNo] = $transactionDate;
}
}
$existingOpenings = $connection->table('fin_account_opening')
->where('opening_date', $date->toDateString())
->get()
->keyBy('account_short');
$byShort = [];
foreach ($accounts as $account) {
$short = trim((string) $account->account_short);
$accountNo = $this->accountNo($account->account_no);
[$balance, $source, $sourceDate] = $this->actualOpening(
$accountNo,
$bankStatementBefore,
$bankBillBefore,
$snapshotBefore,
);
[$carriedBalance, $carriedSource, $carriedSourceDate] = $this->carriedOpening(
$short,
$accountNo,
$openingBefore,
$latestTransactionByShort,
$latestTransactionByAccountNo,
);
$opening = $openingBefore->get($short);
$latestOpeningDate = $opening === null
? ''
: substr((string) $opening->opening_date, 0, 10);
if ($carriedBalance !== null
&& ($balance === null || $carriedSourceDate > $sourceDate)) {
$balance = $carriedBalance;
$source = $carriedSource;
$sourceDate = $carriedSourceDate;
} elseif ($balance !== null
&& $latestOpeningDate !== ''
&& $sourceDate < $latestOpeningDate) {
// 新期初比旧账单余额更晚;若期初后还有未定价动账,不能回退使用旧余额。
$balance = null;
$source = '';
$sourceDate = '';
}
if ($balance === null) {
$byShort[$short][] = [
'account_id' => (int) $account->id,
'balance' => null,
'source' => '',
'source_date' => '',
];
continue;
}
$byShort[$short][] = [
'account_id' => (int) $account->id,
'balance' => $balance,
'source' => $source,
'source_date' => $sourceDate,
];
}
$eligibleAccounts = 0;
$skippedNoBasis = 0;
$skippedConflicts = 0;
$candidates = [];
foreach ($byShort as $short => $items) {
$missing = array_filter($items, static fn (array $item): bool => $item['balance'] === null);
if ($missing !== []) {
$skippedNoBasis += count($items);
continue;
}
$balances = array_values(array_unique(array_map(
static fn (array $item): string => number_format((float) $item['balance'], 2, '.', ''),
$items,
)));
if (count($balances) !== 1) {
$skippedConflicts += count($items);
continue;
}
$eligibleAccounts += count($items);
$candidates[$short] = [
'opening_balance' => (float) $balances[0],
'source' => (string) $items[0]['source'],
'source_date' => (string) $items[0]['source_date'],
];
}
$created = 0;
$updated = 0;
$unchanged = 0;
$preservedExisting = 0;
if ($apply) {
$connection->transaction(function () use (
$connection,
$date,
$candidates,
$existingOpenings,
&$created,
&$updated,
&$unchanged,
&$preservedExisting,
): void {
foreach ($candidates as $short => $candidate) {
$existing = $existingOpenings->get($short);
$remark = '系统锁定:' . $candidate['source_date'] . ' 最后一笔实际余额';
if ($existing === null) {
$connection->table('fin_account_opening')->insert([
'account_short' => $short,
'opening_date' => $date->toDateString(),
'opening_balance' => $candidate['opening_balance'],
'remark' => $remark,
'created_at' => now(),
'updated_at' => now(),
]);
$created++;
continue;
}
if (! str_starts_with((string) $existing->remark, '系统锁定:')) {
$preservedExisting++;
continue;
}
if (abs((float) $existing->opening_balance - (float) $candidate['opening_balance']) < 0.005
&& (string) $existing->remark === $remark) {
$unchanged++;
continue;
}
$connection->table('fin_account_opening')
->where('id', $existing->id)
->update([
'opening_balance' => $candidate['opening_balance'],
'remark' => $remark,
'updated_at' => now(),
]);
$updated++;
}
});
}
return [
'applied' => $apply,
'opening_date' => $date->toDateString(),
'previous_period_end' => $previousEnd->toDateString(),
'eligible_accounts' => $eligibleAccounts,
'unique_account_shorts' => count($candidates),
'created' => $created,
'updated' => $updated,
'unchanged' => $unchanged,
'preserved_existing' => $preservedExisting,
'skipped_no_basis' => $skippedNoBasis,
'skipped_conflicts' => $skippedConflicts,
'candidates' => array_map(
static fn (string $short, array $candidate): array => [
'account_short' => $short,
...$candidate,
],
array_keys($candidates),
array_values($candidates),
),
];
}
/**
* @return array{0:?float,1:string,2:string}
*/
private function actualOpening(
string $accountNo,
array $bankStatementBefore,
array $bankBillBefore,
array $snapshotBefore,
): array {
if ($accountNo === '') {
return [null, '', ''];
}
if (isset($bankStatementBefore[$accountNo])) {
$row = $bankStatementBefore[$accountNo];
return [
round((float) $row->balance, 2),
'bank_statement',
substr((string) $row->txn_date, 0, 10),
];
}
if (isset($bankBillBefore[$accountNo])) {
$row = $bankBillBefore[$accountNo];
return [
round((float) $row->balance, 2),
'bank_bill',
substr((string) $row->txn_date, 0, 10),
];
}
if (isset($snapshotBefore[$accountNo])) {
$row = $snapshotBefore[$accountNo];
return [
round((float) ($row->account_balance ?? $row->available_balance), 2),
'balance_snapshot',
substr((string) $row->balance_date, 0, 10),
];
}
return [null, '', ''];
}
/**
* @return array{0:?float,1:string,2:string}
*/
private function carriedOpening(
string $accountShort,
string $accountNo,
mixed $openingBefore,
array $latestTransactionByShort,
array $latestTransactionByAccountNo,
): array {
$opening = $openingBefore->get($accountShort);
if ($opening === null) {
return [null, '', ''];
}
$openingDate = substr((string) $opening->opening_date, 0, 10);
$latestTransactionDate = max(
(string) ($latestTransactionByShort[$accountShort] ?? ''),
$accountNo !== '' ? (string) ($latestTransactionByAccountNo[$accountNo] ?? '') : '',
);
if ($latestTransactionDate !== '' && $latestTransactionDate >= $openingDate) {
return [null, '', ''];
}
return [
round((float) $opening->opening_balance, 2),
'opening_carry_forward',
$openingDate,
];
}
private function accountNo(mixed $value): string
{
return preg_replace('/\D+/', '', trim((string) $value)) ?? '';
}
}

View File

@ -0,0 +1,104 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Repositories\PlantingReimbursementRepository as Repository;
use Modules\EcommerceFinance\Services\PlantingReimbursementAuditor as Auditor;
use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
use Throwable;
/** 每天 10:25 生成当天种菜报销批次,把核对数、可报销合计、要取消的单和自检结果推到钉钉群并 @ 报销人。只读,不改聚工单。 */
class PlantingReimbursementDailyDigest extends Command
{
protected $signature = 'planting-reimbursement:daily-digest
{--date= : 报销日期 Y-m-d,默认今天}
{--dry-run : 只打印消息,不发送}
{--force : 忽略当天已推送标记}';
protected $description = '推送当天种菜报销批次汇总到钉钉群';
public function handle(Workbench $workbench, Robot $robot, Repository $repository): int
{
$date = trim((string) $this->option('date')) ?: Workbench::defaultDate();
try {
Workbench::parseDate($date);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$failed = false;
foreach (Company::enabled()->orderBy('id')->get() as $company) {
$company->makeCurrent();
if (! $robot->enabled()) {
$this->line("#{$company->id}: 未配置种菜报销群机器人,跳过");
continue;
}
$lock = "planting-reimbursement:digest:{$company->id}:{$date}";
if (! $this->option('dry-run') && ! $this->option('force') && ! Cache::add($lock, now()->toDateTimeString(), now()->addDay())) {
$this->line("#{$company->id}: {$date} 已推送过");
continue;
}
try {
[$title, $text] = $this->message($workbench, $repository, (int) $company->id, $date);
if ($this->option('dry-run')) {
$this->line($title . "\n" . $text);
continue;
}
$robot->sendDigest($title, $text);
$this->info("#{$company->id}: 已推送 {$date} 汇总");
} catch (Throwable $exception) {
Cache::forget($lock);
report($exception);
$this->error("#{$company->id}: 推送失败:" . $exception->getMessage());
$failed = true;
}
}
return $failed ? self::FAILURE : self::SUCCESS;
}
/** @return array{0:string,1:string} */
private function message(Workbench $workbench, Repository $repository, int $companyId, string $date): array
{
$sync = $repository->syncStatus();
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
$title = '种菜报销 ' . $date . ' 批次';
$lines = ['#### ' . $title];
$stale = $sync['code'] !== 'ready' || $sync['last_succeeded_at'] === null
|| now()->diffInMinutes(\Illuminate\Support\Carbon::parse($sync['last_succeeded_at']), true) > 20;
if ($stale) {
$lines[] = '> **聚工单数据不是最新的**(最后同步成功:' . ($sync['last_succeeded_at'] ? substr($sync['last_succeeded_at'], 0, 16) : '无') . '),先别按下面结果报销。';
}
if (! in_array($sync['code'], ['ready', 'failed'], true)) {
$lines[] = '- 聚工单镜像未就绪,暂时无法生成批次。';
$lines[] = '- [打开工作台](' . $url . ')';
return [$title, implode("\n", $lines)];
}
$result = $workbench->build($companyId, $date);
$s = $result['summary'];
$lines[] = '- 待处理(付款 ' . substr($result['window']['from'], 0, 10) . ' ~ ' . substr($result['window']['to'], 0, 10) . '):**' . $s['source']['count'] . ' 条 / ' . number_format((float) $s['source']['amount'], 2) . ' 元**,请先在聚工单核对';
$lines[] = '- 可报销:' . $s['counts'][Auditor::DECISION_PASS] . ' 条 / **' . number_format((float) $s['total'], 2) . ' 元**(三大天猫 ' . number_format((float) $s['group_amounts'][Auditor::GROUP_BIG_TMALL], 2) . ',其他 ' . number_format((float) $s['group_amounts'][Auditor::GROUP_OTHER], 2) . ')';
$lines[] = '- 取消工单:' . $s['counts'][Auditor::DECISION_CANCEL] . ' 条;待复查:' . $s['counts'][Auditor::DECISION_RECHECK] . ' 条';
$bad = array_column(array_filter($s['checks'], static fn (array $check): bool => ! $check['ok']), 'label');
$lines[] = '- 自检:' . ($bad === [] ? '全部通过' : '未通过 ' . implode('、', $bad));
if (($result['uploads']['monitor'] ?? null) === null || substr((string) ($result['uploads']['monitor']['uploaded_at'] ?? ''), 0, 10) !== $date) {
$lines[] = '- 今天还没上传种菜监控看板,超额尚未校验';
}
if (($result['roster_source'] ?? '') === 'none') {
$lines[] = '- 取不到在职名单,收款人在职未校验';
}
$lines[] = '- [打开工作台核对](' . $url . ')';
return [$title, implode("\n", $lines)];
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\PayablesUnpricedCycleProcessor;
class ProcessPayablesUnpricedCycle extends Command
{
protected $signature = 'payables:unpriced-cycle
{price-file : 工作平台定价/变价文件路径}
{--period= : 货款账期,格式 YYYY-MM,默认上月}
{--cutoff= : 定价快照截止日,格式 YYYY-MM-DD,默认今天}
{--company=1 : 公司 ID}
{--user= : 操作用户 ID}';
protected $description = '匹配历史未定价并补入当月新增未定价';
public function handle(PayablesUnpricedCycleProcessor $processor): int
{
$period = (string) ($this->option('period') ?: now()->subMonthNoOverflow()->format('Y-m'));
$cutoff = (string) ($this->option('cutoff') ?: now()->format('Y-m-d'));
$companyId = max(1, (int) $this->option('company'));
$userId = $this->option('user') !== null ? (int) $this->option('user') : null;
$result = $processor->process(
(string) $this->argument('price-file'),
$period,
$cutoff,
$companyId,
$userId,
);
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
return self::SUCCESS;
}
}

View File

@ -9,8 +9,8 @@ use Modules\EcommerceFinance\Repositories\DewuSettlementBillRepository;
use Modules\EcommerceFinance\Repositories\JdDailyBillRepository;
use Modules\EcommerceFinance\Repositories\PinduoduoSettlementBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
@ -150,6 +150,7 @@ class RunAccountBillsExportTask extends Command
'taobao-wechat' => app(TaobaoWechatSettlementBillRepository::class)->exportAccountBills($filters, $sort, $dir),
'pinduoduo' => app(PinduoduoSettlementBillRepository::class)->exportAccountBills($filters, $sort, $dir),
'dewu' => app(DewuSettlementBillRepository::class)->exportAccountBills($filters, $sort, $dir),
'dewu-alipay' => app(StoreReceivingDewuAlipayBillMirrorRepository::class)->exportRows($filters, $sort, $dir),
'jd-transactions', 'jingxi' => JdBillPlatform::isJdBillTab($tab)
? app(JdDailyBillRepository::class)->forPlatform(JdBillPlatform::platformForBillType($tab))->exportRows($filters, $sort, $dir)
: [],

View File

@ -11,7 +11,7 @@ use Symfony\Component\Process\Process;
use Throwable;
/**
* 科目映射表变更后的业绩明细自动重跑队列。
* 科目映射表或原始账单变化后的业绩明细自动重跑队列。
*
* 每轮按预算处理队列里的「平台 × 月份」;实际同步放在独立 PHP 子进程中,
* 避免大平台重跑时的内存累积,并让其它同步有机会取得全局锁。
@ -20,7 +20,7 @@ class RunAccountMappingResync extends Command
{
protected $signature = 'store-receipt:auto-resync {--max-jobs=1 : 每轮最多任务数,0为不限} {--max-seconds=300 : 单个任务结束后检查本轮时间预算}';
protected $description = '处理科目映射表变更触发的业绩明细重跑队列';
protected $description = '处理科目映射表或原始账单变化触发的业绩明细重跑队列';
public function handle(AccountMappingResyncDispatcher $dispatcher): int
{
@ -79,7 +79,7 @@ class RunAccountMappingResync extends Command
'updated_at' => now(),
]);
} catch (Throwable $exception) {
Log::error('科目映射表自动重跑失败:' . $exception->getMessage());
Log::error('业绩明细自动重跑失败:' . $exception->getMessage());
DB::table(AccountMappingResyncDispatcher::JOBS_TABLE)
->where('id', $job->id)
->where('status', 'running')

View File

@ -0,0 +1,52 @@
<?php
namespace App\Console\Commands;
use App\Support\UnshippedWaybills;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
final class SeedUnshippedHistory extends Command
{
protected $signature = 'courier:seed-unshipped-history {cutoff : 历史明细截止日期} {--apply : 确认写入共享镜像}';
protected $description = '从标准输入读取核对后的分来源单号清单,补录历史未发出明细';
public function handle(UnshippedWaybills $service): int
{
$data = json_decode(stream_get_contents(STDIN, 1048577), true);
$cutoff = $this->argument('cutoff');
$validator = Validator::make(['data' => $data, 'cutoff' => $cutoff], [
'cutoff' => ['required', 'date_format:Y-m-d', 'after_or_equal:'.UnshippedWaybills::START, 'before:today'],
'data' => ['required', 'array:intercept,replacement,warehouse', 'size:3'],
'data.*' => ['required', 'array', 'max:10000'],
'data.*.*' => ['required', 'string', 'regex:/^[a-zA-Z0-9-]{7,96}$/', 'not_regex:/^\d+(?:\.\d+)?e[+-]?\d+$/i'],
'data.intercept.*' => ['max:15'],
]);
if ($validator->fails()) {
$this->error('清单格式、快递单号或截止日期校验失败。');
return self::FAILURE;
}
$marker = UnshippedWaybills::HISTORY_PREFIX.$cutoff;
foreach ($data as $source => $numbers) {
$data[$source] = array_values(array_unique($numbers));
$this->info(UnshippedWaybills::label($source).':'.count($data[$source]).' 条。');
}
if (!$this->option('apply')) return self::SUCCESS;
$service->connection()->transaction(function () use ($service, $data, $marker, $cutoff): void {
foreach ($data as $source => $numbers) {
foreach (array_chunk($numbers, 500) as $chunk) {
$service->results()->upsert(array_map(fn ($waybill) => [
'source' => $source, 'waybill_no' => $waybill, 'evidence_no' => $marker,
'evidence_time' => $cutoff.' 00:00:00', 'evidence_text' => '历史导出补录,文件仅含单号和来源;日期为覆盖截止日。',
], $chunk), ['source', 'evidence_no', 'waybill_no'], ['evidence_text']);
}
}
});
return self::SUCCESS;
}
}

View File

@ -0,0 +1,170 @@
<?php
namespace App\Console\Commands;
use DateTimeImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Throwable;
class SendCmbMailFailureNotification extends Command
{
protected $signature = 'cmb-mail:notify-failure
{--date= : 账单日期 YYYY-MM-DD;默认前一天}
{--type=unknown : 失败类型}
{--reason= : 已脱敏的简短失败原因}
{--recipient= : 接收人的钉钉企业昵称}
{--test : 发送通道测试消息}';
protected $description = '由生产服务器向指定钉钉成员发送招商银行邮件任务失败提醒';
public function handle(): int
{
try {
$date = $this->date();
$recipient = trim((string) $this->option('recipient'));
if ($recipient === '') {
throw new RuntimeException('未配置钉钉提醒接收人。');
}
$userIds = DB::table('dingtalk_identities')
->where('nickname', $recipient)
->whereNotNull('dingtalk_user_id')
->pluck('dingtalk_user_id')
->map(static fn ($value): string => trim((string) $value))
->filter()
->unique()
->values();
if ($userIds->count() !== 1) {
throw new RuntimeException(
$userIds->isEmpty()
? '没有找到对应的钉钉企业成员。'
: '该昵称对应多个钉钉企业成员,无法安全确定接收人。'
);
}
[$title, $text] = $this->message(
$date,
trim((string) $this->option('type')) ?: 'unknown',
$this->safeReason((string) $this->option('reason')),
(bool) $this->option('test'),
);
$this->sendToDingTalk([$userIds->first()], $title, $text);
$this->info($this->option('test') ? '钉钉通知通道测试已发送。' : '钉钉失败提醒已发送。');
return self::SUCCESS;
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
private function date(): string
{
$value = trim((string) $this->option('date'));
$value = $value !== '' ? $value : now('Asia/Shanghai')->subDay()->toDateString();
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if (! $parsed || $parsed->format('Y-m-d') !== $value) {
throw new RuntimeException('--date 必须使用 YYYY-MM-DD 格式。');
}
return $value;
}
/** @return array{0:string,1:string} */
private function message(string $date, string $type, string $reason, bool $test): array
{
if ($test) {
return [
'招商银行邮件任务通知通道测试',
implode("\n", [
'### 招商银行邮件任务通知通道测试',
'- 接收方式:生产服务器直接发送至钉钉',
'- 用途:仅发送招商银行邮件任务异常提醒',
'- 结果:通道已接通',
]),
];
}
$labels = [
'auth' => '邮箱授权失效或登录失败',
'config' => '任务配置缺失',
'not_found' => '未找到当天招商银行账单邮件',
'download' => '账单下载失败',
'archive' => '账单解压或安全校验失败',
'import' => '银行账单导入失败',
'unknown' => '任务执行失败',
];
return [
'招商银行邮件任务失败',
implode("\n", [
'### 招商银行邮件任务失败',
'- 账单日期:' . $date,
'- 失败类型:' . ($labels[$type] ?? $labels['unknown']),
'- 执行结果:07:00、07:10 两次均失败',
'- 原因:' . $reason,
'请检查服务器任务日志及 163 邮箱授权状态。',
]),
];
}
private function safeReason(string $reason): string
{
$reason = preg_replace('/[\r\n\t]+/u', ' ', trim($reason)) ?? '';
$reason = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu', '[邮箱已隐藏]', $reason) ?? $reason;
$reason = mb_substr($reason, 0, 200);
return $reason !== '' ? $reason : '服务器日志已记录具体错误。';
}
/** @param list<string> $userIds */
private function sendToDingTalk(array $userIds, string $title, string $text): void
{
$clientId = trim((string) config('dingtalk.client_id'));
$clientSecret = trim((string) config('dingtalk.client_secret'));
$robotCode = trim((string) config('dingtalk.robot.code'));
if ($clientId === '' || $clientSecret === '' || $robotCode === '') {
throw new RuntimeException('钉钉应用通知凭据不完整。');
}
$timeout = max(3, min(30, (int) config('dingtalk.timeout', 10)));
$tokenResponse = Http::asJson()
->acceptJson()
->timeout($timeout)
->post((string) config('dingtalk.robot.access_token_url'), [
'appKey' => $clientId,
'appSecret' => $clientSecret,
]);
$accessToken = trim((string) $tokenResponse->json('accessToken'));
if (! $tokenResponse->successful() || $accessToken === '') {
throw new RuntimeException('钉钉应用访问令牌获取失败。');
}
$response = Http::asJson()
->acceptJson()
->withHeaders(['x-acs-dingtalk-access-token' => $accessToken])
->timeout($timeout)
->post((string) config('dingtalk.robot.send_url'), [
'robotCode' => $robotCode,
'userIds' => $userIds,
'msgKey' => 'sampleMarkdown',
'msgParam' => json_encode([
'title' => $title,
'text' => $text,
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
]);
if (! $response->successful()) {
$code = trim((string) $response->json('code'));
throw new RuntimeException(
'钉钉消息发送失败:HTTP ' . $response->status()
. ($code !== '' ? ' ' . mb_substr($code, 0, 120) : '')
);
}
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\SupplierStatementReminder;
use Throwable;
class SendSupplierStatementReminders extends Command
{
protected $signature = 'supplier-statement:send-reminders
{--date= : 执行日期,格式 Y-m-d,默认今天}
{--supplier= : 仅检查指定供应商}
{--dry-run : 只预览,不发送也不记录}';
protected $description = '在每月 1-14 日提醒上月有入库数据但尚未上传对账单的供应商';
public function handle(SupplierStatementReminder $reminder): int
{
$timezone = (string) config('app.platform_timezone', 'Asia/Shanghai');
$dateValue = trim((string) $this->option('date')) ?: now($timezone)->toDateString();
try {
$date = Carbon::createFromFormat('!Y-m-d', $dateValue, $timezone)->startOfDay();
} catch (Throwable) {
$this->error('执行日期格式无效。');
return self::FAILURE;
}
if ($date->format('Y-m-d') !== $dateValue) {
$this->error('执行日期格式无效。');
return self::FAILURE;
}
$failed = false;
$dryRun = (bool) $this->option('dry-run');
foreach (Company::enabled()->orderBy('id')->get() as $company) {
$company->makeCurrent();
$lock = Cache::lock(sprintf(
'supplier-statement-reminder:%d:%s',
$company->id,
$date->toDateString(),
), 900);
if (! $dryRun && ! $lock->get()) {
$this->warn("#{$company->id} {$company->name}: 已有催办任务运行");
continue;
}
try {
$result = $reminder->send(
$date,
(int) $company->id,
$dryRun,
trim((string) $this->option('supplier')),
);
if (! $result['reminder_day']) {
$this->line("#{$company->id} {$company->name}: 今天不在 1-14 日催办窗口");
continue;
}
if ($result['source_suppliers'] === 0) {
$this->warn("#{$company->id} {$company->name}: 上月对账入库数据尚未导入或没有入库供应商");
continue;
}
$this->line(sprintf(
'#%d %s %s: 入库供应商 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,今日已提醒 %d 家,未配置机器人 %d 家,失败 %d 家',
$company->id,
$company->name,
$result['accounting_month'],
$result['source_suppliers'],
$result['configured'],
$dryRun ? '将提醒' : '已发送',
count($dryRun ? $result['previewed'] : $result['sent']),
count($result['uploaded']),
count($result['already_sent']),
count($result['missing_robot']),
count($result['failed']),
));
foreach ($result['failed'] as $supplier => $message) {
$this->error("{$supplier}: {$message}");
$failed = true;
}
} catch (Throwable $exception) {
report($exception);
$this->error("#{$company->id} {$company->name}: 催办任务失败:" . $exception->getMessage());
$failed = true;
} finally {
if (! $dryRun) {
$lock->release();
}
}
}
return $failed ? self::FAILURE : self::SUCCESS;
}
}

View File

@ -13,9 +13,10 @@ use Throwable;
class SyncBusinessFilesToQiniu extends Command
{
private const PROBE_CLEANUP_MAX_ATTEMPTS = 10;
// Qiniu can briefly report a deleted object as present; keep the wait bounded.
private const PROBE_CLEANUP_MAX_ATTEMPTS = 20;
private const PROBE_CLEANUP_RETRY_DELAY_MICROSECONDS = 500_000;
private const PROBE_CLEANUP_RETRY_DELAY_MICROSECONDS = 1_000_000;
protected $signature = 'storage:business-files:sync
{--require-qiniu : Fail unless the private Qiniu backend is enabled}

View File

@ -3,6 +3,7 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DingInvoiceSyncService;
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
use Throwable;
@ -12,12 +13,15 @@ class SyncDingProcessDetailMirror extends Command
{--full : 从配置起始日期完整重建明细和付款事实}
{--business-id= : 只同步指定审批编号,多个用逗号分隔(最多 50 个)}
{--skip-approval-api : 定向同步时不调用钉钉官方审批接口}
{--skip-invoices : 不执行同轮发票增量识别}
{--dry-run : 只读取上游并校验,不写入镜像}';
protected $description = '从结构化审批镜像同步流程明细,并用钉钉官方接口补取缺失付款';
protected $description = '同步 OA 流程结构化明细,并在同一批处理中增量识别发票';
public function handle(DingProcessDetailMirrorSynchronizer $synchronizer): int
{
public function handle(
DingProcessDetailMirrorSynchronizer $synchronizer,
DingInvoiceSyncService $invoiceSync,
): int {
$businessIds = array_values(array_filter(array_map(
'trim',
explode(',', (string) $this->option('business-id')),
@ -61,6 +65,31 @@ class SyncDingProcessDetailMirror extends Command
$result['bank_amount_total'],
));
if ($businessIds === []
&& ! (bool) $this->option('dry-run')
&& ! (bool) $this->option('skip-invoices')
&& (bool) config('ding_invoice_data.sync_with_oa_process', true)) {
try {
$month = $invoiceSync->latestPendingMonth();
if ($month !== null) {
$invoiceResult = $invoiceSync->syncMonth(
$month,
(int) config('ding_invoice_data.auto_scan_limit', 5),
);
$this->info(sprintf(
'发票增量识别完成:%d 个流程,新识别 %d 张,保留 %d 张,剩余 %d 个流程。',
$invoiceResult['processed_flows'],
$invoiceResult['recognized_invoices'],
$invoiceResult['preserved_invoices'],
$invoiceResult['remaining_flows'],
));
}
} catch (Throwable $exception) {
report($exception);
$this->warn('发票增量识别失败,OA 流程镜像已正常更新:' . $exception->getMessage());
}
}
return self::SUCCESS;
}
}

View File

@ -39,7 +39,11 @@ class SyncDingWorklogs extends Command
$days = max((int) ($this->option('days') ?: config('dingtalk.worklog.lookback_days', 35)), 1);
$templates = $this->templates();
$to = now();
$timezone = (string) config(
'dingtalk.worklog.timezone',
config('app.platform_timezone', config('app.timezone', 'Asia/Shanghai')),
);
$to = now($timezone);
$from = $to->copy()->subDays($days)->startOfDay();
try {

View File

@ -13,6 +13,8 @@ class SyncFinanceLedgerRpt extends Command
{--to= : 业务日期止,默认读取配置或当天}
{--days= : 只拉取最近 N 天并合并到现有明细}
{--merge : 合并到现有明细,不删除历史}
{--dingtalk-only : 只同步钉钉付款明细,用于高频增量}
{--sources= : 只同步指定来源,逗号分隔:dingtalk,payable,store,withdrawal}
{--no-recalculate : 只同步明细,不重算流水}';
protected $description = '从 AI 库 rpt 同步财务台账动账明细,并重算每日流水';
@ -22,18 +24,34 @@ class SyncFinanceLedgerRpt extends Command
$days = (int) ($this->option('days') ?: 0);
$from = $this->option('from') ?: null;
$merge = (bool) $this->option('merge');
$dingtalkOnly = (bool) $this->option('dingtalk-only');
$sources = array_values(array_filter(array_map(
'trim',
explode(',', (string) $this->option('sources')),
)));
if ($dingtalkOnly) {
$sources = ['dingtalk'];
}
if ($days > 0) {
$from = now()->subDays(max(1, $days) - 1)->toDateString();
$merge = true;
}
try {
$result = $synchronizer->sync(
! $this->option('no-recalculate'),
$from,
$this->option('to') ?: null,
$merge,
);
$result = $sources !== []
? $synchronizer->syncSources(
$sources,
! $this->option('no-recalculate'),
$from,
$this->option('to') ?: null,
$merge,
)
: $synchronizer->sync(
! $this->option('no-recalculate'),
$from,
$this->option('to') ?: null,
$merge,
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());

View File

@ -32,8 +32,23 @@ class SyncFinanceLedgerShopData extends Command
$this->option('to') ?: null,
(bool) $this->option('rebuild'),
);
$directoryMappings = $synchronizer->syncAccountMappings();
$publicAccountDefaults = $synchronizer->syncDefaultPublicAccounts();
$result = [
'balance' => $balance,
'account_mappings' => [
'defaulted' => $publicAccountDefaults['defaulted'],
'directory_shops' => $directoryMappings['shops'],
'shop_rows_updated' => $directoryMappings['shop_rows_updated']
+ $publicAccountDefaults['shop_rows_updated'],
'mappings_inserted' => $directoryMappings['mappings_inserted']
+ $publicAccountDefaults['mappings_inserted'],
'mappings_updated' => $directoryMappings['mappings_updated']
+ $publicAccountDefaults['mappings_updated'],
'account_missing' => $publicAccountDefaults['account_missing'],
'ambiguous' => $directoryMappings['ambiguous']
+ $publicAccountDefaults['ambiguous'],
],
'withdrawals' => [
'processed' => 0,
'written' => 0,
@ -68,6 +83,8 @@ class SyncFinanceLedgerShopData extends Command
['重建店铺台账', $result['balance']['rebuilt']],
['已更新店铺余额', $result['balance']['matched']],
['店铺余额合计', number_format((float) $result['balance']['amount'], 2)],
['默认公户补齐店铺', $result['account_mappings']['defaulted']],
['多公户待确认', $result['account_mappings']['ambiguous']],
['提现处理笔数', $result['withdrawals']['processed']],
['提现新增或更新', $result['withdrawals']['written']],
['上游已存在提现', $result['withdrawals']['upstream_duplicates']],

View File

@ -0,0 +1,35 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\InternalFlowWorkbookImporter;
use Throwable;
class SyncInternalFlowCompanies extends Command
{
protected $signature = 'internal-flow:sync-companies';
protected $description = '将内部流转配置公司补齐到当前数据集,并同步其固定标签';
public function handle(InternalFlowWorkbookImporter $importer): int
{
try {
$result = $importer->syncConfiguredCompanies();
} catch (Throwable $exception) {
report($exception);
$this->error('内部流转公司标签同步失败:' . $exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'内部流转公司标签同步完成:新增 %s 家,更新 %s 家,配置共 %s 家。',
number_format($result['inserted']),
number_format($result['updated']),
number_format($result['total']),
));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Console\Commands;
use App\Business\KukaPostingBase\KukaPostingMaterialMapSynchronizer;
use Illuminate\Console\Command;
use InvalidArgumentException;
class SyncKukaPostingMaterialMap extends Command
{
protected $signature = 'business-mirror:sync-kuka-posting-material-map
{--company=1 : 公司 ID}
{--period= : 只匹配指定账期,格式 YYYY-MM}
{--dry-run : 只读取和校验,不覆盖镜像}
{--json : 输出 JSON}';
protected $description = '按货号匹配物料编号,并按款式编码匹配品牌货号及货号回退';
public function handle(KukaPostingMaterialMapSynchronizer $synchronizer): int
{
$companyId = (int) $this->option('company');
if ($companyId <= 0) {
throw new InvalidArgumentException('公司 ID 必须为正整数。');
}
$period = trim((string) $this->option('period'));
if ($period !== '' && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
}
$result = $synchronizer->sync(
$companyId,
$period === '' ? null : $period,
(bool) $this->option('dry-run'),
);
if ((bool) $this->option('json')) {
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
} else {
$this->info(sprintf(
'物料映射%s完成:货号 %d,唯一匹配 %d,未匹配 %d,冲突 %d;直接物料编号 %d,档案条码 %d,品牌SKU %d;页面货号映射 %d(款式品牌 %d,货号品牌回退 %d)。',
$result['dry_run'] ? '校验' : '同步',
$result['items'],
$result['matched'],
$result['unmatched'],
$result['ambiguous'],
$result['direct'],
$result['archive'],
$result['brand_sku'],
$result['brand_item_mappings'],
$result['brand_sku_mappings'],
$result['item_brand_mappings'],
));
}
return self::SUCCESS;
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace App\Console\Commands;
use App\Business\Piaoju\PiaojuSellerQuotaClient;
use App\Business\Piaoju\PiaojuSellerQuotaImporter;
use Illuminate\Console\Command;
use Throwable;
class SyncPiaojuSellerQuotas extends Command
{
protected $signature = 'piaoju:sync-invoice-quotas
{--file= : 票聚销方列表 JSON 文件;省略时调用票聚接口}
{--stdin : 从标准输入读取票聚销方列表 JSON}
{--dry-run : 只读取并校验票聚响应,不写共享镜像}';
protected $description = '同步票聚销方管理的最新可用发票额度到共享业务镜像';
public function handle(PiaojuSellerQuotaClient $client, PiaojuSellerQuotaImporter $importer): int
{
try {
$rows = $this->inputRows($client);
$values = $importer->values($rows);
if ((bool) $this->option('dry-run')) {
$this->info(sprintf('票聚销方额度读取成功:%d 条,未写入镜像。', count($values)));
return self::SUCCESS;
}
$written = $importer->replace($rows);
} catch (Throwable $exception) {
report($exception);
$this->error('票聚销方额度同步失败,已保留上一版镜像。');
return self::FAILURE;
}
$this->info(sprintf('票聚销方额度同步完成:%d 条。', $written));
return self::SUCCESS;
}
/**
* @return list<array<string,mixed>>
*/
private function inputRows(PiaojuSellerQuotaClient $client): array
{
$fromStdin = (bool) $this->option('stdin');
$path = trim((string) $this->option('file'));
if (! $fromStdin && $path === '') {
return $client->fetchAll();
}
$raw = $fromStdin ? stream_get_contents(STDIN) : file_get_contents($path);
if (! is_string($raw) || trim($raw) === '') {
throw new \RuntimeException('piaoju_input_empty');
}
$decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$rows = null;
if (is_array($decoded)) {
if (array_is_list($decoded)) {
$rows = $decoded;
} else {
$data = $decoded['data'] ?? null;
if (is_array($data)) {
$rows = array_is_list($data)
? $data
: ($data['list'] ?? $data['records'] ?? null);
}
}
}
if (! is_array($rows)) {
throw new \RuntimeException('piaoju_input_invalid');
}
return array_values(array_filter($rows, 'is_array'));
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Modules\EcommerceFinance\Services\PromotionExpenseMirrorSynchronizer;
use Throwable;
class SyncPromotionExpenses extends Command
{
private const HISTORY_START = '2026-01-01';
protected $signature = 'business-mirror:sync-promotion-expenses
{--from= : 开始日期(含)}
{--to= : 结束日期(含)}
{--days=7 : 未指定 from/to 时同步最近多少天}
{--full : 从 2026-01-01 开始完整校准}';
protected $description = '按日期、平台和店铺自动汇总聚水潭推广费用到共享镜像';
public function handle(PromotionExpenseMirrorSynchronizer $synchronizer): int
{
try {
[$from, $to] = $this->dateRange();
$result = $synchronizer->sync($from, $to);
} catch (Throwable $exception) {
Log::error('推广费用共享镜像同步失败。', ['exception' => $exception::class]);
$this->error('推广费用同步失败,页面继续显示上一版数据。');
return self::FAILURE;
}
if ($result['days'] === 0) {
$this->warn('上游暂无推广费用数据,未写入镜像。');
return self::SUCCESS;
}
$this->info(sprintf(
'推广费用同步完成:%s 至 %s(源数据截至 %s),%d 天,源记录 %d 条,汇总镜像 %d 行。',
$result['from'],
$result['to'],
$result['effective_to'] ?? '无',
$result['days'],
$result['source_rows'],
$result['stored_rows'],
));
return self::SUCCESS;
}
/** @return array{0:Carbon,1:Carbon} */
private function dateRange(): array
{
$toInput = trim((string) $this->option('to'));
$fromInput = trim((string) $this->option('from'));
$to = $toInput === ''
? now('Asia/Shanghai')->startOfDay()
: Carbon::createFromFormat('Y-m-d', $toInput, 'Asia/Shanghai')->startOfDay();
$from = $fromInput !== ''
? Carbon::createFromFormat('Y-m-d', $fromInput, 'Asia/Shanghai')->startOfDay()
: ($this->option('full')
? Carbon::parse(self::HISTORY_START, 'Asia/Shanghai')->startOfDay()
: $to->copy()->subDays(max(1, (int) $this->option('days')) - 1));
if ($from->gt($to)) {
throw new \InvalidArgumentException('开始日期不能晚于结束日期。');
}
return [$from, $to];
}
}

View File

@ -12,6 +12,7 @@ use App\Business\PlantingOrderLabelLookup;
use Modules\EcommerceFinance\Services\AccountLedgerRemarkMap;
use Modules\EcommerceFinance\Services\AccountMappingStore;
use Modules\EcommerceFinance\Services\LedgerRemarkFilter;
use Modules\EcommerceFinance\Services\ProductCostAutoRefresh;
use Modules\EcommerceFinance\Services\StoreReportMirrorSynchronizer;
use RuntimeException;
use Throwable;
@ -27,7 +28,8 @@ use Throwable;
* 再按「店铺 + 完整线上单号」汇总收入金额与收款笔数
* - 订单侧:销售全量按「店铺 + 线上订单号」先聚合求和(一单多品/多子订单在此合并),金额取 goods_count > 0 的有效行
* - 单号匹配:优先完整线上单号精确匹配;仅当核心号唯一时允许兼容回退,多个完整单号共用核心号时禁止合并
* - 店铺:账单用「线上真实店铺」优先,订单侧用销售全量店铺名,统一把下划线归一为横杠
* - 店铺:业绩明细按账单「原始店铺」归集并匹配主体;「线上单号对应实际店铺」
* 只用于关联订单侧店铺,统一把下划线归一为横杠
* - 同一店铺同一订单号多笔收款 → 标注「同单多笔收款」,商品金额只挂一次
*/
class SyncStoreReceiptOrderMatches extends Command
@ -225,6 +227,13 @@ class SyncStoreReceiptOrderMatches extends Command
if ($result === self::SUCCESS && ! (bool) $this->option('planting-only')) {
$this->refreshStoreReportPaidSales();
}
if (
$result === self::SUCCESS
&& ! (bool) $this->option('dry-run')
&& (int) $this->option('limit') === 0
) {
$this->refreshProductCosts();
}
return $result;
}
@ -822,7 +831,7 @@ class SyncStoreReceiptOrderMatches extends Command
[$productStatus, $productAmount, $productRemark] = $this->matchOrderSide(
(string) $group['online_order_no'],
$core,
(string) $group['shop_key'],
(string) ($group['match_shop_key'] ?? $group['shop_key']),
$orderAmount,
$orderSeen,
$coreSeen,
@ -833,7 +842,7 @@ class SyncStoreReceiptOrderMatches extends Command
[$paidStatus, $paidAmount, $paidRemark] = $this->matchOrderSide(
(string) $group['online_order_no'],
$core,
(string) $group['shop_key'],
(string) ($group['match_shop_key'] ?? $group['shop_key']),
$orderPaidNet,
$orderSeen,
$coreSeen,
@ -872,7 +881,7 @@ class SyncStoreReceiptOrderMatches extends Command
[$altStatus, $altAmount] = $this->matchOrderSide(
(string) $group['online_order_no'],
$core,
(string) $group['shop_key'],
(string) ($group['match_shop_key'] ?? $group['shop_key']),
$orderPaidAlt,
$orderSeen,
$coreSeen,
@ -890,7 +899,7 @@ class SyncStoreReceiptOrderMatches extends Command
[$payStatus, $payValue] = $this->matchOrderSide(
(string) $group['online_order_no'],
$core,
(string) $group['shop_key'],
(string) ($group['match_shop_key'] ?? $group['shop_key']),
$orderPaidPay,
$orderSeen,
$coreSeen,
@ -1075,6 +1084,37 @@ class SyncStoreReceiptOrderMatches extends Command
: sprintf(' 店铺维度报表销量汇总:业绩明细无变化,沿用 %d 行。', $result['stored_rows']));
}
/** 业绩明细写入后,按同一账期和平台自动重算商品成本。 */
private function refreshProductCosts(): void
{
try {
$result = app(ProductCostAutoRefresh::class)->refresh(
trim((string) $this->argument('month')),
(bool) $this->option('planting-only')
? ''
: trim((string) $this->option('platform')),
);
} catch (Throwable $exception) {
$this->warn('商品成本自动更新失败:' . $exception->getMessage());
return;
}
if ($result['status'] === 'skipped') {
return;
}
if ($result['status'] !== 'succeeded') {
$this->warn('商品成本自动更新失败,请查看日志或稍后手动重跑。');
return;
}
$this->line(sprintf(
' 商品成本自动更新:已完成 %d 个平台。',
count($result['platforms']),
));
}
/** 只回填「种菜金额 / 标签」:按种菜明细表与聚水潭种菜标签的并集判断。 */
private function backfillPlantingAmounts(string $reportMonth): int
@ -1365,7 +1405,7 @@ class SyncStoreReceiptOrderMatches extends Command
$promoOnlyGroups = [];
foreach ($bills as $bill) {
$billCount++;
$storeName = (string) ($bill->store_name ?? '');
$storeName = trim((string) ($bill->store_name ?? ''));
$billItem = (string) ($bill->bill_item ?? '');
// 收入 / 优惠 / 冲减 / 退款统一按科目映射表的当前财务备注判桶;
// 只有当前科目映射表没有规则时,remark() 才回落到旧总账备注表。
@ -1399,16 +1439,22 @@ class SyncStoreReceiptOrderMatches extends Command
$rawNo = trim((string) ($bill->{$orderColumn} ?? ''));
$core = self::cleanOrderNo($rawNo);
$identity = self::orderIdentity($rawNo);
$realStore = $realStoreColumn !== '' ? (string) ($bill->{$realStoreColumn} ?? '') : '';
$shopKey = self::normalizeShop($realStore !== '' ? $realStore : (string) $bill->store_name);
$realStore = $realStoreColumn !== ''
? trim((string) ($bill->{$realStoreColumn} ?? ''))
: '';
// 主体变更后,同一实际店铺可能对应不同原始店铺和主体。
// 业绩行必须保留原始店铺作为统计与主体归属维度;实际店铺仅供订单匹配。
$displayStore = $storeName !== '' ? $storeName : $realStore;
$shopKey = self::normalizeShop($displayStore);
$matchShopKey = self::normalizeShop($realStore !== '' ? $realStore : $displayStore);
$key = $shopKey . '|' . $identity;
if (! isset($groups[$key])) {
$groups[$key] = [
'platform' => (string) $source['label'],
// 展示名优先用「线上真实店铺」(与匹配键同源):账户名(如「支付宝-XX公司」)只是收款壳。
'store_name' => $realStore !== '' ? $realStore : (string) ($bill->store_name ?? ''),
'store_name' => $displayStore,
'shop_key' => $shopKey,
'match_shop_key' => $matchShopKey,
'online_order_no' => $rawNo,
'order_core_no' => $core,
'order_identity' => $identity,
@ -1438,7 +1484,8 @@ class SyncStoreReceiptOrderMatches extends Command
if (! isset($promoOnlyGroups[$promoKey])) {
$promoOnlyGroups[$promoKey] = [
'shop_key' => $shopKey,
'store_name' => $realStore !== '' ? $realStore : $storeName,
'match_shop_key' => $matchShopKey,
'store_name' => $displayStore,
'online_order_no' => $rawNo,
'order_core_no' => $core,
'order_identity' => $identity,

View File

@ -254,6 +254,7 @@ class SyncStoreReceiptProductCost extends Command
. " i.name as item_name, i.qty as qty, i.amount as amount, o.status as status, "
. " i.shop_i_id as shop_i_id, i.shop_sku_id as shop_sku_id, "
. " i.outer_oi_id as outer_oi_id, "
. " i.raw_so_id as raw_so_id, o.is_merge as is_merge, "
. " i.properties_value as properties_value, i.src_combine_sku_id as src_combine_sku_id
FROM tmp_cost_order_nos t
STRAIGHT_JOIN {$source['orders']} o ON o.so_id = t.no
@ -273,6 +274,9 @@ class SyncStoreReceiptProductCost extends Command
if ($core === '' || ! isset($billByCore[$core])) {
continue;
}
if (! $this->mergeOrderItemBelongsToCore($row, $core)) {
continue;
}
$sku = trim((string) $row->sku_id);
if ($sku === '') {
continue;
@ -3293,9 +3297,18 @@ class SyncStoreReceiptProductCost extends Command
return [];
}
// 9) 只保留叶子行:o_id 没有被同组其他行的 link_o_id 引用的,才是实际发货行。
// 9) 只保留叶子行:o_id 没有被同组「未取消、非 Merged」行的 link_o_id 引用的,才是实际发货行。
// 全部引用母单的子单都已取消时,不能把已发货的 Sent 母单当成汇总层删除;
// 合单与原始单可能互相 link,Merged 原始单不能反向把 Sent 合单判成母单。
$parentIds = [];
foreach ($unique as $row) {
if (in_array(
strtoupper(trim((string) ($row['status'] ?? ''))),
['CANCELLED', 'MERGED'],
true,
)) {
continue;
}
$parent = trim((string) ($row['parent_o_id'] ?? ''));
if ($parent !== '' && $parent !== '0') {
$parentIds[$parent] = true;
@ -3362,6 +3375,24 @@ class SyncStoreReceiptProductCost extends Command
return array_values($aggregated);
}
/**
* 合单可能包含多个线上订单的商品。当前账单订单只能吸收 raw_so_id
* 或 outer_oi_id 指向自己的商品,避免把合单中的其他订单重复计价。
*/
private function mergeOrderItemBelongsToCore(object $row, string $core): bool
{
if (trim((string) ($row->is_merge ?? '0')) !== '1') {
return true;
}
$sourceOrder = self::cleanOrderNo((string) ($row->raw_so_id ?? ''));
if ($sourceOrder === '') {
$sourceOrder = self::cleanOrderNo((string) ($row->outer_oi_id ?? ''));
}
return $sourceOrder === '' || $sourceOrder === $core;
}
/**
* 组合装条码拆组件:聚水潭的组合装 sku 形如
* ZH-<条码>-<数量>[-<条码>-<数量>...]

View File

@ -0,0 +1,29 @@
<?php
namespace App\Console\Commands;
use App\Support\UnshippedWaybills;
use Illuminate\Console\Command;
final class SyncUnshippedWaybills extends Command
{
protected $signature = 'courier:sync-unshipped-waybills';
protected $description = '从共享镜像和已导入订单日志重算未发出明细';
public function handle(UnshippedWaybills $waybills): int
{
$failed = false;
foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) {
if (!$waybills->sync($source)) {
$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;
}
}

View File

@ -43,24 +43,21 @@ class Kernel extends ConsoleKernel
->withoutOverlapping(60)
->runInBackground();
$schedule->command('business-mirror:sync-product-purchase-prices')
->dailyAt('05:00')
->withoutOverlapping(60)
->runInBackground();
$schedule->command('business-mirror:sync-tables operations_replica.rpt.jst_Orders')
->dailyAt('05:00')
->withoutOverlapping(60)
->runInBackground();
// 退款待确认的当前状态按分钟增量刷新,确认完成后页面可及时移除。
$schedule->command('business-mirror:sync-tables jiansun.dbo.jst_refund_view')
->everyMinute()
->withoutOverlapping(5)
// 聚水潭推广费用按日期、平台、店铺自动汇总到共享镜像;最近 7 天覆盖迟到修订。
$schedule->command('business-mirror:sync-promotion-expenses --days=7 --quiet')
->dailyAt('03:10')
->timezone('Asia/Shanghai')
->withoutOverlapping(90)
->appendOutputTo(storage_path('logs/promotion-expense-sync.log'))
->runInBackground();
// 退款待确认四张镜像每天 06:00 专属刷新,确保 10:00 前完成;
// 当前退款状态单独按分钟刷新,失败状态由财务驾驶舱展示。
// 同步失败状态由财务驾驶舱展示。
$schedule->command('business-mirror:sync-tables --daily-only --max-batches=0')
->dailyAt('06:00')
->timezone('Asia/Shanghai')
@ -75,9 +72,6 @@ class Kernel extends ConsoleKernel
->withoutOverlapping(120)
->runInBackground();
// 供应商主档由 /etc/cron.d/caiwu-jiansun-snapshots 在 08:15 使用
// 全局上游同步锁执行,不能在这里重复调度,避免两个完整同步互相覆盖。
// 店铺违规信息预警:每天同步副本库抓取结果到统一表(本地补充字段不覆盖)。
$schedule->command('store-violations:sync')
->dailyAt('05:30')
@ -111,17 +105,34 @@ class Kernel extends ConsoleKernel
->appendOutputTo(storage_path('logs/inventory-warehouse-mapping-alert.log'))
->runInBackground();
// 四平台账单:每日检查最近 7 天,周日扩展检查最近 62 天。
// 命令只读,若输出 JSON 中的 missing/suspicious 非空,账单自动化应回头比较上游当前控制数。
$schedule->command('bill-sync:audit-window --days=7 --json')
->dailyAt('10:30')
->timezone('Asia/Shanghai')
->withoutOverlapping(30)
->appendOutputTo(storage_path('logs/bill-sync-window-audit.log'))
->runInBackground();
$schedule->command('bill-sync:audit-window --days=62 --json')
->weeklyOn(0, '10:45')
->timezone('Asia/Shanghai')
->withoutOverlapping(30)
->appendOutputTo(storage_path('logs/bill-sync-window-audit.log'))
->runInBackground();
// 财务台账:从 AI 库 rpt 同步动账明细,按日重算账户流水。
// 生产宿主机 cron 仍需配置对应的 finance-ledger:sync-rpt 入口。
$schedule->command('finance-ledger:sync-rpt --days=7 --merge')
$schedule->command('finance-ledger:sync-rpt --days=7 --merge --sources=store,withdrawal')
->dailyAt('02:30')
->timezone('Asia/Shanghai')
->withoutOverlapping(120)
->runInBackground();
$schedule->command('business-mirror:sync-third-party-warehouse-storage --max-batches=0')
->dailyAt('00:00')
->withoutOverlapping(180)
// 钉钉审批和供应商应付每小时增量;店铺相关来源每天同步一次。
$schedule->command('finance-ledger:sync-rpt --days=2 --merge --sources=dingtalk,payable --quiet')
->hourlyAt(5)
->timezone('Asia/Shanghai')
->withoutOverlapping(10)
->runInBackground();
// 钉钉财务日报:高频增量同步,次日 12:00 截止的补交日志也能及时进入统计。
@ -140,6 +151,18 @@ class Kernel extends ConsoleKernel
->appendOutputTo(storage_path('logs/ding-attendance-sync.log'))
->runInBackground();
// 票聚销方管理的可用发票额度按 15 分钟同步到共享镜像;失败时页面继续使用上一版。
$piaojuCookieFile = trim((string) config('piaoju.cookie_file', ''));
if (trim((string) config('piaoju.cookie', '')) !== ''
|| ($piaojuCookieFile !== '' && is_file($piaojuCookieFile))) {
$schedule->command('piaoju:sync-invoice-quotas --quiet')
->cron('*/15 * * * *')
->timezone('Asia/Shanghai')
->withoutOverlapping(15)
->appendOutputTo(storage_path('logs/piaoju-invoice-quota-sync.log'))
->runInBackground();
}
if ((bool) config('services.esign.polling_enabled', false)) {
$schedule->command('esign:poll-signatures --quiet')
->cron('*/2 * * * *')

View File

@ -5,6 +5,7 @@ namespace App\Http\Controllers\Auth;
use App\Abstracts\Http\Controller;
use App\Http\Requests\Auth\Login as Request;
use App\Models\Common\Contact;
use App\Services\Auth\DingTalkOAuthClient;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@ -13,11 +14,6 @@ class Login extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/';
/**
@ -30,108 +26,79 @@ class Login extends Controller
$this->middleware('guest', ['except' => 'destroy']);
}
public function create()
public function create(DingTalkOAuthClient $client)
{
return view('auth.login.create');
return view('auth.login.create', [
'dingtalkAvailable' => $client->isConfigured(),
'passwordLoginEnabled' => (bool) config('auth.password_login_enabled', false),
]);
}
public function store(Request $request)
{
// Attempt to login
if (! auth()->attempt($request->only('email', 'password'), $request->get('remember', false))) {
if (! config('auth.password_login_enabled', false)) {
return $this->credentialsDisabled();
}
if (! auth()->attempt($request->only('email', 'password'), false)) {
return $this->respondLoginFailed();
}
// Get user object
$request->session()->forget(['dingtalk_identity_id', 'dingtalk_roster_checked_at']);
$user = user();
// Check if user is enabled
if (! $user->enabled) {
$this->logout();
// Security (CWE-204): avoid distinct error messages that would
// allow valid email enumeration. Log the real reason server-side
// for administrators/auditing without leaking it to the client.
Log::info('Login denied: account disabled', [
'email' => $request->email,
]);
Log::info('Local login denied: account disabled');
return $this->respondLoginFailed();
}
$company = $user->withoutEvents(function () use ($user) {
return $user->companies()->enabled()->first();
});
// Logout if no company assigned
$company = $user->withoutEvents(fn () => $user->companies()->enabled()->first());
if (! $company) {
$this->logout();
// Security (CWE-204): do not expose "no company" message to the
// client; log it server-side instead.
Log::info('Login denied: no company assigned', [
'email' => $request->email,
]);
Log::info('Local login denied: no company assigned');
return $this->respondLoginFailed();
}
// Redirect to portal if is customer
if ($user->isCustomer()) {
$path = session('url.intended', '');
$portalHome = $user->contact instanceof Contact
&& $user->contact->type === Contact::VENDOR_TYPE
? route('portal.supplier-reconciliation.index', ['company_id' => $company->id])
: route('portal.dashboard', ['company_id' => $company->id]);
// Path must start with company id and 'portal' prefix
if (!Str::startsWith($path, $company->id . '/portal')) {
$path = session('url.intended', '');
if (! Str::startsWith($path, $company->id.'/portal')) {
$path = $portalHome;
}
if (! $request->expectsJson()) {
return redirect()->to($path);
}
return $request->expectsJson()
? response()->json([
'status' => null,
'success' => true,
'error' => false,
'message' => trans('auth.login_redirect'),
'data' => null,
'redirect' => url($path),
])
: redirect()->to($path);
}
return response()->json([
$url = route($user->landing_page, ['company_id' => $company->id]);
$request->session()->forget('url.intended');
return $request->expectsJson()
? response()->json([
'status' => null,
'success' => true,
'error' => false,
'message' => trans('auth.login_redirect'),
'data' => null,
'redirect' => url($path),
]);
}
// Redirect to landing page if is user
$url = route($user->landing_page, ['company_id' => $company->id]);
// 登录后固定回到首页(财务驾驶舱),不再回跳上次打开/被拦截的业务页面。
$request->session()->forget('url.intended');
if (! $request->expectsJson()) {
return redirect()->to($url);
}
return response()->json([
'status' => null,
'success' => true,
'error' => false,
'message' => trans('auth.login_redirect'),
'data' => null,
'redirect' => url($url),
]);
'redirect' => url($url),
])
: redirect()->to($url);
}
/**
* Build the generic failed-login JSON response.
*
* Security (CWE-204): every rejected login returns the same message and
* response shape so an unauthenticated attacker cannot distinguish
* "email does not exist" from "disabled" or "no company" and enumerate
* valid registered email addresses.
*/
protected function respondLoginFailed()
{
$request = app('Illuminate\Http\Request');
@ -152,6 +119,16 @@ class Login extends Controller
]);
}
/**
* Credential-based entry points are intentionally kept as redirects so
* old bookmarks and invitation emails reach the DingTalk-only notice.
*/
public function credentialsDisabled()
{
return redirect()->route('login')
->with('dingtalk_error', trans('auth.dingtalk.credentials_disabled'));
}
public function destroy()
{
$this->logout();

View File

@ -36,7 +36,9 @@ class AccessoryReshipDeductions extends Controller
fputcsv($file, ['交易单号','补发快递单号','补发快递','补发时间','原始条形码','处理后条形码','补发运费','匹配状态','首发快递公司(候选)','首发快递单号(候选)','首发所属月份(候选)','扣款比例(%)','扣款金额','说明']);
foreach ($data->rows($filters) as $row) {
if (!AccessoryReshipPageData::inCategory($row, $filters['match_status'])) continue;
$values = [$row['trade_no'], $row['express_no'], ($row['express_name1'] ?: ($row['express_name2'] ?? '')), $row['ship_time'], $row['barcode'], $row['normalized_barcode'], $row['freight'], $row['deduction_state'] === 'ready' ? '可扣款' : ($row['status'] === 'matched' ? '已匹配待核对' : '未匹配不扣款'), implode(' / ', array_column($row['matches'], 'courier')), implode(' / ', array_column($row['matches'], 'express_no')), implode(' / ', array_column($row['matches'], 'month')), $row['deduction_rate_basis_points'] === null ? '' : number_format($row['deduction_rate_basis_points'] / 100, 2, '.', '') . '%', $row['deduction_cents'] === null ? '' : number_format($row['deduction_cents'] / 100, 2, '.', ''), $row['deduction_note']];
$status = $row['deduction_state'] === 'excluded_courier' ? '不扣款'
: ($row['deduction_state'] === 'ready' ? '可扣款' : ($row['status'] === 'matched' ? '已匹配待核对' : '未匹配不扣款'));
$values = [$row['trade_no'], $row['express_no'], ($row['express_name1'] ?: ($row['express_name2'] ?? '')), $row['ship_time'], $row['barcode'], $row['normalized_barcode'], $row['freight'], $status, implode(' / ', array_column($row['matches'], 'courier')), implode(' / ', array_column($row['matches'], 'express_no')), implode(' / ', array_column($row['matches'], 'month')), $row['deduction_rate_basis_points'] === null ? '' : number_format($row['deduction_rate_basis_points'] / 100, 2, '.', '') . '%', $row['deduction_cents'] === null ? '' : number_format($row['deduction_cents'] / 100, 2, '.', ''), $row['deduction_note']];
fputcsv($file, array_map(static function ($value) {
$value = (string) $value;
return preg_match('/^[=+\-@\t\r\n]/u', $value) ? "'" . $value : $value;

View File

@ -0,0 +1,84 @@
<?php
namespace App\Http\Controllers\Business;
use App\Business\CourierContractPageData;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
use ZipStream\CompressionMethod;
use ZipStream\ZipStream;
final class ContractExport
{
public function supplier(CourierContractPageData $contracts): StreamedResponse
{
return $this->download($contracts, 'supplier', '供应商');
}
public function courier(CourierContractPageData $contracts): StreamedResponse
{
return $this->download($contracts, 'courier', '快递');
}
private function download(CourierContractPageData $contracts, string $partnerType, string $label): StreamedResponse
{
$manifest = tmpfile();
abort_unless($manifest, 500, '无法创建合同清单。');
return response()->streamDownload(static function () use ($contracts, $manifest, $partnerType, $label): void {
$zip = new ZipStream(defaultCompressionMethod: CompressionMethod::STORE, sendHttpHeaders: false);
$disk = Storage::disk('uploads');
try {
fwrite($manifest, "\xEF\xBB\xBF");
$columns = [$label, '期限状态', '合同编号', '开始日期', '结束日期', '距到期天数',
'甲方签署主体', '乙方签署主体', '签署单号', '签署原件'];
if ($partnerType === 'courier') {
$columns = [...$columns, '乙方法定代表人', '创建人', '创建时间', '归档时间'];
}
fputcsv($manifest, $columns, ',', '"', '');
foreach ($contracts->exportRows($partnerType) as $row) {
$path = $row['signed_path'];
$attachment = '归档附件缺失';
if (filled($path) && $disk->exists($path)) {
$pdf = $disk->readStream($path);
if (is_resource($pdf)) {
$attachment = '签署原件/合同-' . $row['id'] . '.pdf';
try {
$zip->addFileFromStream($attachment, $pdf);
} finally {
fclose($pdf);
}
} else {
$attachment = '归档附件读取失败';
}
}
$values = [
$row['courier_name'], CourierContractPageData::STATUSES[$row['status']], $row['number'],
$row['start_date'], $row['end_date'], $row['days'], $row['party_a'], $row['party_b'], $row['business_no'], $attachment,
];
if ($partnerType === 'courier') {
$values = [...$values, $row['legal_representative'], $row['creator'],
$row['created_at']?->format('Y-m-d H:i'), $row['archived_at']?->format('Y-m-d H:i')];
}
$values = array_map(static function ($value): string|int {
if (is_int($value)) {
return $value;
}
$value = (string) $value;
return preg_match('/^[\s\x00-\x1f]*[=+@-]|^[\t\r\n]/u', $value) ? "'" . $value : $value;
}, $values);
fputcsv($manifest, $values, ',', '"', '');
}
rewind($manifest);
$zip->addFileFromStream($label . '合同清单.csv', $manifest);
$zip->finish();
} finally {
fclose($manifest);
}
}, $label . '合作合同-' . now()->format('Ymd-His') . '.zip', [
'Content-Type' => 'application/zip', 'Cache-Control' => 'private, no-store',
]);
}
}

View File

@ -27,8 +27,6 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
class CourierAgreementSignatures extends Controller
{
private const COOPERATION_SECONDARY_ESIGN_ACCOUNT = '18052733960';
public function __construct(
private readonly CourierAgreementSignatureService $service,
private readonly CourierQuoteSignatureService $quoteSignatureService,
@ -66,22 +64,22 @@ class CourierAgreementSignatures extends Controller
abort_unless(Schema::hasTable('business_courier_agreement_signatures'), 503, '协议签署数据表尚未完成迁移,请先执行数据库迁移。');
}
if ($request->input('document_type') === 'cooperation-contract' && $request->input('partner_type') === 'courier') {
// 合作合同统一由我方固定 E 签宝账号完成第二签署方签署。
$request->merge([
'secondary_esign_account' => self::COOPERATION_SECONDARY_ESIGN_ACCOUNT,
]);
}
if (in_array($requestedType, ['account-proof', 'account-change', 'entity-change', 'cooperation-contract', 'authorization', 'shared-contract'], true)
if (in_array($requestedType, ['account-proof', 'account-change', 'entity-change', 'cooperation-contract', 'authorization', 'shared-contract', 'quote-confirmation'], true)
&& ! $request->filled('counterparty_signer_type')) {
// Existing integrations omit this field and historically meant an
// enterprise signer, so keep that behavior as the compatibility default.
$request->merge(['counterparty_signer_type' => 'organization']);
}
if ($requestedType === 'cooperation-contract') {
$request->merge([
'cooperation_party_a_phone' => CourierAgreementSignature::COOPERATION_PARTY_A_PHONE,
'cooperation_party_b_phone' => $request->input('esign_account'),
]);
}
$data = $request->validate($this->rules(), [
'secondary_operator_name.required_if' => '请填写我方 E 签宝账号绑定的实名认证姓名。',
'secondary_esign_account.required_if' => '请填写另一签署方的 E 签宝账号。',
]);
$type = $data['document_type'];
if ($type === 'authorization' && count($data['authorization_items'] ?? []) === 0) {
@ -89,11 +87,6 @@ class CourierAgreementSignatures extends Controller
}
if ($type === 'shared-contract') {
$data['contract_partner_name'] = trim((string) $data['contract_partner_name']);
if ($data['counterparty_signer_type'] === 'person') {
$data['operator_name'] = $data['contract_partner_name'];
} elseif (blank($data['operator_name'] ?? null)) {
throw ValidationException::withMessages(['operator_name' => '请填写物流商归属企业经办人的 E 签宝实名认证姓名。']);
}
$sharedCouriers = collect($data['shared_courier_names'] ?? [])
->map(static fn ($name): string => trim((string) $name))
->filter()
@ -111,15 +104,23 @@ class CourierAgreementSignatures extends Controller
$data['shared_courier_name'] = $sharedCouriers[0];
$data['shared_note'] = trim((string) ($data['shared_note'] ?? '')) ?: null;
}
if (in_array($type, ['account-proof', 'account-change'], true)) {
if (in_array($type, ['account-proof', 'account-change', 'quote-confirmation'], true)) {
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
$data['operator_name'] = trim((string) ($data['operator_name'] ?? '')) ?: null;
if ($data['counterparty_signer_type'] === 'organization' && blank($data['operator_name'])) {
$usesCourierAccountLookup = $type === 'account-proof' && $data['partner_type'] === 'courier';
if ($type !== 'quote-confirmation' && ! $usesCourierAccountLookup
&& $data['counterparty_signer_type'] === 'organization' && blank($data['operator_name'])) {
throw ValidationException::withMessages(['operator_name' => '企业签署主体必须填写 E 签宝实名认证姓名。']);
}
if ($data['counterparty_signer_type'] === 'person') {
if ($type === 'quote-confirmation' && $data['counterparty_signer_type'] === 'organization'
&& in_array($data['operator_name'], [trim($data['courier_name']), trim($data['counterparty_organization_name'])], true)) {
throw ValidationException::withMessages(['operator_name' => '请填写签署账号绑定的个人实名姓名,不能填写快递名称或企业名称。']);
}
if ($data['counterparty_signer_type'] === 'person' && ! $usesCourierAccountLookup) {
// A personal signer uses the same real name for the signer and
// the E-sign identity; the UI should not require it twice.
$data['operator_name'] = trim((string) $data['counterparty_organization_name']);
@ -132,42 +133,9 @@ class CourierAgreementSignatures extends Controller
);
$data['entity_change_old_company_deregistered'] = $formerCompanyDeregistered;
$data['counterparty_signer_type'] = $formerCompanyDeregistered ? 'person' : 'organization';
if (blank($data['operator_name'] ?? null)) {
throw ValidationException::withMessages(['operator_name' => $formerCompanyDeregistered
? '请填写原公司法人的 E 签宝实名认证姓名。'
: '请填写变更前主体签署人的 E 签宝实名认证姓名。']);
}
if (blank($data['secondary_esign_account'] ?? null)) {
throw ValidationException::withMessages(['secondary_esign_account' => '请填写变更后主体的 E 签宝账号。']);
}
if (blank($data['secondary_operator_name'] ?? null)) {
throw ValidationException::withMessages(['secondary_operator_name' => '请填写变更后主体签署人的 E 签宝实名认证姓名。']);
}
}
if ($type === 'cooperation-contract') {
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
if ($data['counterparty_signer_type'] === 'person') {
$data['operator_name'] = trim((string) $data['cooperation_party_b_name']);
} elseif (blank($data['operator_name'] ?? null)) {
$party = $data['partner_type'] === 'supplier' ? '供应商' : '快递方';
throw ValidationException::withMessages(['operator_name' => "请填写{$party}企业经办人的 E 签宝实名认证姓名。"]);
}
if (blank($data['secondary_operator_name'] ?? null)) {
throw ValidationException::withMessages(['secondary_operator_name' => '请填写我方 E 签宝账号绑定的实名认证姓名。']);
}
$companyNames = [trim($data['cooperation_party_a_name'])];
if ($data['counterparty_signer_type'] === 'organization') {
$companyNames[] = trim($data['cooperation_party_b_name']);
}
foreach (['operator_name' => $data['partner_type'] === 'supplier' ? '供应商' : '快递方', 'secondary_operator_name' => '我方'] as $field => $party) {
$data[$field] = trim($data[$field]);
if (in_array($data[$field], $companyNames, true)) {
throw ValidationException::withMessages([
$field => "{$party}实名认证姓名应填写账号绑定的个人姓名,不能填写甲乙方公司名称。",
]);
}
}
if ($type === 'cooperation-contract' && preg_match('/^1\d{10}$/', $data['esign_account']) !== 1) {
throw ValidationException::withMessages(['esign_account' => '合作合同的乙方 E 签宝账号必须填写 11 位手机号。']);
}
if ($type === 'authorization') {
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
@ -337,6 +305,26 @@ class CourierAgreementSignatures extends Controller
{
$this->ensureCanManage();
abort_unless($agreementSignature->status === CourierAgreementSignature::STATUS_COMPLETED && $agreementSignature->remote_status === '2', 422, '只有签署完成的协议可以人工归档。');
$signature = $this->service->archive($agreementSignature, null, user_id(), $this->archiveReason($request));
return redirect()
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
->with('success', "{$signature->documentLabel()}已人工确认并归档。");
}
public function archiveQuote(Request $request, CourierQuoteSignature $quoteSignature): RedirectResponse
{
$this->ensureCanManage();
abort_unless($quoteSignature->company_id === (int) company_id(), 404);
$signature = $this->quoteSignatureService->confirmArchive($quoteSignature, user_id(), $this->archiveReason($request));
return redirect()
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
->with('success', "报价确认单 {$signature->version?->version_code} 已人工确认并归档。");
}
private function archiveReason(Request $request): string
{
$data = $request->validate([
'archive_reason_code' => ['required', 'in:completed,confirmed,backfill,other'],
'archive_note' => ['nullable', 'string', 'max:200'],
@ -351,12 +339,7 @@ class CourierAgreementSignatures extends Controller
if ($data['archive_reason_code'] === 'other' && $note === '') {
throw ValidationException::withMessages(['archive_note' => '选择“其他”时请填写归档说明。']);
}
$reason = $note === '' ? $reasonLabel : $reasonLabel . ':' . $note;
$signature = $this->service->archive($agreementSignature, null, user_id(), $reason);
return redirect()
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
->with('success', "{$signature->documentLabel()}已人工确认并归档。");
return $note === '' ? $reasonLabel : $reasonLabel . ':' . $note;
}
public function destroy(Request $request, CourierAgreementSignature $agreementSignature): JsonResponse|RedirectResponse
@ -371,7 +354,7 @@ class CourierAgreementSignatures extends Controller
private function deleteTask(Request $request, CourierAgreementSignature|CourierQuoteSignature $task): JsonResponse|RedirectResponse
{
$this->ensureCanAdminister();
abort_unless(AgreementSigningPermissions::canDelete(), 403, '当前账号没有协议签署删除权限。');
abort_unless($task->company_id === (int) company_id(), 404);
$request->validate(['delete_confirmed' => ['required', 'accepted']]);
@ -490,14 +473,20 @@ class CourierAgreementSignatures extends Controller
'signature_date' => ['required', 'date'],
'signing_deadline' => $date,
'esign_account' => ['required', 'string', 'max:255'],
'secondary_esign_account' => ['required_if:document_type,cooperation-contract,authorization', 'nullable', 'string', 'max:255'],
'secondary_operator_name' => ['nullable', 'string', 'min:2', 'max:100'],
'operator_name' => ['nullable', 'string', 'min:2', 'max:100'],
'counterparty_organization_name' => ['required_if:document_type,account-proof,account-change', 'nullable', 'string', 'min:2', 'max:255'],
'counterparty_signer_type' => ['required_if:document_type,account-proof,account-change,entity-change,cooperation-contract,authorization,shared-contract', 'nullable', 'in:organization,person'],
'secondary_esign_account' => [Rule::excludeIf(request('document_type') === 'cooperation-contract'), 'required_if:document_type,authorization,entity-change', 'nullable', 'string', 'max:255'],
'secondary_operator_name' => ['exclude_if:document_type,entity-change', 'nullable', 'string', 'min:2', 'max:100'],
'operator_name' => [
Rule::excludeIf(in_array(request('document_type'), ['cooperation-contract', 'entity-change'], true)
|| (request('partner_type') === 'courier'
&& in_array(request('document_type'), CourierAgreementSignature::COURIER_DOCUMENTS_WITH_ACCOUNT_LOOKUP, true))),
'nullable', 'string', 'min:2', 'max:100',
],
'counterparty_organization_name' => ['required_if:document_type,account-proof,account-change,quote-confirmation', 'nullable', 'string', 'min:2', 'max:255'],
'counterparty_signer_type' => ['required_if:document_type,account-proof,account-change,entity-change,cooperation-contract,authorization,shared-contract,quote-confirmation', 'nullable', 'in:organization,person'],
'secondary_signer_type' => ['nullable', 'in:organization,person'],
'entity_change_old_company_deregistered' => ['nullable', 'boolean'],
'archive_mode' => ['required', 'in:auto,manual'],
'quote_reissue_reason' => ['exclude_unless:document_type,quote-confirmation', 'nullable', 'string', 'min:2', 'max:200'],
'account_proof_effective_date' => ['required_if:document_type,account-proof', 'date'],
'account_proof_account_name' => ['required_if:document_type,account-proof', 'string', 'max:255'],
'account_proof_bank_name' => ['required_if:document_type,account-proof', 'string', 'max:255'],
@ -539,7 +528,11 @@ class CourierAgreementSignatures extends Controller
'payment_counterparty' => ['required_if:document_type,authorization', 'string', 'max:255'],
'authorization_start_date' => ['required_if:document_type,authorization', 'date'],
'authorization_end_date' => ['required_if:document_type,authorization', 'date', 'after_or_equal:authorization_start_date'],
] + $supplierFields + CourierAgreementCredentials::rules((string) request('document_type'), request()->boolean('credential_required'));
] + $supplierFields + CourierAgreementCredentials::rules(
(string) request('document_type'),
request()->boolean('credential_required'),
(string) request('partner_type', 'courier'),
);
}
private function payload(array $data): array
@ -548,6 +541,9 @@ class CourierAgreementSignatures extends Controller
$payload = array_intersect_key($data, array_flip($allowed));
unset($payload['esign_account'], $payload['idempotency_key'], $payload['operator_name'], $payload['credential_images']);
$payload['authorization_items'] = array_values(array_map('strval', $data['authorization_items'] ?? []));
if (($data['document_type'] ?? '') === 'cooperation-contract') {
$payload['cooperation_bilateral_signing'] = true;
}
if (($data['document_type'] ?? '') === 'cooperation-contract' && ($data['partner_type'] ?? 'courier') === 'courier') {
$payload['cooperation_party_b_signing_place'] = trim((string) ($data['cooperation_party_b_signing_place'] ?? '')) ?: '常州市';
$payload['cooperation_contract_number'] = trim((string) ($data['cooperation_contract_number'] ?? ''));
@ -555,11 +551,10 @@ class CourierAgreementSignatures extends Controller
? null : trim((string) ($data['cooperation_party_b_legal_representative'] ?? ''));
}
if (($data['document_type'] ?? null) === 'entity-change') {
$payload['former_legal_representative'] = trim((string) ($data['operator_name'] ?? ''));
$payload['entity_proof_date'] = $data['signature_date'] ?? null;
}
if (($data['partner_type'] ?? 'courier') === 'supplier' && ($data['document_type'] ?? '') === 'cooperation-contract') {
$payload['supplier_contract_signer_name'] = $data['operator_name'];
$payload['supplier_contract_signer_name'] = $data['counterparty_signer_type'] === 'person' ? $data['cooperation_party_b_name'] : null;
}
return $payload;
}
@ -571,20 +566,30 @@ class CourierAgreementSignatures extends Controller
->findOrFail((int) $data['quote_version_id']);
$this->ensureQuoteVersionMatchesCourier($version, $data['courier_name']);
$signature = $this->quoteSignatureService->prepareVersion($version, user_id(), $data['signature_date']);
$counterpartyName = trim($data['counterparty_organization_name']);
$reissueReason = trim((string) ($data['quote_reissue_reason'] ?? ''));
abort_if($reissueReason !== '' && ! AgreementSigningPermissions::canDelete(), 403, '当前账号没有更正重签权限。');
$signature = $this->quoteSignatureService->prepareVersion(
$version, user_id(), $data['signature_date'], $data['signing_subject'], $counterpartyName,
$reissueReason === '' ? null : $reissueReason,
);
$account = trim((string) $data['esign_account']);
$signature = $this->quoteSignatureService->send($signature, [
'signing_subject' => $data['signing_subject'],
'organization_name' => $version->carrier_name,
'operator_name' => trim((string) ($data['operator_name'] ?? '')) ?: $version->carrier_name,
'signer_type' => $data['counterparty_signer_type'],
'organization_name' => $counterpartyName,
'operator_name' => $data['operator_name'],
'operator_account' => $account,
'notice_type' => filter_var($account, FILTER_VALIDATE_EMAIL) !== false ? '2' : '1',
'archive_mode' => $data['archive_mode'],
'expires_at' => \Illuminate\Support\Carbon::parse($data['signing_deadline'])->endOfDay(),
], user_id());
$archiveMessage = $signature->requiresManualArchive() ? '回传后由财务确认归档' : '签署完成后自动归档';
return redirect()
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
->with('success', "报价确认单 {$version->version_code} 已推送到 E 签宝,等待快递方签署并自动回传归档。")
->with('success', "报价确认单 {$version->version_code} 已推送到 E 签宝,等待快递方签署,{$archiveMessage}。")
->with('quote_signature_id', $signature->id);
}

View File

@ -0,0 +1,477 @@
<?php
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\Category;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\StatementExporter;
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\CourierBills\Waybill;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use RuntimeException;
/** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */
final class CourierBillController extends Controller
{
public const VIEWS = ['overview' => '对账总览', 'statement' => '单家对账单', 'details' => '对账明细', 'upload' => '上传账单',
'ledger' => '结算台账', 'groups' => '对账分组'];
public function __construct(
private readonly CourierBillStore $store,
private readonly CourierBillMatcher $matcher,
) {}
public function page(Request $request): array
{
$view = array_key_exists((string) $request->query('cb_view'), self::VIEWS) ? (string) $request->query('cb_view') : 'overview';
$data = ['view' => 'business.pages.courier-payables.courier-bills.page', 'cbView' => $view, 'cbViews' => self::VIEWS,
'cbSection' => self::section($request), 'cbUnavailable' => false];
try {
$db = $this->store->db();
$months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all();
$month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m'));
$data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $this->store->groups()];
$data += match ($view) {
'statement' => $this->statementData($request),
'details' => $this->detailsData($request, $month),
'upload' => $this->uploadData($month),
'ledger' => $this->ledgerData($request),
'groups' => $this->groupsData($request),
default => $this->overviewData($month),
};
} catch (QueryException $error) {
report($error);
$data['cbUnavailable'] = true;
}
return $data;
}
private function overviewData(string $month): array
{
$db = $this->store->db();
$statements = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->where('s.bill_month', $month)->orderBy('g.owner')->orderBy('g.name')
->get(['s.*', 'g.name as group_name', 'g.owner', 'g.summary_carrier']);
$sums = $db->table('courier_bill_summary_items')->whereIn('statement_id', $statements->pluck('id'))
->groupBy('statement_id')->selectRaw('statement_id, SUM(bill_amount) as bill, SUM(self_amount) as self')
->get()->keyBy('statement_id');
$pending = $db->table('courier_bill_lines')->whereIn('statement_id', $statements->pluck('id'))
->whereNull('resolution')->whereNotIn('category', [Category::MATCH])
->groupBy('statement_id')->selectRaw('statement_id, COUNT(*) as n')->pluck('n', 'statement_id');
$rows = $statements->map(function ($s) use ($sums, $pending): array {
$bill = (float) ($sums[$s->id]->bill ?? 0);
$self = (float) ($sums[$s->id]->self ?? 0);
return ['id' => $s->id, 'group' => $s->group_name, 'owner' => $s->owner, 'carrier' => $s->summary_carrier ?: $s->group_name,
'status' => $s->status, 'lines' => (int) $s->line_count, 'bill' => $bill, 'diff' => round($bill - $self, 2),
'confirmed' => $self, 'pending' => (int) ($pending[$s->id] ?? 0), 'matched_at' => $s->matched_at];
})->all();
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbTotals' => [
'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')),
]];
}
private function statementData(Request $request): array
{
$db = $this->store->db();
$statement = $db->table('courier_bill_statements')->find((int) $request->query('statement'));
if ($statement === null) {
return ['cbStatement' => null];
}
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$counts = $db->table('courier_bill_lines')->where('statement_id', $statement->id)
->groupBy('category', 'category_month')->selectRaw('category, category_month, COUNT(*) as n, SUM(bill_amount) as bill')
->get();
$tabs = [];
foreach ($counts as $row) {
$key = in_array($row->category, [Category::PRIOR, Category::LATER], true) ? $row->category . ':' . $row->category_month : (string) $row->category;
$tabs[$key] = ['label' => Category::label((string) $row->category, $row->category_month), 'count' => (int) $row->n];
}
uksort($tabs, fn ($a, $b) => array_search(strtok($a, ':'), array_keys(Category::LABELS), true) <=> array_search(strtok($b, ':'), array_keys(Category::LABELS), true) ?: strcmp($a, $b));
$unprovided = $db->table('courier_bill_unprovided')->where('statement_id', $statement->id)->count();
if ($unprovided > 0) {
$tabs[Category::UNPROVIDED] = ['label' => Category::LABELS[Category::UNPROVIDED], 'count' => $unprovided];
}
$tab = (string) $request->query('cat', array_key_first($tabs) ?? '');
if ($tab === Category::UNPROVIDED) {
$lines = $db->table('courier_bill_unprovided')->where('statement_id', $statement->id)->orderBy('id')->paginate(50, ['*'], 'page')->withQueryString();
} else {
[$category, $categoryMonth] = array_pad(explode(':', $tab, 2), 2, null);
$query = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->where('category', $category);
if ($categoryMonth !== null) {
$query->where('category_month', $categoryMonth);
}
$lines = $query->orderBy('id')->paginate(50, ['id', 'waybill_no', 'bill_amount', 'bill_weight', 'ship_time', 'express_name',
'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();
$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();
$shippingSync = null;
try {
$shippingSync = app(\App\Support\CourierBills\ShippingLookup::class)->connection()->table('jst_oms_shipping')->max('ship_time');
} catch (QueryException) {
}
$related = app(StatementExporter::class)->related((int) $statement->id);
$relatedNames = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->whereIn('s.id', $related)->pluck('g.name', 's.id');
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync];
}
private function detailsData(Request $request, string $month): array
{
$filters = $request->validate([
'group_id' => ['nullable', 'integer'], 'category' => ['nullable', Rule::in(array_keys(Category::LABELS))],
'resolution' => ['nullable', Rule::in(['pending', 'all', ...array_keys(Category::RESOLUTIONS)])],
'owner' => ['nullable', 'string', 'max:64'], 'min_diff' => ['nullable', 'numeric'], 'waybills' => ['nullable', 'string', 'max:20000'],
'all_months' => ['nullable', 'boolean'],
]);
$query = $this->detailsQuery($filters, $month);
return ['cbFilters' => $filters, 'cbLines' => $query->orderBy('l.id')->paginate(50, ['l.*', 's.bill_month', 's.status as statement_status', 'g.name as group_name', 'g.owner'])
->withQueryString(), 'cbOwners' => collect($this->store->groups())->pluck('owner')->filter()->unique()->values()->all()];
}
private function detailsQuery(array $filters, string $month)
{
$query = $this->store->db()->table('courier_bill_lines as l')->join('courier_bill_statements as s', 's.id', '=', 'l.statement_id')
->join('courier_bill_groups as g', 'g.id', '=', 's.group_id');
if (empty($filters['all_months'])) {
$query->where('s.bill_month', $month);
}
if (! empty($filters['group_id'])) {
$query->where('s.group_id', (int) $filters['group_id']);
}
if (! empty($filters['category'])) {
$query->where('l.category', $filters['category']);
}
$resolution = $filters['resolution'] ?? 'pending';
if ($resolution === 'pending') {
$query->whereNull('l.resolution')->where('l.category', '<>', Category::MATCH);
} elseif ($resolution !== 'all') {
$query->where('l.resolution', $resolution);
}
if (! empty($filters['owner'])) {
$query->where('g.owner', $filters['owner']);
}
if (isset($filters['min_diff']) && $filters['min_diff'] !== null && $filters['min_diff'] !== '') {
$query->whereRaw('ABS(COALESCE(l.bill_amount,0) - COALESCE(l.self_amount,0)) >= ?', [(float) $filters['min_diff']]);
}
$numbers = array_values(array_unique(array_filter(array_map(fn ($n) => Waybill::normalize($n),
preg_split('/[\r\n,,\s]+/u', (string) ($filters['waybills'] ?? '')) ?: []))));
if (count($numbers) > 1000) {
throw ValidationException::withMessages(['waybills' => '最多同时查询 1000 个快递单号。']);
}
if ($numbers !== []) {
$query->whereIn('l.waybill_no', $numbers);
}
return $query;
}
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')
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
}
private function ledgerData(Request $request): array
{
$db = $this->store->db();
$search = Waybill::normalize((string) $request->query('waybill'));
return [
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
->groupBy('g.name', 'l.settle_month')->selectRaw('g.name as group_name, l.settle_month, COUNT(*) as n, SUM(l.amount) as amount, SUM(CASE WHEN l.statement_id IS NULL THEN 1 ELSE 0 END) as imported')
->orderByDesc('l.settle_month')->orderBy('g.name')->limit(500)->get(),
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
'cbSearch' => $search,
];
}
private function groupsData(Request $request): array
{
$summary = app(\App\Support\CourierBills\PayableSummary::class);
$data = ['cbSummaryMonths' => $summary->months(), 'cbUnassigned' => null, 'cbScanMonth' => null];
$scan = self::monthParam($request->query('scan'));
if ($scan !== null) {
$data['cbScanMonth'] = $scan;
$data['cbUnassigned'] = $this->store->unassignedExpressNames(app(\App\Support\CourierBills\ShippingLookup::class)->monthExpressNames($scan));
}
return $data;
}
public function groupsFromSummary(Request $request)
{
$month = $request->validate(['summary_month' => ['required', 'date_format:Y-m']], [], ['summary_month' => '汇总月份'])['summary_month'];
$rows = app(\App\Support\CourierBills\PayableSummary::class)->rows($month);
if ($rows === []) {
throw ValidationException::withMessages(['courier_bills' => $month . ' 还没有快递应付汇总,请先在「快递应付汇总」导入手工快递汇总表。']);
}
$result = $this->store->groupsFromSummary($rows);
return $this->back($request, ['cb_view' => 'groups'], '已按 ' . $month . ' 快递应付汇总新建 ' . $result['created'] . ' 个分组(每个承运商一个,快递名称1 = 承运商);'
. $result['skipped'] . ' 个跳过(停运且本月无金额,或已有分组)。请再点「检查未归组的快递名称1」,把发货数据里名字不一样的快递名称1 补进对应分组。');
}
public function importGroups(Request $request)
{
$file = $request->validate(['groups' => ['required', 'file', 'max:10240']], [], ['groups' => '分组文件'])['groups'];
$extension = strtolower($file->getClientOriginalExtension());
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
throw ValidationException::withMessages(['groups' => '只支持 xlsx、xls、csv。']);
}
$result = $this->guard(fn () => $this->store->importGroups($file->getRealPath(), $extension));
return $this->back($request, ['cb_view' => 'groups'], '已导入分组:新增 ' . $result['created'] . ' 个,覆盖 ' . $result['updated'] . ' 个。');
}
public function exportGroups()
{
$groups = $this->store->groups();
return response()->streamDownload(function () use ($groups): void {
$book = new StreamingWorkbook();
$book->row('对账分组', CourierBillStore::GROUP_HEADERS, true);
foreach ($groups as $group) {
$book->row('对账分组', [$group->name, implode('、', $group->express_names), $group->summary_carrier, $group->bundle, $group->owner,
$group->keywords, $group->waybill_header, $group->amount_header, $group->weight_header]);
}
if ($groups === []) {
$book->row('对账分组', ['河北中通-江三', '河北中通-江三、河北中通小件-江三', '河北中通-江三', '河北中通-江三+霸州百世快运-雅柏', '负责人姓名', '河北中通', '', '', '']);
}
$book->writeTo(fopen('php://output', 'wb'));
}, '对账分组.xlsx');
}
public function deleteGroup(Request $request, int $group)
{
$this->guard(fn () => $this->store->deleteGroup($group));
return $this->back($request, ['cb_view' => 'groups'], '已删除分组。');
}
public function addExpressName(Request $request, int $group)
{
$data = $request->validate(['express_name' => ['required', 'string', 'max:128']]);
$this->guard(fn () => $this->store->addExpressName($group, $data['express_name']));
return $this->back($request, [], '已把「' . $data['express_name'] . '」加进分组。');
}
public function upload(Request $request)
{
$data = $request->validate([
'month' => ['required', 'date_format:Y-m'],
'files' => ['required', 'array', 'max:60'], 'files.*' => ['file', 'max:51200'],
], [], ['files' => '账单文件', 'files.*' => '账单文件']);
foreach ($data['files'] as $file) {
if (! in_array(strtolower($file->getClientOriginalExtension()), CourierBillStore::EXTENSIONS, true)) {
throw ValidationException::withMessages(['files' => '只支持 xlsx、xls、csv、zip:' . $file->getClientOriginalName()]);
}
}
$ids = $this->guard(fn () => $this->store->upload($data['files'], $data['month'], [], self::user()));
$files = $this->store->db()->table('courier_bill_files')->whereIn('id', $ids)->get();
$split = $files->filter(fn ($f) => str_contains((string) $f->message, '合并账单已拆分'))->count();
return $this->back($request, ['cb_view' => 'upload', 'month' => $data['month']],
'已上传 ' . count($ids) . ' 个文件:已读入 ' . $files->where('status', 'parsed')->count() . ' 个,待选分组 '
. $files->where('status', 'pending_group')->count() . ' 个,失败 ' . $files->where('status', 'failed')->count() . ' 个'
. ($split > 0 ? ';其中 ' . $split . ' 个是合并账单,已按快递名称1 拆到各自分组' : '') . '。');
}
public function assign(Request $request, int $file)
{
$data = $request->validate(['group_id' => ['required', 'integer']]);
$this->guard(fn () => $this->store->assign($file, (int) $data['group_id']));
return $this->back($request, [], '已读入并对账。');
}
public function deleteFile(Request $request, int $file)
{
$this->guard(fn () => $this->store->deleteFile($file));
return $this->back($request, [], '已删除文件。');
}
public function rematch(Request $request, int $statement)
{
$done = $this->guard(fn () => $this->store->rematch($statement));
return $this->back($request, [], '已按当前规则重新读取账单文件、按当前对账分组重新拆分,并按最新发货数据、未发出明细和结算台账重新匹配'
. (count($done) > 1 ? '(同一张账单涉及 ' . count($done) . ' 张对账单,一起更新了)' : '') . '。');
}
public function resolve(Request $request)
{
$data = $request->validate([
'lines' => ['required', 'array', 'max:2000'], 'lines.*' => ['integer'],
'resolution' => ['required', Rule::in(['clear', ...array_keys(Category::RESOLUTIONS)])],
], [], ['lines' => '明细']);
$resolution = $data['resolution'] === 'clear' ? null : $data['resolution'];
$count = 0;
$byStatement = $this->store->db()->table('courier_bill_lines')->whereIn('id', $data['lines'])->get(['id', 'statement_id'])->groupBy('statement_id');
foreach ($byStatement as $statementId => $lines) {
$count += $this->guard(fn () => $this->matcher->resolve((int) $statementId, $lines->pluck('id')->all(), $resolution, self::user()));
}
return $this->back($request, [], '已更新 ' . $count . ' 条明细的处理结果,小汇总已重算。');
}
public function addItem(Request $request, int $statement)
{
$data = $request->validate(['label' => ['required', 'string', 'max:255'], 'bill' => ['nullable', 'numeric'], 'self' => ['nullable', 'numeric']],
[], ['label' => '项目名称', 'bill' => '快递提供金额', 'self' => '自算金额']);
$this->guard(fn () => $this->store->addSummaryItem($statement, $data['label'], isset($data['bill']) ? (float) $data['bill'] : null,
isset($data['self']) ? (float) $data['self'] : null));
return $this->back($request, [], '已加入小汇总。');
}
public function deleteItem(Request $request, int $statement, int $item)
{
$this->guard(fn () => $this->store->deleteSummaryItem($statement, $item));
return $this->back($request, [], '已删除。');
}
public function confirm(Request $request, int $statement)
{
$this->guard(fn () => $this->store->confirm($statement, self::user()));
return $this->back($request, [], '已确认结算,单号已记入结算台账。');
}
public function unconfirm(Request $request, int $statement)
{
$this->guard(fn () => $this->store->unconfirm($statement));
return $this->back($request, [], '已撤销确认,结算台账里这批单号已删除。');
}
public function saveGroup(Request $request)
{
$data = $request->validate([
'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'],
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
], [], ['name' => '分组名称', 'express_names' => '快递名称1']);
$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();
if ($exists) {
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
}
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
$this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
}
public function importLedger(Request $request)
{
$file = $request->validate(['ledger' => ['required', 'file', 'max:51200']], [], ['ledger' => '台账文件'])['ledger'];
$extension = strtolower($file->getClientOriginalExtension());
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
throw ValidationException::withMessages(['ledger' => '只支持 xlsx、xls、csv。']);
}
$result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension));
$message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号';
if ($result['rejected'] > 0) {
$message .= ',' . $result['rejected'] . ' 行未导入' . ($result['unknown_groups'] ? '(分组不存在:' . implode('、', array_slice($result['unknown_groups'], 0, 10)) . ')' : '');
}
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
}
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')
->where('s.id', $statement)->first(['s.bill_month', 'g.name']);
abort_if($row === null, 404);
$related = app(StatementExporter::class)->related($statement);
$label = count($related) > 1 ? $row->name . '等' . count($related) . '家' : $row->name;
$name = str_replace(['/', '\\'], '-', $label) . '_' . $row->bill_month . '_对账(内部版).xlsx';
return response()->streamDownload(function () use ($statement): void {
$output = fopen('php://output', 'wb');
app(StatementExporter::class)->export($statement, $output);
}, $name);
}
public function exportDetails(Request $request)
{
$month = self::monthParam($request->query('month')) ?? now()->subMonth()->format('Y-m');
$filters = $request->validate(['group_id' => ['nullable', 'integer'], 'category' => ['nullable', 'string'],
'resolution' => ['nullable', 'string'], 'owner' => ['nullable', 'string'], 'min_diff' => ['nullable', 'numeric'],
'waybills' => ['nullable', 'string', 'max:20000'], 'all_months' => ['nullable', 'boolean']]);
$query = $this->detailsQuery($filters, $month);
return response()->streamDownload(function () use ($query): void {
$book = new StreamingWorkbook();
$book->row('对账明细', ['账单月份', '对账分组', '负责人', '快递单号', '快递提供运费', '快递提供重量', '分类', '发货时间', '发货数据快递名称1',
'核算运费', '计费重量', '自算金额', '差异', '未发出来源', '处理结果', '处理人'], 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) {
$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,
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->self_amount === null ? null : (float) $line->self_amount, round((float) $line->bill_amount - (float) $line->self_amount, 2),
$line->unshipped_sources, Category::RESOLUTIONS[$line->resolution] ?? null, $line->resolved_by]);
}
$book->writeTo(fopen('php://output', 'wb'));
}, '对账明细.xlsx');
}
/** @template T @param callable():T $action @return T */
private function guard(callable $action): mixed
{
try {
return $action();
} catch (RuntimeException $error) {
throw ValidationException::withMessages(['courier_bills' => $error->getMessage()]);
}
}
private function back(Request $request, array $query, string $message)
{
$target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => self::section($request),
'page' => 'courier-bill-reconciliation', ...$query]);
return redirect()->to($target)->with('courier_bills_message', $message);
}
public static function section(Request $request): string
{
$section = (string) ($request->route('section') ?? $request->input('section') ?? '');
return $section === 'courier-payables-final' ? 'courier-payables-final' : 'courier-payables';
}
private static function monthParam(mixed $value): ?string
{
return is_string($value) && preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $value) ? $value : null;
}
private static function user(): string
{
$user = user();
return (string) ($user?->name ?? $user?->email ?? 'system');
}
}

View File

@ -11,9 +11,19 @@ class CourierContracts extends Controller
{
/** A read-only archive entry point with courier-information page access, not signing-management access. */
public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse
{
return $this->serveFile($agreementSignature, $kind, 'courier');
}
public function downloadSupplier(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse
{
return $this->serveFile($agreementSignature, $kind, 'supplier');
}
private function serveFile(CourierAgreementSignature $agreementSignature, string $kind, string $partnerType): StreamedResponse
{
abort_unless($agreementSignature->company_id === (int) company_id()
&& $agreementSignature->archivedCourierContractPayload() !== null, 404);
&& $agreementSignature->archivedContractPayload($partnerType) !== null, 404);
$path = match ($kind) {
'signed' => $agreementSignature->signed_pdf_path,
'certificate' => $agreementSignature->certificate_path,

View File

@ -93,6 +93,7 @@ class CourierOnboardings extends Controller
/** 后台变价页:复用入驻报价填写区,以最新版本(或已退回的变价单)为底稿。 */
public function requote(CourierOnboarding $onboarding): View|RedirectResponse
{
app(\App\Support\CourierQuoteWorkflowPermissions::class)->assertInitiator((int) user_id());
$this->ensureReady();
$quoteManagement = route('business.pages.show', ['section' => 'courier-payables', 'page' => 'quote-management']);
if ($onboarding->status !== CourierOnboarding::STATUS_ACTIVATED) {
@ -100,9 +101,9 @@ class CourierOnboardings extends Controller
}
$requotes = $this->requotes();
$open = $requotes->openChange($onboarding);
if ($open !== null && $open->status === \App\Models\Business\CourierQuoteChange::STATUS_PENDING_REVIEW) {
if ($open !== null && (in_array($open->status, [\App\Models\Business\CourierQuoteChange::STATUS_PENDING_REVIEW, \App\Models\Business\CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW], true) || $open->created_by !== user_id())) {
return redirect()->route('business.courier-quote-changes.show', $open)
->with('success', "已有待审核的变价单 {$open->number},审核完成后再发起新的变价。");
->with('success', "已有未完成的变价单 {$open->number},请先查看该单;待审核单可由发起人撤回修改。");
}
$version = $requotes->latestVersion($onboarding);
@ -139,6 +140,7 @@ class CourierOnboardings extends Controller
...\App\Http\Controllers\Onboarding\CourierOnboardingForms::quoteRules(),
'summary' => ['required', 'string', 'min:2', 'max:2000'],
'quote_end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:quote_effective_date'],
...\App\Support\CourierQuotePeriods::rules(),
], [
'summary.required' => '请写一下这次变价的原因或依据,审核和对账时要看。',
'quote_end_date.after_or_equal' => '结束日期不能早于执行日期。',

View File

@ -0,0 +1,116 @@
<?php
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\PayableSummary;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use RuntimeException;
/** 快递应付汇总:所有承运商的月度应付,格式同手工快递汇总表。 */
final class CourierPayableSummaryController extends Controller
{
public const STATUSES = ['已确认', '待处理', '本月无账单', '旧账挂账'];
public function __construct(private readonly PayableSummary $summary) {}
public function page(Request $request): array
{
$data = ['view' => 'business.pages.courier-payables.courier-payable-summary', 'psSection' => CourierBillController::section($request),
'psUnavailable' => false, 'psRows' => [], 'psMonths' => [], 'psMonth' => null];
try {
$months = $this->summary->months();
$month = is_string($request->query('month')) && in_array($request->query('month'), $months, true) ? $request->query('month') : ($months[0] ?? null);
$rows = $month === null ? [] : $this->summary->rows($month);
$status = in_array($request->query('status'), self::STATUSES, true) ? $request->query('status') : null;
$keyword = trim((string) $request->query('q'));
$filtered = array_values(array_filter($rows, static function (array $row) use ($status, $keyword, $request): bool {
$c = $row['cells'];
foreach (['company' => 'C', 'owner' => 'D', 'state' => 'E'] as $param => $letter) {
if (filled($request->query($param)) && (string) ($c[$letter] ?? '') !== (string) $request->query($param)) {
return false;
}
}
return ($status === null || $row['status'] === $status)
&& ($keyword === '' || str_contains((string) ($c['H'] ?? ''), $keyword) || str_contains((string) ($c['G'] ?? ''), $keyword));
}));
$counts = array_count_values(array_column($rows, 'status'));
$options = static fn (string $letter): array => collect($rows)->pluck('cells.' . $letter)->filter()->unique()->sort()->values()->all();
$data = array_merge($data, ['psMonths' => $months, 'psMonth' => $month, 'psRows' => $filtered, 'psAll' => count($rows),
'psCounts' => $counts, 'psStatus' => $status, 'psCompanies' => $options('C'), 'psOwners' => $options('D'),
'psTotals' => collect(PayableSummary::MONEY)->mapWithKeys(fn ($k) => [$k => array_sum(array_map(fn ($r) => (float) ($r['cells'][$k] ?? 0), $filtered))])->all()]);
} catch (QueryException $error) {
report($error);
$data['psUnavailable'] = true;
}
return $data;
}
public function import(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'summary' => ['required', 'file', 'max:51200']],
[], ['summary' => '快递汇总表', 'month' => '月份']);
if (strtolower($data['summary']->getClientOriginalExtension()) !== 'xlsx') {
throw ValidationException::withMessages(['summary' => '请上传 xlsx 格式的快递汇总表。']);
}
$result = $this->guard(fn () => $this->summary->import($data['summary']->getRealPath(), $data['month']));
return $this->back($request, $data['month'], '已导入 ' . $data['month'] . ' 快递汇总 ' . $result['rows'] . ' 个承运商。');
}
public function createMonth(Request $request)
{
$month = $request->validate(['month' => ['required', 'date_format:Y-m']])['month'];
$count = $this->guard(fn () => $this->summary->createMonth($month));
return $this->back($request, $month, '已生成 ' . $month . ':' . $count . ' 个承运商,月初结余按上月「本月应付 − 本次实付」结转。');
}
public function update(Request $request, int $row)
{
$data = $request->validate(['column' => ['required', Rule::in(array_keys(PayableSummary::EDITABLE))], 'value' => ['nullable', 'string', 'max:500']]);
$this->guard(fn () => $this->summary->updateCell($row, $data['column'], $data['value'] ?? null));
if ($request->expectsJson()) {
return response()->json(['ok' => true]);
}
return redirect()->to(url()->previous())->with('courier_summary_message', '已保存。');
}
public function addCarrier(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'carrier' => ['required', 'string', 'max:128']], [], ['carrier' => '承运商']);
$this->guard(fn () => $this->summary->addCarrier($data['month'], $data['carrier']));
return $this->back($request, $data['month'], '已新增承运商。');
}
public function export(Request $request)
{
$month = $request->validate(['month' => ['required', 'date_format:Y-m']])['month'];
return response()->streamDownload(function () use ($month): void {
$this->summary->export($month, fopen('php://output', 'wb'));
}, '快递应付汇总_' . $month . '.xlsx');
}
private function guard(callable $action): mixed
{
try {
return $action();
} catch (RuntimeException $error) {
throw ValidationException::withMessages(['courier_summary' => $error->getMessage()]);
}
}
private function back(Request $request, string $month, string $message)
{
return redirect()->route('business.pages.show', ['section' => CourierBillController::section($request),
'page' => 'courier-payable-summary', 'month' => $month])->with('courier_summary_message', $message);
}
}

View File

@ -6,6 +6,7 @@ use App\Abstracts\Http\Controller;
use App\Business\CourierProfileData;
use App\Models\Business\CourierPaymentAccount;
use App\Models\Business\CourierProfile;
use App\Utilities\CourierProfilePermissions;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@ -20,6 +21,7 @@ class CourierProfiles extends Controller
public function update(Request $request, string $expcode): RedirectResponse
{
abort_unless(CourierProfilePermissions::canEdit(), 403, '未获授权编辑快递资料。');
$row = $this->profiles->currentRow($expcode);
abort_if($row === null, 404);
@ -29,6 +31,8 @@ class CourierProfiles extends Controller
in_array($field, CourierProfile::BOOLEAN_FIELDS, true) => ['nullable', 'in:0,1'],
in_array($field, CourierProfile::DATE_FIELDS, true) => ['nullable', 'date'],
$field === 'expname' => ['required', 'string', 'max:100'],
CourierProfile::fieldOptions($field) !== null => ['nullable', \Illuminate\Validation\Rule::in(array_keys(CourierProfile::fieldOptions($field)))],
$field === 'courier_email' => ['nullable', 'email', 'max:255'],
default => ['nullable', 'string', 'max:255'],
};
}

View File

@ -2,10 +2,14 @@
namespace App\Http\Controllers\Business;
use App\Business\CourierProfileData;
use App\Models\Business\CourierQuoteChange;
use App\Models\Business\CourierQuoteVersion;
use App\Models\Business\CourierStockQuoteEntry;
use App\Services\Esign\EsignClient;
use App\Support\CourierQuoteChangeService;
use App\Support\CourierQuoteChangeExport;
use App\Support\CourierQuoteWorkflowPermissions;
use App\Support\CourierOnboardingService;
use App\Support\CourierQuoteSignatureService;
use App\Support\CourierRequoteService;
@ -15,6 +19,10 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\View\View;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
class CourierQuoteChanges extends Controller
{
@ -38,15 +46,30 @@ class CourierQuoteChanges extends Controller
->paginate(20)
->withQueryString();
$quoteReviewer = $this->canReview();
$admin = $this->canAdminister();
$permissions = app(CourierQuoteWorkflowPermissions::class);
$workflow = $permissions->settings();
$stageAccess = [];
$reviewableIds = $changes->filter(function ($change) use ($permissions, &$stageAccess) {
if (!in_array($change->status, [CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW], true)) return false;
// 本页同环节和同自审条件仅核验一次;下个请求重新读取权限和花名册。
$key = $change->status . ':' . (int) $change->isStockQuote() . ':' . (int) ($change->created_by === user_id());
return $stageAccess[$key] ??= $permissions->canReviewChange($change, (int) user_id());
})->pluck('id')->all();
return view('business.pages.courier-payables.quote-change-history', [
'changes' => $changes,
'canReview' => $this->canReview(),
'canReview' => $quoteReviewer || $admin,
'reviewableChangeIds' => $reviewableIds,
'filters' => $filters,
'quoteWorkflow' => $workflow,
'carrierOptions' => CourierQuoteChange::query()->whereNotNull('carrier_name')->distinct()->orderBy('carrier_name')->pluck('carrier_name')->all(),
'changeTypeOptions' => CourierQuoteChange::query()->whereNotNull('change_type')->distinct()->orderBy('change_type')->pluck('change_type')->all(),
'statusOptions' => [
CourierQuoteChange::STATUS_DRAFT => '草稿',
CourierQuoteChange::STATUS_PENDING_REVIEW => '待审核',
CourierQuoteChange::STATUS_PENDING_REVIEW => $workflow['staged'] ? '待初审' : '待审核',
CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW => '待复审',
CourierQuoteChange::STATUS_RETURNED => '已退回',
CourierQuoteChange::STATUS_APPROVED => '已审核',
],
@ -57,7 +80,7 @@ class CourierQuoteChanges extends Controller
private function historyFilters(Request $request): array
{
$status = (string) $request->input('status', '');
$allowed = [CourierQuoteChange::STATUS_DRAFT, CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_RETURNED, CourierQuoteChange::STATUS_APPROVED];
$allowed = [CourierQuoteChange::STATUS_DRAFT, CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW, CourierQuoteChange::STATUS_RETURNED, CourierQuoteChange::STATUS_APPROVED];
return [
'carrier' => mb_substr(trim((string) $request->input('carrier', '')), 0, 100),
@ -68,6 +91,7 @@ class CourierQuoteChanges extends Controller
public function create(Request $request): View|RedirectResponse
{
app(CourierQuoteWorkflowPermissions::class)->assertInitiator((int) user_id());
$quotes = $this->snapshot->load()['quotes'] ?? [];
abort_if($quotes === [], 422, '尚未导入可用于变更的报价版本。');
@ -99,6 +123,11 @@ class CourierQuoteChanges extends Controller
$requoteDiff = $onboarding !== null
? $this->requotes->diff($onboarding, $this->requotes->basePayload($onboarding, $quoteChange), $quoteChange->quote_payload)
: null;
$reviewAllowed = $this->canReview($quoteChange);
$quoteWorkflow = app(CourierQuoteWorkflowPermissions::class)->settings();
$canManageSignature = $this->canAdminister() || $reviewAllowed;
$signingDetails = $canManageSignature && $onboarding === null && $quoteChange->version?->signature?->canSend()
? $this->signingDetailsFor($quoteChange->version) : [];
return view('business.pages.courier-payables.quote-change-show', [
'change' => $quoteChange,
@ -109,15 +138,49 @@ class CourierQuoteChanges extends Controller
? $this->requotes->reviewWarnings($quoteChange, $requoteDiff)
: [],
'voidedBy' => $quoteChange->version?->voided_by ? user_model_class()::query()->find($quoteChange->version->voided_by)?->name : null,
'canReview' => $this->canReview() && ($quoteChange->created_by !== user_id() || config('courier_onboarding.allow_same_reviewer')),
'canManageSignature' => $this->canReview(),
'canReview' => app(CourierQuoteWorkflowPermissions::class)->canReviewChange($quoteChange, (int) user_id()),
'canWithdraw' => ! $quoteChange->isStockQuote() && in_array($quoteChange->status, [CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW], true)
&& $quoteChange->created_by === user_id() && app(CourierQuoteWorkflowPermissions::class)->can('initiators', (int) user_id()),
'canManageSignature' => $canManageSignature,
'canCorrectPeriods' => $reviewAllowed && !$quoteChange->isStockQuote()
&& app(\App\Support\CourierQuotePeriodCorrection::class)->available($quoteChange),
'quoteSigningAccount' => $signingDetails['account'] ?? '',
'quoteSigningParty' => $signingDetails['party_b'] ?? '',
'canVoidQuote' => $this->canAdminister(),
'quoteWorkflow' => $quoteWorkflow,
'esignConfigured' => EsignClient::configured(),
'esignEnvironment' => (string) config('services.esign.environment', 'sandbox'),
]);
}
private function signingDetailsFor(CourierQuoteVersion $version): array
{
try {
$row = app(CourierInformationMirrorRepository::class)->signingAccountSource(
(string) $version->courier_expcode, (string) $version->carrier_name,
);
if ($row === null) {
return [];
}
$profiles = app(CourierProfileData::class);
$row = $profiles->apply($row, $profiles->overrides([(string) $row->expcode])[(string) $row->expcode] ?? []);
return [
'account' => trim((string) ($row->dzqzjbr ?? '')),
'party_b' => trim((string) ($row->tradebody ?? '')),
];
} catch (Throwable $exception) {
report($exception);
return [];
}
}
public function edit(CourierQuoteChange $quoteChange): View|RedirectResponse
{
if (! $quoteChange->isStockQuote()) {
app(CourierQuoteWorkflowPermissions::class)->assertInitiator((int) user_id());
}
abort_unless($quoteChange->isEditable() && $quoteChange->created_by === user_id(), 403);
if ($quoteChange->isStockQuote()) {
return redirect()->route('business.courier-stock-quotes.edit', data_get($quoteChange->quote_payload, 'stock_quote_entry_id'));
@ -149,14 +212,55 @@ class CourierQuoteChanges extends Controller
->with('success', "{$change->number} 已提交审核。");
}
public function withdraw(CourierQuoteChange $quoteChange): RedirectResponse
{
$change = $this->service->withdraw($quoteChange, (int) user_id());
return redirect()->route('business.courier-quote-changes.edit', $change)
->with('success', "{$change->number} 已撤回为草稿,修改后请重新提交审核。");
}
public function correctPeriods(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
$data = $request->validate([
...\App\Support\CourierQuotePeriods::rules(),
'effective_date' => ['required', 'date_format:Y-m-d'],
'execution_mode' => ['required', 'in:permanent,temporary'],
]);
app(\App\Support\CourierQuotePeriodCorrection::class)->correct($quoteChange, $data, (int) user_id());
return redirect()->route('business.courier-quote-changes.show', $quoteChange)
->with('success', '执行区间已更正,价格不变,待签文件已重新生成。请核对后再发起签署。');
}
public function export(CourierQuoteChange $quoteChange): StreamedResponse
{
$book = app(CourierQuoteChangeExport::class)->build($quoteChange);
return response()->streamDownload(function () use ($book): void {
try {
(new Xlsx($book))->save('php://output');
} finally {
$book->disconnectWorksheets();
}
}, $quoteChange->number . '-变价后报价.xlsx', [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Cache-Control' => 'private, no-store',
]);
}
public function approve(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
abort_unless($this->canReview($quoteChange), 403, '当前账号没有报价审核权限。');
if ($quoteChange->isStockQuote()) {
$request->validate(['stock_rules_confirmed' => ['accepted']], ['stock_rules_confirmed.accepted' => '请先核对原报价、计费规则及实际执行日期。']);
}
$change = $this->service->approve($quoteChange, user_id(), $request->boolean('stock_signature_verified'));
if ($change->status === CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW) {
return redirect()->route('business.courier-quote-changes.show', $change)
->with('success', '初审通过,已转复审。任意一名指定复审人员通过后才生成生效报价版本。');
}
$message = "审核完成,已生成新报价版本 {$change->version->version_code}。";
if ($change->isStockQuote()) {
@ -194,7 +298,7 @@ class CourierQuoteChanges extends Controller
public function batchApprove(Request $request): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
abort_unless($this->canReview() || $this->canAdminister(), 403, '当前账号没有报价审核权限。');
$input = $request->validate([
'ids' => ['required', 'array', 'min:1', 'max:100'],
'ids.*' => ['required', 'integer', 'min:1', 'distinct'],
@ -231,7 +335,7 @@ class CourierQuoteChanges extends Controller
/** 已入驻快递的变价版本按入驻资料(重新)推送到快递 e签宝。 */
public function pushToCourier(CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
abort_unless($this->canAdminister() || $this->canReview($quoteChange), 403, '当前账号没有报价审核权限。');
abort_if($quoteChange->isStockQuote(), 422, '存量报价请先核对历史签署资料,补签通过详情页手动发起。');
$onboarding = $this->requotes->onboardingForCourier($quoteChange->carrier_name);
abort_if($onboarding === null || $quoteChange->version === null, 404);
@ -244,7 +348,7 @@ class CourierQuoteChanges extends Controller
/** 作废发错的报价版本(未签完的同时撤回 e签宝 签署任务)。 */
public function void(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
abort_unless($this->canAdminister(), 403, '当前账号没有报价审核权限。');
abort_if($quoteChange->version === null, 404);
$data = $request->validate(
['void_reason' => ['required', 'string', 'min:2', 'max:500']],
@ -257,7 +361,7 @@ class CourierQuoteChanges extends Controller
public function returnForChanges(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
abort_unless($this->canReview($quoteChange), 403, '当前账号没有报价审核权限。');
$validated = $request->validate([
'review_note' => ['required', 'string', 'min:2', 'max:1000'],
]);
@ -270,9 +374,19 @@ class CourierQuoteChanges extends Controller
private function validatedChange(Request $request, bool $requiresSource): array
{
$rules = [
...\App\Support\CourierQuotePeriods::rules(),
'end_date' => ['nullable', 'date_format:Y-m-d'],
'change_type' => ['required', 'in:费率调整,面单调整,规则备注,执行日期,其他'],
'effective_date' => ['required', 'date_format:Y-m-d'],
'summary' => ['required', 'string', 'min:2', 'max:2000'],
'quote_notes' => ['sometimes', 'array', 'max:500'],
'quote_notes.*' => ['nullable', 'string', 'max:10000'],
'province_additions' => ['sometimes', 'array', 'max:34'],
'province_additions.*' => ['array:region,prices,note'],
'province_additions.*.region' => ['required', 'string', 'max:16', 'regex:/^[\p{Han}]+$/u'],
'province_additions.*.prices' => ['required', 'array'],
'province_additions.*.prices.*' => ['required', 'numeric', 'min:0', 'decimal:0,4'],
'province_additions.*.note' => ['nullable', 'string', 'max:10000'],
'items' => ['required', 'array', 'min:1', 'max:500'],
'items.*.source_cell' => ['required', 'regex:/^[A-Z]+[1-9][0-9]*$/'],
'items.*.source_row' => ['required', 'integer', 'min:0'],
@ -302,6 +416,7 @@ class CourierQuoteChanges extends Controller
'quotes' => $quotes,
'source' => $source,
'editableCells' => $this->editableCells($source, $existingItems),
'editableNotes' => \App\Support\CourierQuoteNotes::cells($source, $change?->quote_payload['quote_notes'] ?? []),
];
}
@ -390,7 +505,17 @@ class CourierQuoteChanges extends Controller
}
}
private function canReview(): bool
private function canReview(?CourierQuoteChange $change = null): bool
{
if ($change && (app(CourierQuoteWorkflowPermissions::class)->settings()['staged']
|| $change->status === CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW)) {
return app(CourierQuoteWorkflowPermissions::class)->canReviewChange($change, (int) user_id());
}
return $change?->isStockQuote() ? $this->canAdminister()
: app(CourierQuoteWorkflowPermissions::class)->can('reviewers', (int) user_id());
}
private function canAdminister(): bool
{
return in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true);
}

View File

@ -6,6 +6,7 @@ use App\Models\Business\CourierQuoteSignature;
use App\Models\Business\CourierQuoteVersion;
use App\Services\Esign\EsignClient;
use App\Support\CourierQuoteSignatureService;
use App\Support\CourierQuoteWorkflowPermissions;
use App\Utilities\SystemAccess;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@ -22,26 +23,30 @@ class CourierQuoteSignatures extends Controller
public function prepare(Request $request, CourierQuoteVersion $quoteVersion): RedirectResponse
{
$this->ensureCanManage();
$this->ensureCanManage($quoteVersion);
abort_unless($quoteVersion->status === 'approved', 422, '只有已审核报价版本可以生成签署文件。');
$data = $request->validate([
'signature_date' => ['required', 'date'],
'organization_name' => ['nullable', 'string', 'min:2', 'max:255'],
]);
$signature = $this->service->prepareVersion($quoteVersion, user_id(), $data['signature_date']);
$signature = $this->service->prepareVersion($quoteVersion, user_id(), $data['signature_date'], null, $data['organization_name'] ?? null);
return redirect()->route('business.courier-quote-changes.show', $quoteVersion->source_change_id)
->with('success', "{$quoteVersion->version_code} 的签署 PDF 已生成,文件校验值已固定。")
->withInput($request->only(['signer_type', 'organization_name', 'operator_account', 'notice_type', 'signature_date', 'expires_at']))
->with('signature_id', $signature->id);
}
public function send(Request $request, CourierQuoteSignature $quoteSignature): RedirectResponse
{
$this->ensureCanManage();
$this->ensureCanManage($quoteSignature->version);
abort_unless($quoteSignature->version?->status === 'approved', 422, '只有已审核报价版本可以发起签署。');
abort_unless(EsignClient::configured(), 422, 'E 签宝沙箱尚未配置 App ID 或 AppSecret。');
$data = $request->validate([
'signer_type' => ['nullable', 'in:organization,person'],
'organization_name' => ['required', 'string', 'min:2', 'max:255'],
'operator_name' => ['required', 'string', 'min:2', 'max:100'],
'signing_subject' => ['nullable', 'string', 'min:2', 'max:255'],
'operator_name' => ['nullable', 'string', 'min:2', 'max:100'],
'operator_account' => ['required', 'string', 'max:255'],
'notice_type' => ['required', 'in:1,2'],
'signature_date' => ['required', 'date'],
@ -52,6 +57,8 @@ class CourierQuoteSignatures extends Controller
$quoteSignature->version,
user_id(),
$data['signature_date'],
$data['signing_subject'] ?? null,
$data['organization_name'],
);
$signature = $this->service->send($quoteSignature, $data, user_id());
$environment = $signature->environment === 'sandbox' ? '沙箱' : '正式环境';
@ -62,7 +69,7 @@ class CourierQuoteSignatures extends Controller
public function synchronize(CourierQuoteSignature $quoteSignature): RedirectResponse
{
$this->ensureCanManage();
$this->ensureCanManage($quoteSignature->version);
$signature = $this->service->synchronize($quoteSignature, user_id());
$message = $signature->status === CourierQuoteSignature::STATUS_ARCHIVED
? '签署完成,签署 PDF 和完成证书已私有归档。'
@ -137,8 +144,12 @@ class CourierQuoteSignatures extends Controller
*/
public function sheet(CourierQuoteVersion $quoteVersion): StreamedResponse
{
$values = json_decode((string) $quoteVersion->values_json, true);
$table = self::quoteTableWithNotes(self::quoteLayout(is_array($values) ? $values : []))['rows'];
$confirmation = app(\App\Support\CourierQuoteConfirmation::class)->data($quoteVersion);
$layout = self::quoteLayout($confirmation['values']);
if ($quoteVersion->isTemporary()) {
array_unshift($layout['notes'], $confirmation['temporary_note']);
}
$table = self::quoteTableWithNotes($layout)['rows'];
abort_if($table === [], 404, '这份报价没有可导出的价格表。');
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
@ -147,8 +158,9 @@ class CourierQuoteSignatures extends Controller
foreach ($table as $rowIndex => $row) {
foreach ($row as $columnIndex => $value) {
$cell = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnIndex + 1) . ($rowIndex + 1);
if (is_int($value) || is_float($value)) {
$sheet->setCellValue($cell, $value);
if ($rowIndex > 0 && $columnIndex > 0 && $columnIndex < count($table[0]) - 1 && is_numeric($value)) {
$sheet->setCellValue($cell, (float) $value);
$sheet->getStyle($cell)->getNumberFormat()->setFormatCode('0.00');
} elseif ($value !== null && $value !== '') {
$sheet->setCellValueExplicit($cell, (string) $value, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
}
@ -181,7 +193,7 @@ class CourierQuoteSignatures extends Controller
}
/**
* 从报价矩阵里截出价格表:从「省份」表头行开始,到第一行只有一格文字(说明、备注)为止。
* 从报价矩阵里截出价格表;未报价的省份占位行不输出,也不中断后续报价。
*
* @param array<int,mixed> $values
* @return list<list<string|int|float|null>>
@ -193,7 +205,7 @@ class CourierQuoteSignatures extends Controller
/**
* 报价矩阵拆成「价格表」和「价格表以外的文字」:
* - table:从「省份」表头行开始,到第一行只有一格文字为止;
* - table:从「省份」表头行开始,跳过未报价的省份占位行,到说明文字为止;
* - notes:其余所有文字行(执行时间、计费方式、计泡、起算重量、报价备注等),第一行标题除外;
* - row_keys:价格表每一行在原矩阵里的下标(用于对应公式)。
*
@ -214,6 +226,16 @@ class CourierQuoteSignatures extends Controller
break;
}
}
if ($start === null) {
foreach ($rows as $index => $row) {
if (filled($row[0] ?? null) || $filled($row) < 2) continue;
$next = $rows[$index + 1] ?? [];
if (filled($next[0] ?? null) && collect(array_slice($next, 1))->contains(fn ($cell) => is_numeric($cell))) {
$start = $index;
break;
}
}
}
if ($start === null) {
foreach ($rows as $index => $row) {
if ($filled($row) >= 2) {
@ -229,7 +251,22 @@ class CourierQuoteSignatures extends Controller
$table = [];
$rowKeys = [];
$end = $start;
for ($i = $start; $i < count($rows) && $filled($rows[$i]) >= 2; $i++) {
for ($i = $start; $i < count($rows); $i++) {
if ($filled($rows[$i]) < 2) {
// Imported sheets retain destinations with no quote. They are neither
// prices nor billing notes, and prices may resume below them.
$region = \App\Support\CourierQuoteFreightCalculator::regionKey((string) ($rows[$i][0] ?? ''));
if ($filled($rows[$i]) === 1 && in_array($region, [
'北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙江',
'江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南',
'广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海',
'内蒙古', '广西', '西藏', '宁夏', '新疆', '香港', '澳门', '台湾', '拉萨',
], true)) {
$end = $i + 1;
continue;
}
break;
}
$table[] = array_values($rows[$i]);
$rowKeys[] = $keys[$i];
$end = $i + 1;
@ -266,7 +303,7 @@ class CourierQuoteSignatures extends Controller
}
/**
* 价格表右侧加一列「备注」,每条计费条件占一行;条件比省份多时在表尾补行。
* 复用价格表已有的「备注」列,缺少时再添加;条件比省份多时在表尾补行。
*
* @param array{table:list<list<mixed>>,notes:list<string>,row_keys:list<int|string>} $layout
* @return array{rows:list<list<mixed>>,row_keys:list<int|string|null>}
@ -279,12 +316,19 @@ class CourierQuoteSignatures extends Controller
}
$notes = $layout['notes'];
$width = count($table[0]);
$hasNoteColumn = preg_match('/^(备注|说明)[::]?$/u', trim((string) $table[0][$width - 1])) === 1;
$rows = [];
$keys = [];
$total = max(count($table), count($notes) + 1);
for ($i = 0; $i < $total; $i++) {
$row = $table[$i] ?? array_fill(0, $width, null);
$row[] = $i === 0 ? '备注' : ($notes[$i - 1] ?? null);
if ($hasNoteColumn) {
if ($i > 0 && filled($notes[$i - 1] ?? null)) {
$row[$width - 1] = implode("\n", array_filter([$row[$width - 1], $notes[$i - 1]], static fn ($value) => $value !== null && $value !== ''));
}
} else {
$row[] = $i === 0 ? '备注' : ($notes[$i - 1] ?? null);
}
$rows[] = $row;
$keys[] = $layout['row_keys'][$i] ?? null;
}
@ -309,10 +353,12 @@ class CourierQuoteSignatures extends Controller
}
}
private function ensureCanManage(): void
private function ensureCanManage(?CourierQuoteVersion $version = null): void
{
abort_unless(
in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true),
in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true)
|| ($version?->change && ! $version->change->isStockQuote()
&& app(CourierQuoteWorkflowPermissions::class)->can('reviewers', (int) user_id())),
403,
'当前账号没有报价签署管理权限。',
);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,214 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\PayablesFinalRegistry;
use Modules\EcommerceFinance\Services\PayablesUnpricedCycleProcessor;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PayablesUnpricedCycleExport extends Controller
{
public function __construct(
private readonly SupplierPayableOverrideStore $store,
private readonly PayablesFinalRegistry $registry,
) {
$this->middleware('auth');
$this->middleware('company.identify');
}
public function export(Request $request): StreamedResponse
{
$requestedPeriod = trim((string) $request->query('month', ''));
$period = preg_match('/^\d{4}-\d{2}$/', $requestedPeriod) === 1
? $requestedPeriod
: now()->subMonthNoOverflow()->format('Y-m');
$companyId = (int) (company_id() ?: 1);
$deliveryRows = $this->periodRows(
PayablesUnpricedCycleProcessor::DELIVERY_PRICED_DATASET,
$period,
$companyId,
);
$returnRows = $this->periodRows(
PayablesUnpricedCycleProcessor::RETURN_PRICED_DATASET,
$period,
$companyId,
);
$deliverySummary = $this->summary($deliveryRows, 'guessAmount', 'amount');
$returnSummary = $this->summary($returnRows, 'guess_amount', 'amount');
$spreadsheet = new Spreadsheet();
$summarySheet = $spreadsheet->getActiveSheet();
$summarySheet->setTitle('账期汇总');
$summarySheet->fromArray([
['类型', '记录数', '件数', '金额', '预估金额'],
['送货未定价', $deliverySummary['count'], $deliverySummary['quantity'], $deliverySummary['amount'], $deliverySummary['estimated_amount']],
['退货未定价', $returnSummary['count'], $returnSummary['quantity'], $returnSummary['amount'], $returnSummary['estimated_amount']],
], null, 'A1');
$this->styleSheet($summarySheet, 5, 3, [2 => 'number', 3 => 'number', 4 => 'number', 5 => 'number']);
$summarySheet->getColumnDimension('A')->setWidth(18);
foreach (['B', 'C', 'D', 'E'] as $column) {
$summarySheet->getColumnDimension($column)->setWidth(18);
}
$deliverySheet = $spreadsheet->createSheet();
$this->writeDetailSheet(
$deliverySheet,
'送货未定价',
$this->registry->fields(PayablesFinalRegistry::SECTION_SUPPLIER, 'delivery-unpriced'),
$deliveryRows,
);
$returnSheet = $spreadsheet->createSheet();
$this->writeDetailSheet(
$returnSheet,
'退货未定价',
$this->registry->fields(PayablesFinalRegistry::SECTION_SUPPLIER, 'return-unpriced'),
$returnRows,
);
$spreadsheet->setActiveSheetIndex(0);
$fileName = '之前月未定价-本月定价_' . $period . '_' . now()->format('Ymd_His') . '.xlsx';
return response()->streamDownload(function () use ($spreadsheet): void {
(new Xlsx($spreadsheet))->save('php://output');
$spreadsheet->disconnectWorksheets();
}, $fileName, [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Cache-Control' => 'private, no-store',
]);
}
/**
* @return list<array<string,mixed>>
*/
private function periodRows(string $dataset, string $period, int $companyId): array
{
return array_values(array_filter(
$this->store->listRows($dataset, $companyId),
static fn (array $row): bool => (string) ($row['_accounting_period'] ?? '') === $period,
));
}
/**
* @param list<array<string,mixed>> $rows
* @return array{count:int,quantity:float,amount:float,estimated_amount:float}
*/
private function summary(array $rows, string $estimatedAmountField, string $amountField): array
{
$quantity = 0.0;
$amount = 0.0;
$estimatedAmount = 0.0;
foreach ($rows as $row) {
if (is_numeric($row['qty'] ?? null)) {
$quantity += (float) $row['qty'];
}
if (is_numeric($row[$amountField] ?? null)) {
$amount += (float) $row[$amountField];
}
if (is_numeric($row[$estimatedAmountField] ?? null)) {
$estimatedAmount += (float) $row[$estimatedAmountField];
}
}
return [
'count' => count($rows),
'quantity' => $quantity,
'amount' => $amount,
'estimated_amount' => $estimatedAmount,
];
}
/**
* @param array<string,array{label:string,type:string}> $fields
* @param list<array<string,mixed>> $rows
*/
private function writeDetailSheet(
\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet,
string $title,
array $fields,
array $rows,
): void {
$sheet->setTitle($title);
$headers = array_merge(['序号'], array_column($fields, 'label'));
$sheet->fromArray($headers, null, 'A1');
$data = [];
foreach ($rows as $index => $row) {
$line = [$index + 1];
foreach ($fields as $field => $definition) {
$value = $row[$field] ?? '';
$line[] = $definition['type'] === 'number' && is_numeric($value)
? (float) $value
: (string) $value;
}
$data[] = $line;
}
if ($data !== []) {
$sheet->fromArray($data, null, 'A2');
}
$lastColumn = Coordinate::stringFromColumnIndex(count($headers));
$lastRow = max(1, count($data) + 1);
$types = [];
$columnIndex = 2;
foreach ($fields as $definition) {
if ($definition['type'] === 'number') {
$types[$columnIndex] = 'number';
}
$column = Coordinate::stringFromColumnIndex($columnIndex);
$sheet->getColumnDimension($column)->setWidth(min(32, max(12, mb_strlen($definition['label']) * 2 + 5)));
$columnIndex++;
}
$sheet->getColumnDimension('A')->setWidth(9);
$this->styleSheet($sheet, count($headers), $lastRow, $types);
$sheet->freezePane('A2');
$sheet->setAutoFilter('A1:' . $lastColumn . $lastRow);
}
/**
* @param array<int,string> $types
*/
private function styleSheet(
\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet,
int $columnCount,
int $rowCount,
array $types,
): void {
$lastColumn = Coordinate::stringFromColumnIndex($columnCount);
$headerRange = 'A1:' . $lastColumn . '1';
$sheet->getStyle($headerRange)->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']],
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'D8D2C7']]],
]);
$sheet->getRowDimension(1)->setRowHeight(24);
if ($rowCount > 1) {
$sheet->getStyle('A2:' . $lastColumn . $rowCount)
->getBorders()
->getAllBorders()
->setBorderStyle(Border::BORDER_THIN)
->getColor()
->setRGB('E7E2D8');
}
foreach ($types as $index => $type) {
if ($type !== 'number') {
continue;
}
$column = Coordinate::stringFromColumnIndex($index);
$sheet->getStyle($column . '2:' . $column . max(2, $rowCount))
->getNumberFormat()
->setFormatCode('#,##0.00');
}
}
}

View File

@ -0,0 +1,126 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\PlantingReimbursementReferences as References;
use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbookExporter as Exporter;
use Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData as PageData;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
/** 种菜报销工作台:上传参考名单、导出对账 / 打款明细 / 种菜任务工单导入模板。 */
class PlantingReimbursementWorkbench extends Controller
{
public function upload(Request $request, string $kind, References $references)
{
abort_unless(isset(References::KINDS[$kind]), 404);
$request->validate(['file' => ['required', 'file', 'max:51200']]);
$file = $request->file('file');
$name = (string) $file->getClientOriginalName();
$redirect = redirect()->route('business.pages.show', [
'company_id' => company_id(),
'section' => 'planting-data',
'page' => 'planting-reimbursement-workbench',
'date' => (string) $request->input('date', ''),
'paid_from' => (string) $request->input('paid_from', ''),
'scope' => (string) $request->input('scope', ''),
]);
try {
$rows = $references->parse($kind, (string) $file->getRealPath(), $name);
$references->replace((int) company_id(), $kind, $rows, $name, optional(user())->id);
} catch (InvalidArgumentException $exception) {
return $redirect->with('error', References::KINDS[$kind] . '上传失败:' . $exception->getMessage());
} catch (\Throwable $exception) {
report($exception);
return $redirect->with('error', References::KINDS[$kind] . '上传失败,请检查文件格式后重新上传。');
}
return $redirect->with('success', sprintf('%s已更新:%s 条。', References::KINDS[$kind], number_format(count($rows))));
}
public function export(string $type, PageData $page, Exporter $exporter)
{
abort_unless(isset(Exporter::TYPES[$type]), 404);
$filters = $page->filters();
// 导出前必须先在聚工单核对条数、金额一致。
if (request('verified') !== '1') {
return redirect()->route('business.pages.show', [
'company_id' => company_id(), 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench',
] + array_diff_key($filters, ['decision' => true]))->with('error', '请先在聚工单按同样条件查询,核对条数和最终报销金额一致后,勾选「已核对」再导出。');
}
try {
$result = $page->build($filters);
$spreadsheet = $exporter->build($type, $result);
} catch (\Throwable $exception) {
report($exception);
abort(503, '聚工单镜像未就绪,未生成不完整的导出文件,请稍后重试。');
}
return response()->streamDownload(static function () use ($spreadsheet): void {
(new Xlsx($spreadsheet))->save('php://output');
}, $exporter->fileName($type, $result['summary']), [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
]);
}
public function saveRobot(Request $request, Robot $robot)
{
$robot->save([
'webhook' => (string) $request->input('webhook', ''),
'secret' => (string) $request->input('secret', ''),
'keyword' => (string) $request->input('keyword', ''),
'reporters' => (string) $request->input('reporters', ''),
'digest_webhook' => (string) $request->input('digest_webhook', ''),
'digest_secret' => (string) $request->input('digest_secret', ''),
'clear_digest' => $request->boolean('clear_digest'),
]);
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
}
/** 按发起人把取消 / 待复查通知发到钉钉群(须先勾选已与聚工单核对)。 */
public function notify(Request $request, PageData $page, Robot $robot)
{
$filters = $page->filters();
if ($request->input('verified') !== '1') {
return $this->back($request)->with('error', '请先在聚工单核对条数和金额一致,勾选「已核对」后再发通知。');
}
try {
$result = $page->build($filters);
$sent = $robot->sendNotices((int) company_id(), $filters['date'], $result['summary']['notices'], $request->boolean('force'));
} catch (\Throwable $exception) {
report($exception);
return $this->back($request)->with('error', '群通知发送失败:' . mb_substr($exception->getMessage(), 0, 120));
}
$message = sprintf('群通知:发送 %d 人,跳过已发 %d 人', $sent['sent'], $sent['skipped']);
if ($sent['failed'] > 0) {
$message .= ',失败 ' . $sent['failed'] . ' 人';
}
if ($sent['unmatched'] !== []) {
$message .= ';钉钉里没匹配到、未能 @ 的:' . implode('、', $sent['unmatched']);
}
return $this->back($request)->with($sent['failed'] > 0 ? 'error' : 'success', $message . '。');
}
private function back(Request $request)
{
return redirect()->route('business.pages.show', array_filter([
'company_id' => company_id(),
'section' => 'planting-data',
'page' => 'planting-reimbursement-workbench',
'date' => (string) $request->input('date', ''),
'paid_from' => (string) $request->input('paid_from', ''),
'scope' => (string) $request->input('scope', ''),
], static fn ($v) => $v !== ''));
}
}

View File

@ -0,0 +1,518 @@
<?php
namespace App\Http\Controllers\Business;
use App\Business\CompanyPlan\CompanyPlanRepository;
use App\Business\ServiceCompanyReconciliation\ServiceCompanyReconciliationRepository;
use App\Utilities\FinanceLedgerAccess;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
class ServiceCompanyReconciliation extends Controller
{
public function __construct(
private readonly ServiceCompanyReconciliationRepository $repository,
private readonly CompanyPlanRepository $companyPlanRepository,
) {
$this->middleware('auth');
$this->middleware('company.identify');
}
public function index(Request $request): View
{
$tenantId = (int) (company_id() ?: 1);
$period = $this->period($request);
$companyPlanSyncError = $this->syncCompanyPlan($tenantId);
$serviceCompanies = $this->repository->serviceCompanies($tenantId, $period);
return view('business.pages.financial-operations.service-company-reconciliation', [
'isDetail' => false,
'period' => $period,
'periodOptions' => $this->periodOptions(),
'serviceCompanies' => $serviceCompanies,
'serviceCompany' => null,
'relations' => [],
'settlements' => [],
'assignedPeople' => [],
'availablePeople' => [],
'storeCompanies' => [],
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
'fixedFeeRatePercent' => null,
'companyDirectory' => $this->repository->companyDirectory(),
'companyPlanSyncError' => $companyPlanSyncError,
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
'summary' => [
'companies' => count($serviceCompanies),
'people' => array_sum(array_column($serviceCompanies, 'people_count')),
'labor_cost' => array_sum(array_column($serviceCompanies, 'labor_cost')),
'settlement_amount' => array_sum(array_column($serviceCompanies, 'settlement_amount')),
'pending' => count(array_filter(
$serviceCompanies,
static fn (array $row): bool => in_array(
$row['reconciliation_status'],
['待生成', '待确认', '未配置'],
true,
),
)),
],
]);
}
public function show(Request $request, int $serviceCompany): View
{
$tenantId = (int) (company_id() ?: 1);
$companyPlanSyncError = $this->syncCompanyPlan($tenantId);
$company = $this->repository->serviceCompany($tenantId, $serviceCompany);
abort_if($company === null, 404);
$period = $this->period($request);
$allRelations = $this->repository->relations($tenantId, $serviceCompany);
$settlements = $this->repository->settlements($tenantId, $serviceCompany, $period);
$storeCompanyIncome = $this->repository->storeCompanyIncome($tenantId, $period);
$invoiceCompletion = $this->completionFilter($request, 'invoice_completion');
$paymentCompletion = $this->completionFilter($request, 'payment_completion');
$contractAttachments = $this->repository->contractAttachmentsForRelations(
$tenantId,
$serviceCompany,
array_map(static fn (array $relation): int => (int) $relation['id'], $allRelations),
);
$relations = array_values(array_filter(
$this->relationsWithSettlementState(
$allRelations,
$settlements,
$contractAttachments,
$storeCompanyIncome,
),
static function (array $relation) use ($invoiceCompletion, $paymentCompletion): bool {
if ($invoiceCompletion === 'unfinished' && $paymentCompletion === 'unfinished') {
return $relation['invoice_completion'] === 'unfinished'
|| $relation['payment_completion'] === 'unfinished';
}
return $relation['invoice_completion'] === $invoiceCompletion
&& $relation['payment_completion'] === $paymentCompletion;
},
));
$assignedPeople = $this->repository->assignedPeople($tenantId, $serviceCompany);
$availablePeople = array_values($this->repository->availablePeople($tenantId));
$periodStart = CarbonImmutable::createFromFormat('!Y-m', $period)->startOfMonth();
$periodEnd = $periodStart->endOfMonth();
$currentPersonKeys = array_column(
array_filter($assignedPeople, static fn (array $row): bool => $row['is_current']),
'person_key',
);
return view('business.pages.financial-operations.service-company-reconciliation', [
'isDetail' => true,
'period' => $period,
'periodOptions' => $this->periodOptions(),
'serviceCompanies' => [],
'serviceCompany' => $company,
'relations' => $relations,
'relationTotal' => count($allRelations),
'invoiceCompletion' => $invoiceCompletion,
'paymentCompletion' => $paymentCompletion,
'settlements' => $settlements,
'assignedPeople' => $assignedPeople,
'availablePeople' => $availablePeople,
'currentPersonKeys' => array_flip($currentPersonKeys),
'storeCompanies' => $this->repository->storeCompanies($tenantId),
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
'fixedFeeRatePercent' => ServiceCompanyReconciliationRepository::fixedFeeRatePercent(
(string) $company['service_type_code'],
),
'companyDirectory' => $this->repository->companyDirectory(),
'companyPlanSyncError' => $companyPlanSyncError,
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
'summary' => [
'people' => count($currentPersonKeys),
'labor_cost' => array_sum(array_column(
array_filter($assignedPeople, static fn (array $row): bool => $row['is_current']),
'salary',
)),
'stores' => count(array_filter(
$allRelations,
static fn (array $row): bool => $row['status'] === 'active'
&& $row['effective_from'] <= $periodEnd->toDateString()
&& ($row['effective_to'] === null
|| $row['effective_to'] >= $periodStart->toDateString()),
)),
'settlement_amount' => array_sum(array_column($settlements, 'service_fee')),
],
]);
}
/**
* @param list<array<string,mixed>> $relations
* @param list<array<string,mixed>> $settlements
* @param array<int,list<array<string,mixed>>> $contractAttachments
* @param array<string,float> $storeCompanyIncome
* @return list<array<string,mixed>>
*/
private function relationsWithSettlementState(
array $relations,
array $settlements,
array $contractAttachments,
array $storeCompanyIncome,
): array {
$settlementsByRelation = [];
foreach ($settlements as $settlement) {
$key = (string) $settlement['store_company_key'] . '|' . (string) $settlement['service_type_code'];
$settlementsByRelation[$key] = $settlement;
}
return array_map(static function (array $relation) use (
$settlementsByRelation,
$contractAttachments,
$storeCompanyIncome,
): array {
$key = (string) $relation['store_company_key'] . '|' . (string) $relation['service_type_code'];
$settlement = $settlementsByRelation[$key] ?? null;
$incomeAmount = (float) ($storeCompanyIncome[(string) $relation['store_company_key']] ?? 0);
$calculatedSettlementAmount = round($incomeAmount * (float) $relation['fee_rate'], 2);
$invoiceCompleted = $settlement !== null
&& in_array((string) $settlement['invoice_status'], ['invoiced', 'waived'], true);
$paymentCompleted = $settlement !== null
&& (string) $settlement['payment_status'] === 'paid';
return [
...$relation,
'period_settlement_id' => $settlement['id'] ?? null,
'income_amount' => $incomeAmount,
'settlement_amount' => $settlement !== null
? (float) $settlement['service_fee']
: $calculatedSettlementAmount,
'invoice_status' => $settlement['invoice_status'] ?? null,
'payment_status' => $settlement['payment_status'] ?? null,
'invoice_completion' => $invoiceCompleted ? 'completed' : 'unfinished',
'payment_completion' => $paymentCompleted ? 'completed' : 'unfinished',
'contract_attachments' => $contractAttachments[(int) $relation['id']] ?? [],
];
}, $relations);
}
private function completionFilter(Request $request, string $key): string
{
$value = (string) $request->query($key, 'unfinished');
return in_array($value, ['completed', 'unfinished'], true) ? $value : 'unfinished';
}
public function storeCompany(Request $request): RedirectResponse
{
$this->authorizeEdit();
$validated = $this->validateCompany($request);
$company = $this->repository->saveServiceCompany(
(int) (company_id() ?: 1),
$validated,
(string) user()->name,
);
return redirect()
->route('business.service-company-reconciliation.show', [
'serviceCompany' => $company['id'],
])
->with('success', '服务公司已登记。');
}
public function updateCompany(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $this->validateCompany($request);
$this->repository->saveServiceCompany(
(int) (company_id() ?: 1),
$validated,
(string) user()->name,
$serviceCompany,
);
return back()->with('success', '服务公司信息已更新。');
}
public function storeRelation(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $this->validateRelation($request);
$this->repository->saveRelation(
(int) (company_id() ?: 1),
$serviceCompany,
$validated,
(string) user()->name,
);
return back()->with('success', '店铺公司结算关系已保存。');
}
public function updateRelation(
Request $request,
int $serviceCompany,
int $relation,
): RedirectResponse {
$this->authorizeEdit();
$validated = $this->validateRelation($request);
$this->repository->saveRelation(
(int) (company_id() ?: 1),
$serviceCompany,
$validated,
(string) user()->name,
$relation,
);
return back()->with('success', '店铺公司结算关系已更新并生成新版本。');
}
public function storeRelationAttachment(
Request $request,
int $serviceCompany,
int $relation,
): RedirectResponse {
$this->authorizeEdit();
$validated = $request->validate([
'attachment' => ['required', 'file', 'mimes:pdf,jpg,jpeg,png,webp,doc,docx', 'max:20480'],
'period' => ['required', 'date_format:Y-m'],
'invoice_completion' => ['nullable', 'in:completed,unfinished'],
'payment_completion' => ['nullable', 'in:completed,unfinished'],
]);
$tenantId = (int) (company_id() ?: 1);
$file = $validated['attachment'];
$originalName = mb_substr(basename((string) $file->getClientOriginalName()), 0, 255);
$extension = strtolower((string) $file->getClientOriginalExtension());
$disk = Storage::disk('uploads');
$directory = sprintf(
'service-company-contracts/%d/%d/%d',
$tenantId,
$serviceCompany,
$relation,
);
$filename = Str::uuid()->toString() . ($extension !== '' ? '.' . $extension : '');
$path = $disk->putFileAs($directory, $file, $filename);
if (! is_string($path) || $path === '') {
throw new \RuntimeException('合同附件保存失败,请稍后重试。');
}
try {
$this->repository->saveContractAttachment(
$tenantId,
$serviceCompany,
$relation,
[
'original_name' => $originalName,
'path' => $path,
'mime_type' => $file->getMimeType() ?: 'application/octet-stream',
'size' => (int) $file->getSize(),
],
(string) user()->name,
);
} catch (Throwable $exception) {
$disk->delete($path);
throw $exception;
}
return redirect()
->route('business.service-company-reconciliation.show', [
'serviceCompany' => $serviceCompany,
'period' => $validated['period'],
'tab' => 'relations',
'invoice_completion' => $validated['invoice_completion'] ?? 'unfinished',
'payment_completion' => $validated['payment_completion'] ?? 'unfinished',
])
->with('success', '合同附件已上传。');
}
public function relationAttachment(
int $serviceCompany,
int $relation,
int $attachment,
): StreamedResponse {
$tenantId = (int) (company_id() ?: 1);
$file = $this->repository->contractAttachment(
$tenantId,
$serviceCompany,
$relation,
$attachment,
);
abort_if($file === null, 404);
$disk = Storage::disk('uploads');
abort_unless($disk->exists((string) $file['path']), 404, '合同附件不存在。');
return $disk->response((string) $file['path'], (string) $file['original_name'], [
'Cache-Control' => 'private, no-store',
'Content-Type' => (string) ($file['mime_type'] ?: 'application/octet-stream'),
'X-Content-Type-Options' => 'nosniff',
]);
}
public function assignPerson(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $request->validate([
'person_key' => ['required', 'string', 'max:191'],
'effective_from' => ['required', 'date_format:Y-m-d'],
]);
$this->repository->assignPerson(
(int) (company_id() ?: 1),
$serviceCompany,
$validated['person_key'],
$validated['effective_from'],
(string) user()->name,
);
return back()->with('success', '人员归属已保存。');
}
public function endPerson(Request $request, int $serviceCompany, int $assignment): RedirectResponse
{
$this->authorizeEdit();
$validated = $request->validate([
'effective_to' => ['required', 'date_format:Y-m-d'],
]);
$this->repository->endPersonAssignment(
(int) (company_id() ?: 1),
$serviceCompany,
$assignment,
$validated['effective_to'],
);
return back()->with('success', '人员归属已结束。');
}
public function generateSettlements(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $request->validate([
'period' => ['required', 'date_format:Y-m'],
]);
$result = $this->repository->generateSettlements(
(int) (company_id() ?: 1),
$serviceCompany,
$validated['period'],
(string) user()->name,
);
$message = "已生成 {$result['generated']} 条结算预览。";
if ($result['errors'] !== []) {
$message .= ' 未生成:' . implode(';', array_slice($result['errors'], 0, 5));
}
return redirect()
->route('business.service-company-reconciliation.show', [
'serviceCompany' => $serviceCompany,
'period' => $validated['period'],
'tab' => 'relations',
])
->with($result['generated'] > 0 ? 'success' : 'error', $message);
}
public function updateSettlement(
Request $request,
int $serviceCompany,
int $settlement,
): RedirectResponse {
$this->authorizeEdit();
$validated = $request->validate([
'action' => ['nullable', 'in:confirm,save'],
'invoice_status' => ['nullable', 'in:pending,partial,invoiced,waived'],
'invoice_amount' => ['nullable', 'numeric', 'min:0'],
'payment_status' => ['nullable', 'in:pending,partial,paid'],
'paid_amount' => ['nullable', 'numeric', 'min:0'],
'notes' => ['nullable', 'string', 'max:1000'],
]);
$this->repository->updateSettlement(
(int) (company_id() ?: 1),
$serviceCompany,
$settlement,
$validated,
(string) user()->name,
);
return back()->with('success', '开票与到账状态已更新。');
}
private function period(Request $request): string
{
$period = trim((string) $request->query('period', ''));
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1) {
return $period;
}
return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
}
/** @return list<array{value:string,label:string}> */
private function periodOptions(): array
{
$current = CarbonImmutable::now()->startOfMonth();
return collect(range(0, 11))->map(static function (int $monthsAgo) use ($current): array {
$month = $current->subMonthsNoOverflow($monthsAgo);
return [
'value' => $month->format('Y-m'),
'label' => $month->format('Y年n月'),
];
})->all();
}
private function authorizeEdit(): void
{
abort_unless(FinanceLedgerAccess::canEditMapping(user()), 403, '当前账号没有维护服务公司对账的权限。');
}
private function syncCompanyPlan(int $tenantId): ?string
{
try {
$rows = $this->companyPlanRepository->serviceCompanyRows($tenantId);
$this->repository->syncCompanyPlanServiceCompanies($tenantId, $rows);
return null;
} catch (\Throwable $exception) {
report($exception);
return '公司盘点服务公司同步暂时失败,当前先显示已登记的服务公司。';
}
}
/** @return array<string,mixed> */
private function validateCompany(Request $request): array
{
return $request->validate([
'company_name' => ['required', 'string', 'max:200'],
'unified_social_credit_code' => ['nullable', 'string', 'max:64'],
'service_type_code' => ['required', 'in:' . implode(',', array_keys(
ServiceCompanyReconciliationRepository::SERVICE_TYPES,
))],
'taxpayer_type' => ['nullable', 'string', 'max:64'],
'business_registration_type' => ['nullable', 'string', 'max:64'],
'company_status' => ['nullable', 'in:正常,注销中,已注销'],
'planning_target_amount' => ['nullable', 'numeric', 'min:0'],
'status' => ['required', 'in:active,inactive'],
'notes' => ['nullable', 'string', 'max:500'],
]);
}
/** @return array<string,mixed> */
private function validateRelation(Request $request): array
{
return $request->validate([
'store_company_key' => ['required', 'string', 'max:191'],
'base_metric' => ['required', 'in:' . implode(',', array_keys(
ServiceCompanyReconciliationRepository::BASE_METRICS,
))],
'fee_rate_percent' => ['required', 'numeric', 'min:0', 'max:100'],
'effective_from' => ['required', 'date_format:Y-m-d'],
'effective_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:effective_from'],
'contract_no' => ['nullable', 'string', 'max:64'],
'contract_status' => ['required', 'in:pending,stamped,waived'],
'status' => ['required', 'in:active,inactive'],
'notes' => ['nullable', 'string', 'max:500'],
]);
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\ShippingMeasuredWeightImporter;
class ShippingMeasuredWeights extends Controller
{
public function import(Request $request, ShippingMeasuredWeightImporter $importer): RedirectResponse
{
$request->validate([
'measured_weight_file' => ['required', 'file', 'mimes:xlsx', 'max:10240'],
], [], ['measured_weight_file' => '称重重量表']);
$result = $importer->import(
$request->file('measured_weight_file')->getRealPath(),
(int) company_id(),
(int) $request->user()->id,
);
return back()->with('shipping_measured_weight_message', "已读取 {$result['source_rows']} 行,保存 {$result['keys']} 条快递和条码的称重重量记录。");
}
}

View File

@ -7,6 +7,8 @@ use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\SupplierNegativeAlertDingTalkWorkflow;
use Modules\EcommerceFinance\View\SupplierNegativeAlertPageData;
use RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
class SupplierNegativeAlertDingTalkActions extends Controller
@ -44,6 +46,7 @@ class SupplierNegativeAlertDingTalkActions extends Controller
'supplier' => ['nullable', 'string', 'max:191'],
'checker' => ['nullable', 'string', 'max:191'],
'settlement_method' => ['nullable', 'string', 'max:191'],
'handling' => ['nullable', 'in:,pending'],
]);
$purchaser = trim((string) ($data['purchaser'] ?? ''));
$filters = [
@ -52,6 +55,7 @@ class SupplierNegativeAlertDingTalkActions extends Controller
'checker' => (string) ($data['checker'] ?? ''),
'settlement_method' => (string) ($data['settlement_method'] ?? ''),
'purchaser' => $purchaser,
'handling' => (string) ($data['handling'] ?? ''),
];
$filteredRows = $this->pageData->rowsForFilters([
...$filters,
@ -113,4 +117,64 @@ class SupplierNegativeAlertDingTalkActions extends Controller
return back()->with('success', "已发送至{$result['group_name']}:采购 {$purchaser},"
. "{$result['supplier_count']} 家供应商、{$result['row_count']} 条预警。");
}
public function export(Request $request): StreamedResponse
{
$data = $this->pageData->exportData($request->query());
$fields = array_values(array_filter(
(array) ($data['fields'] ?? []),
static fn (array $field): bool => ($field['name'] ?? '') !== 'company',
));
$fields[] = ['name' => 'handling_result_meta', 'label' => '回传信息', 'type' => 'text'];
$rows = (array) ($data['rows'] ?? []);
$filters = (array) ($data['filters'] ?? []);
$period = trim((string) ($filters['month'] ?? '')) ?: '全部月份';
$filename = '供应商负数预警_' . $period . '_' . now()->format('Ymd_His') . '.csv';
return response()->streamDownload(function () use ($fields, $rows): void {
$stream = fopen('php://output', 'w');
if ($stream === false) {
throw new RuntimeException('无法创建供应商负数预警导出文件。');
}
fwrite($stream, "\xEF\xBB\xBF");
fputcsv($stream, array_map(
static fn (array $field): string => (string) ($field['label'] ?? ''),
$fields,
));
foreach ($rows as $row) {
$values = [];
foreach ($fields as $field) {
$name = (string) ($field['name'] ?? '');
$value = $row[$name] ?? '';
if ($name === 'handling_result' && trim((string) $value) === '') {
$value = '采购未回传';
} elseif (is_array($value)) {
$value = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$values[] = $this->csvCell($value);
}
fputcsv($stream, $values);
}
fclose($stream);
}, $filename, [
'Content-Type' => 'text/csv; charset=UTF-8',
'Cache-Control' => 'private, no-store',
]);
}
private function csvCell(mixed $value): string
{
$text = trim((string) $value);
if ($text === '' || is_numeric($text)) {
return $text;
}
if (preg_match('/^\d{12,}$/', $text) === 1) {
return "'" . $text;
}
return preg_match('/^[=+@\t\r]/u', $text) === 1 ? "'" . $text : $text;
}
}

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