Compare commits

...

280 Commits

Author SHA1 Message Date
5633ed2430 安全整合存量报价计费规则与独立成本价观测 (#410) 2026-10-20 19:08:47 +08:00
d68548646d 修复多人发布并发覆盖及旧客户端绕过保护 (#409) 2026-10-20 18:13:01 +08:00
chenxi
0ec6f703fe 商品成本:移除两个筛选复选框,默认全部数据展示
- 去掉「只看未匹配商品单价」「包含-不看仓」两个复选框
- 页面与导出默认展示全部行:已匹配/未匹配单价、含「-不看」仓全部纳入
- 汇总卡片按全部口径统计,移除「已隐藏的-不看仓行数」
2026-10-20 17:46:34 +08:00
a317ab9dea 供应商对账:比对汇总改按我方商品编码匹配 (#408)
对照我方货款对账的商品编码匹配厂家条码,页面、CSV导出和钉钉通知统一切换。
2026-10-20 17:45:55 +08:00
db08b2c264 供应商对账:新增财务比对汇总导出 (#407)
财务端比对明细新增CSV导出,包含筛选汇总和完整比对结果。
2026-10-20 17:29:46 +08:00
chenxi
32cd0d0a15 商品成本:常州简尚家居有限公司的仓库简称对应映射表「配件单仓」行
业务确认:仓储方=常州简尚家居有限公司 / 仓库=配件单仓 → 简称=配件单仓-不看。
仓库简称匹配增加这一档:主仓行 → 同名仓库 → 配件单仓行(仅在没有前两者时使用)。
2026-10-20 17:15:49 +08:00
8162afa969 供应商对账:财务比对筛选与分页优化 (#406)
财务端增加供应商精确搜索、比对明细吸顶表头和每页15条分页。
2026-10-20 17:03:27 +08:00
chenxi
bcb29aac1c 商品成本:仓库简称只认映射表里「仓储方 + 主仓」那条
发货仓库是聚水潭仓储方级别的名称,映射表里同一仓储方下还有次品仓/销退仓/配件单仓等行,
之前无主仓行时会兜底取到这些行的简称(如常州简尚家居有限公司→退货报废-不看),
把主仓发货误判成不看仓。改为:仓储方匹配仓库名含「主仓」的行的简称;
没有主仓行时只接受「仓库名=仓储方名」的同名仓库,不再兜底次品/销退行。
2026-10-20 15:19:32 +08:00
d1b751c79c 业绩明细:补齐拼多多退款支付立减备注并延长联动缓存 2026-10-20 15:14:55 +08:00
chenxi
fce31f0c09 商品成本:种菜金额有数据的账单行整条排除
账单侧按业绩明细取数时,除「收入金额有数据且不为 0」外,再排除 planting_amount > 0 的账单行
(种菜订单整条不参与商品成本匹配),页面口径说明同步补充。
2026-10-20 14:12:19 +08:00
acad1f4577 修复业绩明细日期前缀串单并增加防碰撞匹配 2026-10-20 14:01:26 +08:00
ad8da1264d 供应商对账:按采购单号日期条码核对数量金额 (#405)
厂家账单改为按采购单号+日期+条码匹配,逐项比较双方数量、单价和金额,页面与钉钉通知明确展示厂家多算或少算。
2026-10-20 13:44:00 +08:00
6470346392 修复账单覆盖校验日期边界 2026-10-20 13:26:20 +08:00
f08c600961 合并京东钱包每日账单同步修复 2026-10-20 13:19:37 +08:00
144937bfa3 补齐京东钱包每日账单同步并增加覆盖校验 2026-10-20 12:20:13 +08:00
chenxi
5fe92bd05c 商品成本:订单侧不取套餐/服务占位编码 TCXJ、FUWU
订单原始数据里的 TCXJ(套餐)、FUWU(服务)不是实物商品,商品成本同步时直接剔除
(SQL 层过滤 + 组合装拆出的组件里同样剔除),页面口径说明同步补充。
2026-10-20 11:53:03 +08:00
81bf2bd779 供应商对账:厂家端隐藏上传记录并调整内部位置 (#404)
厂家门户隐藏最近上传摘要;内部厂家端上传记录保留并移动到页面底部。
2026-10-20 11:39:20 +08:00
cad8369fdb 业绩明细:新增1688红包补贴备注并优化筛选统计 2026-10-20 11:28:53 +08:00
2a2df7451e 供应商对账:退货表格改为十条并固定表头 (#403)
退货表格调整为每页十条,并增加固定高度滚动区和吸顶表头。
2026-10-20 11:21:22 +08:00
chenxi
5e05a8728e 商品成本:未匹配单价统计排除「数量与单价口径不一致」行,避免两处重复计数 2026-10-20 11:19:53 +08:00
chenxi
6b044e727b 商品成本:单价增加「普通商品资料成本价」第三档兜底
取价顺序改为:商品月加权平均单价(仓库简称+商品编码)→ 线上代发价格(采购单价/钉钉代发单价)
→ 普通商品资料(operations_replica.rpt.jst_sku)里的商品成本价(sku_type=normal 且成本价>0)。
页面汇总新增「其中用商品资料成本价兜底」,同步命令日志同步输出三档兜底行数。

7 月未匹配单价行数 3,599→2,098(资料成本价补 1,071 行),8 月 2,713→2,765(含数据重跑差异)。
2026-10-20 11:16:56 +08:00
145a62c397 供应商对账:增加发货日期范围筛选 (#402)
内部厂家端和厂家门户增加日期面板与近7天、本月、上月、全部日期快捷筛选。
2026-10-20 11:00:43 +08:00
21b29d06eb 种菜未报销排除种菜明细已报销订单 2026-10-20 11:03:06 +08:00
ffa4bbf15f 业绩明细新增种菜未报销列 2026-10-20 10:55:41 +08:00
75aac2e5aa 供应商对账:厂家端退货汇总改为件数与金额 (#401)
内部厂家端和厂家门户改为大号退货件数、退货金额及确认状态卡片,汇总不再显示行数。
2026-10-20 10:50:08 +08:00
0104b9b18e 供应商对账:内部可搜索厂家并隔离厂家名称 (#400)
内部厂家端改为可搜索且精确匹配供应商名称;厂家账号仅能上传和查看自己绑定的供应商数据。
2026-10-20 10:35:54 +08:00
4511f6c71a 业绩明细新增种菜报销列 2026-10-20 10:36:24 +08:00
cdabffb3a6 业绩明细删除费用项列及相关归集逻辑 2026-10-20 10:20:55 +08:00
4e174963e8 fix(种菜损耗): 透明挂钩/虚拟条码整单不扣款;拍A发B 从种菜报销直接挑出发运营
财务确认(2026-10-20):种菜损耗是查种菜报销的单有没有真实发出有价值的货——
- 发货数据中交易单号下出现信誉订单虚拟条码或透明挂钩(含条形码 GG 开头)即整单不扣款;
- 任务备注/卖家备注含拍A发B/拍A发A 的不扣款,且无论是否匹配到发货都从种菜报销中挑出发运营;
- “导出拍A发B(发运营)”直接按「种菜报销」页字段输出;其余真实发货的单按成本价×数量+运费扣款。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
2026-10-20 10:10:29 +08:00
9b6c3d2477 业绩明细排除京东网银钱包账户数据 2026-10-20 10:00:55 +08:00
366dcc1da7 业绩明细新增费用项并按科目映射费用备注归集 2026-10-20 10:00:53 +08:00
56909bd669 货款对账:每页固定展示15条数据 (#399) 2026-10-20 09:48:25 +08:00
19bb6a8a75 退货对账:每页固定展示15条数据 (#398) 2026-10-20 09:33:20 +08:00
dd9cab671b 合并业绩明细万元显示与口径说明整理 2026-10-20 09:32:52 +08:00
1acd97b9e0 业绩明细:金额改为万元并整理指标口径说明
金额构成统一按万元显示两位小数并逐项标注万;长口径说明拆为匹配口径、金额字段、差额判定、匹配原因四组,完整规则默认折叠。
2026-10-20 09:32:42 +08:00
c0cc8c7e60 供应商对账:同步退货转物流记账归属 (#397) 2026-10-20 09:21:55 +08:00
bf290d5353 fix(种菜损耗): 交易单号下含信誉订单虚拟条码的整单不扣款
10 月生产数据里,部分种菜单的交易单号在发货数据中与大量合并发货的别的订单商品挂在一起(同一交易单号下几十个实物+信誉订单虚拟条码),
被错算为扣款。财务确认信誉订单虚拟条码不扣款:该单号下出现信誉订单虚拟条码(X00006/X00002)即整单归入不扣款;
“晒图有奖励(无实物)”等无实物商品也不计扣款。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
2026-10-20 08:53:17 +08:00
31f6c72bf3 优化订单与账单镜像分批读取及内存释放 2026-10-19 21:04:42 +08:00
bbb967e110 降低业绩匹配任务峰值内存 2026-10-19 19:08:39 +08:00
a6e0b2ac7d 业绩明细汇总拆开复杂差额规则
月度汇总先按默认差额聚合,只有实收/应付兜底行再计算完整差额原因。7月验证结果一致,汇总耗时由约3.49秒降到0.71秒。
2026-10-19 18:24:13 +08:00
8e4bf99483 优化京东账单首次汇总与候选查询的覆盖索引 2026-10-19 18:14:37 +08:00
d735de7864 修复发布冷缓存时店铺筛选退回大范围扫描 2026-10-19 18:07:12 +08:00
e4d82dab2a chore(部署): 发布前拦截会覆盖线上已发布提交的版本
今天连续发生多次热修复/旧版本发布把别人刚上线的改动冲掉(种菜损耗运费口径被撤回两次)。
发布脚本读取线上 .deployed-sha 后:本地没有该提交先 git fetch 再判断;线上提交不是本次发布版本的祖先时直接拒绝(服务器不做任何变更);
新增 -AllowRollback / --allow-rollback 仅供负责人决定撤回时使用。AGENTS.md 第 8 节补充热修复须基于线上版本并立即合入 main。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
2026-10-19 18:00:07 +08:00
17429d65ab perf(财务): 减少大表扫描与重复重算,串行受限导出 2026-10-19 17:53:14 +08:00
a124e9906b 业绩明细收入统一按科目映射表判桶
账单明细页已优先使用科目映射表,但业绩同步的收入仍优先取旧总账备注表,导致两套口径冲突。改为收入、优惠、冲减、退款统一使用当前科目映射表,旧表仅在当前映射缺失时兜底。
2026-10-19 17:28:31 +08:00
4c617fd063 fix(种菜损耗): 扣款金额改为 成本价×数量 + 该单发货运费
财务更正口径:种菜损耗扣款 = Σ 发货条码在普通商品资料的成本价 × 数量 + 该订单在发货数据中的运费合计,
不再按成本价×1.2;运费为空的订单标"运费缺失",缺失部分不计入扣款金额。

涉及:金额计算展示(只读);不涉及迁移、权限和上游写入。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
2026-10-19 16:46:46 +08:00
528701fdec 附加费结算导入核验:只填单号+类型,自动匹配快递并按报价核算 (#391) 2026-10-19 16:44:50 +08:00
chenxi
e0abc6732b 商品成本:拆单订单有子单时只取子单,避免主单与子单重复计
聚水潭拆单后主单保留原始下单行、子单才是实际发货行;之前按「商品+数量+金额+仓库」去重,
主单 10 件与子单各 1 件键不同,会重复累加。改为:有子单时只取子单(按 o_id+oi_id 去重),
整单没有子单才用主单;再按「发货仓库 + 商品编码」汇总数量。

回归样例 5122123095012119232:31202C 计 10 件(10 个子单各 1 件)、DNZ032916N887V01 计 10 件。
2026-10-19 16:31:16 +08:00
aaron
c44d267902 chore(部署): 增加财务台账每日同步 cron 2026-10-19 16:07:32 +08:00
aaron
02d21ce9ac feat(财务台账): 新增财务台账模块与 rpt 取数 2026-10-19 16:06:55 +08:00
eec820bfc5 修复1688多店铺前缀收入漏取
同一平台多个店铺名前缀应使用 OR 命中;原实现把阿里巴巴、1688、新佰广三个 LIKE 用 AND 连接,导致1688店铺的订单收入账单行被排除。新增多前缀回归测试。
2026-10-19 15:35:30 +08:00
424311a441 财务经营风险管控:「流程统计」页面及菜单改名为「店铺流程」 2026-10-19 15:18:28 +08:00
79f6937e75 字段查询页去掉重复的页面标题栏和多余的列设置条
- 移除页面内重复的「页面名 + 查询与导出说明」标题块(顶部已有页面标题和已打开页面标签)
- 这类页面筛选条件里本来就有「筛选字段」,隐藏脚本额外注入的「列设置」条
2026-10-19 15:06:40 +08:00
1f4f6f48d4 优化财务资源:减少重复扫描、隔离重型任务、约束系统日志 (#390) 2026-10-19 14:56:54 +08:00
eb0f246765 财务经营风险管控:网页端不再重复显示目录页签
- 目录内页签(店铺违规信息预警/预览统计/流程统计)只在钉钉单页入口(?focus=1 或钉钉 UA)显示
- 网页端已有左侧菜单和已打开页面标签栏,页面内只保留内容本身
- 单页模式判断抽到 FocusMode,与布局共用
2026-10-19 14:56:08 +08:00
9e199243b6 合并已上线的 hotfix:科目映射表保存后自动重跑业绩明细(cbbf32bb) 2026-10-19 14:47:36 +08:00
74906ac5f6 侧边栏常用网址:新增工作平台、预策、由壹点「脉象」 2026-10-19 14:45:37 +08:00
ea479733ab feat(种菜数据汇总): 接入聚工单种菜报销,新增种菜损耗扣款页面
- 种菜报销:复用已登记镜像 jiansun.dbo.jst_workOrderInfo,工单类型“种菜报销”、状态已完成,
  按完成时间归属报销月份(M 月 = [M-02 00:00, M+1-02 00:00)),自 2026-09-02 起;同一工单只取最新一版
- 种菜损耗:当月种菜报销的线上订单号匹配上月+本月发货数据(jst_oms_shipping)交易单号;
  任务备注/卖家备注含“拍A发B/拍A发A”的不扣款(单独导出发运营),只发信誉订单虚拟条码/透明挂钩的不扣款,
  其余按发货条码在普通商品资料(ops_jst_sku)的成本价 × 数量 × 1.2 扣款,成本价缺失单独提示
- 两页均支持筛选、列设置、CSV 导出;按月缓存 10 分钟
- 测试:窗口口径、免扣字样、虚拟条码/挂钩、成本价取数与缺失、页面筛选和导出

涉及:金额计算展示(只读);不涉及数据库迁移、权限模型和上游写入。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
2026-10-19 14:37:09 +08:00
566a3ef4db 登录后固定进入首页,不再回跳上次打开的业务页面
- 账号密码登录与钉钉免登都忽略 url.intended,直接进 landing_page(首页/财务驾驶舱)
- 补充登录落地测试,修正首页改版后仍按旧行为断言的测试
2026-10-19 14:26:10 +08:00
9f4f4f0cbb 科目映射表:新增费用备注列并回填费用备注数据 2026-10-19 14:24:42 +08:00
cbbf32bb5c 科目映射表保存后自动重跑业绩明细
映射表保存、删除、恢复、导入和重置后,自动把受影响平台已存在的月份排入后台队列;后台按平台×月份逐个独立进程重跑,数据库锁防重复,生产 cron 每分钟兜底。保存响应直接提示排队任务数。
2026-10-19 14:22:43 +08:00
664fc05faf 首页改为财务驾驶舱骨架,并加入常用网址入口
- 首页不再展示业务目录:改为财务驾驶舱(本月收入/支出/毛利/毛利率/应收/应付 + 趋势 + 风险预警位置),指标待接入
- 侧边栏常用网址:新增聚水潭,搜索框右侧书签入口展示
- 更新首页相关测试
2026-10-19 14:15:27 +08:00
chenxi
9b2edfe1de 商品成本:组合装按子订单拆成组件行
聚水潭组合装 sku 形如 ZH-<条码>-<数量>-<条码>-<数量>,之前整包按一个商品行列出,
月加权/代发价都匹配不到。现在按组件拆分:一个订单有几个发货仓库、商品编码、数量就分开列,
组件数量 = 明细数量 × 组件倍数;解析不了的(条码被截断等)保持原样。
组件行的明细金额按整包处理,不参与「数量×单价 vs 明细金额」校验。
2026-10-19 14:06:56 +08:00
0cb970eeec 业绩明细备注:京喜「订单实付取供货价」证据按活动代过滤——修复多代账单把直营服务费算两倍,导致 9 月 4.4 万行误落差额待核实(修复后 9 月 44897→1245 行) 2026-10-19 13:45:50 +08:00
chenxi
5fdd3bba17 科目映射规则加进程内缓存,修复业绩明细逐行重查规则表
业绩明细同步里每一行账单都会调用 AccountMappingMatcher,而 match() 每次都走
AccountMappingStore::all() 重新 SELECT 整张规则表;9 月得物 3.6 万行要跑近半小时。
改为进程内静态缓存(写入 create/update/importRows 时清空),行为不变,单平台同步回到 1-2 分钟。
2026-10-19 13:19:25 +08:00
87788d87ff fix(发货数据): 快递名称以出库单/发货明细当前值为准,发货数据视图仅兜底
- 聚水潭换单、改快递公司后,出库单、发货明细、订单的快递公司都会更新(如 崔桥顺丰干配→常州德邦、德邦快递→申通E物流),
  工作平台随之显示新值;发货数据视图的 expressName 却停在旧值。此前优先取视图,9 月 111 个包裹快递名称与工作平台不一致。
- 改为:快递名称取出库单/发货明细当前值,视图只在两者都没有时兜底;仓库仍按视图 wareHoursName。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf
2026-10-19 11:56:56 +08:00
13d54d0c76 fix(厂家记账): 配置表中没有的供应商按可扣款处理
财务更正口径:厂家记账配置表中没有的供应商(含配置不在生效期内)视同正常记账,作为厂家扣款项;
取消“待配置”判定。工单未带供应商、或多供应商判定不一致的仍为“待确认”,不计入扣款。

涉及:扣款金额汇总口径;无数据库变更。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JouFR6TJ7vGscRJanYScEo
2026-10-19 11:19:27 +08:00
b22eb61541 侧边栏:搜索框右侧增加常用网址入口
- 搜索框右侧新增书签按钮,点开显示 config/sidebar_links.php 中配置的网址,新标签页打开
- 未配置时给出去哪里加的提示
- 补充导航测试
2026-10-19 11:13:49 +08:00
efb6d9c992 业绩明细备注:京喜拆单/合并单货款含直营服务费正差与分位尾差归因 2026-10-19 11:07:29 +08:00
a3b36b1fb6 店铺维度报表销量改为收入+优惠+冲减+退款合计 (#389) 2026-10-19 10:47:29 +08:00
9d8133cc73 登录后进入首页导航,不再直接打开第一个业务页面
- 新增首页导航页:常用分组沿用侧边栏分组,下面是全部业务模块(可展开)
- Pages@home 由跳转首个业务页改为渲染首页;侧边栏分组定义抽到 SidebarMenu 复用
- 侧边栏顶部标识可点回首页
- 更新钉钉登录落地断言,补充首页导航测试
2026-10-19 10:42:16 +08:00
09b4ffcb8a 供应商应付-厂家记账:新增厂家记账配置并按配置判定厂家扣款
- 新增配置表 business_supplier_bookkeeping_configs(+ 操作日志表),迁移时导入财务提供的 209 家存量配置
- 记账方式:正常记账 / 仅代发仓发错货记账 / 不记账,支持生效期;配置页支持新增、编辑、删除恢复、Excel 导入导出
- 扣款判定:厂家记账按供应商配置,仅正常记账扣款;仓库记账仅订单发货仓库为代发仓且二级原因含“仓库发错货”时作为厂家扣款项,其余不扣
- 未配置/生效期外显示待配置,多供应商判定不一致显示待确认,均不计入扣款金额
- 明细页新增厂家扣款判定筛选、扣款工单数与扣款金额指标、导出列

涉及:数据库迁移(新建配置表并写入存量配置)、金额汇总展示;不涉及上游写入和权限模型。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JouFR6TJ7vGscRJanYScEo
2026-10-19 10:38:36 +08:00
68b16a95c0 业绩明细备注:京喜「直营补贴款」覆盖扩至全部京喜自营工厂店(按实付≈商品金额/供货价特征自动识别,10 家已核验店沿用名单;待核实负差消除) 2026-10-19 09:34:57 +08:00
bcbb9e72af fix(发货数据): 每晚重拉最近 40 天,并清除上游已作废的出库/采购退货包裹
- 聚水潭常在发货后数天到数周内换单/改快递公司(如崔桥顺丰干配→常州德邦、德邦→申通E物流)、作废采购退货出库;
  原先每天只重拉最近 3 天,上月数据停在旧值:9 月 111 个包裹快递名称与工作平台不一致,14 个已作废的采购退货单仍在。
- 01:28 定时同步改为最近 40 天(覆盖上月结算期),07:28 仍补拉最近 3 天。
- 窗口重跑时,出库单兜底/采购退货出库包裹若本次完整扫描中已不存在(作废/换单),直接删除;扫描为空时不删。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf
2026-10-19 09:31:17 +08:00
ed58e8ef43 供应商应付:新增厂家记账,接入聚工单记账工单(2026-09-01 起)
- 复用已登记镜像 jiansun.dbo.jst_workOrderInfo,不新增上游链路
- 口径与聚工单「记账」视图一致:工单类型“记账”,状态待审核/已拒绝/待处理/处理中/已完成,
  记账原因为厂家记账 12 项 + 仓库记账 5 项二级原因,发起时间 >= 2026-09-01;同一工单只取最新一版
- 新页面 供应商应付 → 厂家记账:筛选、记账金额合计、列设置、CSV 导出;首次同步未完成时明确提示
- 镜像索引迁移 (woTypeId, created, Id)

涉及:金额展示(只读)、镜像索引迁移;不涉及权限模型和上游写入。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N5KQeRJaLrbJY9iKNC5veV
2026-10-18 22:27:16 +08:00
b2dd1e5e6b 报价管理:修复列设置后筛选翻页表头与内容错位 (#388) 2026-10-18 14:25:25 +08:00
e428cf5de2 报价历史:支持勾选并批量审核通过 (#387) 2026-10-18 14:05:40 +08:00
2d30aea624 报价管理:移除列表黄色分组说明行 (#386) 2026-10-18 13:29:18 +08:00
409da4cae8 feat: 提现管理余额日期改为下拉选择 2026-10-18 12:09:42 +08:00
da794c3ddb feat: 提现管理支持按余额日期筛选并长期保留每日余额 2026-10-18 11:52:02 +08:00
b49d23d090 供应商配件运费:外采快递不扣款 (#385) 2026-10-17 21:49:09 +08:00
23887059f1 多时期补录保留选定快递网点编号 (#384) 2026-10-17 21:09:11 +08:00
10d9c22e3e 报价执行期间冲突显示明确错误提示 (#383) 2026-10-17 21:02:31 +08:00
bd39a7fdda 存量报价支持多时期导入、快递分组及按日期查看 (#382) 2026-10-17 20:58:04 +08:00
077701d24a 供应商应付:新增新河北仓、曹县仓配件运费扣除明细 (#381) 2026-10-17 20:54:13 +08:00
d24eefb687 补全工作平台供应商管理字段同步和展示 (#380) 2026-10-17 13:12:52 +08:00
3638a8cee9 货款对账:差异支持勾选多条推送 (#379) 2026-10-17 13:05:10 +08:00
41f6946a2b 货款对账:差异支持按厂家钉钉机器人推送 (#378) 2026-10-17 12:54:30 +08:00
3fedeef59a 修复存量报价审核生效、原件预览与配件补发可扣款清单 (#377) 2026-10-17 12:49:39 +08:00
a0a6e9285a 供应商对账:新增厂家账号门户与独立退货视图 (#376) 2026-10-17 12:01:30 +08:00
18d03fe092 供应商对账:厂家退货支持查询导出并精简字段 (#375) 2026-10-17 11:13:18 +08:00
b0d7096241 供应商对账:厂家端退货表表头与退货明细完全一致 (#374)
厂家端退货表列头与退货明细一致(补齐月份/条形码/商品名称等),类型/操作在最后。
2026-10-17 10:53:13 +08:00
c69796b0d3 供应商对账:退货明细按导入顺序展示 (#373)
退货扣减确认取消金额排序,按导入顺序分页展示。
2026-10-17 10:24:25 +08:00
a8ffb6fc23 供应商对账:退货扣减确认展示全部退货行 (#372)
退货行按扣减金额从高到低分页展示(每页 15 行 + 页码),不再只显示前 15 行。
2026-10-17 10:05:08 +08:00
670faf2b80 供应商对账:表格改为卡片内横向滚动 (#371)
宽表不再撑开页面:卡片/滚动容器 min-width:0 + max-width:100%,表格在卡片内横向滚动。
2026-10-17 09:54:38 +08:00
feea2ed8b6 供应商对账:厂家上传的对账数据改为每页 15 行 + 页码翻页 (#370)
上传的对账数据表改为每页 15 行短表,底部总行数+页码(含上一页/下一页),翻页保留所选厂家。
2026-10-17 09:47:59 +08:00
2848c81a5e 供应商对账:退货明细改为「退货扣减确认」面板 (#369)
退货扣减确认:顶部汇总、逐行确认/异议、全部确认(不覆盖异议)、金额空按预估金额扣减,展示金额最高 15 行。
2026-10-17 09:40:54 +08:00
8aa7676853 供应商对账:查看比对改为独立明细视图 (#368)
财务端点「查看比对」进入只显示该厂家明细的视图(汇总+行级差异),带返回列表按钮并保留筛选。
2026-10-17 09:23:52 +08:00
3b4db0e273 供应商对账:单价/金额留空自动补齐 (#367)
单价留空按金额÷数量补齐、金额留空按数量×单价补齐、都空按 0(数量必填),未定价行厂家可直接上传。
2026-10-17 09:16:51 +08:00
2ffb49ca92 供应商对账:条码匹配去掉厂家编号/版本后缀,表头不符提示缺列 (#366)
比对键先去掉厂家编号+版本后缀再匹配(实测雪翔家居文件),页面显示厂家原始条码;表头校验失败列出缺少/多出的列名。
2026-10-17 09:07:16 +08:00
2a80f380e6 供应商对账:财务端数据在月份后新增「对账人」筛选 (#365)
对账人筛选取自终版货款对账的对账人列,按月过滤后生成选项;选择后供应商列表与比对明细同步过滤。
2026-10-17 08:57:14 +08:00
87eaf48c2c 供应商对账:应付款项下新增对账页面(财务端数据 / 厂家端数据) (#364)
新增供应商对账目录:财务端实时上传情况与行级差异(条码+单价匹配,四类口径),厂家端严格按模板上传(表头不一致/必填缺失/非数字/串厂一律失败);复用终版存储与流式读取。
2026-10-17 08:49:17 +08:00
82c79dadc3 feat: 店铺维度报表销量改取业绩明细的订单实付/实收金额 (#363) 2026-10-17 00:19:09 +08:00
bcf8ea8fb7 应付款终版导入:流式读取改用 zip:// 管道,解析内存 274MB→76MB (#362)
sharedStrings 与工作表 XML 改为 XMLReader 经 zip:// 流式解析;200k 行基准读取从 6.2s/274MB 降到 2.3s/76MB。
2026-10-17 00:05:05 +08:00
656c655c91 应付款终版导入:支持 20 万行(流式读取 + 分片导入 + 进度显示) (#361)
新增流式 xlsx/csv 读取器与分片导入:上传建行缓存,按片处理(2 万行/25 秒预算),批量 upsert + 批量审计事件,前端进度条自动续跑;上限 20 万行,上传 50MB。
2026-10-16 23:54:03 +08:00
7742163632 应付款终版导入:分块读取工作簿,避免大文件把进程撑爆导致 500 (#359)
按 2000 行分块读取(大文件不再整表载入内存),读满 1 万行立即提示拆分文件;php.ini 补 log_errors/error_log,致命错误可查。
2026-10-16 23:15:33 +08:00
8429ad0642 应付款终版货款对账:采购单号后新增「日期」列 (#358)
「月份」后依次为入库单号、采购单号、日期;导入模板/表格/导入/编辑/导出同一套字段,只作用于终版目录。
2026-10-16 22:34:01 +08:00
0a54775b3b 配件补发扣款:快递比例配置、Excel导入和归属选择 (#357) 2026-10-16 22:27:46 +08:00
b26ab9f85d 快递应付:首发信息拆列及明细字段筛选 (#356) 2026-10-16 22:17:52 +08:00
688ae30747 应付款终版退货对账:wms配货单号调整到标题后 (#355)
「标题」在前、「wms配货单号」在后(与基础页面一致),导入模板与页面/导出同步;其他页签不受影响。
2026-10-16 22:17:05 +08:00
b4eaa1e102 快递应付:新增配件补发扣款匹配界面 (#353) 2026-10-16 21:36:03 +08:00
e6f4b61761 应付款终版退货对账:创建人调整到对账人前 (#352)
「标记多标签」后补创建人、「对账人」保持末列,导入模板与页面/导出同步;其他页签不受影响。
2026-10-16 21:35:39 +08:00
3e1d211d1b 应付款终版退货对账:新增「wms配货单号/创建人」列并去掉「快递名称」 (#352)
「备注」后插入 wms配货单号,末尾补创建人,删除快递名称列;导入模板/表格/导入/编辑/导出同一套字段,只作用于终版目录。
2026-10-16 21:23:25 +08:00
7fbcd061af 应付款终版货款对账:新增「入库单号/采购单号/对账人」列 (#351)
「月份」后补入库单号、采购单号,末尾「未发出」后补对账人;导入模板/表格/导入/编辑/导出同一套字段,只作用于终版目录。
2026-10-16 20:58:42 +08:00
da2a26c485 应付款终版货款对账:导入模板与表格新增「未发出」列 (#350)
终版目录的货款对账页在现有字段后追加「未发出」(导入模板/表格/导入/编辑/导出同一套字段);基础目录的「未发出」是按来源数据计算的标记,保持不变。
2026-10-16 20:12:23 +08:00
37c11f4e8e fix: 提现管理店铺余额保留最近5天 (#349)
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-10-16 19:00:49 +08:00
2399d42d6d feat(存量报价): 支持按发货名称手填录入及无编号报价 2026-10-16 17:58:35 +08:00
chenxi
5b89692318 商品成本:收入为 0 的账单行不取数、单价加线上代发价格兜底
- 账单侧只取收入金额有数据且不为 0 的业绩明细账单行(收入为 0 的是补出来的优惠/冲减/无收款账单行)
- 商品单价按「仓库简称 + 商品编码」取月加权平均价,匹配不到时退回「线上代发价格」
  (采购单管理的采购单价优先,其次钉钉线上代发的代发订单金额 ÷ 发货数量),并记录 price_source
- 新增数量与单价口径校验:定制配件行把配件件数写进商品数量,乘成品单价会放大几百倍,
  成本单价高于该行明细单价 3 倍时成本留空、标注「数量与单价口径不一致」,不计入合计
- 页面与导出列改为业务口径的 9 列(发生时间/店铺名称/线上单号/发货仓库/仓库简称/商品编码/商品数量/商品单价/商品成本),
  汇总卡片新增「线上代发价格兜底」「数量与单价口径不一致」两项
2026-10-16 17:34:06 +08:00
c4a39ec265 科目映射表:存储改共享数据库(ec_account_mapping_rules / ec_account_mapping_events,本地与生产同一份,改完两边同时生效);旧文件保留为只读备份镜像;账单明细改读共享库;新增 account-mapping:import-files 导入命令 2026-10-16 17:19:37 +08:00
c50244544d 业绩明细备注:京喜「直营补贴款」两条规则扩到 10 家店(出类拔萃 + 胜思创博家具/久伴吾家具/悦家/蓄势待发/日进斗金/上彩/美栖家/荣屹/亿家达京喜自营,均已逐店在结算单核实) 2026-10-16 17:18:42 +08:00
f3df42f46b fix(存量报价): 修复批量保存被安全检查误拦截 (#347) 2026-10-16 16:28:18 +08:00
706b07b4ad 业绩明细:淘系支付宝/微信新增「订单实付含已退款部分」核实(差额/收款缺口/整单全退对上聚水潭已确认退款,与抖音同口径,EXISTS+HAVING 提速);店铺名优先展示线上真实店铺(修复「支付宝-公司」壳名);字段说明同步 2026-10-16 16:18:23 +08:00
9a25db91cc feat(报价管理): 存量报价整本批量录入及签署原图归档 (#346)
保留各家工作表报价原文、公式、独立执行日期及签署原件;审核后按执行日期管理版本。33项测试、336项断言通过。生产业务迁移已获明确授权,服务器私有备份已完成并逐条校验。
2026-10-16 14:56:44 +08:00
6c76a373a3 业绩明细:合单发货取数优先取原单行(merge_so_id 为空),修复 878 行误取合并汇总金额(7/8月实付合计修正 -11.17 万);商品金额/实付/实收/应付统一三档优先级;字段结构说明同步新取数与口径兜底/待核实顺序 2026-10-16 12:00:42 +08:00
8fbc9abd53 聚胜算每日账单导出:等待胜算标签页注册并提高导出重试次数
- export-daily.mjs:点击「胜算」后轮询等待 ss.erp321.com 标签页注册(最多 30s,中途补点一次),
  避免 targetInfos 尚未出现时直接读 targetId 抛 TypeError(2026-10-13 09:30 首次尝试即因此失败)。
- run-erp-daily.ps1:导出重试 2 次提高到 3 次(2026-10-12 两次全败后只能人工补跑)。
2026-10-16 10:17:58 +08:00
b0ea247ca1 聚胜算每日账单导出:修复授权过期弹窗卡住与日期面板点空导致的导出失败
1) 店铺授权过期提醒弹窗在无头 Edge 下会卡在 leave 动画,弹窗与遮罩一直可见,挡住日期面板和查询/导出按钮;补发 animationend/transitionend 让 antd 正常卸载,仍残留则退化为隐藏该弹窗自己的 portal 容器(并解除 body 滚动锁),只影响这一棵弹窗。
2) 日期面板有时只渲染在屏幕外(left/top=-9999):原逻辑按 getBoundingClientRect 拿到负坐标去点,点了空还当成选中,最终日期框没变(表现为「日期设置失败」或整月导出失败);现在视口内照旧坐标点击,视口外退回 DOM click。
3) 页签切换后筛选区偶尔未渲染,取「开始日期」输入框坐标会报 undefined;改为先等输入框出现,并在取不到时重试而不是抛错。

验证:7/8/9 月历史复核导出各 1 次成功(23771/25020/44702,与启用代次一致);10-01→10-11 当日导出首次即成功。
2026-10-16 10:17:57 +08:00
e064492a95 业绩明细备注:撤销「订单实付未减退款」(价保扣款类回归通用档「订单实付未减冲减」,该档 = 订单实付=收入+优惠 → 差额=冲减金额) 2026-10-16 10:02:57 +08:00
422497cfcc 业绩明细:C 方案——三条通用等式档(未减冲减/优惠/优惠和冲减)在口径标识行让位给口径兜底;差额待核实档排除口径标识行 2026-10-16 09:44:21 +08:00
74a9b5b81f fix(表格列设置): 修复面板被侧栏遮挡并适配视口边缘 (#345) 2026-10-15 22:02:06 +08:00
23b8087d35 fix(报价签署): 修复临时报价说明中文显示问号 (#344) 2026-10-15 21:21:15 +08:00
d1b14fc10d feat: 合作合同乙方签约地支持编辑 (#343) 2026-10-15 18:13:24 +08:00
5c20defc79 业绩明细:修正有效差额 SQL(排除「差额待核实」兜底档,口径兜底行才真正按 0 计入合计/筛选) 2026-10-15 17:56:03 +08:00
01abeb4124 业绩明细备注:京东价保扣款负差额(差额=账单「价保扣款」合计)新增标注「订单实付未减退款」(含索菲亚智能店 3587456013325741 等 20 单) 2026-10-15 17:58:11 +08:00
173ca7c2ec 业绩明细:差额判定改为「原因优先 → 实收/应付口径兜底 → 待核实」;口径命中不再抹差额、页面与合计/筛选/联动同一套判定 2026-10-15 17:51:01 +08:00
564eb1ef08 fix: 协议签署业务操作授权与按钮权限一致 (#342) 2026-10-15 17:38:17 +08:00
1706131d9c 业绩明细备注:索菲亚功能店并入「商家承担优惠」备注组(8 单已用营销对账逐单核实);索菲亚智能店负差为价保扣款、不属本类未纳入 2026-10-15 17:35:21 +08:00
f4a0014690 业绩明细备注:京东五店负差额按单拆分——含国补(聚水潭应付−账单收入>0)标注「订单实付包含商家承担优惠和以旧换新国补」,其余标注「订单实付包含商家承担优惠」 2026-10-15 17:19:26 +08:00
288184c8dc feat: 快递资料合同甲乙方与协议签署联动 (#341)
新增合同主体(乙方)与签订公司(甲方)只读展示和导出;协议签署自动带出唯一乙方,缺失或冲突留空核对。19项直接相关测试与实际浏览器联动验证通过。无权限、金额、数据库结构或配置改动。
2026-10-15 17:00:21 +08:00
60163f6c32 业绩明细备注:京东索菲亚书房/亿家达全屋/朴美家居店负差额标注「订单实付包含商家承担优惠和以旧换新国补」(营销对账逐单核实) 2026-10-15 16:54:07 +08:00
c30cff7d0d fix: 移除快递合同管理签署完成证书列 (#340)
删除合同管理中的证书列和对应入口,保留已签合同查看、下载及归档文件。9 项测试 / 71 断言及实际浏览器验证通过。
2026-10-15 15:55:41 +08:00
6518995e45 业绩明细备注:京东索菲亚客厅/办公店负差额标注「订单实付包含商家承担优惠和以旧换新国补」 2026-10-15 15:40:54 +08:00
3e222e0035 业绩明细:实收对不上账单时也退回按应付/已付核对(覆盖拆单主单实收为空、子单有值的情况) 2026-10-15 15:38:07 +08:00
f41a8fa6ba 钉钉登录:单独授权人员仅访问三个快递报价页面 (#339)
按精确企业身份开放受限登录,保留在职校验和普通角色;统一限制菜单、页面、导出与预览。59 项相关测试通过,无数据库迁移。
2026-10-15 15:21:05 +08:00
1214fc365e 业绩明细:「订单实付按应付/已付核对」标注在页面展示并纳入筛选与联动计数(此前只在库里有、页面不显示) 2026-10-15 14:59:44 +08:00
a4952dfa42 Revert "业绩明细:新增备注「订单退款未参与差额」;字段结构说明同步(差额待核实/匹配原因/三档新备注)"
This reverts commit 0d215fe20c22e2e2ba3dbe82411d760aa0d7bac2.
2026-10-15 14:27:47 +08:00
0d215fe20c 业绩明细:新增备注「订单退款未参与差额」;字段结构说明同步(差额待核实/匹配原因/三档新备注) 2026-10-15 14:23:10 +08:00
cccd321195 快递应付:清空运费对账页面并停用错误数据源 (#338) 2026-10-15 14:08:05 +08:00
1131d073ce 快递入驻:指定钉钉初复审人员,复审任一人通过 (#337) 2026-10-15 13:52:30 +08:00
72b3f43da5 业绩明细:实收缺失时退回按应付/已付核对;同步命令新增 --dry-run 开关 2026-10-15 13:21:36 +08:00
c314209705 业绩明细备注:京喜出类拔萃店负差额标注直营补贴款(待开票结算/订单退款已冲回) 2026-10-15 12:04:41 +08:00
4e38a1cf11 业绩明细:双口径兜底阈值放宽到 0.5 分(1 分尾差也按卖家实收核对归零) 2026-10-15 10:43:37 +08:00
fd4b155979 feat(快递资料): 归档合同管理与到期提醒 (#336) 2026-10-15 10:22:35 +08:00
8d7f6da49f feat(协议签署): 按需生成证件推送单并独立签署归档 (#335) 2026-10-15 08:19:32 +08:00
8ba7ac8327 feat(快递入驻/快递资料): 生成二维码时必填快递资料并对齐到快递资料;去掉「发起报价变更」按钮;自定义3 改名扣款方式
- 生成入驻二维码新增 11 个必填项(快递方看不到,放在入驻流程下方单独一块):快递类型、快递合作方式、快递属性、扣款方式、单号类型、快递邮箱、
  是否需要核对物流点、快递发货方式、是否已有工作平台账号、快递网点代码、网点所在地区;入驻列表、入驻详情可查看和修改
- 快递资料:扣款方式对齐到「扣款方式」列(工作平台没填时用入驻的),其余字段接在入驻信息列里;网点代码/地区进网点明细;导出同步
- 不再依赖钉钉「新建快递」流程字段,ERP 开通改为手动补录 ERP账户ID
- 快递资料「自定义3」列、筛选、编辑和导出表头改名为「扣款方式」(字段仍是 undefined3)
- 报价管理工具栏、报价历史页去掉「发起报价变更」:它默认拿第一份报价走老的改格子流程,对入驻快递会绕开后台变价;
  变价统一从报价列表每一行的「变价」进入;老报价编辑页新增 …/changes/new 入口,避免套餐限制中间件把 GET …/create 跳到用户页
- 新增迁移 2026_10_14_300000:business_courier_onboardings 加 11 个可空字段

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019gzfsnV3fJ89CoUy1D9V9g
2026-10-14 18:31:25 +08:00
c0aab60862 业绩明细:订单侧双口径核对(买家实付/卖家实收)+ 差额待核实 + 列名与筛选改名
- 同步:账单能对上卖家实收时按实收核对(差额归零、订单实付/实收列显示实收值),并写入标识「订单实付按卖家实收核对」
- 页面:新增兜底备注「差额待核实」(可筛选);该标识在「匹配原因」列展示并纳入筛选与联动计数
- 列名:「订单实付金额」→「订单实付/实收金额」;「未匹配原因」→「匹配原因」
- 新增 scripts/docker-fix-start.ps1(Docker 因僵尸 socket 起不来时一键清理并启动)
2026-10-14 17:54:56 +08:00
9c63f36944 fix(发货数据): 无快递单号的自动发货仓旧包裹也按被取代清除
- 10.11/10.12 剩余约 476 个省份空白包裹:凌晨同步时按自动发货仓入库、当时订单还没有快递单号;之后订单有了发货明细,
  改由发货明细来源键吐出,旧包裹因无单号未被识别为被取代而残留(重复且省份空白)。
- 窗口内未再出现的旧包裹,若为自动发货仓来源且该订单本次已有发货明细,或无单号但同一交易单号本次已由其它包裹吐出,视为被取代删除。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf
2026-10-14 15:34:47 +08:00
afd8487cd4 部署工具:密码提示改为 -Command 方式调用脚本(修复 ssh 子环境下 -File 被系统拒绝导致登录失败) 2026-10-14 15:11:33 +08:00
71652c5a64 feat(快递入驻): 快递扫码填写入驻资料 + 两级审核 + 首版报价 + 签署开通
快递应付 → 快递报价 下新增「快递入驻」页:生成入驻二维码发给快递方,
对方免登录在手机上填写主体、联系人、e签宝签署人、结算账户、报价并上传资质,
内部对接人初审、管理员财务复审后生成首版报价,并自动生成报价确认单 PDF
推送到快递填写的 e签宝账号,签署归档后开通。

- 新增三张表 business_courier_onboardings / _files / _events(纯新增,不改旧表)
- 免登录填报页 /onboarding/courier/{token}:40 位随机 token,可暂存、提交、退回后补件,
  链接有效期可延长、可作废;银行账号加密存储;附件存 uploads 盘
- 新增 COURIER_ONBOARDING_PUBLIC_URL 配置二维码里的站点地址(留空用当前访问地址)
- 内置纯 PHP 二维码生成(App\Support\QrCode,SVG 输出,无新增依赖)
- 生成二维码时必须定好系统快递名称(唯一,快递方不可见);财务复审沿用该名称,快递所填报价写成报价管理的 CourierQuoteVersion,
  复用 CourierQuoteSignatureService 生成报价确认单并推送 e签宝(失败可重推/同步状态);初审人默认不能复审(COURIER_ONBOARDING_ALLOW_SAME_REVIEWER=true 可在测试环境放开)
- 支持公司 / 个人两种入驻:个人填姓名+身份证号(加密)、传身份证和银行卡,报价确认单按个人身份在 e签宝签署
- 扫码先选入驻方式;证件改为 营业执照 / 法人身份证正反面 / 银行卡正反面 各一张(个人营业执照选填),手机端上传前自动压缩,超限回到填报页提示
- 报价支持 4 种计费方式(面单+费率 / 首重+续重 / 按重量段一口价 / 小重量一口价+超出另算,费率可分段)+「其他」上传报价表;附加规则:计泡、起算重量、取整、每票加收(CourierQuoteStructure)
- 不再要求上传盖章报价单,至少填写一行在线报价
- 开通:报价确认单签署归档、或匹配到已签署协议、或填写线下签署说明
- 生成二维码前必填「快递公司代码」(自动大写、不可重复),入驻信息按代码对齐快递资料
- 公司入驻对公(营业执照主体)+ 对私(法定代表人)两个打款账户必填并自动核对;个人入驻对私必填、对公选填
- 变价:报价管理里后台改价 → 审核 → 自动推送快递 e签宝 → 回签;回签单导出 xlsx/zip;误发版本可作废
- 短期(临时)变价:变价单/报价版本加选填「结束日期」(end_date);按日期取价,期间用临时价,到期次日自动恢复原长期报价,
  不用重签;报价管理显示 生效中(临时)/ 暂停中 / 已到期,确认单写明执行期间和到期后恢复的版本,审核提醒期间重叠
- 快递资料分四类:快递资料 / 网点 / 打款信息 / 操作日志,支持查询、导出、重置、编辑;
  财务系统入驻的快递直接作为快递资料行,合同起止取协议签署里已签署的合作合同;
  点开一行在下方看该快递的网点 / 打款信息(完整账号)/ 操作日志
- 编辑存财务系统覆盖值(business_courier_profiles,不回写工作平台),改动记操作日志(business_courier_profile_events)
- 打款信息新增 / 变更(business_courier_payment_accounts,账号加密)保存后跳到协议签署,自动预填收款账户证明 / 收款账户变更,
  按签署状态显示 待推送协议 / 签署中 / 已生效;入口在快递资料明细和「打款信息」页签(表格每个账户可直接「变更」)
- ERP 开通:入驻开通后标「待 ERP 开通」,可手动补录(钉钉「新建快递」流程同步待接入)
- 新增 CourierOnboardingWorkflowTest(8 个用例),更新快递报价目录顺序断言

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019gzfsnV3fJ89CoUy1D9V9g
2026-10-14 13:47:00 +08:00
1684902863 业绩明细取数:「买家实付」字段未同步改价/退款时,采用能与账单对平的「已付」金额(仅负向纠偏) 2026-10-14 13:47:25 +08:00
e26c1e467e 业绩明细取数:合并发货行不再当作单笔金额(实付与商品优先取本单非合并行) 2026-10-14 09:56:10 +08:00
f6497f5afc fix(发货数据): 重跑时清除被取代的兜底包裹,保留包裹也刷新省市区/快递/仓库
- 凌晨同步时发货明细常未到齐,包裹先按自动发货仓/出库单兜底入库(无省份、无商品);之后发货明细到齐换成发货明细来源键,
  旧兜底包裹因"上游未再出现"被保留,造成重复和空白省份(10 月重跑 2,226 个)。现在:旧包裹的快递单号已由本次其它包裹吐出时
  视为被取代并删除;无对应的仍保留待核对。
- 商品金额无法安全匹配(或新商品明细缺失)而保留的旧包裹(10 月 28,201 个),此前整包不更新;现在商品与金额不动,
  省市区、快递名称、仓库、店铺、平台、交易单号、付款时间按本次上游刷新。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf
2026-10-14 08:54:45 +08:00
b4f8416794 店铺违规预警:已超时口径限定需提醒范围,字典导入命令兼容大维度文件 (#334) 2026-10-13 20:13:53 +08:00
0c04860d69 店铺违规预警:修复重算命令严格模式报错,新增违规字典导入命令 (#333) 2026-10-13 20:04:02 +08:00
ea80148dfc 店铺违规预警:级别/责任人/处理截止/超时/推送状态 + 处理状态四档 + 群推送接口 + 预览统计页 (#332) 2026-10-13 19:54:01 +08:00
530c9858ec 业绩明细:月份选完自动查询(月份选择器补值变更事件 + 筛选栏自动提交) 2026-10-13 17:57:28 +08:00
8a67c7d768 业绩明细:1688采销专用收款单独成档(未匹配原因新增两档)
- 同步逻辑:「支付宝-1688采销专用」账户的未匹配行写「账单无单号(采销收款)」「1688采销收款(非销售单)」,不再混进「订单表无此单」
- 页面筛选:未匹配原因下拉补上两档
- 字段结构说明同步更新
2026-10-13 17:46:18 +08:00
10d3067aee 业绩明细:京喜备注统一为「订单实付取供货价」(替换此前的宽判定版本,负责人确认)
同事此前以「差额=直营服务费(已计销售费用)」宽判定(京喜正差额即标,约 2% 与本单服务费对不上);经负责人确认,统一为「订单实付取供货价」:逐单核对差额=直营服务费规模或净额(部分退款场景),对不上不标。
2026-10-13 16:44:17 +08:00
d8d5196628 chore:.gitignore/.dockerignore 排除本地演示文件 2026-10-13 16:43:05 +08:00
5ab7786a90 业绩明细:京喜新增「订单实付取供货价」备注(差额=直营服务费规模或净额);联动缓存延至 10 分钟;计数与合计合并一次扫描
京喜工厂店/直营为供货模式:聚水潭订单实付=供货价(净收),账单按「应收−直营服务费=供货价」结算,正差额即直营服务费(含部分退款后的净额场景);逐单核对后标注,对不上不标。得物/京东补充索引已就绪。
2026-10-13 16:43:05 +08:00
7258d09238 业绩明细:列顺序统一「差额→差额异常备注→匹配状态→未匹配原因」;差额筛选并入统一多选组件(联动计数/导出/重置) 2026-10-13 16:43:04 +08:00
ae54706ceb 业绩明细:抖音「订单实付含已退款部分」再补充口径(退款合计≈实付 整单全退) 2026-10-13 16:37:45 +08:00
2be4d4700e 业绩明细:抖音「订单实付含已退款部分」补充口径(退款合计+账单退款净额≈实付−收入) 2026-10-13 16:08:38 +08:00
45a28aa76c 快递报价:工作区 iframe 内不再重复显示已打开页面标签栏
- 已打开页面标签栏只在最外层窗口渲染,iframe 子页面不再出现同一条标签栏,
  避免点标签时在 iframe 内部再套一层快递报价工作区(页面上出现两份同样的页签+标签行)
- 快递报价工作区注入的样式同时隐藏 .open-tabs,兜住浏览器缓存的旧子页面
2026-10-13 15:51:04 +08:00
1c00548396 标签栏:刷新后至少保留当前页,避免空着 2026-10-13 15:26:40 +08:00
a8a0c6d4c9 已打开页面标签栏改为按浏览器会话保留
之前存在 localStorage:跨浏览器重启也不会清,前几天点过的标签刷新后又出现
(用户反馈"没点过/刷新后其他标签又弹出来")。改成 sessionStorage:同一次浏览器
会话内刷新、来回切换都保留,关掉浏览器或另开窗口重新进来就是干净的;同时清掉
旧版本写在 localStorage 里的记录。
2026-10-13 15:24:26 +08:00
add787edf5 已打开页面标签栏上移到页面标题行上方
按使用习惯把标签栏放在内容区最上面,页面标题/操作那一行在它下面。
2026-10-13 15:18:37 +08:00
c5c71dab74 已打开页面标签栏:只收录从系统里点开的页面
之前只要在浏览器里加载过业务页面就会固定上去,包括浏览器恢复会话、另外标签页
静默加载的页面(用户没点过也会出现)。改成只在导航来自同源页面(即从系统内点击
进入)时才新增标签;已经在标签里的页面仍会更新标题和最近一次地址。
2026-10-13 15:13:14 +08:00
5970572274 业绩明细:抖音「订单实付含已退款部分」判定放宽(退款金额≈差额 或 ≈实付−收入 命中即可) 2026-10-13 15:11:42 +08:00
a884da7057 侧边栏菜单搜索 + 已打开页面标签栏
1)侧边栏菜单上方新增搜索框:按关键字过滤菜单项(如输「快递应付」直接定位),
   无匹配时给出提示,Esc 清空。
2)页面顶部新增「已打开页面」标签栏:点开过的业务页面并排固定在页面上方,
   点标签直接切回(回到最近一次带筛选的地址);同一张页面按路径去重;
   标签按账号存在浏览器本地(localStorage),没退出登录就一直保留;
   支持单个关闭和「清空(保留当前页)」,最多并排 15 个,超出横向滚动。
   钉钉单页入口模式下不显示这个标签栏。
2026-10-13 14:57:22 +08:00
cdcb1c6662 应付云仓车费:明细行点击高亮 (#331) 2026-10-13 14:29:57 +08:00
d3049686b4 应付云仓车费:移除「全部表单字段/付款明细/审批任务」三列 (#330) 2026-10-13 14:12:47 +08:00
8905192b78 应付云仓车费:附件支持点击下载 (#329) 2026-10-13 13:58:31 +08:00
26b83bd8e7 钉钉入口单页模式扩到整个「财务经营风险管控」目录
上一版只对店铺违规信息预警单页;在钉钉里点该目录的另一个页签(流程统计)又会
冒出整排菜单。改成:只要属于 financial-risk-control 目录、且来自钉钉容器
(或显式 ?focus=1),就隐藏全局菜单,只保留该目录自己的页签。
2026-10-13 13:53:49 +08:00
7a5f04287c 钉钉工作台入口:店铺违规信息预警整页展示(隐藏全局菜单)
钉钉工作台里点进来的这个入口,现在只显示这一张页面:不再渲染全局侧边栏,
内容区占满宽度,其余页面和网页端登录完全不受影响。

判断依据:当前页面是 financial-risk-control/store-violation-alert,且请求来自
钉钉容器(UA 含 DingTalk)或显式带 ?focus=1;路由参数取不到时按路径段兜底。
2026-10-13 13:28:59 +08:00
57f2dccfac 应付云仓车费:修复附件列为空 (#328) 2026-10-13 13:26:59 +08:00
b962c23e92 附加费结算:导入/明细头收紧、结果统计并入导入行右侧 (#327) 2026-10-13 13:13:14 +08:00
0fa52090f7 退货取件管理:同步条与筛选区收紧、列表区放大 (#326) 2026-10-13 12:10:58 +08:00
7223a2eb2e 应付云仓车费:表格数据区填满到底部 (#325) 2026-10-13 11:53:43 +08:00
6b6b97a375 应付云仓车费:筛选区收紧、表格区放大 (#324) 2026-10-13 11:32:28 +08:00
d47a72c175 店铺违规预警:新增违规原因与处置方式两列(页面/统一表/导入导出) (#323) 2026-10-13 11:32:27 +08:00
ac40c6d8a9 镜像索引:dewu_settlement_bill_rows 增加 (online_order_no, bill_item) 索引(业绩明细得物备注联动计数 69s 慢查询) 2026-10-13 11:31:50 +08:00
7e1ded5112 附加费结算:修复筛选设置面板左缘溢出被裁切 (#322) 2026-10-13 11:14:07 +08:00
f8a83cf684 业绩明细:京喜正差额新增「差额=直营服务费(已计销售费用)」备注 2026-10-13 11:15:21 +08:00
d1ffaf773c 业绩明细:得物负差额新增「订单实付未减联合营销费」备注;抖音备注改名「订单实付含已退款部分」
得物:负差额 = 联合营销费未让利尾数(该单营销费支出 + 差额恰为整数)时标注;规则排在通用「未减冲减/优惠」之前,避免被笼统备注抢先;证据子查询仅在得物负差额行计算。抖音:备注名统一加「订单」前缀。导航说明同步更新。
2026-10-13 11:07:55 +08:00
53b0821384 快递应付:仓储运费更名为仓储费 (#320) 2026-10-13 10:59:30 +08:00
8b62ba0504 附加费结算:筛选字段可自选显示(筛选设置) (#321) 2026-10-13 10:59:29 +08:00
bbf8c1f16c 附加费结算:分页改为退货取件管理同款紧凑样式 (#319) 2026-10-13 10:41:33 +08:00
03fea599fb 附加费结算:收紧顶部概览/筛选/导入区 (#318) 2026-10-13 10:29:37 +08:00
f663ddc51f 附加费结算:明细行点击高亮,方便核对时标记当前行 (#317) 2026-10-13 09:56:41 +08:00
7ecd5a59e6 fix(发货数据): 快递名称、仓库按发货数据视图取值,与工作平台一致
- 9 月核对剩余 256 条快递名称、44 条仓库不一致;抽样 14/14 工作平台显示的就是发货数据视图
  (Jst_SendData_View_extension) 的 expressName / wareHoursName。视图有值时以视图为准,
  视图没有该出库单时保留出库单/发货明细推断的值。
- 发货数据视图、出库单头按 300 个出库单一批查询(原 800),减少副本库超时导致整月重跑中断。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf
2026-10-13 09:53:02 +08:00
63f9e2a418 店铺违规预警:同步 SQL 在源端转换 date 列,修复 FreeTDS 区域日期解析失败 (#316) 2026-10-13 09:40:53 +08:00
e61e3b50fb 店铺违规预警:补充生产每日同步定时任务(cron 遗漏) (#315) 2026-10-13 09:36:14 +08:00
c55c06026f 快递应付:报价维护只留报价页签 + 附加费结算定时同步(每日7天/每周90天) (#314) 2026-10-12 17:49:10 +08:00
fba094ce26 业绩明细:抖音负差额新增「实付已退款部分」备注(聚水潭退款单/取消子单金额≈差额时命中) 2026-10-12 17:27:09 +08:00
e883d262f0 快递应付:修复三方仓进销存加载超时 2026-10-12 17:22:17 +08:00
26f945ba29 本地预览:测试断言同步到已启用的 OPcache 配置
deploy/php-local.ini 已改为 OPcache 开启 + 每次请求校验时间戳,测试仍断言 opcache.enable=0 导致失败;更新为 enable=1 并校验时间戳。
2026-10-12 17:12:10 +08:00
a90736592a 业绩明细同步:订单实付命中即算订单存在,修复部分订单被误判「订单表无此单」
部分订单(退款流程 / 拆单 / 商品明细未同步)在订单侧只有订单头与实付、没有商品明细行,原匹配逻辑仅按商品明细判断订单存在性导致误判。改为实付命中同样计入订单存在性;商品金额仍只由商品明细构建(无明细时保持为空)。实跑修复 8 月 1791 行(得物 57 / 京喜 497 / 抖音 46 / 京东 153 / 拼多多 1038)。
2026-10-12 17:12:10 +08:00
20eccf616c 业绩明细:新增「未匹配原因」列与筛选联动;差额异常备注只保留原因说明
新增「未匹配原因」列(账单无单号 / 单号格式异常 / 订单表无此单 / 订单无实付金额 / 无收款账单),支持多选筛选与联动候选;「差额异常备注」对未匹配行统一显示「订单实付未匹配」,细分原因改看新列。
2026-10-12 17:12:09 +08:00
45b9feb8c4 快递应付:附加费结算增加独立页签入口 2026-10-12 16:59:51 +08:00
9c62f4364b 快递运费:固定列宽+收紧内边距,12 列表头一屏可见(超长内容省略+悬停提示) 2026-10-12 15:46:01 +08:00
66d6146c19 快递运费:导入兼容「店铺」列名(财务系统提供成本5-6.xlsx 用)
列名别名扩展:店铺名称/店铺;csv 与 xlsx 两条路径的用例同步覆盖。
2026-10-12 14:55:01 +08:00
0da349e51b 快递应付:仓储核算移为独立仓储运费 (#311) 2026-10-12 14:46:52 +08:00
c8eb6e2e5f fix(发货数据): 早上补跑一次发货同步,副本库超时重连改为逐次拉长等待
- 凌晨 01:28 同步时副本库最近一两天的订单/商品明细常未到齐,10-12 凌晨一轮写入 4,669 个只有单号、缺商品明细的包裹
  (10.10/10.11);工作平台导出为实时查询不受影响。新增每天 07:28 再拉最近 3 天,补齐商品明细。
- selectWithReconnect:副本库超时/游标失败的重试由 2 次(间隔 0.25 秒)改为 5 次,等待 2/5/10/20/30 秒,
  白天整月重跑不再因单次超时中断(单测环境不等待)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhry6eiuwf
2026-10-12 14:39:11 +08:00
9f6a5f6fde 退货取件管理:整行点击异步加载详情,本地 opcache 提速 2026-10-12 13:47:01 +08:00
3e24bc5111 快递应付:左侧增加快递报价入口并打开四个页面 (#309) 2026-10-12 13:26:22 +08:00
10c22a655d 退货取件管理:详情精简置底、当前行高亮、内部滚动与快递公司多选 2026-10-12 13:14:53 +08:00
f7547bc9a1 feat(快递应付): 四个报价相关模块归入快递报价子目录 (#307) 2026-10-12 12:17:13 +08:00
f3143e6959 快递运费:修复 XlsxSheetReader 可选列漏传闭包导致 xlsx 导入报未定义变量
补 xlsx 路径导入测试(csv/xlsx 是两条代码路径,此前只测了 csv)
2026-10-12 12:07:09 +08:00
f805920fda 快递运费:新增「店铺名称 / 快递单号 / 条形码」列,并按「财务系统运费整理.xlsx」重新导入
- 迁移:courier_freight_rows 增加 express_no / barcode / shop_name(可空)
- 导入器支持可选列(快递单号 / 条形码 / 店铺名称),老文件缺这三列也能导;XlsxSheetReader 支持可选列表头
- 页面与导出新增三列;运费差 / 结算运费 / 其他附加费汇总 / 退件费 表头与取数逻辑不变
- 测试:新增新列导入、老文件兼容、页面展示用例
2026-10-12 11:56:00 +08:00
50cfbf1c14 feat(协议签署): 接入供应商代发、代销和生产合作合同模板 (#306) 2026-10-12 10:48:04 +08:00
d8dfb33437 fix(发货数据): 仓库按实际出库单发货仓、补入无需物流虚拟发货、作废单号识别换单
- 仓库一律按实际出库单 wms_co_id 映射(从快递公司一致的明细行学习仓库名,样本>=3 且占比>=90% 才回填),
  修正发货明细写总仓而实际由工厂代发仓出库(如 710099981090 千优代发仓)的情况。
- 快递名称为"无需物流"(补差/信誉/运费等虚拟发货,如 X00006)的包裹仓库统一为"简尚-自动发货仓",与工作平台一致。
- 换单配对:快递明细单号只对应作废出库单时视为已换单,改用有效出库单的新单号(如 DPK366101313659 -> SF1549142274850)。
- 出库单兜底不再跳过"无需物流"的无单号出库单(信誉订单/补差价/运费专用等虚拟发货),按工作平台口径补入自动发货仓、快递单号为空;
  9 月核对工作平台有、线上无的 565 条虚拟链接,抽查确认为此原因(出库单无单号被跳过)。
- 换单配对查询(logistic_id 无索引)副本库超时时跳过本页,不再中断整轮同步;结果返回 tracking_pairing_skipped_pages。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhry6eiuwf
2026-10-12 09:58:05 +08:00
1e689d254e 附加费结算:超长费/退回费/拦截费拉取、导入核验与模板导出 2026-10-12 09:33:24 +08:00
chenxi
d9646b4ac9 财务经营分析表:按「时间-平台-店铺」聚合收入与成本
财务经营报表新增「财务经营分析表」页面,一行 = 一个月的一个平台的一个店铺,
表头:时间、平台、店铺、收入、成本、运费。
- 收入 = 业绩明细的(收入金额 + 优惠金额 + 冲减金额 + 退款金额)按各字段记账符号求和
- 成本 = 商品成本表按店铺汇总的商品成本
- 运费暂不取数,页面显示「—」、导出留空列
支持月份(含全部月份)/平台/店铺筛选、汇总卡片与 CSV 导出,聚合结果按月份缓存 5 分钟。
2026-10-11 22:04:54 +08:00
597104430e 协议签署:每条公司主体增加删除功能 (#304)
每条公司主体增加确认删除,保留历史快照,删除默认主体后选择剩余主体,全部删除回退当前公司。相关21项测试246条断言及隔离页面交互通过。
2026-10-11 14:26:31 +08:00
976db7e4f1 授权委托书三处往来方名称跟随我方签署主体
## 变更

- 授权委托书的“账单往来方”“借支协议相对方”“代收货款往来方”三项改为跟随“我方签署主体”。
- 快递公司和供应商共用授权委托书模板,因此两种合作方均同步生效。

## 验证

- `AgreementSigningPageTest.php`:14 tests, 197 assertions passed。
- 实际生成授权委托书页面确认三处字段初始值均来自当前我方主体。

仅涉及页面模板字段标记,不涉及金额、权限、数据库迁移或配置。
2026-10-11 14:18:36 +08:00
cbec6a8b62 供应商管理增加每天08:15完整同步 (#302) 2026-10-11 13:57:28 +08:00
ad7226081a 协议签署:供应商合作合同显示模板待提供
供应商合作合同使用待提供模板提示;授权委托书复用现有模板,快递合作合同正常。页面测试及浏览器切换和预览验证通过。
2026-10-11 13:47:19 +08:00
ad3961b82d 修正供应商易签宝账号并接入签署选择 (#300) 2026-10-11 13:39:03 +08:00
87e5ce0df2 协议签署:供应商增加合作合同和授权委托书选项
开放已有模板,适配供应商签署账号标签与乙方名称提示;14 项页面测试、193 条断言及浏览器模板切换和预览验证通过。
2026-10-11 13:30:14 +08:00
49c6e1ecd1 修复供应商管理资料镜像索引与存储分类 (#298) 2026-10-11 12:34:31 +08:00
665b8fafd2 接入供应商管理页面与共享镜像 (#297) 2026-10-11 12:11:15 +08:00
ad6d70a0a2 协议签署:增加合作方类型与供应商待接入展示
合作方类型与供应商待接入展示;53 项测试、825 条断言通过。
2026-10-11 11:55:11 +08:00
48553c001d 协议签署:每条任务支持自主删除
全部状态、两类任务支持确认软删除,保留文件及外部签署流程。相关72项测试通过,权限及公司隔离保持不变。
2026-10-11 11:24:30 +08:00
766a85b097 协议签署:待处理任务增加删除和确认 2026-10-11 10:37:28 +08:00
0e1feaf1e6 修复协议文件签字盖章区域过小 (#293) 2026-10-11 10:17:32 +08:00
118f030220 fix(协议签署): 修复授权委托书编号重叠 (#292) 2026-10-11 10:09:47 +08:00
4eb09a1fcc 协议签署:待处理与已归档视图、归档原因及文件下载 (#291) 2026-10-11 09:55:46 +08:00
22133450a6 业绩明细:种菜金额口径加上货号 X00006(与标签明细页同一规则)
- 种菜订单集合 = 种菜明细表 ∪ 标签明细里「是否种菜订单=是」;后者改为命中种菜标签映射或货号含信誉订单虚拟条码 X00006
- 种菜明细表部分不再依赖标签映射是否为空
2026-10-10 17:20:05 +08:00
29f801bd92 聚水潭订单标签明细:修复货号回填进度打印引用未定义变量导致中断的问题 2026-10-10 16:18:27 +08:00
0a89a24f28 聚水潭订单标签明细:修复货号回填把纯数字订单号绑成整数导致的 MariaDB 1292 报错
订单号改用值对列表传递、全程按字符串绑定,避免 PHP 数组键自动转 int 后与字符列 order_no 比较被强转数字
2026-10-10 16:11:52 +08:00
53cd0c3ce6 聚水潭订单标签明细:新增「货号」列,货号 X00006 的订单判为种菜订单
- 新增 jst_order_labels.item_code 迁移;导入时从商品明细镜像按 o_id 写入货号(被替换/取消的明细不计入)
- 「是否种菜订单」增加规则:货号含 X00006(信誉订单虚拟条码)直接判「是」
- 页面与导出新增货号列;新增 jst-order-labels:sync-item-codes 回填命令
- 测试:新增货号/种菜判定/回填命令用例,并修正导出表头过时断言
2026-10-10 16:06:02 +08:00
2da46a2a86 业绩明细:修复导出「差额」列把未匹配行写成 0 的问题
- 未匹配行的差额在库里是 NULL,导出取值用了 ?? '' 变成空字符串,原判断只认 null,
  这些行被导成 0.00,导出合计只剩已匹配行的差额(2026-07 只有 14.7 万)
- 现在空差额按「比对基准金额=0」补算 收入+优惠+冲减,与页面/统计卡口径一致
- 验证:2026-07 全部平台导出 300,707 行,差额列合计 1,354,719.44(与页面同值);
  只看未匹配 3,968 行,差额列合计 1,207,560.77
2026-10-10 15:38:31 +08:00
158c5e1b23 业绩明细:差额/匹配状态/备注改为与订单实付金额核对;科目映射表筛选改按财务备注
- 业绩明细「差额 / 匹配状态 / 差额异常备注」的比对基准由「订单商品金额」换成「订单实付金额」:
  差额=(收入金额+优惠金额+冲减金额)− 订单实付金额;匹配状态以订单侧能否取到订单实付为准;
  备注文案改为 订单实付未匹配(账单无单号/单号格式异常/订单表无此单/订单无实付金额/无收款账单)、
  订单实付取数为0(种菜)、订单实付取数为0、订单实付未减冲减、订单实付未减优惠、订单实付未减优惠和冲减
- 商品金额列保留展示、不再作为核对基准;退款金额仍单独列示、不参与差额
- 两个口径共用同一条取数链(同店同号 → 店铺名不一致 → 同号多条 → 空店铺兜底),
  差额口径做成开关:config/performance_details.php 的 difference_basis 填 product 即可切回旧口径
- 统计卡「金额构成」补「订单实付金额合计」,与差额公式对齐
- 科目映射表筛选:第二个筛选项由「账单项目」改为「财务备注」(候选按平台收窄、可搜索、多选);
  账单项目仍可用左上角关键词搜索
2026-10-10 15:14:06 +08:00
37d18612a6 修复合作合同 PDF 方框、文字重叠与签字区分页 (#290) 2026-10-10 14:34:13 +08:00
107c883eb2 业绩明细:新增「退款金额」列,按总账备注=退款取数
- 新增列「退款金额」:店铺收款账户账单里总账备注=退款的金额(收入侧 − 支出侧),
  与优惠金额/冲减金额同一口径,单独列示、不参与差额计算;统计卡、导出字段、
  字段结构说明同步补充
- 同步命令支持账单表的 expense 列(京东账单/京喜账单/京东网银钱包/抖音用 expense,
  淘系/拼多多/得物用 expense_amount),此前只认 expense_amount,
  导致这些平台支出侧的退款、扣回金额被当成 0
- 重建后自检改为「本月账单确有优惠/冲减/退款行、但三列一行都没写」才报错,
  并把退款金额纳入判定,避免无数据月份误报
- 新增迁移:store_receipt_order_match_rows.refund_amount
2026-10-10 13:41:03 +08:00
153b823ab8 修复已注销主体变更遗漏现公司签署 (#289) 2026-10-10 13:28:37 +08:00
0234bae83f 修正共用合同合作方及归属主体,支持个人实名签署 (#288) 2026-10-10 12:10:32 +08:00
951fde9c46 账单页签:总账备注下拉候选合并科目映射表的财务备注
- 之前候选只来自总账备注映射表,科目映射表里新加的备注在下拉里选不到
- 现在两个来源取并集,改完映射表下一次请求即可筛选
2026-10-10 11:20:18 +08:00
dd03037105 账单页签/账单明细:财务备注按科目映射表关键词取最具体规则
- 行内财务备注把 channel/business_type/order_type 等业务字段纳入关键词匹配(得物退款行可识别)
- 「总账备注/财务备注」筛选折算 SQL 时支持同一账单项目多条规则的关键词条件与兜底反向条件
- 与业绩明细、科目映射表口径对齐(得物退款行统一显示/筛选为退款)
2026-10-10 11:13:46 +08:00
c1431b8b38 协议签署支持个人签署及已注销公司原法人签署 (#287) 2026-10-10 11:12:13 +08:00
b92a3b0ed0 修复共用合同 E 签宝主体与实名认证字段 (#286) 2026-10-10 11:01:51 +08:00
2bf8d3538a 修复合作合同双方 E 签宝个人实名信息 (#285) 2026-10-10 10:48:09 +08:00
25cf3f8f0f 业绩明细:同步取财务备注时带上业务备注与商品名称
- 之前只按「平台+账单项目」匹配,退款行与正常行走同一条规则(得物卖家承担优惠券/折扣活动/联合营销费被算进冲减收入)
- 现在按行传入业务备注(custom_remark/business_type/order_type/channel 等)与商品名称,与店铺收款账户账单页同一套口径;账单查询同步补取这些列
- 配合科目映射表给得物这三个账单项目新增「退款」规则后:退款行→退款,正常扣款行→冲减收入
2026-10-10 10:30:06 +08:00
073e82ea32 业绩明细:差额异常备注改为「差额原因」口径
- 备注只由差额公式判定:商品金额未匹配(账单无单号/订单表无此单/无收款账单)、商品金额未加种菜、商品金额取数为0、商品金额未减冲减/未减优惠/未减优惠和冲减;命中不了留空
- 未匹配行按商品金额=0 计入差额,差额合计与导出同步
- 列名「异常标注」改「差额异常备注」,筛选、联动行数、导出表头同步
- 联动接口:5 条原因合并为 1 次统计 + 60 秒缓存(1.5s → 0.8s,缓存内 11ms)
2026-10-09 18:27:07 +08:00
chenxi
fe8c271fcf 商品成本:新增财务经营报表「商品成本」页面与同步命令
以业绩明细的账单行为基数,按「店铺 + 线上订单号」展开订单原始数据的商品行:
- 发货仓库取订单 wms_co_id 对应的聚水潭仓库名称,仓库简称查仓库映射表
- 商品单价按「仓库简称 + 商品编码」取商品月加权平均单价里的加权平均价
- 商品成本 = 商品数量 × 商品单价(四舍五入两位小数)
- 拆单子单重复列出的同一批商品只算一次;同一单分多仓发货按子单实际仓库分行
- 排除虚拟条码(X0000x)与数量金额都为 0 的占位行;默认隐藏仓库映射表里标「-不看」的仓
页面提供月份、平台、店铺、线上单号、商品编码、仓库简称筛选与汇总、CSV 导出。
2026-10-09 17:36:14 +08:00
41d0e5169f 快递运费:运费差后面新增「结算运费」列(= 提供成本运费 + 运费差)
- 列定义加在 运费差 与 其他附加费汇总 之间,金额列同样左对齐、不参与查询条件
- 行数据按交易单号取到运费差后,由页面计算 结算运费;两者都没有时显示 —
- 描述文字同步(前端导出按表格列生成,新列自动带上)
2026-10-09 17:36:33 +08:00
df9ec2cb1e 账套科目表:销售费用下新增二级科目「会员价保」(5601.05.10)
- 科目映射表里唯品会JX「会员价保」已挂 销售费用/会员价保,账套里原先没有这个明细科目
- 校验由「借方二级科目找不到」警告变为正常
2026-10-09 17:03:29 +08:00
217b953a03 唯品会JX账户:科目映射与总账备注按行内「账单项目」匹配
- AccountLedgerRemarkMap:JX 页签取 payload.second_remark 作为映射的账单项目,
  与「科目映射表」里按账单项目(处罚款/客服特殊退款-仅退款/盘盈盘亏…)维护的规则对齐
- AccountBills:总账备注筛选对 JX 改为按行内账单项目过滤,其余页签不变
- 测试同步(总账备注筛选按账单项目命中)
2026-10-09 16:57:28 +08:00
499a9e12a6 唯品会JX账户:「账单项目」筛选改为按行内账单项目过滤
- 筛选下拉与筛选条件都取 payload.second_remark(处罚款 / 客服特殊退款-仅退款 / 盘盈盘亏 …),与页面「账单项目」列同源
- 唯品会MP页签维持按账单项目列过滤;导出走同一套过滤逻辑
- 同步更新 JX 页签测试(筛选选项与导出断言)
2026-10-09 16:36:09 +08:00
f82856a6f7 唯品会JX账户:列名「二次备注」改为「账单项目」
- 与费用规则里「账单项目」的叫法统一(该列即账单项目/业务备注,用于匹配科目映射表)
- 同步更新列名断言
2026-10-09 16:29:18 +08:00
9ce9ee74eb 唯品会JX账户:表头改为「明细类型/二次备注/总账备注/订单号SO/收入/支出/合计」模板
- 按财务给的「唯品会JX汇总10.9」模板调整页签列:类型→明细类型、销售订单号→订单号/SO、
  含税金额→合计金额,总账备注与二次备注紧跟明细类型,收入/支出保持独立列
- 同步更新 VipshopJxReceivingBillsTest 的列名断言(原先还在断言已改名的「订单结算时间」)
2026-10-09 15:58:01 +08:00
74b2d3a086 Revert "业绩明细:新增「种菜订单」筛选(全部/只看种菜/排除种菜),页面统计与导出同步生效"
This reverts commit 9ba90667b148aa8da62fdf7d7dd20ed5cf12b03a.
2026-10-09 14:35:19 +08:00
9ba90667b1 业绩明细:新增「种菜订单」筛选(全部/只看种菜/排除种菜),页面统计与导出同步生效 2026-10-09 14:23:48 +08:00
ed89882661 业绩明细:重建后自检优惠/冲减列,映射有项目但两列为空时直接报错,避免静默丢列 2026-10-09 13:56:07 +08:00
chenxi
cb26d5da17 业绩明细:商品金额改为只取主单,拆单子单不再重复累加
聚水潭拆单子单会把主单的商品行再列一遍,子单的平台子订单号与主单不同时
原「子订单号 + 条码」去重键拦不住,同一批商品被计两次。
现在商品金额只取主单(link_o_id 为空/0),整单没有任何主单行时退化为取全部行,
与订单实付「主单优先、无主单退化」保持同一套规则。
2026-10-09 12:14:26 +08:00
7e335b19a9 账单明细:发生时间移到平台后面,筛选栏重新配列 2026-10-09 11:46:57 +08:00
a4899e440e 账单明细:去掉账单项目筛选(改用关键词搜索),筛选栏回到 平台/店铺/财务类型/财务备注 + 关键词 + 日期 2026-10-09 11:45:31 +08:00
35bd7cb7f0 账单明细:财务类型与关键词同一行,筛选栏按平台/店铺/财务备注 + 账单项目/财务类型/关键词 重排 2026-10-09 11:39:43 +08:00
3136f29d33 账单明细:账单项目挪到关键词同一行,筛选栏改 12 列栅格对齐 2026-10-09 11:26:41 +08:00
0f7f72be71 账单明细联动:行数为0的取值不展示,联动结果缓存放宽到5分钟 2026-10-09 11:19:21 +08:00
cfdda94da8 账单明细:财务备注/财务类型筛选按平台限定,修同项目跨平台串行(优惠收入带出冲减收入) 2026-10-09 10:36:27 +08:00
a0faaa116b Merge remote-tracking branch 'origin/main' into feature/yueyang-billing-details-filters 2026-10-09 10:33:35 +08:00
65112a2bff 店铺账号密码:状态映射缓存键升到 v4,强制刷新流程状态
换成 jiansun 实时 OA 流程表后,旧的 v3 缓存(30 分钟)里还留着 7 月之后
审批状态为空的结果,页面会继续显示横杠;升版缓存键让所有环境重新计算。
2026-10-09 10:32:00 +08:00
f56bd9d3ea 账单明细:新增财务备注筛选、筛选联动(行数为0的取值不展示)、行距放宽 2026-10-09 10:30:43 +08:00
473b6f4ebb 修复流程审批状态取不到:OA 流程表改用 jiansun 的实时副本
原来取的是中台库 dbo.flow_flow,那份数据停在 2026-07-16,7 月之后的申请
(比如 shp20260716165004772 京喜-清木居工厂店 关店流程)审批状态全是空的,
而工作平台显示「流程中」。

jiansun.dbo.flow_flow 是实时表(今天还在更新,10543 行),同名单据里
flowStatus=1、当前审批人=山时。已登记并完成首次全量 + 建 flowId 索引;
中台那份旧副本改为停止同步(数据保留)。

流程统计页与店铺账号密码的「流程类型 / 审批状态 / 流程状态」两处取值都跟着换成实时表。
2026-10-09 10:25:43 +08:00
b4821ca933 唯品会MP/JX账户:订单结算时间改为「账单期间」,筛选项也按账单期间过滤
1) 两列改名:AccountBillColumns 里唯品会两个页签的「订单结算时间」→「账单期间」(金额式账期月份,如 2026-07),列类型从 date 改 text 避免被当日期格式化;
2) 筛选标签:DATE_FILTER_LABELS 里 vipshop / vipshop-jx 从「结算时间」改成「账单期间」;
3) 筛选真正生效:这两个页签的 start/end 不再过滤 occurred_at,改为按 payload.settle_period(YYYY-MM)与所选区间取月份交集,页面列表与导出同步生效。
同步更新 AccountBillsTableTest 的断言。
2026-10-09 09:35:16 +08:00
chenxi
a334f65962 业绩明细:订单实付金额排除虚拟条码后的实付
订单实付=订单级实付 − 虚拟条码(X0000x)明细行实付,下限 0,
与商品金额保持同一口径;纯信誉/虚拟订单的实付归零。
同时更新页面口径说明。

影响:京东账单 2026-08 实付 5673.8 万 → 424.9 万(虚拟条码占 5248.9 万)。
2026-10-08 18:31:20 +08:00
0cca2aac70 业绩明细全量重跑:命令内自行放宽 memory_limit,免去手工传 -d memory_limit 参数 2026-10-08 17:41:05 +08:00
8207dc0d95 业绩明细:订单金额/优惠金额/冲减金额统一按「收入-支出」取数,只回填金额时同步刷新差额列 2026-10-08 17:07:11 +08:00
09077c3661 导出进度改为真实百分比(按发生时间流式取数),并修日期框在宽屏下被裁掉 2026-10-08 16:39:42 +08:00
480 changed files with 69050 additions and 2891 deletions

View File

@ -22,6 +22,7 @@ storage/debugbar
storage/framework/cache/data/*
storage/framework/sessions/*
storage/framework/views/*
storage/framework/testing
storage/logs/*
tests
test-data
@ -29,3 +30,6 @@ docs
scripts
npm-debug.log
yarn-error.log
public/net-layer-demo.html
public/perf-diff-plan.html
public/plan-a-changes-202608.csv

3
.gitignore vendored
View File

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

View File

@ -64,6 +64,7 @@
## 8. 构建与生产部署
- 发布脚本会拒绝覆盖“不在本次版本里”的线上提交(防止互相冲掉已上线的改动)。热修复必须基于线上当前版本构建,发布后立即合入 `main`;遇到拦截先 `git fetch` 并合入最新 `main` 或线上热修复分支,不得随手加 `-AllowRollback`(`--allow-rollback`),撤回线上发布需负责人明确决定。
- 普通代码发布由任务 Codex 在完成验证与合并后直接执行,不要求用户再次说“部署、上线”;用户明确要求仅本地开发、仅审查或暂不上线时遵循其范围。正式发布只使用已合并的最新 `main`。
- Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`,macOS 开发机使用 `bash scripts/deploy-from-mac.sh`;两者流程一致(本机构建前端与镜像、迁移拦截、增量推送服务器本机 Registry、激活与健康检查、双版本保留)。服务器只运行开发机已构建的 `caiwu_akaunting:<commit>` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。
- 新人只需表达部署需求;Codex 使用默认生产入口运行脚本。首次通过本机窗口提供一次服务器密码后,加密保存在本人电脑供后续自动使用,不要求新人准备私钥、执行命令或每次重输密码。已有私钥认证仍兼容。

View File

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

View File

@ -9,7 +9,9 @@ use RuntimeException;
/**
* 快递运费导入(.xlsx / .csv)。
*
* 源表头:来源 / 成品配件(也接受「成品运费」)/ 交易单号 / 提供成本运费(按表头名匹配,列顺序无关)。
* 源表头(按表头名匹配,列顺序无关):
* - 必需:来源 / 成品配件(也接受「成品运费」)/ 交易单号 / 提供成本运费;
* - 可选:快递单号 / 条形码 / 店铺名称(「财务系统运费整理.xlsx」起提供的列,老文件没有也能导)。
* 快递方给的文件常见几十万行,xlsx 走 XlsxSheetReader 流式读取,不整表进内存。
*/
class CourierFreightImporter
@ -20,14 +22,21 @@ class CourierFreightImporter
'成品配件' => 'part',
'成品运费' => 'part',
'交易单号' => 'transaction_no',
'快递单号' => 'express_no',
'条形码' => 'barcode',
'店铺名称' => 'shop_name',
'提供成本运费' => 'freight_amount',
];
private const HEADERS = ['来源', '成品配件', '交易单号', '提供成本运费'];
/** 表头别名:源文件里这一列有时写「成品配件」、有时写「成品运费」。 */
/** 可选列:文件里有就导入,没有就留空(老文件兼容)。 */
private const OPTIONAL_HEADERS = ['快递单号', '条形码', '店铺名称'];
/** 表头别名:源文件的列名写法不统一(成品配件 / 成品运费;店铺名称 / 店铺)。 */
private const HEADER_ALIASES = [
'成品配件' => ['成品配件', '成品运费'],
'店铺名称' => ['店铺名称', '店铺'],
];
private const CHUNK = 2000;
@ -86,6 +95,9 @@ class CourierFreightImporter
'source' => $sourceValue ?? '',
'part' => $this->text($line['成品配件'] ?? null, 191),
'transaction_no' => $transactionNo ?? '',
'express_no' => $this->text($line['快递单号'] ?? null, 64),
'barcode' => $this->text($line['条形码'] ?? null, 191),
'shop_name' => $this->text($line['店铺名称'] ?? null, 191),
'freight_amount' => number_format($value, 4, '.', ''),
'created_at' => $now,
'updated_at' => $now,
@ -152,8 +164,12 @@ class CourierFreightImporter
static fn (string $name): array|string => self::HEADER_ALIASES[$name] ?? $name,
self::HEADERS,
);
$optionalColumns = array_map(
static fn (string $name): array|string => self::HEADER_ALIASES[$name] ?? $name,
self::OPTIONAL_HEADERS,
);
yield from ($this->reader ?? app(XlsxSheetReader::class))->rows($path, $columns);
yield from ($this->reader ?? app(XlsxSheetReader::class))->rows($path, $columns, $optionalColumns);
}
/** 把表头别名折回规范列名。 */

View File

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

View File

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

View File

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

View File

@ -30,6 +30,7 @@ class JstOrderLabelImporter
public function __construct(
private readonly DatabaseManager $databases,
private readonly ?XlsxSheetReader $exportReader = null,
private readonly ?JstOrderLabelItemCodes $itemCodes = null,
) {}
/**
@ -53,6 +54,8 @@ class JstOrderLabelImporter
$target = $this->databases->connection();
$startedAt = microtime(true);
$itemCodes = $this->itemCodes ?? new JstOrderLabelItemCodes();
$hasItemTable = $mirror->getSchemaBuilder()->hasTable('ops_jst_order_item');
if ($replace) {
$target->table('jst_order_labels')
@ -60,6 +63,7 @@ class JstOrderLabelImporter
->where('ordered_at', '>=', $start)
->where('ordered_at', '<', $end)
->delete();
app(PlantingOrderLabelLookup::class)->forget($companyId);
}
$now = now();
@ -68,9 +72,10 @@ class JstOrderLabelImporter
$noLabelOrders = 0;
$buffer = [];
$flush = function () use (&$buffer, &$rows, $target): void {
$flush = function () use (&$buffer, &$rows, $target, $companyId): void {
foreach (array_chunk($buffer, self::INSERT_CHUNK) as $chunk) {
$target->table('jst_order_labels')->insert($chunk);
app(PlantingOrderLabelLookup::class)->forget($companyId);
$rows += count($chunk);
}
$buffer = [];
@ -80,7 +85,12 @@ class JstOrderLabelImporter
->where('order_date', '>=', $start)
->where('order_date', '<', $end)
->orderBy('Id')
->chunkById(self::READ_CHUNK, function ($records) use (&$buffer, &$orders, &$noLabelOrders, $flush, $companyId, $source, $now): void {
->chunkById(self::READ_CHUNK, function ($records) use (&$buffer, &$orders, &$noLabelOrders, $flush, $companyId, $source, $now, $itemCodes, $hasItemTable, $mirror): void {
// 货号:同批订单的商品编码(镜像商品明细,按 o_id 取),导入时一并写入
$orderCodes = $hasItemTable
? $itemCodes->forOrderIds($mirror, 'ops_jst_order_item', $records->pluck('o_id')->all())
: [];
foreach ($records as $record) {
$orders++;
$orderedAt = $record->order_date === null ? null : substr((string) $record->order_date, 0, 19);
@ -94,6 +104,8 @@ class JstOrderLabelImporter
$noLabelOrders++;
}
$itemCode = $orderCodes[(int) $record->o_id] ?? null;
foreach ($labels as $label) {
$buffer[] = [
'company_id' => $companyId,
@ -101,6 +113,7 @@ class JstOrderLabelImporter
'shop_name' => mb_substr((string) ($record->shop_name ?? ''), 0, 191),
'ordered_at' => $orderedAt,
'label' => $label,
'item_code' => $itemCode,
'created_from' => $source,
'created_at' => $now,
'updated_at' => $now,
@ -180,6 +193,7 @@ class JstOrderLabelImporter
->where('ordered_at', '>=', $start)
->where('ordered_at', '<', $end)
->delete();
app(PlantingOrderLabelLookup::class)->forget($companyId);
};
$cleared = ! $replace;
@ -192,9 +206,10 @@ class JstOrderLabelImporter
$orderSeen = [];
$buffer = [];
$flush = function () use (&$buffer, &$rows, $target): void {
$flush = function () use (&$buffer, &$rows, $target, $companyId): void {
foreach (array_chunk($buffer, self::INSERT_CHUNK) as $chunk) {
$target->table('jst_order_labels')->insert($chunk);
app(PlantingOrderLabelLookup::class)->forget($companyId);
$rows += count($chunk);
}
$buffer = [];

View File

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

View File

@ -9,7 +9,9 @@ use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* 聚水潭订单标签明细的「是否种菜订单」判断:按(公司 + 标签)匹配映射表。
* 聚水潭订单标签明细的「是否种菜订单」判断:
* - 按(公司 + 标签)匹配财务维护的映射表;
* - 订单货号含信誉订单虚拟条码(X00006)的直接判为「是」。
*
* 映射表由财务维护(判断种菜单.xlsx)并按公司缓存,页面与导出共用同一份结果;
* 映射表缺失或未导入时不报错,统一按「否」展示。
@ -18,6 +20,9 @@ class JstOrderLabelPlantingRules
{
private const TTL_HOURS = 24;
/** 该货号(信誉订单虚拟条码)的订单直接判为种菜订单。 */
public const PLANTING_ITEM_CODE = 'X00006';
/** @return array<string,string> [标签 => 是/否] */
public function map(int $companyId): array
{
@ -46,20 +51,38 @@ class JstOrderLabelPlantingRules
});
}
/** 单个标签的判断结果:命中映射表取映射值(默认是),未命中为否。 */
public function flag(int $companyId, ?string $label): string
/**
* 单条(标签 + 货号)的判断结果:标签命中映射表取其值;
* 货号含 X00006 的一律为「是」,其余未命中为「否」。
*/
public function flag(int $companyId, ?string $label, ?string $itemCode = null): string
{
$key = trim((string) $label);
if ($key === '') {
return '否';
$flag = $key === '' ? '否' : ($this->map($companyId)[$key] ?? '否');
if ($flag === '否' && $this->hasPlantingItemCode($itemCode)) {
return '是';
}
return $this->map($companyId)[$key] ?? '否';
return $flag;
}
/** 货号(可能多个,逗号连接)里是否含信誉订单虚拟条码。 */
private function hasPlantingItemCode(?string $itemCode): bool
{
foreach (explode(',', (string) $itemCode) as $code) {
if (mb_strtoupper(trim($code)) === self::PLANTING_ITEM_CODE) {
return true;
}
}
return false;
}
public function forget(int $companyId): void
{
Cache::forget($this->key($companyId));
app(PlantingOrderLabelLookup::class)->forget($companyId);
}
private function key(int $companyId): string

View File

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

View File

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

View File

@ -72,6 +72,9 @@ class StoreViolationMapper
'shop_name' => mb_substr(trim((string) ($row['shop_name'] ?? '')), 0, 191),
'violation_type' => $content === '' ? null : mb_substr($content, 0, 500),
'violation_category' => $this->categoryForContent($content),
// 上游视图补齐这两列后由同步命令自动带出(见 SyncStoreViolations 的列探测)。
'violation_reason' => $this->normalizeLabel($row['violation_reason'] ?? null, 500),
'disposition' => $this->normalizeLabel($row['disposition'] ?? null, 500),
'violation_no' => mb_substr(trim((string) ($row['violation_no'] ?? '')), 0, 100),
'violation_date' => $this->normalizeDate($row['violation_date'] ?? null),
'status' => $this->normalizeLabel($row['status'] ?? null, 64),

View File

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

View File

@ -19,6 +19,7 @@ class StoreViolationWorkbookImporter
public function __construct(
private readonly StoreViolationMapper $mapper,
private readonly StoreViolationRecordRepository $repository,
private readonly StoreViolationAlertCalculator $alerts,
) {
}
@ -139,6 +140,11 @@ class StoreViolationWorkbookImporter
}
$updateColumns[] = 'source';
$updateColumns[] = 'updated_at';
// 预警派生字段(级别/责任人/处理截止等):导入时按当前字典自动计算写入。
$updateColumns = array_values(array_unique(array_merge(
$updateColumns,
StoreViolationRecordRepository::ALERT_DERIVED_COLUMNS,
)));
$payload = [];
$created = 0;
@ -155,6 +161,17 @@ class StoreViolationWorkbookImporter
continue;
}
$matchType = trim((string) ($data['violation_type'] ?? '')) !== ''
? (string) $data['violation_type']
: ($data['violation_reason'] ?? null);
$data = array_merge($data, $this->alerts->calculate(
$platform,
(string) ($data['shop_name'] ?? ''),
$matchType,
$data['violation_date'] ?? null,
$data['appeal_deadline'] ?? null,
));
foreach (array_values(array_diff($updateColumns, ['source', 'updated_at'])) as $column) {
if (! array_key_exists($column, $data)) {
$data[$column] = null;
@ -305,13 +322,25 @@ class StoreViolationWorkbookImporter
$data['violation_type'] = $type === '' ? null : mb_substr($type, 0, 500);
}
$reason = $has('violation_reason') ? trim((string) ($raw['violation_reason'] ?? '')) : null;
if ($has('violation_reason')) {
$data['violation_reason'] = $reason === '' ? null : mb_substr($reason, 0, 500);
}
if ($has('disposition')) {
$disposition = trim((string) ($raw['disposition'] ?? ''));
$data['disposition'] = $disposition === '' ? null : mb_substr($disposition, 0, 500);
}
if ($has('violation_category')) {
$categorySource = ($type !== null && $type !== '') ? $type : (string) $reason;
$category = trim((string) ($raw['violation_category'] ?? ''));
$data['violation_category'] = $category === ''
? $this->mapper->categoryForContent($type)
? $this->mapper->categoryForContent($categorySource)
: mb_substr($category, 0, 64);
} elseif ($has('violation_type')) {
$data['violation_category'] = $this->mapper->categoryForContent($type);
} elseif ($has('violation_type') || $has('violation_reason')) {
$categorySource = ($type !== null && $type !== '') ? $type : (string) $reason;
$data['violation_category'] = $this->mapper->categoryForContent($categorySource);
}
if ($has('violation_date')) {
@ -357,6 +386,8 @@ class StoreViolationWorkbookImporter
if ($has('handling_status')) {
$handling = trim((string) ($raw['handling_status'] ?? ''));
$legacyMap = (array) config('store_violations.handling_status_legacy', []);
$handling = (string) ($legacyMap[$handling] ?? $handling);
$options = (array) config('store_violations.handling_statuses', []);
if ($handling === '') {
$data['handling_status'] = (string) config('store_violations.default_handling_status', '未处理');
@ -368,6 +399,15 @@ class StoreViolationWorkbookImporter
}
}
if ($has('ignore_reason')) {
$ignoreReason = trim((string) ($raw['ignore_reason'] ?? ''));
$data['ignore_reason'] = $ignoreReason === '' ? null : mb_substr($ignoreReason, 0, 191);
}
if (($data['handling_status'] ?? null) === '已忽略' && trim((string) ($data['ignore_reason'] ?? '')) === '') {
$errors[] = '处理状态为“已忽略”时必须填写忽略原因';
}
return [
'row_number' => $rowNumber,
'status' => $errors === [] ? 'valid' : 'invalid',

View File

@ -3,6 +3,7 @@
namespace App\Business;
use App\Models\Business\StoreReceivingAccount;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
@ -30,12 +31,12 @@ class WithdrawalManagementReport
/**
* @return array{
* filters:array{platform:string,withdrawalPath:string,storeEntity:string,keyword:string,balanceStatus:string},
* filters:array{platform:string,withdrawalPath:string,storeEntity:string,keyword:string,balanceStatus:string,balanceDate:string},
* platforms:list<string>,paths:list<string>,storeEntities:list<string>,rows:Collection<int,StoreReceivingAccount>,
* balances:array<int,array{status:string,balance:?float,source_store_name:?string,source_platform:?string}>,
* reserveStandards:array<int,int|null>,withdrawalAmounts:array<int,float|null>,compliance:array<int,string|null>,
* summary:array{source:int,matched:int,ambiguous:int,unmatched:int,not_ready:int},
* balanceColumnLabel:string,balanceDate:string,sort:array{field:string,direction:string}
* balanceColumnLabel:string,balanceDate:string,balanceDates:list<string>,sort:array{field:string,direction:string}
* }
*/
public function results(Request $request): array
@ -61,7 +62,14 @@ class WithdrawalManagementReport
}
$today = now()->startOfDay();
$balanceDate = $today->copy()->subDay()->toDateString();
// 余额快照按日期长期保留:默认显示最新余额日期,也可指定历史日期回看。
$latestBalanceDate = $this->shopBalances->latestBalanceDate($today);
$balanceDate = $filters['balanceDate'] !== ''
? $filters['balanceDate']
: ($latestBalanceDate ?? $today->copy()->subDay()->toDateString());
$labelDate = $filters['balanceDate'] !== ''
? CarbonImmutable::parse($balanceDate)
: $today;
$rows = $query->orderByDesc('id')->get();
$balances = $this->shopBalances->matchesForStores($rows, $balanceDate);
$balanceCounts = collect($balances)->countBy(
@ -117,21 +125,28 @@ class WithdrawalManagementReport
'unmatched' => (int) $balanceCounts->get('unmatched', 0),
'not_ready' => (int) $balanceCounts->get('not_ready', 0),
],
'balanceColumnLabel' => $today->format('n月j日') . '店铺余额',
'balanceColumnLabel' => $labelDate->format('n月j日') . '店铺余额',
'balanceDate' => $balanceDate,
'balanceDates' => $this->shopBalances->availableDates($today),
'sort' => $sort,
];
}
/** @return array{platform:string,withdrawalPath:string,storeEntity:string,keyword:string,balanceStatus:string} */
/** @return array{platform:string,withdrawalPath:string,storeEntity:string,keyword:string,balanceStatus:string,balanceDate:string} */
public function filters(Request $request): array
{
$clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length);
$balanceStatus = $clean($request->query('balance_status'));
$balanceDate = $clean($request->query('balance_date'), 10);
if (! in_array($balanceStatus, ['matched', 'unmatched', 'ambiguous', 'not_ready'], true)) {
$balanceStatus = '';
}
$validDate = preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $balanceDate, $parts) === 1
&& checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1]);
if (! $validDate || $balanceDate > now()->toDateString()) {
$balanceDate = '';
}
return [
'platform' => $clean($request->query('platform')),
@ -139,6 +154,7 @@ class WithdrawalManagementReport
'storeEntity' => $clean($request->query('store_entity'), 191),
'keyword' => $clean($request->query('keyword'), 191),
'balanceStatus' => $balanceStatus,
'balanceDate' => $balanceDate,
];
}

View File

@ -13,6 +13,7 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
@ -30,6 +31,11 @@ class WithdrawalManagementSpreadsheet
private const CLEAR_VALUE = '[清空]';
public function __construct(
private readonly JushuitanShopBalanceRepository $shopBalances,
) {
}
/**
* @param array{
* rows:\Illuminate\Support\Collection<int,StoreReceivingAccount>,
@ -63,7 +69,7 @@ class WithdrawalManagementSpreadsheet
['1. 店铺平台、ERP店铺名称用于定位店铺;有平台店铺ID时优先按平台和ID匹配。'],
['2. 店铺主体、提现路径、提现账户名称、银行卡号后四位和提现金额为可更新字段。'],
['3. 可更新字段留空表示保持原值,填写“' . self::CLEAR_VALUE . '”表示清空原值。'],
['4. 提现金额须为非负数,最多两位小数,只用于导入当天对应的余额数据日期;上传后先预览再确认。'],
['4. 提现金额须为非负数,最多两位小数,只用于当前页面显示的余额数据日期(最近 5 天内最新可用日期);上传后先预览再确认。'],
], null, 'A1');
$instructions->getStyle('A1')->getFont()->setBold(true)->setSize(14);
$instructions->getColumnDimension('A')->setWidth(88);
@ -97,7 +103,7 @@ class WithdrawalManagementSpreadsheet
}
[$headerIndex, $headers] = $this->headers($matrix);
$indexes = array_flip($headers);
$balanceDate = now()->subDay()->toDateString();
$balanceDate = $this->currentBalanceDate();
$accounts = StoreReceivingAccount::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
@ -221,6 +227,7 @@ class WithdrawalManagementSpreadsheet
{
return DB::transaction(function () use ($plan, $companyId): int {
$updated = 0;
$currentBalanceDate = null;
foreach ($plan as $item) {
/** @var StoreReceivingAccount|null $account */
@ -238,11 +245,13 @@ class WithdrawalManagementSpreadsheet
}
if (isset($item['changes']['withdrawal_balance_date'])
&& $item['changes']['withdrawal_balance_date'] !== null
&& $item['changes']['withdrawal_balance_date'] !== now()->subDay()->toDateString()) {
throw ValidationException::withMessages([
'import' => '余额日期已滚动,请重新上传并预览提现金额。',
]);
&& $item['changes']['withdrawal_balance_date'] !== null) {
$currentBalanceDate ??= $this->currentBalanceDate();
if ($item['changes']['withdrawal_balance_date'] !== $currentBalanceDate) {
throw ValidationException::withMessages([
'import' => '余额日期已滚动,请重新上传并预览提现金额。',
]);
}
}
foreach ($item['changes'] as $field => $value) {
@ -423,6 +432,14 @@ class WithdrawalManagementSpreadsheet
return $changes;
}
private function currentBalanceDate(): string
{
$today = now()->startOfDay();
return $this->shopBalances->latestBalanceDate($today)
?? $today->copy()->subDay()->toDateString();
}
private function key(string $platform, string $identity): string
{
return trim($platform) . "\0" . trim($identity);

View File

@ -24,12 +24,13 @@ class XlsxSheetReader
/**
* 逐行读取导出文件(跳过表头行)。
*
* @param list<string|list<string>> $columns 需要取出的列。给字符串就是精确匹配表头;
* @param list<string|list<string>> $columns 需要取出的列(缺列会报错)。给字符串就是精确匹配表头;
* 给数组表示同一列有多个可选表头(取第一个命中的,
* 返回键用数组里的第一个名字)。
* @param list<string|list<string>> $optionalColumns 可选列:文件里有就取,没有就跳过(不报错)。
* @return Generator<int, array<string, string>>
*/
public function rows(string $path, array $columns): Generator
public function rows(string $path, array $columns, array $optionalColumns = []): Generator
{
if (! is_file($path)) {
throw new RuntimeException('订单导出文件不存在:' . $path);
@ -48,7 +49,7 @@ class XlsxSheetReader
}
try {
yield from $this->parseSheet($stream, $this->sharedStrings($zip), $columns);
yield from $this->parseSheet($stream, $this->sharedStrings($zip), $columns, $optionalColumns);
} finally {
fclose($stream);
$zip->close();
@ -59,9 +60,10 @@ class XlsxSheetReader
* @param resource $stream
* @param list<string> $shared
* @param list<string|list<string>> $columns
* @param list<string|list<string>> $optionalColumns
* @return Generator<int, array<string, string>>
*/
private function parseSheet($stream, array $shared, array $columns): Generator
private function parseSheet($stream, array $shared, array $columns, array $optionalColumns): Generator
{
$state = [
'row' => [],
@ -98,7 +100,7 @@ class XlsxSheetReader
break;
}
},
static function ($parser, string $name) use (&$state, $shared, $columns): void {
static function ($parser, string $name) use (&$state, $shared, $columns, $optionalColumns): void {
switch ($name) {
case 'v':
case 't':
@ -112,7 +114,7 @@ class XlsxSheetReader
case 'row':
$state['rowNumber']++;
if ($state['rowNumber'] === 1) {
$state['wanted'] = self::wantedColumns($state['row'], $columns);
$state['wanted'] = self::wantedColumns($state['row'], $columns, $optionalColumns);
break;
}
@ -168,13 +170,14 @@ class XlsxSheetReader
}
/**
* 表头行 -> [列下标 => 列名],并校验需要的列都在。
* 表头行 -> [列下标 => 列名],并校验需要的列都在;可选列缺了不算错。
*
* @param array<int, string> $header
* @param list<string|list<string>> $columns
* @param list<string|list<string>> $optionalColumns
* @return array<int, string>
*/
private static function wantedColumns(array $header, array $columns): array
private static function wantedColumns(array $header, array $columns, array $optionalColumns = []): array
{
$byName = [];
foreach ($header as $index => $name) {
@ -200,6 +203,20 @@ class XlsxSheetReader
$wanted[$byName[$matched]] = $names[0];
}
foreach ($optionalColumns as $column) {
$names = is_array($column) ? array_values($column) : [$column];
$matched = null;
foreach ($names as $name) {
if (isset($byName[$name])) {
$matched = $name;
break;
}
}
if ($matched !== null && ! isset($wanted[$byName[$matched]])) {
$wanted[$byName[$matched]] = $names[0];
}
}
return $wanted;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,683 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
use Throwable;
/**
* 按「附加费报价维护」里启用的超长费规则,从销售出库单拉取结算行。
*
* 口径(第一期只做超长费,且只处理“按尺寸/最长边”的规则):
* - 规则状态必须是 active;
* - 生效条件解析出单边阈值(如“单边超160cm”);
* - 计价标准解析出每单金额(如“8元/单”);
* - 出库单按 logistics_company = 快递名称 匹配,运单号取 l_id,只取已分配运单号的单;
* - 长宽高按明细条形码 sku_id 到商品及库存管理(商品资料 jst_sku)换算,一票多件取最大边;
* - 查件类型/查件原因/退回单号/平台商品ID 在出库单与商品资料里取不到,留空。
*/
class PullCourierSurchargeOverlength extends Command
{
protected $signature = 'courier-surcharge:pull-overlength
{--days=90 : 默认拉取最近多少天(无 --from/--to 时生效)}
{--from= : 出库日期起(含),Y-m-d}
{--to= : 出库日期止(不含),Y-m-d}
{--rule=* : 只跑指定规则 ID,可多次传入}
{--chunk=300 : 每批处理的出库单数量}';
protected $description = '按启用的超长费报价规则,从销售出库单拉取附加费结算行';
public function handle(): int
{
$from = $this->option('from') !== null && $this->option('from') !== ''
? Carbon::parse((string) $this->option('from'))->startOfDay()
: now()->subDays(max((int) $this->option('days'), 1))->startOfDay();
$to = $this->option('to') !== null && $this->option('to') !== ''
? Carbon::parse((string) $this->option('to'))->startOfDay()
: now()->addDay()->startOfDay();
$onlyRules = array_filter(array_map('intval', (array) $this->option('rule')));
$chunkSize = min(max((int) $this->option('chunk'), 50), 500);
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$schema = DB::connection($connection)->getSchemaBuilder();
if (! $schema->hasTable('courier_surcharge_settlement_rows')) {
$this->error('结算表 courier_surcharge_settlement_rows 不存在,请先执行迁移。');
return self::FAILURE;
}
$rules = $this->overlengthRules($onlyRules);
if ($rules === []) {
$this->warn('没有启用且可自动计算的超长费规则。');
return self::SUCCESS;
}
$upstream = app(UpstreamReadOnlyQueryFactory::class)->forSource('jiansun');
$totalWritten = 0;
foreach ($rules as $rule) {
$threshold = $rule['threshold'];
$amount = $rule['amount'];
$this->info(sprintf(
'规则 #%d %s:单边超 %scm 计 %s 元/单,取数 %s ~ %s',
$rule['id'],
$rule['courier'],
$threshold,
$amount,
$from->toDateString(),
$to->toDateString(),
));
$orders = $this->pullOrders($upstream, $rule['courier'], $from, $to, $chunkSize);
if ($orders === []) {
$this->line(' 没有运单号非空的出库单,跳过。');
continue;
}
$written = $this->writeSettlementRows($connection, $rule, $orders, $threshold, $amount, $from, $to);
$totalWritten += $written;
$this->line(' 出库单 ' . count($orders) . ' 单,命中超长并写入 ' . $written . ' 行。');
}
$this->info('完成,共写入 ' . $totalWritten . ' 行结算数据。');
return self::SUCCESS;
}
/**
* @param list<int> $onlyRules
* @return list<array{id:int,courier:string,threshold:float,amount:float}>
*/
private function overlengthRules(array $onlyRules): array
{
$rules = [];
foreach (DB::table('business_courier_surcharge_quotes')->where('status', 'active')->orderBy('id')->get() as $rule) {
$types = json_decode((string) $rule->types, true) ?: [];
if (! in_array('超长费', $types, true)) {
continue;
}
if (! str_contains((string) $rule->mode, '按尺寸') && ! str_contains((string) $rule->mode, '最长边')) {
continue;
}
if ($onlyRules !== [] && ! in_array((int) $rule->id, $onlyRules, true)) {
continue;
}
$condition = (string) $rule->condition;
$standard = (string) $rule->standard;
if (preg_match('/单边超\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米|CM|㎝)/u', $condition, $matched) !== 1) {
$this->warn('规则 #' . $rule->id . ' 的生效条件解析不出单边阈值,已跳过:' . $condition);
continue;
}
$threshold = (float) $matched[1];
if (preg_match('/(\d+(?:\.\d+)?)\s*元\s*\/?\s*单/u', $standard, $priceMatched) !== 1) {
$this->warn('规则 #' . $rule->id . ' 的计价标准解析不出每单金额,已跳过:' . $standard);
continue;
}
$rules[] = [
'id' => (int) $rule->id,
'courier' => trim((string) $rule->courier),
'threshold' => $threshold,
'amount' => (float) $priceMatched[1],
];
}
return $rules;
}
/**
* 拉取出库单(只取已分配运单号的单)。
*
* @return list<array<string,mixed>>
*/
private function pullOrders(
UpstreamReadOnlyQuery $upstream,
string $courier,
Carbon $from,
Carbon $to,
int $chunkSize,
): array {
$orders = [];
$lastId = 0;
while (true) {
$rows = $upstream->select(
'SELECT TOP ' . $chunkSize . ' Id, io_id, o_id, l_id, so_id, shop_name, io_date, weight, f_weight '
. 'FROM dbo.jst_salesOutboundInfo '
. 'WHERE logistics_company = ? AND io_date >= ? AND io_date < ? '
. "AND LEN(ISNULL(l_id, '')) > 0 AND Id > ? "
. 'ORDER BY Id',
[$courier, $from->toDateTimeString(), $to->toDateTimeString(), $lastId],
);
if ($rows === []) {
break;
}
foreach ($rows as $row) {
$row = (array) $row;
$orders[] = $row;
$lastId = max($lastId, (int) $row['Id']);
}
if (count($rows) < $chunkSize) {
break;
}
}
return $orders;
}
/**
* @param list<array<string,mixed>> $orders
*/
private function writeSettlementRows(
string $connection,
array $rule,
array $orders,
float $threshold,
float $amount,
Carbon $from,
Carbon $to,
): int {
$ioIds = array_values(array_filter(array_map(
static fn (array $order): int => (int) ($order['io_id'] ?? 0),
$orders,
), static fn (int $value): bool => $value > 0));
$items = $this->pullItems($ioIds);
$dimensions = $this->dimensionMap($items);
$platformProductIds = $this->platformProductIds($items, $orders);
$onlineOrderNumbers = $this->onlineOrderNumbers($orders);
$now = now();
$written = 0;
$rows = [];
foreach ($orders as $order) {
$ioId = (int) ($order['io_id'] ?? 0);
if ($ioId <= 0) {
continue;
}
$best = null;
foreach ($items[$ioId] ?? [] as $item) {
$skuId = trim((string) ($item['sku_id'] ?? ''));
$dim = $dimensions[$skuId] ?? null;
if ($dim === null) {
continue;
}
$maxSide = max($dim['l'], $dim['w'], $dim['h']);
if ($best === null || $maxSide > $best['max_side']) {
$best = [
'max_side' => $maxSide,
'sku_id' => $skuId,
'i_id' => trim((string) ($item['i_id'] ?? '')),
'length' => $dim['l'],
'width' => $dim['w'],
'height' => $dim['h'],
'platform_product_id' => $platformProductIds[$ioId][$skuId] ?? ($platformProductIds[$ioId][''] ?? null),
];
}
}
if ($best === null || $best['max_side'] <= $threshold) {
continue;
}
$rows[] = [
'rule_id' => $rule['id'],
'surcharge_type' => '超长费',
'courier_name' => $rule['courier'],
'waybill' => trim((string) ($order['l_id'] ?? '')),
'outbound_io_id' => $ioId,
'platform_product_id' => $best['platform_product_id'],
'product_code' => $best['sku_id'] !== '' ? $best['sku_id'] : ($best['i_id'] !== '' ? $best['i_id'] : null),
'shop_name' => mb_substr(trim((string) ($order['shop_name'] ?? '')), 0, 191) ?: null,
'online_order_no' => $onlineOrderNumbers[(int) ($order['o_id'] ?? 0)] ?? null,
'length' => $best['length'],
'width' => $best['width'],
'height' => $best['height'],
'volume' => round($best['length'] * $best['width'] * $best['height'], 2),
'inspection_type' => null,
'inspection_reason' => null,
'return_waybill_no' => null,
'settlement_weight' => null,
'settlement_amount' => $amount,
'settlement_status' => '已计算',
'evidence' => mb_substr(sprintf(
'条形码 %s 尺寸 %s×%s×%s,最长边 %scm > %scm',
$best['sku_id'] !== '' ? $best['sku_id'] : '(无)',
$this->trimNumber($best['length']),
$this->trimNumber($best['width']),
$this->trimNumber($best['height']),
$this->trimNumber($best['max_side']),
$this->trimNumber($threshold),
), 0, 500),
'shipped_at' => $order['io_date'] ?? null,
'pulled_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
$written++;
}
$target = DB::connection($connection)->table('courier_surcharge_settlement_rows');
// 同一规则、同一取数窗口内重跑时先清掉旧行,避免残留历史判断。
$target->where('rule_id', $rule['id'])
->where('shipped_at', '>=', $from->toDateTimeString())
->where('shipped_at', '<', $to->toDateTimeString())
->delete();
foreach (array_chunk($rows, 500) as $chunk) {
$target->insert($chunk);
}
return $written;
}
/**
* @param list<int> $ioIds
* @return array<int,list<array<string,mixed>>>
*/
private function pullItems(array $ioIds): array
{
if ($ioIds === []) {
return [];
}
$upstream = app(UpstreamReadOnlyQueryFactory::class)->forSource('jiansun');
$items = [];
foreach (array_chunk($ioIds, 500) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
$rows = $upstream->select(
'SELECT io_id, sku_id, i_id, name, qty FROM dbo.jst_salesOutboundItem WHERE io_id IN (' . $placeholders . ')',
$chunk,
);
foreach ($rows as $row) {
$row = (array) $row;
$items[(int) $row['io_id']][] = $row;
}
}
return $items;
}
/**
* 线上订单号:优先用出库单自带 so_id,为空时按 o_id 到「未发货订单」表兜底。
*
* 部分渠道(如阿里巴巴-常州玖阔)的出库单 so_id 为空,但发货中订单表
* jst_nosend_orders 里仍能按 o_id 找到线上单号。
*
* @param list<array<string,mixed>> $orders
* @return array<int,string>
*/
private function onlineOrderNumbers(array $orders): array
{
$map = [];
$missing = [];
foreach ($orders as $order) {
$oId = (int) ($order['o_id'] ?? 0);
$soId = trim((string) ($order['so_id'] ?? ''));
if ($soId !== '') {
$map[$oId] = mb_substr($soId, 0, 191);
} elseif ($oId > 0) {
$missing[$oId] = true;
}
}
if ($missing === []) {
return $map;
}
$upstream = app(UpstreamReadOnlyQueryFactory::class)->forSource('jiansun');
foreach (array_chunk(array_keys($missing), 500) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
try {
$rows = $upstream->select(
"SELECT o_id, so_id FROM dbo.jst_nosend_orders WHERE o_id IN (" . $placeholders . ')'
. " AND LEN(ISNULL(so_id, '')) > 0",
$chunk,
);
} catch (Throwable) {
continue;
}
foreach ($rows as $row) {
$row = (array) $row;
$map[(int) $row['o_id']] = mb_substr(trim((string) $row['so_id']), 0, 191);
}
}
// 仍未补到的(多为已发货、已离开未发货订单表的单),到订单视图兜底;
// 该视图覆盖部分不在 jst_Orders 主表里的店铺(如阿里巴巴-常州玖阔)。
$remaining = array_values(array_diff(array_keys($missing), array_keys($map)));
foreach (array_chunk($remaining, 500) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
try {
$rows = $upstream->select(
"SELECT o_id, so_id FROM dbo.jst_ordersView WHERE o_id IN (" . $placeholders . ')'
. " AND LEN(ISNULL(so_id, '')) > 0",
$chunk,
);
} catch (Throwable) {
continue;
}
foreach ($rows as $row) {
$row = (array) $row;
$map[(int) $row['o_id']] = mb_substr(trim((string) $row['so_id']), 0, 191);
}
}
// 再兜底:发货数据视图在订单离开 jst_Orders/ordersView/nosend 后仍保留 o_id → so_id,
// 例如 2026-07-31 新佰广1688 已归档的出库单。
$remaining = array_values(array_diff(array_keys($missing), array_keys($map)));
foreach (array_chunk($remaining, 200) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
try {
$rows = $upstream->select(
'SELECT DISTINCT o_id, so_id FROM dbo.Jst_SendData_View WHERE o_id IN (' . $placeholders . ')'
. ' AND LEN(so_id) > 0',
$chunk,
);
} catch (Throwable) {
continue;
}
foreach ($rows as $row) {
$row = (array) $row;
$map[(int) $row['o_id']] = mb_substr(trim((string) $row['so_id']), 0, 191);
}
}
// 最后兜底:全渠道订单列表按月归档,部分天猫订单只在该表保留 o_id → so_id。
$remaining = array_values(array_diff(array_keys($missing), array_keys($map)));
if ($remaining !== []) {
$monthById = [];
foreach ($orders as $order) {
$oId = (int) ($order['o_id'] ?? 0);
$ioDate = trim((string) ($order['io_date'] ?? ''));
if ($oId <= 0 || $ioDate === '') {
continue;
}
try {
$monthById[$oId] = Carbon::parse($ioDate)->format('Ym');
} catch (Throwable) {
// io_date 无法解析时只查当前表。
}
}
$tables = ['jst_qmcust_orderlist' => array_values($remaining)];
foreach ($remaining as $oId) {
$month = $monthById[$oId] ?? null;
if ($month !== null) {
$tables['jst_qmcust_orderlist_' . $month][] = $oId;
}
}
foreach ($tables as $table => $ids) {
foreach (array_chunk($ids, 200) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
try {
$rows = $upstream->select(
'SELECT o_id, so_id FROM dbo.' . $table . ' WHERE o_id IN (' . $placeholders . ')'
. ' AND LEN(so_id) > 0',
$chunk,
);
} catch (Throwable) {
continue;
}
foreach ($rows as $row) {
$row = (array) $row;
$map[(int) $row['o_id']] = mb_substr(trim((string) $row['so_id']), 0, 191);
}
}
}
}
return $map;
}
/**
* 平台商品ID:查件工单里的 platformItemId 与订单/发货明细的 shop_i_id 同源。
* 优先按 io_id + sku_id 从发货明细视图取;缺行时按 o_id 到全渠道订单明细(当前表 + 月度归档)兜底。
*
* @param array<int,list<array<string,mixed>>> $items
* @param list<array<string,mixed>> $orders
* @return array<int,array<string,string>>
*/
private function platformProductIds(array $items, array $orders): array
{
$map = [];
$ioIds = array_keys($items);
if ($ioIds === []) {
return $map;
}
$upstream = app(UpstreamReadOnlyQueryFactory::class)->forSource('jiansun');
foreach (array_chunk($ioIds, 200) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
try {
$rows = $upstream->select(
'SELECT io_id, sku_id, shop_i_id FROM dbo.Jst_SendDataDetail_View WHERE io_id IN (' . $placeholders . ')'
. ' AND LEN(shop_i_id) > 0',
$chunk,
);
} catch (Throwable) {
continue;
}
foreach ($rows as $row) {
$row = (array) $row;
$ioId = (int) ($row['io_id'] ?? 0);
$skuId = trim((string) ($row['sku_id'] ?? ''));
$shopIId = mb_substr(trim((string) ($row['shop_i_id'] ?? '')), 0, 191);
if ($ioId <= 0 || $shopIId === '') {
continue;
}
if ($skuId !== '') {
$map[$ioId][$skuId] = $shopIId;
}
$map[$ioId][''] ??= $shopIId;
}
}
// 剩余按 o_id 到全渠道订单明细(当前表 + 月度归档)兜底。
$oIdByIoId = [];
$monthByIoId = [];
foreach ($orders as $order) {
$ioId = (int) ($order['io_id'] ?? 0);
$oId = (int) ($order['o_id'] ?? 0);
$ioDate = trim((string) ($order['io_date'] ?? ''));
if ($ioId <= 0 || $oId <= 0) {
continue;
}
$oIdByIoId[$ioId] = $oId;
if ($ioDate === '') {
continue;
}
try {
$monthByIoId[$ioId] = Carbon::parse($ioDate)->format('Ym');
} catch (Throwable) {
// io_date 无法解析时只查当前表。
}
}
$missing = [];
foreach ($ioIds as $ioId) {
if (($map[$ioId] ?? []) !== []) {
continue;
}
$oId = $oIdByIoId[$ioId] ?? 0;
if ($oId > 0) {
$missing[$ioId] = $oId;
}
}
if ($missing === []) {
return $map;
}
$tables = ['jst_qmcust_orderlist_item' => $missing];
foreach ($missing as $ioId => $oId) {
$month = $monthByIoId[$ioId] ?? null;
if ($month !== null) {
$tables['jst_qmcust_orderlist_item_' . $month][$ioId] = $oId;
}
}
foreach ($tables as $table => $idsByIo) {
$oIds = array_values(array_unique(array_values($idsByIo)));
foreach (array_chunk($oIds, 200) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
try {
$rows = $upstream->select(
'SELECT o_id, sku_id, shop_i_id FROM dbo.' . $table . ' WHERE o_id IN (' . $placeholders . ')'
. ' AND LEN(shop_i_id) > 0',
$chunk,
);
} catch (Throwable) {
continue;
}
$byOrder = [];
foreach ($rows as $row) {
$row = (array) $row;
$skuId = trim((string) ($row['sku_id'] ?? ''));
$shopIId = mb_substr(trim((string) ($row['shop_i_id'] ?? '')), 0, 191);
if ($shopIId === '') {
continue;
}
$byOrder[(int) ($row['o_id'] ?? 0)][] = ['sku_id' => $skuId, 'shop_i_id' => $shopIId];
}
foreach ($idsByIo as $ioId => $oId) {
foreach ($byOrder[$oId] ?? [] as $entry) {
if ($entry['sku_id'] !== '') {
$map[$ioId][$entry['sku_id']] = $entry['shop_i_id'];
}
$map[$ioId][''] ??= $entry['shop_i_id'];
}
}
}
}
return $map;
}
/**
* @param array<int,list<array<string,mixed>>> $items
* @return array<string,array{l:float,w:float,h:float}>
*/
private function dimensionMap(array $items): array
{
$skuIds = [];
foreach ($items as $rows) {
foreach ($rows as $row) {
$skuId = trim((string) ($row['sku_id'] ?? ''));
if ($skuId !== '') {
$skuIds[$skuId] = true;
}
}
}
$skuIds = array_keys($skuIds);
$dimensions = [];
// 商品及库存管理(商品资料)已在共享镜像里,直接读镜像,不再压上游。
foreach (array_chunk($skuIds, 500) as $chunk) {
try {
$rows = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'))
->table('ops_jst_sku')
->whereIn('sku_id', $chunk)
->get(['sku_id', 'l', 'w', 'h']);
} catch (Throwable) {
continue;
}
foreach ($rows as $row) {
$l = (float) $row->l;
$w = (float) $row->w;
$h = (float) $row->h;
if ($l > 0 && $w > 0 && $h > 0) {
$dimensions[trim((string) $row->sku_id)] = ['l' => $l, 'w' => $w, 'h' => $h];
}
}
}
return $dimensions;
}
private function trimNumber(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');
}
}

View File

@ -0,0 +1,727 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
use Throwable;
/**
* 按「附加费报价维护」里启用的退回费 / 拦截费规则,从查件扣单拉取结算行。
*
* 口径:
* - 规则状态 active、生效条件含「查件扣单」;
* - 退回费:types 含「退回费」,支持 固定单价 / 按重量;已退回(售后退货退款
* receive_date 进仓时间 + r_qty 实退数量)按标准计价,未退回计 0;
* 结算重量取商品资料 ops_jst_sku.weight,按实退数量汇总;未退回时按发货数量展示;
* - 拦截费:types 含「拦截费」且模式为固定单价,查件扣单即按标准金额计价;
* - 扣单来源:共享镜像 js_jst_work_order_info 中 title=查件、查件类型=扣单 的工单。
*/
class PullCourierSurchargeReturn extends Command
{
private const CHECK_TYPE_FIELD = 'SELECT_CASCADEField1413856620250813172526';
protected $signature = 'courier-surcharge:pull-return
{--days=90 : 默认拉取最近多少天(无 --from/--to 时生效,按查件工单创建时间)}
{--from= : 查件工单创建起(含),Y-m-d}
{--to= : 查件工单创建止(不含),Y-m-d}
{--rule=* : 只跑指定规则 ID,可多次传入}
{--type=* : 只跑指定附加费类型(退回费/拦截费),可多次传入}
{--limit=0 : 调试用,最多处理多少张扣单工单,0 表示不限}';
protected $description = '按启用的退回费/拦截费报价规则,从查件扣单拉取结算行';
public function handle(): int
{
$from = $this->option('from') !== null && $this->option('from') !== ''
? Carbon::parse((string) $this->option('from'))->startOfDay()
: now()->subDays(max((int) $this->option('days'), 1))->startOfDay();
$to = $this->option('to') !== null && $this->option('to') !== ''
? Carbon::parse((string) $this->option('to'))->startOfDay()
: now()->addDay()->startOfDay();
$onlyRules = array_filter(array_map('intval', (array) $this->option('rule')));
$onlyTypes = array_values(array_filter(
array_map(static fn ($type): string => trim((string) $type), (array) $this->option('type')),
static fn (string $type): bool => in_array($type, ['退回费', '拦截费'], true),
));
$limit = max((int) $this->option('limit'), 0);
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$schema = DB::connection($connection)->getSchemaBuilder();
if (! $schema->hasTable('courier_surcharge_settlement_rows')) {
$this->error('结算表 courier_surcharge_settlement_rows 不存在,请先执行迁移。');
return self::FAILURE;
}
if (! $schema->hasTable('js_jst_work_order_info')) {
$this->error('查件工单镜像 js_jst_work_order_info 不存在,请先完成镜像同步。');
return self::FAILURE;
}
$rules = $this->rules($onlyRules, $onlyTypes);
if ($rules === []) {
$this->warn('没有启用且可自动计算的退回费/拦截费规则。');
return self::SUCCESS;
}
$orders = $this->pullDeductOrders($connection, $from, $to, $limit);
$this->info(sprintf('取数 %s ~ %s,扣单工单 %d 单。', $from->toDateString(), $to->toDateString(), count($orders)));
if ($orders === []) {
return self::SUCCESS;
}
$ordersByCourier = [];
foreach ($orders as $order) {
$ordersByCourier[$order['courier']][] = $order;
}
$totalWritten = 0;
foreach ($rules as $rule) {
$matched = $ordersByCourier[$rule['courier']] ?? [];
if ($matched === []) {
$this->line('规则 #' . $rule['id'] . ' ' . $rule['courier'] . ':没有匹配的扣单工单,跳过。');
continue;
}
$written = $this->writeSettlementRows($connection, $rule, $matched);
$totalWritten += $written;
$this->line('规则 #' . $rule['id'] . ' ' . $rule['courier'] . '(' . $rule['type'] . '/' . $rule['mode'] . '):扣单 ' . count($matched) . ' 单,写入 ' . $written . ' 行。');
}
$this->info('完成,共写入 ' . $totalWritten . ' 行附加费结算数据。');
return self::SUCCESS;
}
/**
* @param list<int> $onlyRules
* @param list<string> $onlyTypes
* @return list<array{id:int,type:string,courier:string,mode:string,value:float,effective_at:?string}>
*/
private function rules(array $onlyRules, array $onlyTypes): array
{
$rules = [];
foreach (DB::table('business_courier_surcharge_quotes')->where('status', 'active')->orderBy('id')->get() as $rule) {
$types = json_decode((string) $rule->types, true) ?: [];
$candidateTypes = array_values(array_intersect(['退回费', '拦截费'], $types));
if ($candidateTypes === []) {
continue;
}
if ($onlyRules !== [] && ! in_array((int) $rule->id, $onlyRules, true)) {
continue;
}
$condition = trim((string) $rule->condition);
if (! str_contains($condition, '扣单')) {
$this->warn('规则 #' . $rule->id . ' 的生效条件不含「扣单」,已跳过:' . $condition);
continue;
}
$mode = trim((string) $rule->mode);
$standard = trim((string) $rule->standard);
foreach ($candidateTypes as $type) {
if ($onlyTypes !== [] && ! in_array($type, $onlyTypes, true)) {
continue;
}
if ($type === '退回费') {
if ($mode === '固定单价') {
$value = $this->parseFixedAmount($standard);
} elseif ($mode === '按重量') {
$value = $this->parseWeightRate($standard);
} else {
$this->line('规则 #' . $rule->id . ' ' . $rule->courier . ' 的退回费模式「' . $mode . '」暂不支持自动计算,已跳过。');
continue;
}
} else {
if ($mode === '固定单价') {
$value = $this->parseFixedAmount($standard);
} else {
$this->line('规则 #' . $rule->id . ' ' . $rule->courier . ' 的拦截费模式「' . $mode . '」暂不支持自动计算,已跳过。');
continue;
}
}
if ($value === null) {
$this->warn('规则 #' . $rule->id . ' 的' . $type . '计价标准解析失败,已跳过:' . $standard);
continue;
}
$rules[] = [
'id' => (int) $rule->id,
'type' => $type,
'courier' => trim((string) $rule->courier),
'mode' => $mode,
'value' => $value,
'effective_at' => $rule->effective_at !== null && $rule->effective_at !== ''
? (string) $rule->effective_at
: null,
];
}
}
return $rules;
}
private function parseFixedAmount(string $standard): ?float
{
return preg_match('/(\d+(?:\.\d+)?)\s*(?:元)?\s*\/?\s*单/u', $standard, $matched) === 1
? (float) $matched[1]
: null;
}
private function parseWeightRate(string $standard): ?float
{
return preg_match('/(\d+(?:\.\d+)?)\s*元\s*\/\s*(?:kg|KG|公斤|千克)/u', $standard, $matched) === 1
? (float) $matched[1]
: null;
}
/**
* 从查件工单镜像按创建时间拉取扣单工单。
*
* @return list<array<string,mixed>>
*/
private function pullDeductOrders(string $connection, Carbon $from, Carbon $to, int $limit): array
{
$orders = [];
$lastId = 0;
$batchSize = 500;
while (true) {
$rows = DB::connection($connection)->table('js_jst_work_order_info')
->where('title', '查件')
->where('businessFieldList', 'like', '%"value":"扣单/%')
->where('created', '>=', $from->toDateTimeString())
->where('created', '<', $to->toDateTimeString())
->where('Id', '>', $lastId)
->orderBy('Id')
->limit($batchSize)
->get(['Id', 'woNo', 'created', 'businessFieldList']);
if ($rows->isEmpty()) {
break;
}
foreach ($rows as $row) {
$lastId = max($lastId, (int) $row->Id);
$order = $this->parseWorkOrder((string) $row->businessFieldList, (string) $row->woNo, (string) $row->created);
if ($order !== null) {
$orders[] = $order;
}
if ($limit > 0 && count($orders) >= $limit) {
break 2;
}
}
if ($rows->count() < $batchSize) {
break;
}
}
return $orders;
}
/**
* @return array<string,mixed>|null
*/
private function parseWorkOrder(string $json, string $woNo, string $created): ?array
{
$fields = json_decode($json, true);
if (! is_array($fields)) {
return null;
}
$flat = [];
foreach ($fields as $field) {
if (is_array($field) && isset($field['fieldId'])) {
$flat[(string) $field['fieldId']] = $field;
}
}
$waybill = trim((string) ($flat['lIdField']['value'] ?? ''));
$oId = (int) ($flat['o_id']['value'] ?? 0);
$courier = trim((string) ($flat['logisticsField']['value'] ?? ''));
$cascade = trim((string) ($flat[self::CHECK_TYPE_FIELD]['value'] ?? ''));
if ($waybill === '' || $courier === '' || ! str_starts_with($cascade, '扣单')) {
return null;
}
[$inspectionType, $inspectionReason] = array_pad(explode('/', $cascade, 2), 2, '');
$items = [];
foreach (($flat['itemInfo']['childFieldList'] ?? []) as $group) {
if (! is_array($group)) {
continue;
}
$item = [];
foreach ($group as $field) {
if (is_array($field) && isset($field['fieldId'])) {
$item[(string) $field['fieldId']] = $field['value'] ?? null;
}
}
$skuId = strtoupper(trim((string) ($item['skuId'] ?? '')));
if ($skuId === '') {
continue;
}
$items[] = [
'sku_id' => $skuId,
'qty' => (float) ($item['qty'] ?? 0),
'platform_product_id' => mb_substr(trim((string) ($item['platformItemId'] ?? '')), 0, 191),
'i_id' => trim((string) ($item['iid'] ?? '')),
'name' => mb_substr(trim((string) ($item['name'] ?? '')), 0, 191),
];
}
$createdAt = null;
try {
$createdAt = Carbon::parse($created);
} catch (Throwable) {
// created 无法解析时仍保留工单,仅规则生效时间过滤会放宽。
}
return [
'wo_no' => $woNo,
'waybill' => $waybill,
'o_id' => $oId,
'courier' => $courier,
'online_order_no' => mb_substr(trim((string) ($flat['orderField']['value'] ?? '')), 0, 191),
'shop_name' => mb_substr(trim((string) ($flat['shopField']['valueLabel'] ?? ($flat['shopField']['value'] ?? ''))), 0, 191),
'inspection_type' => mb_substr(trim((string) $inspectionType), 0, 60),
'inspection_reason' => mb_substr(trim((string) $inspectionReason), 0, 120),
'send_time' => trim((string) ($flat['orderSendTime']['value'] ?? '')),
'created_at' => $createdAt,
'items' => $items,
];
}
/**
* @param array{id:int,courier:string,mode:string,value:float,effective_at:?string} $rule
* @param list<array<string,mixed>> $orders
*/
private function writeSettlementRows(string $connection, array $rule, array $orders): int
{
$effectiveAt = null;
if (($rule['effective_at'] ?? null) !== null) {
try {
$effectiveAt = Carbon::parse((string) $rule['effective_at'])->startOfDay();
} catch (Throwable) {
// 规则生效时间无法解析时不做下界过滤。
}
}
if ($effectiveAt !== null) {
$orders = array_values(array_filter(
$orders,
static fn (array $order): bool => ! $order['created_at'] instanceof Carbon
|| $order['created_at']->greaterThanOrEqualTo($effectiveAt),
));
}
if ($orders === []) {
return 0;
}
$oIds = [];
$waybills = [];
$skuIds = [];
foreach ($orders as $order) {
if ((int) ($order['o_id'] ?? 0) > 0) {
$oIds[(int) $order['o_id']] = true;
}
$waybills[(string) $order['waybill']] = true;
foreach ($order['items'] as $item) {
$skuIds[(string) $item['sku_id']] = true;
}
}
$type = (string) $rule['type'];
$returns = $type === '退回费' ? $this->pullReturns($orders) : [];
$weights = $this->pullWeights($connection, array_keys($skuIds));
$now = now();
$rows = [];
$hasReturnByWaybill = [];
foreach ($orders as $order) {
$matched = [];
$receiveDates = [];
$returnWaybills = [];
$hasReturn = false;
$settlementWeight = 0.0;
$orderWeight = 0.0;
foreach ($order['items'] as $item) {
$weight = $weights[(string) $item['sku_id']] ?? null;
if ($weight !== null) {
$orderWeight += (float) $item['qty'] * $weight;
}
}
if ($type === '拦截费') {
// 拦截费口径:查件扣单即按固定单价结算,不要求退货进仓。
$amount = (float) $rule['value'];
$status = '已计算';
} else {
foreach ($returns[(int) ($order['o_id'] ?? 0)] ?? [] as $return) {
$rQty = (float) ($return['r_qty'] ?? 0);
$receiveDate = trim((string) ($return['receive_date'] ?? ''));
if ($rQty <= 0 || $receiveDate === '') {
continue;
}
$hasReturn = true;
$matched[] = $return;
$receiveDates[] = $receiveDate;
$returnWaybill = trim((string) ($return['l_id'] ?? ''));
if ($returnWaybill !== '') {
$returnWaybills[$returnWaybill] = true;
}
}
$returnedWeight = 0.0;
foreach ($matched as $return) {
$weight = $weights[strtoupper(trim((string) ($return['sku_id'] ?? '')))] ?? null;
if ($weight !== null) {
$returnedWeight += (float) $return['r_qty'] * $weight;
}
}
$settlementWeight = $hasReturn
? ($returnedWeight > 0 ? $returnedWeight : $orderWeight)
: $orderWeight;
if ($rule['mode'] === '固定单价') {
$amount = $hasReturn ? (float) $rule['value'] : 0.0;
$status = '已计算';
} elseif (! $hasReturn) {
$amount = 0.0;
$status = '已计算';
} elseif ($settlementWeight > 0) {
$amount = round($settlementWeight * (float) $rule['value'], 2);
$status = '已计算';
} else {
$amount = 0.0;
$status = '待核价';
}
}
$primary = $this->primaryItem($order['items'], $matched);
$waybill = (string) $order['waybill'];
// 同一运单可能有多张扣单工单;只保留一行,优先保留有退回记录的那行。
if (($hasReturnByWaybill[$waybill] ?? null) === true && ! $hasReturn) {
continue;
}
$rows[$waybill] = [
'rule_id' => $rule['id'],
'surcharge_type' => $type,
'courier_name' => $rule['courier'],
'waybill' => $waybill,
'outbound_io_id' => null,
'platform_product_id' => $primary['platform_product_id'] !== '' ? $primary['platform_product_id'] : null,
'product_code' => $primary['sku_id'] !== '' ? $primary['sku_id'] : ($primary['i_id'] !== '' ? $primary['i_id'] : null),
'shop_name' => $order['shop_name'] !== '' ? $order['shop_name'] : null,
'online_order_no' => $order['online_order_no'] !== '' ? $order['online_order_no'] : null,
'length' => null,
'width' => null,
'height' => null,
'volume' => null,
'inspection_type' => $order['inspection_type'],
'inspection_reason' => $order['inspection_reason'],
'return_waybill_no' => $returnWaybills === []
? null
: mb_substr(implode(',', array_keys($returnWaybills)), 0, 191),
'settlement_weight' => $settlementWeight > 0 ? round($settlementWeight, 2) : null,
'settlement_amount' => $amount,
'settlement_status' => $status,
'evidence' => mb_substr($this->evidence($rule, $order, $hasReturn, $matched, $receiveDates, $settlementWeight, $amount), 0, 500),
'shipped_at' => $this->shippedAt($order),
'pulled_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
$hasReturnByWaybill[$waybill] = $hasReturn;
}
foreach (array_chunk(array_keys($waybills), 500) as $chunk) {
DB::connection($connection)->table('courier_surcharge_settlement_rows')
->where('rule_id', $rule['id'])
->where('surcharge_type', $type)
->whereIn('waybill', $chunk)
->delete();
}
foreach (array_chunk(array_values($rows), 500) as $chunk) {
DB::connection($connection)->table('courier_surcharge_settlement_rows')->insert($chunk);
}
return count($rows);
}
/**
* 售后退货退款:进仓时间取 receive_date,实退数量取 r_qty。
*
* @param list<array<string,mixed>> $orders
* @return array<int,list<array<string,mixed>>>
*/
private function pullReturns(array $orders): array
{
$map = [];
$oIds = [];
$oIdByWaybill = [];
foreach ($orders as $order) {
$oId = (int) ($order['o_id'] ?? 0);
$waybill = trim((string) ($order['waybill'] ?? ''));
if ($oId > 0) {
$oIds[$oId] = true;
}
if ($oId > 0 && $waybill !== '') {
$oIdByWaybill[$waybill] = $oId;
}
}
$upstream = app(UpstreamReadOnlyQueryFactory::class)->forSource('operations_replica');
foreach (array_chunk(array_keys($oIds), 200) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
foreach ($this->selectReturns($upstream, 'a.o_id IN (' . $placeholders . ')', $chunk) as $row) {
$oId = (int) ($row['o_id'] ?? 0);
if ($oId > 0) {
$map[$oId][] = $row;
}
}
}
// 部分售后单的 o_id 与查件工单不一致,按原始运单号再兜底一次。
$remainingWaybills = [];
foreach ($oIdByWaybill as $waybill => $oId) {
if (($map[$oId] ?? []) === []) {
$remainingWaybills[] = $waybill;
}
}
foreach (array_chunk($remainingWaybills, 200) as $chunk) {
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
foreach ($this->selectReturns($upstream, 'a.l_id IN (' . $placeholders . ')', $chunk) as $row) {
$oId = $oIdByWaybill[trim((string) ($row['l_id'] ?? ''))] ?? 0;
if ($oId > 0) {
$map[$oId][] = $row;
}
}
}
return $map;
}
/**
* @param list<mixed> $bindings
* @return list<array<string,mixed>>
*/
private function selectReturns(UpstreamReadOnlyQuery $upstream, string $where, array $bindings): array
{
try {
$rows = $upstream->select(
'SELECT a.o_id, a.as_id, a.l_id, a.status, CONVERT(varchar(19), a.confirm_date, 120) AS confirm_date, '
. 'ri.sku_id, ri.qty, ri.r_qty, '
. 'CONVERT(varchar(19), ri.receive_date, 120) AS receive_date '
. 'FROM rpt.jst_returnAndRefundInfo a '
. 'INNER JOIN rpt.jst_returnAndRefundItem ri ON ri.as_id = a.as_id '
. 'WHERE ' . $where,
$bindings,
);
} catch (Throwable) {
return [];
}
return array_map(static fn ($row): array => (array) $row, $rows);
}
/**
* @param list<string> $skuIds
* @return array<string,float>
*/
private function pullWeights(string $connection, array $skuIds): array
{
$map = [];
foreach (array_chunk($skuIds, 500) as $chunk) {
$rows = DB::connection($connection)->table('ops_jst_sku')
->whereIn('sku_id', $chunk)
->get(['sku_id', 'weight']);
foreach ($rows as $row) {
$skuId = strtoupper(trim((string) $row->sku_id));
$weight = $row->weight;
if ($skuId === '' || $weight === null || $weight === '' || isset($map[$skuId])) {
continue;
}
$map[$skuId] = (float) $weight;
}
}
return $map;
}
/**
* @param list<array<string,mixed>> $items
* @param list<array<string,mixed>> $returns
* @return array{sku_id:string,i_id:string,platform_product_id:string,name:string}
*/
private function primaryItem(array $items, array $returns): array
{
$returnSkus = [];
foreach ($returns as $return) {
$skuId = strtoupper(trim((string) ($return['sku_id'] ?? '')));
if ($skuId !== '') {
$returnSkus[$skuId] = true;
}
}
foreach ($items as $item) {
if (isset($returnSkus[$item['sku_id']])) {
return $item;
}
}
foreach ($items as $item) {
if ($item['platform_product_id'] !== '') {
return $item;
}
}
return $items[0] ?? ['sku_id' => '', 'i_id' => '', 'platform_product_id' => '', 'name' => ''];
}
/**
* @param array{id:int,type:string,courier:string,mode:string,value:float,effective_at:?string} $rule
* @param array<string,mixed> $order
* @param list<array<string,mixed>> $matched
* @param list<string> $receiveDates
*/
private function evidence(
array $rule,
array $order,
bool $hasReturn,
array $matched,
array $receiveDates,
float $settlementWeight,
float $amount,
): string {
$parts = ['查件扣单/' . $order['inspection_reason']];
if (($rule['type'] ?? '退回费') === '拦截费') {
$parts[] = '拦截费规则 ' . $this->trimNumber((float) $rule['value']) . '元/单';
$parts[] = '结算金额 ' . number_format($amount, 2, '.', '');
return implode(';', $parts);
}
if ($hasReturn) {
$returnQty = 0.0;
$confirmDates = [];
foreach ($matched as $return) {
$returnQty += (float) ($return['r_qty'] ?? 0);
$confirmDate = trim((string) ($return['confirm_date'] ?? ''));
if ($confirmDate !== '') {
$confirmDates[] = $confirmDate;
}
}
if ($confirmDates !== []) {
$parts[] = '退款确认 ' . max($confirmDates);
}
$parts[] = '售后退货退款已进仓 ' . ($receiveDates === [] ? '' : max($receiveDates));
$parts[] = '实退 ' . $this->trimNumber($returnQty);
} else {
$parts[] = '售后退货退款无进仓/实退记录';
}
$parts[] = '商品资料重量合计 ' . $this->trimNumber($settlementWeight) . 'kg';
$parts[] = $rule['mode'] === '固定单价'
? '规则 ' . $this->trimNumber((float) $rule['value']) . '元/单'
: '规则 ' . $this->trimNumber((float) $rule['value']) . '元/kg';
$parts[] = '结算金额 ' . number_format($amount, 2, '.', '');
return implode(';', $parts);
}
/**
* @param array<string,mixed> $order
*/
private function shippedAt(array $order): ?string
{
$sendTime = trim((string) ($order['send_time'] ?? ''));
if ($sendTime !== '') {
try {
return Carbon::parse($sendTime)->toDateTimeString();
} catch (Throwable) {
// 发货时间无法解析时回退到查件工单创建时间。
}
}
return $order['created_at'] instanceof Carbon ? $order['created_at']->toDateTimeString() : null;
}
private function trimNumber(float $value): string
{
$text = rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.');
return $text === '' ? '0' : $text;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use App\Business\StoreViolationNotifier;
use Illuminate\Console\Command;
/**
* 店铺违规信息预警:P0/P1 即时推送(每天 09:00 起由生产 cron 每 5 分钟触发)。
*/
class PushStoreViolationAlerts extends Command
{
protected $signature = 'store-violations:push-instant
{--limit=200 : 单轮最多推送条数}
{--retry-failed : 同时重试推送失败的记录}';
protected $description = '推送店铺违规预警即时消息(P0/P1,含责任人@与去认领链接)';
public function handle(StoreViolationNotifier $notifier): int
{
if (! $notifier->enabled()) {
$this->line('推送未配置,跳过。');
return self::SUCCESS;
}
$summary = $notifier->pushInstant(
max((int) $this->option('limit'), 1),
(bool) $this->option('retry-failed'),
);
$this->info(sprintf(
'即时推送:待推 %d 条,成功 %d 条,失败 %d 条。',
$summary['attempted'],
$summary['succeeded'],
$summary['failed'],
));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use App\Business\StoreViolationNotifier;
use Illuminate\Console\Command;
/**
* 店铺违规信息预警:P2 每日 10:00 汇总日报。
*/
class PushStoreViolationDigest extends Command
{
protected $signature = 'store-violations:push-digest';
protected $description = '推送店铺违规预警每日汇总(P2 汇总与超时未认领点名)';
public function handle(StoreViolationNotifier $notifier): int
{
if (! $notifier->enabled()) {
$this->line('推送未配置,跳过。');
return self::SUCCESS;
}
$summary = $notifier->pushDigest();
$this->info(sprintf(
'日报推送:%s;P0 %d / P1 %d / P2 %d,超时未认领 %d 条。',
$summary['sent'] ? '已发送' : '发送失败',
(int) ($summary['pending']['P0'] ?? 0),
(int) ($summary['pending']['P1'] ?? 0),
(int) ($summary['pending']['P2'] ?? 0),
(int) $summary['overdue'],
));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Console\Commands;
use App\Business\StoreViolationAlertCalculator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\StoreViolationRecordRepository;
/**
* 店铺违规信息预警:按当前字典/归属重新计算全部记录的预警派生字段。
*
* 用于字典维护或店铺归属调整后的校准;不触碰处理状态、忽略原因与推送状态。
*/
class RecalcStoreViolationAlerts extends Command
{
protected $signature = 'store-violations:recalc-alerts
{--platform= : 只重算指定平台}
{--chunk=500 : 每批更新行数}';
protected $description = '重算店铺违规记录的预警级别、责任人与处理截止';
public function handle(StoreViolationAlertCalculator $calculator, StoreViolationRecordRepository $repository): int
{
if (! $repository->available()) {
$this->error('统一表 store_violation_records 尚未建立。');
return self::FAILURE;
}
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$chunk = max(min((int) $this->option('chunk'), 2000), 100);
$platform = trim((string) $this->option('platform'));
$total = 0;
$query = $connection->table(StoreViolationRecordRepository::TABLE)
->select(['id', 'platform', 'violation_no', 'shop_name', 'violation_type', 'violation_reason', 'violation_date', 'appeal_deadline'])
->orderBy('id');
if ($platform !== '') {
$query->where('platform', $platform);
}
$query->chunk($chunk, function ($rows) use ($calculator, $connection, &$total): void {
$updates = [];
foreach ($rows as $row) {
$matchType = trim((string) ($row->violation_type ?? '')) !== ''
? (string) $row->violation_type
: ($row->violation_reason ?? null);
// upsert 的插入侧会校验非空列,带上 platform / violation_no 以通过严格模式;
// 命中已有记录时只会更新派生字段(update 列表)。
$updates[] = [
'id' => $row->id,
'platform' => (string) $row->platform,
'violation_no' => (string) ($row->violation_no ?? ''),
] + $calculator->calculate(
(string) $row->platform,
$row->shop_name,
$matchType,
$row->violation_date ? (string) $row->violation_date : null,
$row->appeal_deadline ? (string) $row->appeal_deadline : null,
);
}
if ($updates !== []) {
$connection->table(StoreViolationRecordRepository::TABLE)->upsert(
$updates,
['id'],
StoreViolationRecordRepository::ALERT_DERIVED_COLUMNS,
);
$total += count($updates);
}
});
$this->info(sprintf('预警重算完成:%d 行。', $total));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\FinanceLedgerCalculator;
use Throwable;
class RecalculateFinanceLedger extends Command
{
protected $signature = 'finance-ledger:recalculate';
protected $description = '重算财务台账的每日资金流水、账户余额和店铺余额';
public function handle(FinanceLedgerCalculator $calculator): int
{
try {
$result = $calculator->recalculate();
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '值'], [
['账户数', $result['accounts']],
['流水行数', $result['flows']],
['期末余额合计', number_format($result['balance_sum'], 2)],
['期初日期', $result['opening_date']],
]);
$this->info('财务台账流水重算完成。');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\StoreReportMirrorSynchronizer;
class RefreshStoreReportPaidSales extends Command
{
protected $signature = 'business-mirror:refresh-paid-sales {--full : 强制全量校准派生汇总}';
protected $description = '只刷新业绩明细派生的销量汇总,不修改原始财务明细';
public function handle(StoreReportMirrorSynchronizer $synchronizer): int
{
$result = $synchronizer->syncPaidSales((bool) $this->option('full'));
$this->info(json_encode($result));
return $result['status'] === 'succeeded' ? self::SUCCESS : self::FAILURE;
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\AccountBillsExportTasks;
class RunAccountBillsExportQueue extends Command
{
protected $signature = 'account-bills:exports:run {--max-jobs=1}';
protected $description = '依次消费账单导出任务,生产从受限批容器启动';
public function handle(AccountBillsExportTasks $tasks): int
{
$limit = max(0, (int) $this->option('max-jobs'));
for ($processed = 0; $limit === 0 || $processed < $limit; $processed++) {
$task = $tasks->nextQueued();
if ($task === null) break;
$code = $this->call('account-bills:export-run', ['token' => $task['token']]);
if ($code === 75) break;
}
return self::SUCCESS;
}
}

View File

@ -28,6 +28,17 @@ class RunAccountBillsExportTask extends Command
protected $description = '执行店铺收款账户账单导出任务(后台进程调用)';
public function handle(AccountBillsExportTasks $tasks, AccountLedgerRemarkMap $remarkMap): int
{
$lock = \Illuminate\Support\Facades\Cache::store('upstream_shared')->lock('account-bills:export-worker', 10800);
if (! $lock->get()) return 75;
try {
return $this->runTask($tasks, $remarkMap);
} finally {
$lock->release();
}
}
private function runTask(AccountBillsExportTasks $tasks, AccountLedgerRemarkMap $remarkMap): int
{
$token = (string) $this->argument('token');
$task = $this->findTask($tasks, $token);
@ -36,6 +47,7 @@ class RunAccountBillsExportTask extends Command
return self::FAILURE;
}
if (($task['status'] ?? '') !== 'queued') return self::SUCCESS;
$task = $tasks->patch($task, ['status' => 'running', 'started_at' => AccountBillsExportTasks::beijingNow()]);
@ -56,6 +68,10 @@ class RunAccountBillsExportTask extends Command
throw new \RuntimeException('无法创建导出文件。');
}
// 让「行数」列能显示真实百分比:镜像连接改为不缓冲取数,
// 行一取到就写盘,进度按 已写行数 / 总行数 实时刷新。
$this->streamRowsWithoutBuffering($remarkMap);
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($csv, array_map(static fn (array $column): string => (string) ($column['label'] ?? ''), $columns));
@ -106,7 +122,7 @@ class RunAccountBillsExportTask extends Command
private function findTask(AccountBillsExportTasks $tasks, string $token): ?array
{
$root = storage_path('app/account-bills-exports');
$root = $tasks->rootDir();
foreach (glob($root . '/*/' . $token . '.json') ?: [] as $path) {
$task = json_decode((string) file_get_contents($path), true);
if (is_array($task) && ($task['token'] ?? null) === $token) {
@ -122,9 +138,10 @@ class RunAccountBillsExportTask extends Command
{
$tab = (string) ($task['tab'] ?? '');
$filters = (array) ($task['filters'] ?? []);
// 后台导出固定按「记录编码」(数据库自增列)顺序取数:
// 整月按「发生时间」排序要先对上千万行排序,首批数据要几分钟,阶段进度长时间是 0;按自增列取数快很多。
$sort = 'record_code';
// 后台导出固定按「发生时间」取数:该列上有 (occurred_at, record_code) 联合索引,
// 数据库能按索引顺序边扫边返回,首行几百毫秒内到达,进度可实时刷新;
// 按「记录编码」走主键反向扫描过滤日期,要扫完整表才出首行,进度会长时间停在 0%。
$sort = 'occurred_at';
$dir = strtolower((string) ($filters['dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';
unset($filters['sort'], $filters['dir'], $filters['export'], $filters['token'], $filters['total'], $filters['columns']);
@ -144,6 +161,33 @@ class RunAccountBillsExportTask extends Command
return $remarkMap->decorateAll($rows, $tab);
}
/**
* 把镜像连接切成「不缓冲」并预热总账备注映射,使取数阶段逐批返回行。
*
* Web/CLI 默认用缓冲查询:整段结果集在数据库端算完才返回,进度会长时间停在 0%,
* 最后一次性跳到 100%。切到不缓冲后行随查询推进到达,进度即真实百分比。
*/
private function streamRowsWithoutBuffering(AccountLedgerRemarkMap $remarkMap): void
{
try {
// 预热:避免逐行装饰时中途再去读缓存/文件。
$remarkMap->map();
$connection = app(\Illuminate\Database\DatabaseManager::class)
->connection((string) config('upstream_mirrors.connection', 'business_mirror'));
if (! $connection instanceof \Illuminate\Database\MySqlConnection) {
return;
}
$pdo = $connection->getPdo();
$pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
// 读连接与写连接是两套句柄,这里统一成同一个不缓冲句柄。
$connection->setReadPdo($pdo);
} catch (Throwable) {
// 拿不到句柄时退回默认行为,不影响导出结果。
}
}
/** @param array<string,mixed> $row */
private static function cellValue(array $row, array $column): string
{

View File

@ -0,0 +1,112 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
use Symfony\Component\Process\Process;
use Throwable;
/**
* 科目映射表变更后的业绩明细自动重跑队列。
*
* 每轮按预算处理队列里的「平台 × 月份」;实际同步放在独立 PHP 子进程中,
* 避免大平台重跑时的内存累积,并让其它同步有机会取得全局锁。
*/
class RunAccountMappingResync extends Command
{
protected $signature = 'store-receipt:auto-resync {--max-jobs=1 : 每轮最多任务数,0为不限} {--max-seconds=300 : 单个任务结束后检查本轮时间预算}';
protected $description = '处理科目映射表变更触发的业绩明细重跑队列';
public function handle(AccountMappingResyncDispatcher $dispatcher): int
{
// 页面(Apache)与每分钟 cron 都以 www-data 运行,使用共享数据库锁,
// 不受 storage/framework/cache 文件属主影响,也能避免多容器重复消费。
$lock = Cache::store('upstream_shared')->lock('store-receipt:auto-resync', 86400);
if (! $lock->get()) {
// 已有进程在跑;本次新入队的任务会在当前进程下一轮循环或每分钟兜底时执行。
return self::SUCCESS;
}
try {
// 进程崩溃遗留的 running 任务超过 60 分钟视为可重试。
DB::table(AccountMappingResyncDispatcher::JOBS_TABLE)
->where('status', 'running')
->where('updated_at', '<', now()->subMinutes(60))
->update(['status' => 'pending', 'updated_at' => now()]);
$processed = 0;
$maxJobs = max(0, (int) $this->option('max-jobs'));
$deadline = microtime(true) + max(1, (int) $this->option('max-seconds'));
while (($maxJobs === 0 || $processed < $maxJobs) && microtime(true) < $deadline) {
$job = DB::table(AccountMappingResyncDispatcher::JOBS_TABLE)
->where('status', 'pending')
->orderBy('id')
->first();
if ($job === null) {
break;
}
$processed++;
DB::table(AccountMappingResyncDispatcher::JOBS_TABLE)
->where('id', $job->id)
->where('status', 'pending')
->update([
'status' => 'running',
'attempts' => DB::raw('attempts + 1'),
'updated_at' => now(),
]);
try {
[$succeeded, $output] = $this->runSync($job);
// 同步期间又保存了映射时,dispatchFor 已把状态改回 pending;
// 这里只在仍为 running 时写 done,不能吞掉新请求。
DB::table(AccountMappingResyncDispatcher::JOBS_TABLE)
->where('id', $job->id)
->where('status', 'running')
->update([
'status' => $succeeded ? 'done' : 'failed',
'message' => mb_substr(
$output !== '' ? $output : ($succeeded ? 'OK' : '同步命令执行失败'),
0,
1000
),
'updated_at' => now(),
]);
} catch (Throwable $exception) {
Log::error('科目映射表自动重跑失败:' . $exception->getMessage());
DB::table(AccountMappingResyncDispatcher::JOBS_TABLE)
->where('id', $job->id)
->where('status', 'running')
->update([
'status' => 'failed',
'message' => mb_substr($exception->getMessage(), 0, 1000),
'updated_at' => now(),
]);
}
}
} finally {
$lock->release();
}
return self::SUCCESS;
}
/** @return array{bool,string} */
protected function runSync(object $job): array
{
$process = new Process([
PHP_BINARY ?: 'php', 'artisan', 'store-receipt:order-match:sync',
(string) $job->month, '--platform=' . $job->platform,
], base_path());
$process->setTimeout(7200);
$process->run();
return [$process->isSuccessful(), trim($process->getOutput() . "\n" . $process->getErrorOutput())];
}
}

View File

@ -155,9 +155,18 @@ class SyncBusinessMirrors extends Command
if (($state['status'] ?? '') === 'failed' && ! empty($state['last_attempted_at'])
&& now()->diffInSeconds(\Illuminate\Support\Carbon::parse($state['last_attempted_at'])) < 300) continue;
// Only explicitly opted-in small datasets receive periodic full reconciliation.
// Keep an interrupted full run in full mode so its cursor/generation can resume.
$hours = (int) $datasets->definitionValue($key, 'full_reconcile_hours', 0);
$lastFull = $state['last_full_succeeded_at'] ?? null;
$reconcile = $hours > 0 && (empty($lastFull)
|| \Illuminate\Support\Carbon::parse($lastFull)->addHours($hours)->lte(now()));
$resumeFull = $hours > 0 && ($state['run_mode'] ?? '') === 'full'
&& in_array($state['status'] ?? '', ['running', 'failed'], true);
$scheduled[] = [
'key' => $key,
'full' => $initial || (bool) $this->option('full'),
'full' => $initial || $reconcile || $resumeFull || (bool) $this->option('full'),
'catchup' => $initial || ($state['status'] ?? '') === 'running',
'last_attempted_at' => (string) ($state['last_attempted_at'] ?? ''),
];

View File

@ -0,0 +1,49 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\FinanceLedgerRptSynchronizer;
use Throwable;
class SyncFinanceLedgerRpt extends Command
{
protected $signature = 'finance-ledger:sync-rpt
{--from= : 业务日期起,默认读取配置}
{--to= : 业务日期止,默认读取配置或当天}
{--no-recalculate : 只同步明细,不重算流水}';
protected $description = '从 AI 库 rpt 同步财务台账动账明细,并重算每日流水';
public function handle(FinanceLedgerRptSynchronizer $synchronizer): int
{
try {
$result = $synchronizer->sync(
! $this->option('no-recalculate'),
$this->option('from') ?: null,
$this->option('to') ?: null,
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '值'], [
['明细行数', $result['rows']],
['收入合计', number_format($result['income'], 2)],
['支出合计', number_format($result['expense'], 2)],
['日期范围', $result['from'] . ' ~ ' . $result['to']],
['每日流水行数', $result['recalculated']['flows'] ?? '-'],
['期末余额合计', isset($result['recalculated']) ? number_format($result['recalculated']['balance_sum'], 2) : '-'],
]);
$this->line('来源分布:');
foreach (($result['source_counts'] ?? []) as $source => $count) {
$this->line(' ' . $source . ': ' . $count);
}
$this->info('财务台账 rpt 同步完成。');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,182 @@
<?php
namespace App\Console\Commands;
use App\Business\JstOrderLabelItemCodes;
use Illuminate\Console\Command;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
/**
* 把聚水潭商品明细(共享镜像)里的商品编码回填到「聚水潭订单标签明细」的货号列。
*
* 两个来源:
* - 主镜像 ops_jst_orders + ops_jst_order_item;
* - 全渠道镜像 ops_jst_qmcust_orders + ops_jst_qmcust_order_items。
*
* 页面/命令导入(jst-order-labels:import)已自带货号;本命令用于历史数据回填与修复,可反复执行。
*/
class SyncJstOrderLabelItemCodes extends Command
{
protected $signature = 'jst-order-labels:sync-item-codes
{--from= : 起始下单日期 YYYY-MM-DD(默认取标签明细里最早的下单日期)}
{--to= : 结束下单日期 YYYY-MM-DD(默认取标签明细里最晚的下单日期)}
{--company=1 : 公司 ID}
{--chunk=800 : 每批处理的订单数}';
protected $description = '按订单号把聚水潭商品明细里的货号回填到聚水潭订单标签明细';
/** 订单镜像 → 商品明细镜像。 */
private const SOURCES = [
['orders' => 'ops_jst_orders', 'items' => 'ops_jst_order_item'],
['orders' => 'ops_jst_qmcust_orders', 'items' => 'ops_jst_qmcust_order_items'],
];
public function handle(DatabaseManager $databases, JstOrderLabelItemCodes $itemCodes): int
{
$companyId = (int) $this->option('company');
$chunk = max((int) $this->option('chunk'), 100);
$prefix = $databases->connection()->getTablePrefix();
try {
[$from, $to] = $this->resolveWindow($databases, $companyId);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$start = $from . ' 00:00:00';
$end = date('Y-m-d', strtotime($to . ' +1 day')) . ' 00:00:00';
$mirror = $databases->connection(config('upstream_mirrors.connection', 'business_mirror'));
$this->info(sprintf('同步货号:%s ~ %s(公司 %d)', $from, $to, $companyId));
$startedAt = microtime(true);
$totalUpdated = 0;
foreach (self::SOURCES as $source) {
if (! $mirror->getSchemaBuilder()->hasTable($source['orders']) || ! $mirror->getSchemaBuilder()->hasTable($source['items'])) {
$this->warn(sprintf('跳过 %s:镜像表不存在。', $source['orders']));
continue;
}
$scanned = 0;
$matched = 0;
$updated = 0;
$chunks = 0;
$mirrorName = $source['orders'];
try {
$mirror->table($source['orders'])
->select(['Id', 'o_id', 'so_id'])
->where('order_date', '>=', $start)
->where('order_date', '<', $end)
->orderBy('Id')
->chunkById($chunk, function ($records) use ($mirror, $itemCodes, $source, $prefix, $companyId, $start, $end, $mirrorName, &$scanned, &$matched, &$updated, &$chunks): void {
$chunks++;
$scanned += count($records);
$orderCodes = $itemCodes->forOrderIds($mirror, $source['items'], $records->pluck('o_id')->all());
$pairs = [];
foreach ($records as $record) {
$orderNo = trim((string) $record->so_id);
$codes = $orderCodes[(int) $record->o_id] ?? null;
if ($orderNo !== '' && $codes !== null && $codes !== '') {
$pairs[] = [$orderNo, $codes];
}
}
$matched += count($pairs);
if ($pairs !== []) {
$updated += $this->applyMap($prefix, $pairs, $companyId, $start, $end);
}
if ($chunks % 20 === 0) {
$this->line(sprintf(' …%s:已扫描 %d 单,匹配 %d,更新行 %d', $mirrorName, $scanned, $matched, $updated));
}
}, 'Id');
} catch (Throwable $exception) {
$this->error(sprintf('%s 同步失败:%s', $mirrorName, $exception->getMessage()));
return self::FAILURE;
}
$totalUpdated += $updated;
$this->info(sprintf('%s:扫描 %d 单,匹配 %d,更新标签行 %d', $mirrorName, $scanned, $matched, $updated));
}
$this->info(sprintf('完成:共更新标签行 %d,耗时 %.0f 秒。', $totalUpdated, microtime(true) - $startedAt));
return self::SUCCESS;
}
/**
* 一批订单的货号按订单号写回标签表(CASE 更新,命中 order_no 索引)。
*
* 订单号必须全程按字符串绑定:纯数字订单号一旦被 PHP 数组键或 PDO 当成整数,
* MariaDB 会把字符列 order_no 强转成数字比较,带「-」的订单号直接报 1292。
*
* @param list<array{0:string,1:string}> $pairs [[线上订单号, 货号], ...]
*/
private function applyMap(string $prefix, array $pairs, int $companyId, string $start, string $end): int
{
$cases = [];
$bindings = [];
$orderNos = [];
foreach ($pairs as [$orderNo, $codes]) {
$orderNo = (string) $orderNo;
$cases[] = 'WHEN ? THEN ?';
$bindings[] = $orderNo;
$bindings[] = $codes;
$orderNos[] = $orderNo;
}
$sql = 'UPDATE ' . $prefix . 'jst_order_labels SET item_code = CASE order_no ' . implode(' ', $cases) . ' END '
. 'WHERE company_id = ? AND order_no IN (' . implode(',', array_fill(0, count($orderNos), '?')) . ') '
. 'AND ordered_at >= ? AND ordered_at < ?';
$params = array_merge($bindings, [$companyId], $orderNos, [$start, $end]);
$updated = DB::connection()->update($sql, $params);
if ($updated > 0) {
app(\App\Business\PlantingOrderLabelLookup::class)->forget($companyId);
}
return $updated;
}
/** @return array{0:string,1:string} 起止日期(Y-m-d) */
private function resolveWindow(DatabaseManager $databases, int $companyId): array
{
$from = trim((string) $this->option('from'));
$to = trim((string) $this->option('to'));
if ($from === '' || $to === '') {
$row = $databases->table('jst_order_labels')
->where('company_id', $companyId)
->selectRaw('MIN(ordered_at) AS min_at, MAX(ordered_at) AS max_at')
->first();
if ($row === null || $row->min_at === null || $row->max_at === null) {
throw new RuntimeException('标签明细里没有数据,无法推断同步区间,请用 --from/--to 指定。');
}
$from = $from === '' ? substr((string) $row->min_at, 0, 10) : $from;
$to = $to === '' ? substr((string) $row->max_at, 0, 10) : $to;
}
foreach (['起始' => $from, '结束' => $to] as $label => $value) {
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
throw new RuntimeException($label . '日期必须是 YYYY-MM-DD:' . $value);
}
}
if ($from > $to) {
throw new RuntimeException('起始日期不能晚于结束日期。');
}
return [$from, $to];
}
}

View File

@ -6,12 +6,14 @@ use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Modules\EcommerceFinance\Repositories\JushuitanCostPriceHistoryMirrorRepository;
use Modules\EcommerceFinance\Services\JushuitanCostPriceHistorySynchronizer;
use Modules\EcommerceFinance\Services\JushuitanCostPriceSnapshotDiffer;
use Throwable;
class SyncJushuitanCostPriceHistory extends Command
{
protected $signature = 'business-mirror:sync-jushuitan-cost-price-history
{--full : 强制启动或继续首次全量同步}
{--source=open_api : open_api 为正式操作历史;snapshot 为独立的镜像价格观测}
{--page-size= : 聚水潭接口每页读取条数,最大 50}
{--max-pages= : 本轮最多读取页数,0 表示直到完成}';
@ -25,6 +27,25 @@ class SyncJushuitanCostPriceHistory extends Command
return self::SUCCESS;
}
if ($this->option('source') === 'snapshot') {
try {
$result = app(JushuitanCostPriceSnapshotDiffer::class)->sync(
$this->option('page-size') === null ? 500 : (int) $this->option('page-size'),
$this->option('max-pages') === null ? 20 : (int) $this->option('max-pages'),
);
$this->info(sprintf('镜像价格观测:%s,本轮读取 %d 条,发现 %d 次价格变化;不代表完整操作历史。', $result['status'], $result['rows'], $result['changes']));
return self::SUCCESS;
} catch (Throwable $exception) {
Log::error('镜像价格观测失败。', ['exception' => $exception::class]);
$this->error('镜像价格观测失败,已保留基线、记录和续传游标。');
return self::FAILURE;
}
}
if ($this->option('source') !== 'open_api') {
$this->error('source 仅支持 open_api 或 snapshot。');
return self::FAILURE;
}
try {
$state = $mirror->state();
$full = $this->shouldRunFull($state);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,673 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use Throwable;
/**
* 商品成本:以「业绩明细」(店铺收款账户账单 × 订单原始数据)的账单行为基数,
* 按「店铺 + 线上订单号」展开订单侧的商品行,带出发货仓库、仓库简称、商品单价和商品成本。
*
* 发货仓库取订单上的 wms_co_id 对应的聚水潭仓库名称;仓库简称查仓库映射表;
* 商品单价按「仓库简称 + 商品编码」取商品月加权平均单价里的加权平均价;商品成本 = 商品数量 × 商品单价。
*/
class SyncStoreReceiptProductCost extends Command
{
protected $signature = 'store-receipt:product-cost:sync
{month : 账期月份,格式 YYYY-MM}
{--platform= : 只重建某个平台页签,留空表示全部}
{--chunk=1000 : 临时表批量写入行数}';
protected $description = '展开业绩明细对应的订单商品行,计算商品成本(发货仓库 → 仓库简称 → 商品单价 → 商品成本)';
private const SOURCE_TABLE = 'store_receipt_order_match_rows';
private const TARGET_TABLE = 'store_receipt_product_cost_rows';
private const PRICE_TABLE = 'product_monthly_weighted_average_rows';
private const WAREHOUSE_MAPPING_TABLE = 'business_inventory_warehouse_name_mappings';
/** 虚拟条码(信誉订单/虚拟订单)不是真实商品,不计入商品成本。 */
private const VIRTUAL_SKU_PREFIX = 'X0000';
/** 套餐 / 服务占位编码:不是实物商品,商品成本不取数。 */
private const EXCLUDED_SKUS = ['TCXJ', 'FUWU'];
private const REMARK_NO_WAREHOUSE = '未匹配仓库简称';
private const REMARK_NO_PRICE = '未匹配商品单价';
/**
* 数量单位与单价口径不一致:定制配件这类明细行,聚水潭把配件尺寸/件数写进了「商品数量」
* (例如数量 9524、金额 2000.04,实际单价 0.21),再乘成品的月加权/代发单价会放大几百倍。
* 成本单价高于该行明细单价 3 倍以上时判定为口径不一致,成本留空不计入合计。
*/
private const REMARK_UNIT_MISMATCH = '数量与单价口径不一致';
private const UNIT_MISMATCH_FACTOR = 3.0;
/** 单价来源:月加权平均单价(首选)与线上代发价格(兜底)。 */
private const PRICE_SOURCE_WEIGHTED = '月加权平均单价';
private const PRICE_SOURCE_PURCHASE = '线上代发价格-采购单价';
private const PRICE_SOURCE_DING = '线上代发价格-代发单价';
/** 最后兜底:普通商品资料(operations_replica.rpt.jst_sku)里的成本价。 */
private const PRICE_SOURCE_CATALOG = '普通商品资料成本价';
/** 线上代发价格的采购单来源(与「线上代发价格」页面同一口径)。 */
private const PURCHASE_PRICE_TABLE = 'product_purchase_price_mirror_rows';
/** 线上代发价格的钉钉代发来源。 */
private const DING_DAIFA_TABLE = 'ding_online_daifa_price_mirror';
/**
* 订单侧两个来源:淘系(企微客户订单)与聚水潭订单。
* 两边的仓库字段不同:淘系明细没有 send_warehouse,用订单上的 wms_co_id;
* 聚水潭优先取明细行的 send_warehouse,为空时退回订单的 wms_co_id(与「订单原始数据」一致)。
*/
private const SOURCES = [
[
'orders' => 'ops_jst_qmcust_orders',
'items' => 'ops_jst_qmcust_order_items',
'warehouse' => 'o.wms_co_id',
],
[
'orders' => 'ops_jst_orders',
'items' => 'ops_jst_order_item',
'warehouse' => "COALESCE(NULLIF(i.send_warehouse, ''), o.wms_co_id)",
],
];
/**
* 账单页签 key → 业绩明细里的平台名:--platform 既接受页签 key(jingxi),
* 也接受平台名(京喜账单),避免命令行和页面口径对不上。
*/
private const PLATFORM_LABELS = [
'taobao-alipay' => '淘系支付宝',
'taobao-wechat' => '淘系微信',
'pinduoduo' => '拼多多',
'dewu' => '得物',
'jd-wallet' => '京东网银钱包',
'jd-transactions' => '京东账单',
'jingxi' => '京喜账单',
'douyin' => '抖音',
];
public function handle(): int
{
if ((int) ini_get('memory_limit') > 0) {
@ini_set('memory_limit', '2G');
}
$month = trim((string) $this->argument('month'));
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
throw new InvalidArgumentException('月份格式应为 YYYY-MM,例如 2026-08。');
}
$reportMonth = $month . '-01';
$platformInput = trim((string) $this->option('platform'));
$platform = self::PLATFORM_LABELS[$platformInput] ?? $platformInput;
$chunkSize = max((int) $this->option('chunk'), 100);
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$mirror = DB::connection($connection);
// 账单侧取数:业绩明细里本月(可按平台限定)的账单行,一行 = 一个店铺的一个订单。
// 只取「收入金额有数据且不为 0」的账单行:收入为 0 的行是补出来的优惠/冲减/无收款账单行,
// 没有对应的收款商品,不参与商品成本。
// 「种菜金额」有数据(>0)的账单行整条排除,不参与匹配。
$billQuery = $mirror->table(self::SOURCE_TABLE)
->where('report_month', $reportMonth)
->whereNotNull('income_amount')
->where('income_amount', '!=', 0)
->where(static function ($query): void {
$query->whereNull('planting_amount')
->orWhere('planting_amount', '<=', 0);
});
if ($platform !== '') {
$billQuery->where('platform', $platform);
}
$bills = $billQuery->get([
'platform', 'store_name', 'order_core_no', 'online_order_no', 'occurred_date',
]);
$this->info(sprintf(
'账期 %s%s:业绩明细账单行 %d 条',
$month,
$platform !== '' ? '(' . $platform . ')' : '',
$bills->count()
));
/** @var array<string,object> $billByCore 核心单号 → 账单行 */
$billByCore = [];
$candidates = [];
foreach ($bills as $bill) {
$core = self::cleanOrderNo((string) ($bill->order_core_no ?? ''));
if ($core === '') {
continue;
}
if (! isset($billByCore[$core])) {
$billByCore[$core] = $bill;
}
$candidates[$core] = true;
$raw = trim((string) ($bill->online_order_no ?? ''));
if ($raw !== '') {
$candidates[$raw] = true;
}
}
if ($billByCore === []) {
$this->warn('没有可匹配的账单单号,已清空本月数据。');
$this->pruneTarget($connection, $reportMonth, $platform);
return self::SUCCESS;
}
// 订单侧数据量大(企微 500 万单 / 聚水潭 900 万行),先用临时表收敛候选单号,
// 再走 so_id / o_id 索引取明细,避免逐批 IN 查询退化成全表扫描。
$mirror->statement('DROP TEMPORARY TABLE IF EXISTS tmp_cost_order_nos');
$mirror->statement('CREATE TEMPORARY TABLE tmp_cost_order_nos (no varchar(64) NOT NULL, PRIMARY KEY (no)) ENGINE=InnoDB');
foreach (array_chunk(array_keys($candidates), $chunkSize) as $batch) {
$mirror->table('tmp_cost_order_nos')->insertOrIgnore(
array_map(static fn (string $no): array => ['no' => $no], $batch)
);
}
$this->info('订单侧候选单号:' . count($candidates));
/** @var array<string,list<array{sku:string,qty:float,amount:float,warehouse:string,is_main:bool,row_key:string}>> $lines */
$lines = [];
$excludedSkuSql = "'" . implode("','", self::EXCLUDED_SKUS) . "'";
foreach (self::SOURCES as $source) {
try {
$rows = $mirror->select(
"SELECT o.so_id as so_id, "
. $source['warehouse'] . " as warehouse_code, "
. " COALESCE(wh.name, '') as warehouse_name, "
. " CASE WHEN o.link_o_id IS NULL OR o.link_o_id = 0 THEN 1 ELSE 0 END as is_main, "
. " CONCAT(o.o_id, '-', i.oi_id) as row_key, "
. " i.sku_id as sku_id, i.qty as qty, i.amount as amount
FROM tmp_cost_order_nos t
STRAIGHT_JOIN {$source['orders']} o ON o.so_id = t.no
STRAIGHT_JOIN {$source['items']} i ON i.o_id = o.o_id
LEFT JOIN ops_jst_warehouse_info wh ON wh.wms_co_id = o.wms_co_id
WHERE COALESCE(i.sku_id, '') NOT LIKE 'X0000%'
AND UPPER(TRIM(COALESCE(i.sku_id, ''))) NOT IN ({$excludedSkuSql})"
);
} catch (Throwable $exception) {
$this->error('订单明细查询失败(' . $source['items'] . '):' . $exception->getMessage());
return self::FAILURE;
}
foreach ($rows as $row) {
$core = self::cleanOrderNo((string) $row->so_id);
if ($core === '' || ! isset($billByCore[$core])) {
continue;
}
$sku = trim((string) $row->sku_id);
if ($sku === '') {
continue;
}
$qty = (float) $row->qty;
$amount = (float) $row->amount;
// 数量与金额都为 0 的行是拆单/换货留下的占位行,不是真实发货商品。
if ($qty == 0.0 && $amount == 0.0) {
continue;
}
$warehouse = trim((string) $row->warehouse_name);
if ($warehouse === '') {
$warehouse = trim((string) ($row->warehouse_code ?? ''));
// 订单上的 wms_co_id 为 0 表示没有仓库信息,不能当成仓库名。
if ($warehouse === '0') {
$warehouse = '';
}
}
// 组合装条码(ZH-条码-数量-条码-数量)按子订单拆成组件行:
// 一个订单有几个发货仓库、商品编码、数量就分开列,组件数量 = 明细数量 × 组件倍数。
// 解析不了的组合条码(条码被截断等)保持原样,避免丢行。
foreach (self::expandComboSku($sku, $qty) as [$code, $codeQty, $isComponent]) {
$lines[$core][] = [
// 月加权平均单价表里的商品编码统一大写,订单侧可能小写,统一成大写再比。
'sku' => mb_strtoupper($code),
'qty' => $codeQty,
// 组合装明细金额对应整包,拆到组件后不再参与「数量×单价 vs 明细金额」校验。
'amount' => $isComponent ? 0.0 : $amount,
'warehouse' => $warehouse,
// 拆单后子单(link_o_id 非空)才是实际发货行;主单只是原始下单记录。
'is_main' => (int) $row->is_main === 1,
'row_key' => (string) $row->row_key,
];
}
}
}
$this->info('订单侧命中核心单号:' . count($lines));
$shortNames = $this->warehouseShortNames();
$prices = $this->weightedAverageUnitPrices($mirror, $reportMonth);
// 月加权平均单价匹配不到时,用「线上代发价格」(采购单价 / 钉钉代发单价)兜底。
$fallbackPrices = $this->onlineDaifaUnitPrices($mirror);
// 代发价格也没有时,再用普通商品资料里的商品成本价兜底。
$catalogPrices = $this->catalogCostPrices($mirror);
$this->info(sprintf(
'仓库映射条目:%d,月加权单价条目:%d,线上代发价格条目:%d,商品资料成本价条目:%d',
count($shortNames['by_provider']),
count($prices),
count($fallbackPrices),
count($catalogPrices)
));
$this->pruneTarget($connection, $reportMonth, $platform);
$target = DB::connection($connection)->table(self::TARGET_TABLE);
$now = now();
$buffer = [];
$imported = 0;
$quantityTotal = 0.0;
$costTotal = 0.0;
$missingPriceRows = 0;
$missingWarehouseRows = 0;
$fallbackPriceRows = 0;
$catalogPriceRows = 0;
$mismatchRows = 0;
foreach ($billByCore as $core => $bill) {
foreach ($this->costLines($lines[$core] ?? []) as $line) {
$short = $shortNames['by_provider'][$line['warehouse']] ?? '';
$price = $short !== '' ? ($prices[$short . "\0" . $line['sku']] ?? null) : null;
$priceSource = $price === null ? null : self::PRICE_SOURCE_WEIGHTED;
// 月加权平均单价按「仓库简称 + 商品编码」匹配不到时,退回线上代发价格(按商品编码)。
if ($price === null) {
$fallback = $fallbackPrices[$line['sku']] ?? null;
if ($fallback !== null) {
$price = $fallback['price'];
$priceSource = $fallback['source'];
$fallbackPriceRows++;
}
}
// 线上代发价格也没有时,最后用普通商品资料的商品成本价兜底。
if ($price === null) {
$catalogPrice = $catalogPrices[$line['sku']] ?? null;
if ($catalogPrice !== null) {
$price = $catalogPrice;
$priceSource = self::PRICE_SOURCE_CATALOG;
$catalogPriceRows++;
}
}
$quantity = round($line['qty'], 4);
$unitPrice = $price === null ? null : round((float) $price, 2);
$cost = $unitPrice === null ? null : round($quantity * $unitPrice, 2);
// 数量单位与单价口径校验:该行明细单价 = 明细金额 ÷ 数量。
// 成本单价高于明细单价 3 倍以上说明两边单位不是一回事(定制配件行),成本留空。
$detailUnitPrice = $quantity > 0 ? (float) $line['amount'] / $quantity : 0.0;
$unitMismatch = $unitPrice !== null
&& $detailUnitPrice > 0
&& $unitPrice > $detailUnitPrice * self::UNIT_MISMATCH_FACTOR;
if ($unitMismatch) {
$cost = null;
$unitPrice = null;
$priceSource = null;
}
$remarks = [];
if ($unitMismatch) {
$remarks[] = self::REMARK_UNIT_MISMATCH;
$mismatchRows++;
}
if ($short === '') {
$remarks[] = self::REMARK_NO_WAREHOUSE;
$missingWarehouseRows++;
}
if ($unitPrice === null) {
if (! $unitMismatch) {
$remarks[] = self::REMARK_NO_PRICE;
$missingPriceRows++;
}
} else {
$quantityTotal += $quantity;
$costTotal += (float) $cost;
}
$buffer[] = [
'report_month' => $reportMonth,
'row_key' => md5($reportMonth . '|' . $bill->platform . '|' . $bill->store_name . '|' . $core . '|' . $line['warehouse'] . '|' . $line['sku']),
'platform' => $bill->platform,
'occurred_date' => $bill->occurred_date,
'store_name' => $bill->store_name,
'online_order_no' => $core,
'warehouse' => $line['warehouse'] !== '' ? $line['warehouse'] : null,
'warehouse_short_name' => $short !== '' ? $short : null,
'product_code' => $line['sku'],
'product_quantity' => $quantity,
'unit_price' => $unitPrice,
'price_source' => $priceSource,
'product_cost' => $cost,
'remark' => $remarks === [] ? null : implode(' / ', $remarks),
'imported_at' => $now,
];
if (count($buffer) >= 500) {
$target->insertOrIgnore($buffer);
$imported += count($buffer);
$buffer = [];
}
}
}
if ($buffer !== []) {
$target->insertOrIgnore($buffer);
$imported += count($buffer);
}
$this->info(sprintf('写入完成,共 %d 行。', $imported));
$this->info(sprintf(' 商品数量合计:%s', number_format($quantityTotal, 2)));
$this->info(sprintf(' 商品成本合计:%s', number_format($costTotal, 2)));
$this->info(sprintf(
' 未匹配仓库简称:%d 行;线上代发价格兜底:%d 行;商品资料成本价兜底:%d 行;仍未匹配商品单价:%d 行;数量与单价口径不一致(不计成本):%d 行',
$missingWarehouseRows,
$fallbackPriceRows,
$catalogPriceRows,
$missingPriceRows,
$mismatchRows
));
return self::SUCCESS;
}
/**
* 拆单取数:聚水潭拆单后,主单(link_o_id 为空)保留的是原始下单行,
* 子单(link_o_id 指向主单)才是实际发货行。一个订单只要出现子单,就只取子单,
* 否则主单和子单会被各算一遍(主单的原始商品 + 子单的实际发货商品)。
* 没有子单的订单才用主单行。
*
* 同一订单的多条子单(不同仓库 / 分批发货)按「发货仓库 + 商品编码」汇总,数量相加,
* 这样「一个订单有几个发货仓库、商品编码、数量」会分开列。
*
* @param list<array{sku:string,qty:float,amount:float,warehouse:string,is_main:bool,row_key:string}> $rows
* @return list<array{sku:string,qty:float,amount:float,warehouse:string}>
*/
private function costLines(array $rows): array
{
if ($rows === []) {
return [];
}
// 1) 先按订单明细主键去掉上游的完全重复行(同一 o_id + oi_id 只算一次)。
$unique = [];
foreach ($rows as $row) {
$key = $row['row_key'] . "\0" . $row['sku'];
$unique[$key] = $row;
}
// 2) 有子单就只取子单(实际发货行);整单没有子单才用主单行。
$hasSubOrder = false;
foreach ($unique as $row) {
if (! $row['is_main']) {
$hasSubOrder = true;
break;
}
}
if ($hasSubOrder) {
$unique = array_filter($unique, static fn (array $row): bool => ! $row['is_main']);
}
// 3) 汇总到「发货仓库 + 商品编码」。
$aggregated = [];
foreach ($unique as $row) {
$key = $row['warehouse'] . "\0" . $row['sku'];
$aggregated[$key] = [
'sku' => $row['sku'],
'warehouse' => $row['warehouse'],
'qty' => ($aggregated[$key]['qty'] ?? 0.0) + $row['qty'],
'amount' => ($aggregated[$key]['amount'] ?? 0.0) + $row['amount'],
];
}
return array_values($aggregated);
}
/**
* 组合装条码拆组件:聚水潭的组合装 sku 形如
* ZH-<条码>-<数量>[-<条码>-<数量>...]
* 条码本身含横杠,所以按「纯数字段」识别数量,再按组件展开。
*
* 返回 [条码, 数量, 是否组件];非组合装或解析失败时返回原条码 / 原数量。
*
* @return list<array{0:string,1:float,2:bool}>
*/
private static function expandComboSku(string $sku, float $quantity): array
{
if (! str_starts_with(mb_strtoupper($sku), 'ZH-')) {
return [[$sku, $quantity, false]];
}
$parts = explode('-', substr($sku, 3));
$components = [];
$buffer = [];
foreach ($parts as $part) {
if ($part === '') {
return [[$sku, $quantity, false]];
}
if (preg_match('/^\d+(\.\d+)?$/', $part) === 1) {
if ($buffer === []) {
return [[$sku, $quantity, false]];
}
$components[] = [implode('-', $buffer), (float) $part];
$buffer = [];
continue;
}
$buffer[] = $part;
}
if ($buffer !== [] || $components === []) {
return [[$sku, $quantity, false]];
}
$expanded = [];
foreach ($components as [$code, $multiplier]) {
// 组合装里如果拆出套餐/服务占位编码,同样不取数。
if (in_array(mb_strtoupper(trim($code)), self::EXCLUDED_SKUS, true)) {
continue;
}
$expanded[] = [$code, $quantity * $multiplier, true];
}
return $expanded === [] ? [] : $expanded;
}
/**
* 仓库映射表:发货仓库 → 仓库简称。
*
* 映射表按「仓储方 + 仓库」登记,仓库名带「主仓」的那条代表该仓储方的正式出货仓,
* 因此优先用它作为发货仓库对应的简称;同时保留「完整仓库名 → 简称」的精确匹配。
*
* @return array{by_provider:array<string,string>,by_warehouse:array<string,string>}
*/
private function warehouseShortNames(): array
{
$byProvider = [];
foreach (DB::table(self::WAREHOUSE_MAPPING_TABLE)
->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']) as $mapping) {
$provider = trim((string) $mapping->warehouse_provider);
$warehouse = trim((string) $mapping->warehouse);
$short = trim((string) $mapping->warehouse_short_name);
if ($short === '') {
continue;
}
if ($provider === '') {
continue;
}
// 只认「仓储方 + 仓库含主仓」的那条:发货仓库是仓储方级别的名称,
// 次品仓 / 销退仓 / 客退仓这些行的简称(多为「-不看」)不能套到主仓发货上。
$isMain = str_contains($warehouse, '主仓');
if ($isMain) {
$byProvider[$provider] = $short;
continue;
}
// 映射表没有主仓行时,仅接受「仓库名 = 仓储方名」这种同名仓库(如重庆渝北仓),
// 其余(次品仓、配件单仓等)不再兜底,避免把主仓订单误判成不看仓。
if ($warehouse === $provider && ! isset($byProvider[$provider])) {
$byProvider[$provider] = $short;
continue;
}
// 业务确认:常州简尚家居有限公司的发货仓对应映射表里的「配件单仓」行
// (仓储方=常州简尚家居有限公司 / 仓库=配件单仓 → 配件单仓-不看)。
if (str_contains($warehouse, '配件单仓') && ! isset($byProvider[$provider])) {
$byProvider[$provider] = $short;
}
}
return ['by_provider' => $byProvider];
}
/**
* 商品月加权平均单价:按「仓库简称 + 商品编码」取加权平均价。
*
* @return array<string,float> 键为「仓库简称\0商品编码」
*/
private function weightedAverageUnitPrices($mirror, string $reportMonth): array
{
$prices = [];
$query = $mirror->table(self::PRICE_TABLE)
->where('report_month', $reportMonth)
->whereNotNull('weighted_average_unit_price');
foreach ($query->cursor() as $row) {
$prices[trim((string) $row->warehouse_short_name) . "\0" . mb_strtoupper(trim((string) $row->product_code))]
= (float) $row->weighted_average_unit_price;
}
return $prices;
}
/**
* 线上代发价格:月加权平均单价匹配不到时的兜底单价(按商品编码)。
*
* 与「线上代发价格」页面同源,取两个来源:
* 1. 采购单管理(product_purchase_price_mirror_rows):按商品编码取最新一次采购单价;
* 2. 钉钉线上代发审批(ding_online_daifa_price_mirror):商品ID 关联商品目录拿到商品编码,
* 单价 = 代发订单金额 ÷ 订单发货数量。
*
* 同一商品编码两边都有时取采购单价(本身就是单价字段,口径更直接)。
*
* @return array<string,array{price:float,source:string}>
*/
private function onlineDaifaUnitPrices($mirror): array
{
$prices = [];
try {
// 采购单管理:同一商品分多次采购时,后发生的记录覆盖先发生的,最终留下最新采购单价。
$purchaseRows = $mirror->table(self::PURCHASE_PRICE_TABLE)
->whereIn('document_status', ['Confirmed', 'Finished'])
->where('unit_price', '>', 0)
->orderByRaw('COALESCE(finished_at, document_created_at, purchase_updated_at, created_at)')
->get(['sku_id', 'unit_price']);
foreach ($purchaseRows as $row) {
$sku = mb_strtoupper(trim((string) $row->sku_id));
if ($sku !== '') {
$prices[$sku] = [
'price' => round((float) $row->unit_price, 2),
'source' => self::PRICE_SOURCE_PURCHASE,
];
}
}
} catch (Throwable $exception) {
$this->warn('采购单价格读取失败(跳过该兜底来源):' . $exception->getMessage());
}
try {
// 钉钉线上代发:镜像只存商品ID(= 聚水潭 shop_i_id),需要经商品目录换成商品编码。
$daifaRows = $mirror->table(self::DING_DAIFA_TABLE)
->where('ship_qty', '>', 0)
->where('daifa_amount', '>', 0)
->orderBy('workflow_created_at')
->get(['product_id', 'ship_qty', 'daifa_amount']);
$productIds = [];
foreach ($daifaRows as $row) {
$productId = trim((string) $row->product_id);
// 商品ID 是聚水潭的数字ID:审批表里偶尔填了文字(如「详情参考表格」),
// 混进 IN 条件会让 bigint 列做隐式类型转换、索引失效,这里只保留纯数字。
if ($productId !== '' && ctype_digit($productId)) {
$productIds[$productId] = true;
}
}
/** @var array<string,string> $skuByProductId */
$skuByProductId = [];
// 注意:shop_i_id 是 varchar,PHP 会把「纯数字字符串」的数组键转成 int,
// 直接传进去会让 MariaDB 做隐式类型转换、索引失效(实测 2500 万行全表扫)。
// 这里显式转字符串再绑定。
foreach (array_chunk(array_map('strval', array_keys($productIds)), 500) as $batch) {
foreach ($mirror->table('ops_jst_sku_map')->whereIn('shop_i_id', $batch)
->get(['shop_i_id', 'sku_id']) as $row) {
$sku = mb_strtoupper(trim((string) $row->sku_id));
if ($sku !== '') {
$skuByProductId[(string) $row->shop_i_id] = $sku;
}
}
}
foreach ($daifaRows as $row) {
$sku = $skuByProductId[trim((string) $row->product_id)] ?? '';
$quantity = (float) $row->ship_qty;
if ($sku === '' || $quantity <= 0 || isset($prices[$sku])) {
continue;
}
$prices[$sku] = [
'price' => round((float) $row->daifa_amount / $quantity, 2),
'source' => self::PRICE_SOURCE_DING,
];
}
} catch (Throwable $exception) {
$this->warn('线上代发价格读取失败(跳过该兜底来源):' . $exception->getMessage());
}
return $prices;
}
/**
* 普通商品资料(operations_replica.rpt.jst_sku → ops_jst_sku)里的商品成本价:
* 只取普通商品(sku_type=normal)且成本价大于 0 的记录,按商品编码建索引。
*
* @return array<string,float>
*/
private function catalogCostPrices($mirror): array
{
$prices = [];
try {
foreach ($mirror->table('ops_jst_sku')
->where('sku_type', 'normal')
->where('cost_price', '>', 0)
->get(['sku_id', 'cost_price']) as $row) {
$sku = mb_strtoupper(trim((string) $row->sku_id));
if ($sku !== '') {
$prices[$sku] = round((float) $row->cost_price, 2);
}
}
} catch (Throwable $exception) {
$this->warn('普通商品资料成本价读取失败(跳过该兜底来源):' . $exception->getMessage());
}
return $prices;
}
private function pruneTarget(string $connection, string $reportMonth, string $platform): void
{
$query = DB::connection($connection)->table(self::TARGET_TABLE)->where('report_month', $reportMonth);
if ($platform !== '') {
$query->where('platform', $platform);
}
$query->delete();
}
/**
* 订单号清洗沿用业绩明细的同一套口径(去日期前缀 / 空格 / 各类横杠,统一大写)。
*/
private static function cleanOrderNo(string $value): string
{
return SyncStoreReceiptOrderMatches::cleanOrderNo($value);
}
}

View File

@ -38,7 +38,7 @@ class SyncStoreReportMirror extends Command
}
$this->info(sprintf(
'店铺报表镜像:流程期间 %s/%d 行,主体变更 %s(检查 %d 店,新增 %d 条),账单 %s/%d 行,日汇总 %s/%d 行。',
'店铺报表镜像:流程期间 %s/%d 行,主体变更 %s(检查 %d 店,新增 %d 条),账单 %s/%d 行,日汇总 %s/%d 行,销量汇总 %s/%d 行。',
$result['lifecycles']['status'],
$result['lifecycles']['source_rows'],
$result['period_changes']['status'],
@ -48,6 +48,8 @@ class SyncStoreReportMirror extends Command
$result['bills']['source_rows'],
$result['daily']['status'],
$result['daily']['source_rows'],
$result['paid_sales']['status'],
$result['paid_sales']['stored_rows'],
));
return self::SUCCESS;

View File

@ -0,0 +1,51 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\StoreReportMirrorSynchronizer;
use Throwable;
/**
* 店铺维度报表的「销量」汇总:业绩明细「收入金额 + 优惠金额 + 冲减金额 + 退款金额」
* 按「店铺名称 + 发生日期」预汇总。
*
* 业绩明细同步(store-receipt:order-match:sync)结束后会自动刷新一次;
* 这个命令用于单独重跑(例如补数据或按最新代码强制重建)。
*/
class SyncStoreReportPaidSales extends Command
{
protected $signature = 'business-mirror:sync-store-report-paid-sales
{--force : 忽略来源指纹,强制重建销量汇总}';
protected $description = '把业绩明细的收入/优惠/冲减/退款金额按店铺和发生日期汇总,供店铺维度报表销量列读取';
public function handle(StoreReportMirrorSynchronizer $synchronizer): int
{
try {
$result = $synchronizer->syncPaidSales((bool) $this->option('force'));
} catch (Throwable $exception) {
$this->error('店铺维度报表销量汇总失败:' . $exception->getMessage());
return self::FAILURE;
}
if ($result['status'] === 'skipped') {
$this->warn('镜像里还没有业绩明细表,销量汇总未执行。');
return self::SUCCESS;
}
if ($result['status'] !== 'succeeded') {
$this->error('店铺维度报表销量汇总失败,页面继续读取上一版数据。');
return self::FAILURE;
}
$this->info($result['changed']
? sprintf('销量汇总已重建:业绩明细 %d 行 → 汇总 %d 行。', $result['source_rows'], $result['stored_rows'])
: sprintf('业绩明细没有变化,沿用当前销量汇总(%d 行)。', $result['stored_rows']));
return self::SUCCESS;
}
}

View File

@ -2,6 +2,7 @@
namespace App\Console\Commands;
use App\Business\StoreViolationAlertCalculator;
use App\Business\StoreViolationMapper;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Repositories\StoreViolationRecordRepository;
@ -23,7 +24,11 @@ class SyncStoreViolations extends Command
protected $description = '同步店铺违规信息(operations_replica.rpt.crawl_shop_violation → store_violation_records)';
public function handle(StoreViolationMapper $mapper, StoreViolationRecordRepository $repository): int
public function handle(
StoreViolationMapper $mapper,
StoreViolationRecordRepository $repository,
StoreViolationAlertCalculator $calculator,
): int
{
if (! $repository->available()) {
$this->error('统一表 store_violation_records 尚未建立,请先执行数据库迁移。');
@ -68,11 +73,32 @@ class SyncStoreViolations extends Command
$skipped = 0;
$read = 0;
// 违规原因/处置方式:上游视图补齐后自动参与同步;未提供时不触碰这两列,
// 避免每日同步把导入补充的数据清空。
$extraColumns = $this->availableExtraColumns($pdo);
$updateColumns = $extraColumns === []
? StoreViolationRecordRepository::CRAWL_UPDATE_COLUMNS
: array_merge(StoreViolationRecordRepository::CRAWL_UPDATE_COLUMNS, array_keys($extraColumns));
// 预警派生字段(级别/责任人/处理截止等)每次都随同步重算写入。
$updateColumns = array_values(array_unique(array_merge(
$updateColumns,
StoreViolationRecordRepository::ALERT_DERIVED_COLUMNS,
)));
try {
while (true) {
$sql = 'SELECT TOP ' . $batchSize
. ' id, shop_name, violation_no, violation_date, deadline, violation_content,'
. ' status, window_name, platform, crawl_date'
// FreeTDS 可能按连接区域返回 date(例如 "Oct 4 2026 12:00:00:AM"),
// 与镜像同步器保持一致:在源端转成 ISO 字符串再交给 PHP 解析。
$selectedColumns = ' id, shop_name, violation_no,'
. ' CONVERT(varchar(10), violation_date, 23) AS violation_date,'
. ' CONVERT(varchar(10), deadline, 23) AS deadline,'
. ' violation_content, status, window_name, platform,'
. ' CONVERT(varchar(10), crawl_date, 23) AS crawl_date';
foreach ($extraColumns as $target => $sourceColumn) {
$selectedColumns .= ', ' . $sourceColumn . ' AS ' . $target;
}
$sql = 'SELECT TOP ' . $batchSize . $selectedColumns
. ' FROM rpt.crawl_shop_violation WHERE id > ?';
$params = [$lastId];
@ -102,6 +128,14 @@ class SyncStoreViolations extends Command
continue;
}
$mapped = array_merge($mapped, $calculator->calculate(
(string) $mapped['platform'],
$mapped['shop_name'],
$mapped['violation_type'],
$mapped['violation_date'],
$mapped['appeal_deadline'],
));
$payload[] = $mapped + [
'synced_at' => $now,
'created_at' => $now,
@ -109,7 +143,7 @@ class SyncStoreViolations extends Command
];
}
$upserted += $repository->upsertRows($payload, StoreViolationRecordRepository::CRAWL_UPDATE_COLUMNS);
$upserted += $repository->upsertRows($payload, $updateColumns);
}
} catch (Throwable $exception) {
report($exception);
@ -132,4 +166,47 @@ class SyncStoreViolations extends Command
return self::SUCCESS;
}
/** @return array<string,string> 统一表字段 => 上游视图列名 */
private function availableExtraColumns(PDO $pdo): array
{
try {
$statement = $pdo->query(
"SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('rpt.crawl_shop_violation')"
);
$names = $statement->fetchAll(PDO::FETCH_COLUMN);
$statement->closeCursor();
} catch (Throwable) {
return [];
}
return self::pickExtraColumns(array_map('strval', $names));
}
/**
* 从上游可用列名中挑选可同步的扩展列;列名以数据平台实际提供的为准。
*
* @param list<string> $availableColumns
* @return array<string,string>
*/
public static function pickExtraColumns(array $availableColumns): array
{
$candidates = [
'violation_reason' => ['violation_reason', 'reason'],
'disposition' => ['disposition', 'handling_method', 'disposal'],
];
$available = array_map(static fn (string $name): string => strtolower($name), $availableColumns);
$selected = [];
foreach ($candidates as $target => $names) {
foreach ($names as $name) {
if (in_array($name, $available, true)) {
$selected[$target] = $name;
break;
}
}
}
return $selected;
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer;
use Throwable;
class SyncSupplierManagementMirror extends Command
{
protected $signature = 'business-mirror:sync-supplier-management';
protected $description = '完整校准供应商管理的档案、合同、联系人和打款资料共享镜像';
public function handle(BusinessMirrorDatasetRegistry $datasets, BusinessMirrorSynchronizer $synchronizer): int
{
if (! (bool) config('upstream_mirrors.refresh_enabled', false)) {
return self::SUCCESS;
}
$failed = false;
foreach ([SupplierManagementMirrorRepository::DATASET, ...array_values(SupplierManagementMirrorRepository::RELATED)] as $key) {
if (! $datasets->scheduled($key)) {
$this->warn($key . ':未启用后台同步,已跳过。');
continue;
}
try {
// 四个已接入的小数据集顺序校准,每批沿用现有大小,直到完整结束。
$result = $synchronizer->sync($key, true, null, 0);
if ($result['status'] !== 'succeeded') {
$failed = true;
$this->error($key . ':同步未完成,请检查同步状态。');
continue;
}
$this->info(sprintf('%s:同步完成,本轮 %d 批,累计处理 %d 行。', $key, $result['batches'], $result['rows']));
} catch (Throwable $exception) {
$failed = true;
Log::error('供应商管理每日镜像同步失败。', ['dataset' => $key, 'exception' => $exception::class]);
$this->error($key . ':同步失败,请检查同步状态。');
}
}
return $failed ? self::FAILURE : self::SUCCESS;
}
}

View File

@ -0,0 +1,172 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class VerifyErpDailyBillCoverage extends Command
{
protected $signature = 'business-mirror:verify-erp-daily-coverage
{--from=2026-07-01 : 起始日期 YYYY-MM-DD}
{--to= : 截止日期 YYYY-MM-DD,默认昨日}
{--json : 输出 JSON}';
protected $description = '核对京东日账单、京东钱包、头条放心购的月份与截止日覆盖是否完整';
private const TARGETS = [
'jd-daily' => [
'label' => '京东日账单',
'periods' => 'jd_daily_bill_periods',
'rows' => 'jd_daily_bill_rows',
],
'jd-wallet' => [
'label' => '京东钱包',
'periods' => 'jd_wallet_bill_periods',
'rows' => 'jd_wallet_bill_rows',
],
'douyin' => [
'label' => '头条放心购',
'periods' => 'douyin_authoritative_periods',
'rows' => 'douyin_authoritative_bills',
],
];
public function handle(): int
{
$fromText = (string) $this->option('from');
$toText = (string) ($this->option('to') ?: now('Asia/Shanghai')->subDay()->toDateString());
$from = $this->date($fromText);
$to = $this->date($toText);
if ($from === null || $to === null || $from->gt($to)) {
$this->error('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。');
return self::FAILURE;
}
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
$schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror'));
$results = [];
$failed = false;
foreach (self::TARGETS as $key => $target) {
if (! $schema->hasTable($target['periods']) || ! $schema->hasTable($target['rows'])) {
$results[] = [
'dataset' => $key,
'label' => $target['label'],
'month' => null,
'required_start' => $from->toDateString(),
'required_through' => $to->toDateString(),
'imported_start' => null,
'imported_end' => null,
'row_count' => 0,
'registered_rows' => null,
'income' => null,
'expense' => null,
'status' => 'missing_table',
'issue' => '镜像表不存在',
];
$failed = true;
continue;
}
$month = $from->copy()->startOfMonth();
while ($month->lte($to)) {
$monthEnd = $month->copy()->endOfMonth();
$requiredStart = ($month->lt($from) ? $from->copy() : $month->copy())->startOfDay();
$requiredThrough = ($monthEnd->gt($to) ? $to->copy() : $monthEnd->copy())->startOfDay();
$requiredEndExclusive = $requiredThrough->copy()->addDay();
$period = $db->table($target['periods'])
->where('period_start', $month->toDateString())
->first();
$status = 'ok';
$rowCount = 0;
$issue = null;
$summary = null;
if ($period === null) {
$status = 'missing_month';
$issue = '缺少该月份导入记录';
} elseif (Carbon::parse((string) $period->period_end)->lt($requiredEndExclusive)) {
$status = 'partial';
$issue = '导入截止日早于要求日期';
} else {
$summary = $db->table($target['rows'])
->where('generation', $period->active_generation)
->selectRaw('COUNT(*) AS rows_count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense')
->first();
$rowCount = (int) ($summary->rows_count ?? 0);
if ($rowCount === 0) {
$status = 'empty';
$issue = '有效版本没有明细';
} elseif ($rowCount !== (int) $period->row_count) {
$status = 'row_count_mismatch';
$issue = '有效版本实际行数与期间登记不一致';
} elseif (abs(round((float) $summary->income, 2) - (float) $period->income) > 0.005
|| abs(round((float) $summary->expense, 2) - (float) $period->expense) > 0.005) {
$status = 'amount_mismatch';
$issue = '有效版本收支合计与期间登记不一致';
}
}
if ($status !== 'ok') {
$failed = true;
}
$results[] = [
'dataset' => $key,
'label' => $target['label'],
'month' => $month->format('Y-m'),
'required_start' => $requiredStart->toDateString(),
'required_through' => $requiredThrough->toDateString(),
'imported_start' => $period?->period_start,
'imported_end' => $period?->period_end,
'row_count' => $rowCount,
'registered_rows' => $period === null ? null : (int) $period->row_count,
'income' => isset($summary) ? round((float) $summary->income, 2) : null,
'expense' => isset($summary) ? round((float) $summary->expense, 2) : null,
'status' => $status,
'issue' => $issue,
];
unset($summary);
$month->addMonthNoOverflow()->startOfMonth();
}
}
if ($this->option('json')) {
$this->line(json_encode($results, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
} else {
$this->table(
['数据集', '月份', '要求覆盖', '导入覆盖', '实际行数', '登记行数', '收入', '支出', '状态', '说明'],
array_map(static fn (array $row): array => [
$row['label'],
$row['month'] ?? '—',
($row['required_start'] ?? '—') . ' ~ ' . ($row['required_through'] ?? '—'),
($row['imported_start'] ?? '—') . ' ~ ' . ($row['imported_end'] ?? '—'),
number_format((int) $row['row_count']),
$row['registered_rows'] === null ? '—' : number_format((int) $row['registered_rows']),
$row['income'] === null ? '—' : number_format((float) $row['income'], 2),
$row['expense'] === null ? '—' : number_format((float) $row['expense'], 2),
$row['status'],
$row['issue'] ?? '',
], $results),
);
}
return $failed ? self::FAILURE : self::SUCCESS;
}
private function date(string $value): ?Carbon
{
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
return null;
}
$date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class VerifyFinanceLedger extends Command
{
protected $signature = 'finance-ledger:verify';
protected $description = '校验财务台账数量、金额勾稽和流水平衡(只读)';
public function handle(): int
{
$db = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$accounts = (int) $db->table('fin_accounts')->count();
$shops = (int) $db->table('fin_shops')->count();
$companies = (int) $db->table('fin_companies')->count();
$openingRows = (int) $db->table('fin_account_opening')->count();
$transactions = (int) $db->table('fin_transactions')->count();
$flows = (int) $db->table('fin_daily_flows')->count();
$maps = (int) $db->table('fin_account_map')->count();
$mapped = (int) $db->table('fin_account_map')->whereNotNull('account_short')->where('account_short', '<>', '')->count();
$accountBalance = round((float) $db->table('fin_accounts')->sum('current_balance'), 2);
$openingSum = round((float) $db->table('fin_account_opening')->sum('opening_balance'), 2);
$income = round((float) $db->table('fin_transactions')->sum('income'), 2);
$expense = round((float) $db->table('fin_transactions')->sum('expense'), 2);
$flowOpening = round((float) $db->table('fin_daily_flows')->sum('opening_balance'), 2);
$flowInflow = round((float) $db->table('fin_daily_flows')->sum('inflow'), 2);
$flowOutflow = round((float) $db->table('fin_daily_flows')->sum('outflow'), 2);
$flowClosing = round((float) $db->table('fin_daily_flows')->sum('closing_balance'), 2);
$diff = round($flowOpening + $flowInflow - $flowOutflow - $flowClosing, 2);
$this->table(['项目', '值'], [
['账户', $accounts],
['店铺', $shops],
['公司', $companies],
['期初账户', $openingRows],
['期初合计', number_format($openingSum, 2)],
['账户余额合计', number_format($accountBalance, 2)],
['动账明细', $transactions],
['收入合计', number_format($income, 2)],
['支出合计', number_format($expense, 2)],
['每日流水', $flows],
['流水期末合计', number_format($flowClosing, 2)],
['流水勾稽差异', number_format($diff, 2)],
['映射记录', $maps],
['已映射', $mapped],
]);
$errors = [];
if (abs($openingSum - $accountBalance) > 0.01) {
$errors[] = '期初合计与账户余额合计不一致。';
}
if (abs($diff) > 0.01) {
$errors[] = '每日流水期末不等于期初+入账-出账。';
}
if ($openingRows !== $flows) {
$errors[] = '期初账户数与当前流水行数不一致(期初日应一账户一行)。';
}
foreach ($errors as $error) {
$this->error($error);
}
return $errors === [] ? self::SUCCESS : self::FAILURE;
}
}

View File

@ -9,14 +9,14 @@ use Throwable;
class WarmOrderDataShopCandidates extends Command
{
protected $signature = 'order-data:warm-shop-candidates';
protected $signature = 'order-data:warm-shop-candidates {--full : 全量核对店铺候选(夜间维护)}';
protected $description = '预热订单售后费用明细的店铺候选(要扫两张百万级订单宽表,不能放在页面请求里)';
protected $description = '增量预热订单售后费用明细的店铺候选,夜间使用 --full 全量核对';
public function handle(OrderDataMirrorRepository $orders): int
{
try {
$names = $orders->refreshShopNamesCache();
$names = $orders->refreshShopNamesCache((bool) $this->option('full'));
$this->info(sprintf('店铺候选已预热,共 %d 个店铺。', count($names)));
return self::SUCCESS;

View File

@ -53,12 +53,37 @@ class Kernel extends ConsoleKernel
->withoutOverlapping(60)
->runInBackground();
$schedule->command('business-mirror:sync-supplier-management')
->dailyAt('08:15')
->timezone('Asia/Shanghai')
->withoutOverlapping(60)
->runInBackground();
// 店铺违规信息预警:每天同步副本库抓取结果到统一表(本地补充字段不覆盖)。
$schedule->command('store-violations:sync')
->dailyAt('05:30')
->withoutOverlapping(60)
->runInBackground();
// 店铺违规预警推送:P0/P1 每天 09:00 起每 5 分钟检查;P2 每日 10:00 汇总。
$schedule->command('store-violations:push-instant')
->cron('*/5 9-21 * * *')
->withoutOverlapping(5)
->runInBackground();
$schedule->command('store-violations:push-digest')
->dailyAt('10:00')
->withoutOverlapping(30)
->runInBackground();
// 财务台账:从 AI 库 rpt 同步动账明细,按日重算账户流水。
// 生产宿主机 cron 仍需配置对应的 finance-ledger:sync-rpt 入口。
$schedule->command('finance-ledger:sync-rpt')
->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)
@ -71,11 +96,18 @@ class Kernel extends ConsoleKernel
->runInBackground();
}
// 聚水潭发货数据每日重拉最近三天,覆盖副本库迟到更新。
// 聚水潭发货数据:凌晨重拉最近 40 天。聚水潭常在发货后数天到数周内换单/改快递公司/作废采购退货出库,
// 只拉最近几天会让上月数据停在旧值(快递名称不一致、已作废的单仍在);40 天覆盖上月结算期。
// 默认关闭(JST_SYNC_ENABLED=false);填好凭证并完成迁移后再打开。
if ((bool) env('JST_SYNC_ENABLED', false)) {
$schedule->command('jushuitan:sync-shipping --days=3')
$schedule->command('jushuitan:sync-shipping --days=40')
->dailyAt('01:28')
->withoutOverlapping(300)
->runInBackground();
// 凌晨副本库最近一两天的订单/商品明细常未到齐(视图、订单商品表滞后),
// 早上再拉一次最近 3 天,补齐凌晨只写入单号、缺商品明细的包裹。
$schedule->command('jushuitan:sync-shipping --days=3')
->dailyAt('07:28')
->withoutOverlapping(120)
->runInBackground();
}

View File

@ -100,6 +100,12 @@ class Handler extends ExceptionHandler
*/
public function render($request, Throwable $exception)
{
// 快递扫码填报页:手机原图超过上传上限时,回到填报页给出能看懂的提示,而不是报错页。
if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException
&& $request->is('onboarding/courier/*')) {
return redirect()->to($request->url() . '?too_large=1');
}
if (request_is_api($request)) {
return $this->handleApiExceptions($request, $exception);
}

View File

@ -157,7 +157,10 @@ class DingTalkLogin extends Controller
$url = $this->applicationRoute($user->landing_page, ['company_id' => $company->id]);
return redirect()->intended($url);
// 免登后固定回到首页(财务驾驶舱),不再回跳上次打开的业务页面。
$request->session()->forget('url.intended');
return redirect()->to($url);
}
protected function failed(): RedirectResponse

View File

@ -4,6 +4,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 Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@ -79,10 +80,14 @@ class Login extends Controller
// 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 = route('portal.dashboard', ['company_id' => $company->id]);
$path = $portalHome;
}
if (! $request->expectsJson()) {
@ -102,8 +107,11 @@ class Login extends Controller
// 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()->intended($url);
return redirect()->to($url);
}
return response()->json([
@ -112,7 +120,7 @@ class Login extends Controller
'error' => false,
'message' => trans('auth.login_redirect'),
'data' => null,
'redirect' => redirect()->intended($url)->getTargetUrl(),
'redirect' => url($url),
]);
}

View File

@ -0,0 +1,93 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\AccessoryReshipCourierImporter;
use Modules\EcommerceFinance\Services\AccessoryReshipCourierStore;
use Modules\EcommerceFinance\Services\AccessoryReshipRateCalculator;
use Modules\EcommerceFinance\View\AccessoryReshipConfigPageData;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class AccessoryReshipCourierConfigs extends Controller
{
public function __construct(private readonly AccessoryReshipCourierStore $store) {}
public function store(Request $request)
{
$this->store->save((int) company_id(), $this->validated($request), $this->actor());
return $this->back('快递扣款配置已新增。');
}
public function update(Request $request, int $configId)
{
$this->store->save((int) company_id(), $this->validated($request), $this->actor(), $configId);
return $this->back('快递扣款配置已更新,核对清单将按新比例重新计算。');
}
public function destroy(int $configId)
{
$this->store->changeDeleted((int) company_id(), $configId, true, $this->actor());
return $this->back('配置已删除,该快递暂不参与扣款计算。');
}
public function restore(int $configId)
{
$this->store->changeDeleted((int) company_id(), $configId, false, $this->actor());
return $this->back('快递扣款配置已恢复。');
}
public function import(Request $request, AccessoryReshipCourierImporter $importer)
{
$request->validate(['file' => ['required', 'file', 'mimes:xlsx', 'max:10240']]);
$path = $request->file('file')->getRealPath();
$rows = $importer->read($path);
$result = $this->store->import((int) company_id(), $rows, $this->actor(), hash_file('sha256', $path));
return $this->back("导入完成:新增{$result['added']}条,重复跳过{$result['skipped']}条。");
}
public function export(AccessoryReshipConfigPageData $data)
{
$rows = $this->store->filtered((int) company_id(), $data->filters())->get();
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->setTitle('快递配置');
$sheet->fromArray([['快递代码', '快递公司', '创建时间', '创建人', '扣款比率(%)', '删除状态']]);
foreach ($rows as $index => $row) {
$number = $index + 2;
foreach ([$row->courier_code, $row->courier_name, $row->source_created_at ?: $row->created_at, $row->creator] as $column => $value) {
$sheet->setCellValueExplicit([$column + 1, $number], (string) $value, DataType::TYPE_STRING);
}
$sheet->setCellValue([5, $number], $row->rate_basis_points / 10000);
$sheet->getStyle('E' . $number)->getNumberFormat()->setFormatCode('0.00%');
$sheet->setCellValueExplicit([6, $number], $row->deleted_at ? '已删除' : '正常', DataType::TYPE_STRING);
}
foreach (['A' => 24, 'B' => 30, 'C' => 24, 'D' => 18, 'E' => 18, 'F' => 14] as $column => $width) {
$sheet->getColumnDimension($column)->setWidth($width);
}
$sheet->freezePane('A2');
return response()->streamDownload(function () use ($book): void {
try { (new Xlsx($book))->save('php://output'); } finally { $book->disconnectWorksheets(); }
}, '快递扣款配置.xlsx', ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
}
private function validated(Request $request): array
{
$data = $request->validate(['courier_code' => ['required', 'string', 'max:64'], 'courier_name' => ['required', 'string', 'max:191'], 'rate_percent' => ['required', 'string']]);
$data['rate_basis_points'] = AccessoryReshipRateCalculator::basisPoints($data['rate_percent']);
return $data;
}
private function actor(): string
{
return mb_substr((string) user()->name, 0, 191);
}
private function back(string $message)
{
return redirect()->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'accessory-reship-deductions', 'reship_view' => 'config'])->with('reship_config_message', $message);
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\View\AccessoryReshipPageData;
class AccessoryReshipDeductions extends Controller
{
public function selectCourier(\Illuminate\Http\Request $request, AccessoryReshipPageData $data, \Modules\EcommerceFinance\Services\AccessoryReshipSelectionStore $store)
{
$input = $request->validate([
'month' => ['required', 'date_format:Y-m', 'after_or_equal:2000-01'],
'row_key' => ['required', 'regex:/^[a-f0-9]{64}$/'],
'courier' => ['required', 'string', 'max:191'],
]);
// 重新读取候选,禁止提交任意快递名称或其他公司的包裹。
$found = false;
foreach ($data->rows(['month' => $input['month']]) as $row) {
if ($row['selection_key'] !== $input['row_key']) continue;
$found = in_array($input['courier'], array_column($row['courier_candidates'], 'courier'), true);
break;
}
abort_unless($found, 422, '该快递已不在当前首发候选中,请刷新后重新选择。');
$store->save((int) company_id(), $input['month'], $input['row_key'], $input['courier'], mb_substr((string) user()->name, 0, 191));
return response()->json(['message' => '扣款快递已保存。']);
}
public function export(AccessoryReshipPageData $data)
{
$filters = $data->filters();
// 先完成读取,失败时返回正常错误,避免下载半份扣款清单。
$file = tmpfile();
if ($file === false) abort(500, '无法创建导出文件。');
fwrite($file, "\xEF\xBB\xBF");
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']];
fputcsv($file, array_map(static function ($value) {
$value = (string) $value;
return preg_match('/^[=+\-@\t\r\n]/u', $value) ? "'" . $value : $value;
}, $values));
}
rewind($file);
return response()->streamDownload(function () use ($file) { fpassthru($file); fclose($file); }, '配件补发扣款-' . $filters['month'] . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}

View File

@ -12,6 +12,7 @@ use Modules\EcommerceFinance\Services\AccountMappingCoa;
use Modules\EcommerceFinance\Services\AccountMappingStore;
use Modules\EcommerceFinance\Services\AccountMappingValidator;
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
use RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse;
@ -42,6 +43,7 @@ class AccountMappingActions extends Controller
'memo' => '财务备注',
'invoice' => '票据口径',
'category' => '大类',
'feeMemo' => '费用备注',
'dAcct' => '借方科目',
'dSub' => '借方二级',
'cAcct' => '贷方科目',
@ -74,27 +76,37 @@ class AccountMappingActions extends Controller
$this->store->create($values, $this->userId());
return response()->json(['message' => '已新增 1 条规则。'] + $this->payload());
$hint = $this->dispatchResync([(string) ($values['platform'] ?? '')]);
return response()->json(['message' => '已新增 1 条规则。' . $hint] + $this->payload());
}
public function update(Request $request, int $id): JsonResponse
{
if ($this->store->find($id) === null) {
$before = $this->store->find($id);
if ($before === null) {
throw ValidationException::withMessages(['id' => '这条规则已经不存在了,请刷新页面。']);
}
$this->store->update($id, $this->payloadValues($request), $this->userId());
$values = $this->payloadValues($request);
$after = $this->store->update($id, $values, $this->userId());
return response()->json(['message' => '已保存。'] + $this->payload());
$hint = AccountMappingStore::requiresReceiptResync($before, $after)
? $this->dispatchResync([(string) ($before['platform'] ?? ''), (string) ($after['platform'] ?? '')]) : '';
return response()->json(['message' => '已保存。' . $hint] + $this->payload());
}
public function destroy(int $id): JsonResponse
{
$before = $this->store->find($id);
if (! $this->store->destroy($id, $this->userId())) {
throw ValidationException::withMessages(['id' => '这条规则已经不存在了,请刷新页面。']);
}
return response()->json(['message' => '已删除 1 条规则。'] + $this->payload());
$hint = $this->dispatchResync([(string) ($before['platform'] ?? '')]);
return response()->json(['message' => '已删除 1 条规则。' . $hint] + $this->payload());
}
/**
@ -181,21 +193,24 @@ class AccountMappingActions extends Controller
}
$restored = $this->store->create($before, $this->userId());
$hint = $this->dispatchResync([(string) ($restored['platform'] ?? '')]);
return response()->json([
'message' => '已恢复「' . $restored['platform'] . ' · ' . $restored['item'] . '」(新记录 #' . (int) $restored['id'] . ')。',
'message' => '已恢复「' . $restored['platform'] . ' · ' . $restored['item'] . '」(新记录 #' . (int) $restored['id'] . ')。' . $hint,
] + $this->payload());
}
if ($action === 'update') {
if ($this->store->find($ruleId) === null) {
$current = $this->store->find($ruleId);
if ($current === null) {
throw ValidationException::withMessages(['history' => '这条规则已经被删掉了,请用同一条的「删除」记录恢复。']);
}
$this->store->update($ruleId, $before, $this->userId());
$hint = $this->dispatchResync([(string) ($current['platform'] ?? ''), (string) ($before['platform'] ?? '')]);
return response()->json([
'message' => '已恢复成这次修改前的内容(记录 #' . $ruleId . ')。',
'message' => '已恢复成这次修改前的内容(记录 #' . $ruleId . ')。' . $hint,
] + $this->payload());
}
@ -227,6 +242,8 @@ class AccountMappingActions extends Controller
$parsed = $this->importer->parse($file);
$result = $this->store->importRows($parsed['rows'], $request->boolean('overwrite'), $this->userId());
$message = "导入完成:识别 {$result['total']} 行,新增 {$result['created']} 条,更新 {$result['updated']} 条,跳过重复 {$result['skipped']} 条。";
$platforms = $result['resync_platforms'];
$message .= $this->dispatchResync($platforms);
return response()->json(['message' => $message, 'result' => $result] + $this->payload());
}
@ -302,7 +319,7 @@ class AccountMappingActions extends Controller
{
$total = $this->store->reset($this->userId());
return response()->json(['message' => "已恢复为初始 {$total} 条规则。"] + $this->payload());
return response()->json(['message' => "已恢复为初始 {$total} 条规则。" . $this->dispatchResyncAll()] + $this->payload());
}
/** 账套科目(一级 + 各一级下的明细),供下拉使用 */
@ -353,8 +370,8 @@ class AccountMappingActions extends Controller
public function template(): StreamedResponse
{
$samples = [
['得物', '平台服务费', '平台服务费', '0.06', '费用', '销售费用', '平台佣金', '其他货币资金', '', '支出基准'],
['淘宝', '交易收入', '订单', '-', '收入', '其他货币资金', '', '主营业务收入', '', '收入基准'],
['得物', '平台服务费', '平台服务费', '-', '0.06', '费用', '平台服务费', '销售费用', '平台服务费', '其他货币资金', '', '支出基准'],
['淘宝', '交易收入', '订单', '-', '-', '收入', '收入', '其他货币资金', '', '主营业务收入', '', '收入基准'],
];
return response()->streamDownload(function () use ($samples): void {
@ -406,6 +423,44 @@ class AccountMappingActions extends Controller
return user_id() ? (int) user_id() : null;
}
/**
* 保存映射后把受影响的平台排进后台重跑队列。
*
* 映射表本身是实时读取的,但业绩明细的优惠/冲减/退款金额是同步时落库的,
* 所以保存成功后需要自动重跑对应平台和月份。队列创建失败不能把已经保存成功的规则回滚。
*
* @param list<string> $platforms
*/
private function dispatchResync(array $platforms): string
{
try {
$result = app(AccountMappingResyncDispatcher::class)->dispatchFor($platforms);
} catch (\Throwable $exception) {
report($exception);
return ' 业绩明细自动重跑任务创建失败,请稍后重试保存或联系管理员。';
}
return $result['jobs'] > 0
? " 业绩明细已自动排队重跑:{$result['jobs']} 个平台×月份任务,后台依次执行。"
: '';
}
private function dispatchResyncAll(): string
{
try {
$result = app(AccountMappingResyncDispatcher::class)->dispatchAll();
} catch (\Throwable $exception) {
report($exception);
return ' 业绩明细自动重跑任务创建失败,请稍后重试或联系管理员。';
}
return $result['jobs'] > 0
? " 业绩明细已自动排队重跑:{$result['jobs']} 个平台×月份任务,后台依次执行。"
: '';
}
/**
* 原始操作记录 + 页面/CSV 直接可用的字段(变更内容与操作人只在服务端算一次)。
*

View File

@ -8,10 +8,12 @@ use App\Models\Business\CourierQuoteVersion;
use App\Models\Business\CourierSigningSubject;
use App\Services\Esign\EsignClient;
use App\Support\CourierAgreementFileArchive;
use App\Support\CourierAgreementCredentials;
use App\Support\CourierAgreementSignatureService;
use App\Support\CourierQuoteConfirmation;
use App\Support\CourierQuoteSignatureService;
use App\Utilities\SystemAccess;
use App\Support\SupplierCooperationTemplates;
use App\Utilities\AgreementSigningPermissions;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@ -19,6 +21,7 @@ use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Rule;
use RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse;
@ -37,6 +40,20 @@ class CourierAgreementSignatures extends Controller
public function store(Request $request): RedirectResponse
{
$this->ensureCanManage();
$request->merge(['partner_type' => $request->input('partner_type', 'courier')]);
$request->validate(['partner_type' => ['required', 'in:courier,supplier']]);
if ($request->input('partner_type') === 'supplier') {
if ($request->input('document_type') === 'cooperation-contract') {
$request->validate(['supplier_contract_template' => ['required', Rule::in(array_keys(SupplierCooperationTemplates::TEMPLATES))]]);
}
$request->validate(['supplier_id' => ['required', 'integer', 'min:1'],
'document_type' => ['required', 'in:account-proof,account-change,entity-change,authorization,cooperation-contract']]);
$supplier = app(\Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository::class)
->signingSupplier((int) $request->input('supplier_id'));
if (! $supplier) throw ValidationException::withMessages(['supplier_id' => '供应商资料暂不可用,请重新选择供应商。']);
$request->merge(['courier_name' => trim((string) $supplier->scmname)]);
if (! $request->filled('esign_account')) $request->merge(['esign_account' => trim((string) $supplier->accountbankno)]);
}
abort_unless(EsignClient::configured(), 422, 'E 签宝沙箱尚未配置 App ID 或 AppSecret。');
$requestedType = (string) $request->input('document_type');
if ($requestedType === 'quote-confirmation') {
@ -49,26 +66,34 @@ class CourierAgreementSignatures extends Controller
abort_unless(Schema::hasTable('business_courier_agreement_signatures'), 503, '协议签署数据表尚未完成迁移,请先执行数据库迁移。');
}
if ($request->input('document_type') === 'cooperation-contract') {
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'], true)
if (in_array($requestedType, ['account-proof', 'account-change', 'entity-change', 'cooperation-contract', 'authorization', 'shared-contract'], 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']);
}
$data = $request->validate($this->rules());
$data = $request->validate($this->rules(), [
'secondary_operator_name.required_if' => '请填写我方 E 签宝账号绑定的实名认证姓名。',
]);
$type = $data['document_type'];
if ($type === 'authorization' && count($data['authorization_items'] ?? []) === 0) {
throw ValidationException::withMessages(['authorization_items' => '授权委托书至少选择一项授权事项。']);
}
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()
@ -100,6 +125,64 @@ class CourierAgreementSignatures extends Controller
$data['operator_name'] = trim((string) $data['counterparty_organization_name']);
}
}
if ($type === 'entity-change') {
$formerCompanyDeregistered = filter_var(
$data['entity_change_old_company_deregistered'] ?? false,
FILTER_VALIDATE_BOOLEAN,
);
$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 === 'authorization') {
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
$data['secondary_signer_type'] = $data['secondary_signer_type'] ?? 'organization';
if ($data['counterparty_signer_type'] === 'person') {
$data['operator_name'] = trim((string) $data['principal_name']);
} elseif (blank($data['operator_name'] ?? null)) {
throw ValidationException::withMessages(['operator_name' => '请填写委托方企业经办人的 E 签宝实名认证姓名。']);
}
if ($data['secondary_signer_type'] === 'person') {
$data['secondary_operator_name'] = trim((string) $data['trustee_name']);
} elseif (blank($data['secondary_operator_name'] ?? null)) {
throw ValidationException::withMessages(['secondary_operator_name' => '请填写受托方企业经办人的 E 签宝实名认证姓名。']);
}
}
$this->validateEsignAccount($data['esign_account'], 'esign_account');
if (! empty($data['secondary_esign_account'])) {
$this->validateEsignAccount($data['secondary_esign_account'], 'secondary_esign_account');
@ -116,6 +199,12 @@ class CourierAgreementSignatures extends Controller
$data['operator_account'] = $data['esign_account'];
$data['payload'] = $this->payload($data);
$data['payload']['credential_required'] = $request->boolean('credential_required');
$data['payload']['credential_signer'] = (int) ($data['credential_signer'] ?? ($type === 'entity-change' ? 1 : 0));
if ($request->boolean('credential_required') && $type === 'entity-change'
&& $data['payload']['credential_signer'] === 0 && $data['counterparty_signer_type'] === 'person') {
throw ValidationException::withMessages(['credential_signer' => '营业执照需要企业盖章,请选择变更后主体签署证件。']);
}
$signature = $this->service->send($data, user_id());
@ -135,7 +224,7 @@ class CourierAgreementSignatures extends Controller
*/
public function storeSubject(Request $request): JsonResponse
{
$this->ensureCanManage();
$this->ensureCanAdminister();
if ($response = $this->subjectsTableUnavailable()) {
return $response;
@ -162,7 +251,7 @@ class CourierAgreementSignatures extends Controller
public function updateSubject(Request $request, CourierSigningSubject $subject): JsonResponse
{
$this->ensureCanManage();
$this->ensureCanAdminister();
$this->ensureSubjectBelongsToCurrentCompany($subject);
if ($response = $this->subjectsTableUnavailable()) {
@ -183,7 +272,7 @@ class CourierAgreementSignatures extends Controller
public function setDefaultSubject(CourierSigningSubject $subject): JsonResponse
{
$this->ensureCanManage();
$this->ensureCanAdminister();
$this->ensureSubjectBelongsToCurrentCompany($subject);
if ($response = $this->subjectsTableUnavailable()) {
@ -208,6 +297,32 @@ class CourierAgreementSignatures extends Controller
return $this->subjectResponse($subject->fresh(), '默认签署主体已切换。');
}
public function destroySubject(Request $request, CourierSigningSubject $subject): JsonResponse
{
$this->ensureCanAdminister();
$this->ensureSubjectBelongsToCurrentCompany($subject);
if ($response = $this->subjectsTableUnavailable()) {
return $response;
}
$request->validate(['delete_confirmed' => ['required', 'accepted']]);
DB::transaction(function () use ($subject): void {
$subject = CourierSigningSubject::query()->disableCache()->lockForUpdate()->findOrFail($subject->id);
$wasDefault = $subject->is_default;
$subject->forceFill(['is_default' => false, 'updated_by' => user_id()])->save();
$subject->delete();
if ($wasDefault) {
$nextDefault = CourierSigningSubject::query()->disableCache()->orderBy('id')->lockForUpdate()->first();
$nextDefault?->forceFill(['is_default' => true, 'updated_by' => user_id()])->save();
}
});
return $this->subjectResponse(null, '公司主体已删除,历史协议的主体快照保留。');
}
public function synchronize(CourierAgreementSignature $agreementSignature): RedirectResponse
{
$this->ensureCanManage();
@ -218,20 +333,77 @@ class CourierAgreementSignatures extends Controller
->with('success', "{$signature->documentLabel()}状态已同步:{$signature->statusLabel()}。");
}
public function archive(CourierAgreementSignature $agreementSignature): RedirectResponse
public function archive(Request $request, CourierAgreementSignature $agreementSignature): RedirectResponse
{
$this->ensureCanManage();
abort_unless($agreementSignature->status === CourierAgreementSignature::STATUS_COMPLETED && $agreementSignature->remote_status === '2', 422, '只有签署完成的协议可以人工归档。');
$signature = $this->service->archive($agreementSignature, null, user_id());
$data = $request->validate([
'archive_reason_code' => ['required', 'in:completed,confirmed,backfill,other'],
'archive_note' => ['nullable', 'string', 'max:200'],
]);
$reasonLabel = match ($data['archive_reason_code']) {
'completed' => '签署完成',
'confirmed' => '财务已确认',
'backfill' => '历史补录',
'other' => '其他',
};
$note = trim((string) ($data['archive_note'] ?? ''));
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()}已人工确认并归档。");
}
public function destroy(Request $request, CourierAgreementSignature $agreementSignature): JsonResponse|RedirectResponse
{
return $this->deleteTask($request, $agreementSignature);
}
public function destroyQuote(Request $request, CourierQuoteSignature $quoteSignature): JsonResponse|RedirectResponse
{
return $this->deleteTask($request, $quoteSignature);
}
private function deleteTask(Request $request, CourierAgreementSignature|CourierQuoteSignature $task): JsonResponse|RedirectResponse
{
$this->ensureCanAdminister();
abort_unless($task->company_id === (int) company_id(), 404);
$request->validate(['delete_confirmed' => ['required', 'accepted']]);
DB::transaction(function () use ($task): void {
$signature = $task::query()->disableCache()->lockForUpdate()->findOrFail($task->id);
// Soft-delete only the local task, retaining its files, remote flow and audit records.
$signature->updated_by = user_id();
$signature->save();
$signature->delete();
});
$message = '签署任务已删除。';
return $request->expectsJson()
? response()->json(['message' => $message])
: redirect()->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
->with('success', $message);
}
public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse|RedirectResponse
{
$this->ensureCanManage();
abort_unless($agreementSignature->company_id === (int) company_id(), 404);
if (preg_match('/^credential-(license|identity|bank)-(source|signed)$/', $kind, $match)) {
$document = $agreementSignature->credentialDocuments()[$match[1]] ?? null;
abort_unless($document, 404);
$path = $document[$match[2] . '_path'] ?? null;
abort_if(blank($path) || ! \Storage::disk('uploads')->exists($path), 404, '证件推送单不存在。');
return \Storage::disk('uploads')->response($path,
$agreementSignature->business_no . '-' . $document['name'] . ($match[2] === 'signed' ? '-已签署' : '-原文') . '.pdf',
['Content-Type' => 'application/pdf'], request()->boolean('preview') ? 'inline' : 'attachment');
}
try {
[$path, $suffix] = match ($kind) {
'source' => [$this->agreementFileArchive->sourcePath($agreementSignature), '签署原文'],
@ -292,7 +464,23 @@ class CourierAgreementSignatures extends Controller
{
$date = ['required', 'date', 'after_or_equal:today', 'before_or_equal:' . now()->addDays(90)->toDateString()];
$supplierContract = request('partner_type') === 'supplier' && request('document_type') === 'cooperation-contract';
$supplierFields = [];
foreach (SupplierCooperationTemplates::FIELDS as $key => $field) {
$supplierFields['supplier_contract_fields.' . $key] = [
Rule::requiredIf($supplierContract && ($field['required'] ?? false)), 'nullable', 'string',
'max:' . ($key === 'supply_price' ? 1000 : 255),
];
if (($field['type'] ?? '') === 'email') {
$supplierFields['supplier_contract_fields.' . $key][] = 'email';
}
}
return [
'supplier_contract_template' => [Rule::requiredIf($supplierContract), 'nullable', Rule::in(array_keys(SupplierCooperationTemplates::TEMPLATES)), Rule::prohibitedIf(! $supplierContract)],
'supplier_contract_fields' => ['nullable', 'array:' . implode(',', array_keys(SupplierCooperationTemplates::FIELDS))],
'partner_type' => ['required', 'in:courier,supplier'],
'supplier_id' => ['required_if:partner_type,supplier', 'nullable', 'integer', 'min:1'],
'idempotency_key' => ['required', 'string', 'max:80', 'regex:/^[A-Za-z0-9_-]+$/'],
'courier_name' => ['required', 'string', 'max:255'],
'document_type' => ['required', 'in:' . implode(',', array_keys(CourierAgreementSignature::DOCUMENTS))],
@ -302,10 +490,13 @@ class CourierAgreementSignatures extends Controller
'signature_date' => ['required', 'date'],
'signing_deadline' => $date,
'esign_account' => ['required', 'string', 'max:255'],
'secondary_esign_account' => ['required_if:document_type,entity-change,cooperation-contract,authorization', 'nullable', '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', 'nullable', 'in:organization,person'],
'counterparty_signer_type' => ['required_if:document_type,account-proof,account-change,entity-change,cooperation-contract,authorization,shared-contract', 'nullable', 'in:organization,person'],
'secondary_signer_type' => ['nullable', 'in:organization,person'],
'entity_change_old_company_deregistered' => ['nullable', 'boolean'],
'archive_mode' => ['required', 'in:auto,manual'],
'account_proof_effective_date' => ['required_if:document_type,account-proof', 'date'],
'account_proof_account_name' => ['required_if:document_type,account-proof', 'string', 'max:255'],
@ -323,7 +514,7 @@ class CourierAgreementSignatures extends Controller
'entity_change_date' => ['required_if:document_type,entity-change', 'date'],
'changed_company_name' => ['required_if:document_type,entity-change', 'string', 'max:255'],
'changed_company_start_date' => ['required_if:document_type,entity-change', 'date'],
'contract_partner_name' => ['required_if:document_type,shared-contract', 'string', 'max:255'],
'contract_partner_name' => ['required_if:document_type,shared-contract', 'string', 'min:2', 'max:255'],
'shared_courier_names' => ['nullable', 'array', 'min:1'],
'shared_courier_names.*' => ['required', 'string', 'max:255'],
'shared_courier_name' => ['nullable', 'string', 'max:255'],
@ -332,6 +523,9 @@ class CourierAgreementSignatures extends Controller
'cooperation_party_a_phone' => ['required_if:document_type,cooperation-contract', 'string', 'max:64'],
'cooperation_party_b_name' => ['required_if:document_type,cooperation-contract', 'string', 'max:255'],
'cooperation_party_b_phone' => ['required_if:document_type,cooperation-contract', 'string', 'max:64'],
'cooperation_party_b_signing_place' => ['nullable', 'string', 'max:100'],
'cooperation_contract_number' => ['nullable', 'string', 'max:100'],
'cooperation_party_b_legal_representative' => ['nullable', 'string', 'max:100'],
'cooperation_start_date' => ['required_if:document_type,cooperation-contract', 'date'],
'cooperation_end_date' => ['required_if:document_type,cooperation-contract', 'date', 'after_or_equal:cooperation_start_date'],
'principal_name' => ['required_if:document_type,authorization', 'string', 'max:100'],
@ -345,15 +539,28 @@ 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'));
}
private function payload(array $data): array
{
$allowed = array_keys($this->rules());
$payload = array_intersect_key($data, array_flip($allowed));
unset($payload['esign_account'], $payload['idempotency_key'], $payload['operator_name']);
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' && ($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'] ?? ''));
$payload['cooperation_party_b_legal_representative'] = ($data['counterparty_signer_type'] ?? 'organization') === 'person'
? 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'];
}
return $payload;
}
@ -393,7 +600,7 @@ class CourierAgreementSignatures extends Controller
{
return match ($data['document_type']) {
'account-proof', 'account-change' => trim((string) $data['counterparty_organization_name']),
'shared-contract' => trim((string) (($data['shared_courier_names'][0] ?? null) ?: ($data['shared_courier_name'] ?? $data['courier_name']))),
'shared-contract' => trim((string) $data['contract_partner_name']),
'entity-change' => trim((string) ($data['former_company_name'] ?? $data['courier_name'])),
'authorization' => trim((string) ($data['principal_name'] ?? $data['courier_name'])),
default => trim((string) $data['courier_name']),
@ -403,12 +610,17 @@ class CourierAgreementSignatures extends Controller
private function ensureCanManage(): void
{
abort_unless(
in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true),
AgreementSigningPermissions::canOperate(),
403,
'当前账号没有协议签署管理权限。',
'当前账号没有协议签署操作权限,请联系管理员授权。',
);
}
private function ensureCanAdminister(): void
{
abort_unless(AgreementSigningPermissions::canAdminister(), 403, '当前账号没有协议签署管理权限。');
}
private function subjectData(Request $request): array
{
$data = $request->validate([
@ -439,11 +651,11 @@ class CourierAgreementSignatures extends Controller
}
}
private function subjectResponse(CourierSigningSubject $subject, string $message): JsonResponse
private function subjectResponse(?CourierSigningSubject $subject, string $message): JsonResponse
{
return response()->json([
'message' => $message,
'subject' => $this->serializeSubject($subject),
'subject' => $subject ? $this->serializeSubject($subject) : null,
'subjects' => CourierSigningSubject::query()
->orderByDesc('is_default')
->orderBy('name')

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers\Business;
use App\Models\Business\CourierAgreementSignature;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
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
{
abort_unless($agreementSignature->company_id === (int) company_id()
&& $agreementSignature->archivedCourierContractPayload() !== null, 404);
$path = match ($kind) {
'signed' => $agreementSignature->signed_pdf_path,
'certificate' => $agreementSignature->certificate_path,
default => abort(404),
};
abort_if(blank($path) || ! Storage::disk('uploads')->exists($path), 404, '归档附件不存在,请核对协议签署记录。');
$suffix = $kind === 'signed' ? '已签署合作合同' : '签署完成证书';
return Storage::disk('uploads')->response($path, $agreementSignature->business_no . '-' . $suffix . '.pdf',
['Content-Type' => 'application/pdf'], request()->boolean('preview') ? 'inline' : 'attachment');
}
}

View File

@ -0,0 +1,367 @@
<?php
namespace App\Http\Controllers\Business;
use App\Models\Business\CourierOnboarding;
use App\Models\Business\CourierOnboardingEvent;
use App\Models\Business\CourierOnboardingFile;
use App\Support\CourierOnboardingService;
use App\Support\CourierOnboardingReviewers;
use App\Support\QrCode;
use App\Utilities\SystemAccess;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
class CourierOnboardings extends Controller
{
public function __construct(private readonly CourierOnboardingService $service)
{
}
public function store(Request $request): RedirectResponse
{
$this->ensureReady();
$data = $request->validate([
'courier_name' => ['required', 'string', 'max:100'],
'invite_label' => ['nullable', 'string', 'max:100'],
'valid_days' => ['nullable', 'integer', 'min:1', 'max:180'],
'workplatform_expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_\-]+$/'],
...CourierOnboarding::profileRules(),
], [
'courier_name.required' => '请先定好系统快递名称(需与报价名、发货数据里的快递名称一致)。',
'workplatform_expcode.required' => '请填写快递公司代码(与快递资料「快递公司代码」一致)。',
'workplatform_expcode.regex' => '快递公司代码只能包含字母、数字、下划线和短横线。',
...CourierOnboarding::profileMessages(),
], CourierOnboarding::profileAttributes());
$code = strtoupper(trim((string) $data['workplatform_expcode']));
$taken = CourierOnboarding::query()
->where('workplatform_expcode', $code)
->whereNotIn('status', [CourierOnboarding::STATUS_REJECTED, CourierOnboarding::STATUS_CANCELLED])
->exists();
if ($taken) {
throw ValidationException::withMessages(['workplatform_expcode' => "快递公司代码「{$code}」已被其他入驻申请使用。"]);
}
$onboarding = $this->service->invite(
$data['invite_label'] ?? null,
(int) ($data['valid_days'] ?? CourierOnboardingService::DEFAULT_VALID_DAYS),
(int) user_id(),
$data['courier_name'],
);
$onboarding->update(['workplatform_expcode' => $code, ...$this->profileValues($data)]);
return redirect()->route('business.courier-onboardings.show', $onboarding)
->with('success', '入驻二维码已生成,发给快递方扫码填写即可。');
}
public function show(CourierOnboarding $onboarding): View
{
$this->ensureReady();
try {
app(\App\Support\CourierQuoteSignatureService::class)->refreshPending();
} catch (\Throwable $exception) {
report($exception);
}
$onboarding->load(['files', 'events.actor', 'quoteVersion.signature']);
$reviewers = app(CourierOnboardingReviewers::class);
$reviewAccess = in_array($onboarding->status, ['submitted', 'first_approved', 'returned'], true)
? $reviewers->access($onboarding, (int) user_id()) : ['allowed' => false, 'message' => '当前申请无需审核。'];
return view('business.pages.courier-payables.courier-onboarding-show', [
'onboarding' => $onboarding,
'formUrl' => $this->formUrl($onboarding),
'signatures' => $this->service->agreementSignatures($onboarding),
'signedAgreement' => $this->service->signedAgreement($onboarding),
'quoteSignature' => $onboarding->quoteSignature(),
'esignReady' => $this->service->esignReady(),
'canFirstReview' => $reviewAccess['allowed'],
'canFinalReview' => $reviewAccess['allowed'],
'reviewAccess' => $reviewAccess,
'reviewerSettings' => $reviewers->settings(),
'isAdmin' => $this->isAdmin(),
'quoteVersions' => $onboarding->status === CourierOnboarding::STATUS_ACTIVATED ? $this->requotes()->versions($onboarding) : collect(),
]);
}
/** 后台变价页:复用入驻报价填写区,以最新版本(或已退回的变价单)为底稿。 */
public function requote(CourierOnboarding $onboarding): View|RedirectResponse
{
$this->ensureReady();
$quoteManagement = route('business.pages.show', ['section' => 'courier-payables', 'page' => 'quote-management']);
if ($onboarding->status !== CourierOnboarding::STATUS_ACTIVATED) {
return redirect()->to($quoteManagement)->with('success', '这家快递还没开通,开通后才能变价。');
}
$requotes = $this->requotes();
$open = $requotes->openChange($onboarding);
if ($open !== null && $open->status === \App\Models\Business\CourierQuoteChange::STATUS_PENDING_REVIEW) {
return redirect()->route('business.courier-quote-changes.show', $open)
->with('success', "已有待审核的变价单 {$open->number},审核完成后再发起新的变价。");
}
$version = $requotes->latestVersion($onboarding);
$payload = $open?->quote_payload ?? $requotes->currentPayload($onboarding);
if ($open === null) {
// 新变价默认从明天起执行。
$payload['quote_effective_date'] = today()->addDay()->toDateString();
}
return view('onboarding.courier-form', [
'onboarding' => $requotes->draftModel($onboarding, $payload),
'token' => '',
'provinces' => CourierOnboarding::PROVINCES,
'fileKinds' => CourierOnboardingFile::KINDS,
'requiredKinds' => CourierOnboardingFile::REQUIRED_KINDS,
'personKinds' => CourierOnboardingFile::PERSON_KINDS,
'personRequiredKinds' => CourierOnboardingFile::PERSON_REQUIRED_KINDS,
'requote' => [
'action' => route('business.courier-onboardings.requote.store', $onboarding),
'back' => $quoteManagement,
'courier' => $onboarding->courier_name,
'signer' => trim(($onboarding->isPerson() ? '' : $onboarding->company_full_name . ' · ') . $onboarding->esign_operator_name . ' ' . $onboarding->esign_account),
'version' => $version,
'change' => $open,
'summary' => old('summary', $open?->summary),
],
]);
}
public function storeRequote(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$this->ensureReady();
$data = $request->validate([
...\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'],
], [
'summary.required' => '请写一下这次变价的原因或依据,审核和对账时要看。',
'quote_end_date.after_or_equal' => '结束日期不能早于执行日期。',
]);
$change = $this->requotes()->submit($onboarding, $data, (int) user_id());
return redirect()->route('business.courier-quote-changes.show', $change)
->with('success', "变价单 {$change->number} 已提交审核。审核通过后会自动推送到快递的 e签宝签署。");
}
/** @return array<string,?string> */
private function profileValues(array $data): array
{
$values = [];
foreach (array_keys(CourierOnboarding::PROFILE_FIELDS) as $field) {
$values[$field] = filled($data[$field] ?? null) ? trim((string) $data[$field]) : null;
}
return $values;
}
private function requotes(): \App\Support\CourierRequoteService
{
return app(\App\Support\CourierRequoteService::class);
}
public function qr(Request $request, CourierOnboarding $onboarding): Response
{
$this->ensureReady();
$svg = QrCode::svg($this->formUrl($onboarding), 8);
$headers = ['Content-Type' => 'image/svg+xml; charset=utf-8', 'Cache-Control' => 'private, no-store'];
if ($request->boolean('download')) {
$headers['Content-Disposition'] = 'attachment; filename="courier-onboarding-' . $onboarding->number . '.svg"';
}
return response($svg, 200, $headers);
}
public function file(CourierOnboarding $onboarding, CourierOnboardingFile $file): StreamedResponse
{
$this->ensureReady();
abort_unless((int) $file->onboarding_id === (int) $onboarding->id, 404);
abort_unless(Storage::disk('uploads')->exists($file->path), 404, '附件不存在。');
return Storage::disk('uploads')->response($file->path, $file->original_name, [
'Content-Type' => $file->mime ?: 'application/octet-stream',
], request()->boolean('download') ? 'attachment' : 'inline');
}
public function firstApprove(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$note = $request->validate(['note' => ['nullable', 'string', 'max:1000']])['note'] ?? null;
$this->service->firstApprove($onboarding, (int) user_id(), $note);
return $this->back($onboarding, '初审通过,已转财务复审。');
}
public function returnForChanges(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$reason = $request->validate(['reason' => ['required', 'string', 'max:1000']], ['reason.required' => '请写明需要快递方补充或修改的内容。'])['reason'];
$this->service->returnForChanges($onboarding, (int) user_id(), $reason);
return $this->back($onboarding, '已退回补件,快递方用原二维码即可修改后重新提交。');
}
public function reject(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$reason = $request->validate(['reason' => ['required', 'string', 'max:1000']], ['reason.required' => '请填写不予合作的原因。'])['reason'];
$this->service->reject($onboarding, (int) user_id(), $reason);
return $this->back($onboarding, '已标记为不予合作。');
}
public function cancel(CourierOnboarding $onboarding): RedirectResponse
{
$this->service->cancel($onboarding, (int) user_id());
return $this->back($onboarding, '邀请已作废,原二维码不能再打开。');
}
public function extend(CourierOnboarding $onboarding): RedirectResponse
{
$this->service->extend($onboarding, (int) user_id());
return $this->back($onboarding, '链接有效期已延长 30 天。');
}
public function updateInternal(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$data = $request->validate([
'courier_name' => ['nullable', 'string', 'max:100'],
'reconciler' => ['nullable', 'string', 'max:100'],
...CourierOnboarding::profileRules(true),
], CourierOnboarding::profileMessages(), CourierOnboarding::profileAttributes());
if ($request->hasAny(['courier_name', 'reconciler'])) {
// 只提交了其中一项时,另一项沿用原值。
$data['courier_name'] = $request->has('courier_name') ? ($data['courier_name'] ?? null) : $onboarding->courier_name;
$data['reconciler'] = $request->has('reconciler') ? ($data['reconciler'] ?? null) : $onboarding->reconciler;
$this->service->updateInternal($onboarding, $data, (int) user_id());
}
// 表单里带了快递资料字段才更新(只改名称/对账人的旧表单不会清空它们)。
$profile = array_intersect_key($this->profileValues($data), $request->only(array_keys(CourierOnboarding::PROFILE_FIELDS)));
if ($profile !== []) {
$onboarding->update([...$profile, 'updated_by' => (int) user_id()]);
}
return $this->back($onboarding, '内部信息已保存。');
}
/**
* 手动补录 ERP 开通信息(钉钉流程同步不到、或名称对不上时用)。
* 快递资料按快递代码把入驻和工作平台老数据合成一行。
*/
public function erpOpening(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$data = $request->validate([
'workplatform_expcode' => ['nullable', 'string', 'max:64'],
'erp_account_id' => ['nullable', 'string', 'max:64'],
]);
// 快递公司代码在发码时已必填;这里留空表示沿用原代码。填了代码或 ERP账户ID 视为已开通,都空则恢复「待 ERP 开通」。
$code = filled($data['workplatform_expcode'] ?? null) ? strtoupper(trim((string) $data['workplatform_expcode'])) : null;
$accountId = filled($data['erp_account_id'] ?? null) ? trim((string) $data['erp_account_id']) : null;
$opened = $code !== null || $accountId !== null;
$onboarding->update([
'workplatform_expcode' => $code ?? $onboarding->workplatform_expcode,
'erp_account_id' => $accountId,
'erp_opened_at' => $opened ? ($onboarding->erp_opened_at ?? now()) : null,
'erp_opened_source' => $opened ? 'manual' : null,
'updated_by' => (int) user_id(),
]);
return $this->back($onboarding, $opened ? 'ERP 开通信息已保存(快递公司代码 ' . $onboarding->workplatform_expcode . ')。' : '已清空 ERP 开通信息,恢复为「待 ERP 开通」。');
}
public function finalApprove(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$data = $request->validate([
'courier_name' => [$onboarding->courier_name ? 'nullable' : 'required', 'string', 'max:100'],
'reconciler' => ['nullable', 'string', 'max:100'],
'note' => ['nullable', 'string', 'max:1000'],
], ['courier_name.required' => '请填写系统快递名称(需与报价名、发货数据里的快递名称完全一致)。']);
$onboarding = $this->service->finalApprove($onboarding, $data, (int) user_id());
if (! $onboarding->quote_version_id) {
return $this->back($onboarding, '财务复审通过。快递没有填写报价明细,请在报价管理补录后再发起报价确认。');
}
if (! $this->service->esignReady()) {
return $this->back($onboarding, '财务复审通过,首版报价已生成。E 签宝尚未配置,报价确认单暂不能推送;线下签署后可直接开通。');
}
try {
$this->service->pushQuote($onboarding->fresh(), (int) user_id());
} catch (ValidationException $exception) {
$message = collect($exception->errors())->flatten()->first() ?: '推送失败';
CourierOnboardingEvent::create([
'company_id' => $onboarding->company_id, 'onboarding_id' => $onboarding->id, 'event_type' => 'quote_push_failed',
'from_status' => $onboarding->status, 'to_status' => $onboarding->status, 'note' => $message,
'actor_type' => 'user', 'actor_id' => (int) user_id(),
]);
return $this->back($onboarding, '财务复审通过,首版报价已生成,但报价确认单推送失败:' . $message . '。可在右侧重新推送。');
}
return $this->back($onboarding, '财务复审通过,报价确认单已推送到快递的 e签宝,等待对方签署。');
}
public function pushQuote(CourierOnboarding $onboarding): RedirectResponse
{
$this->ensureAdmin();
$this->service->pushQuote($onboarding, (int) user_id());
return $this->back($onboarding, '报价确认单已推送到快递的 e签宝,等待对方签署。');
}
public function syncQuote(CourierOnboarding $onboarding): RedirectResponse
{
$signature = $this->service->syncQuote($onboarding, (int) user_id());
return $this->back($onboarding, '已同步 e签宝状态:' . $signature->statusLabel() . '。');
}
public function signUrl(CourierOnboarding $onboarding): RedirectResponse
{
$url = $this->service->quoteSignUrl($onboarding);
return $this->back($onboarding, '已获取签署链接,签署人用手机打开或扫码即可签署。')->with('quote_sign_url', $url);
}
public function activate(Request $request, CourierOnboarding $onboarding): RedirectResponse
{
$this->ensureAdmin();
$note = $request->validate(['offline_note' => ['nullable', 'string', 'max:1000']])['offline_note'] ?? null;
$this->service->activate($onboarding, (int) user_id(), $note);
return $this->back($onboarding, '快递已开通,快递资料「入驻快递」里可以查到。');
}
private function formUrl(CourierOnboarding $onboarding): string
{
$base = trim((string) config('courier_onboarding.public_url', ''));
if ($base === '') {
return route('courier-onboarding.form', ['token' => $onboarding->token]);
}
return rtrim($base, '/') . route('courier-onboarding.form', ['token' => $onboarding->token], false);
}
private function back(CourierOnboarding $onboarding, string $message): RedirectResponse
{
return redirect()->route('business.courier-onboardings.show', $onboarding)->with('success', $message);
}
private function ensureReady(): void
{
abort_unless($this->service->ready(), 503, '快递入驻数据表尚未完成迁移,请联系管理员执行数据库迁移。');
}
private function isAdmin(): bool
{
return in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true);
}
private function ensureAdmin(): void
{
abort_unless($this->isAdmin(), 403, '财务复审和开通需要管理员账号。');
}
}

View File

@ -0,0 +1,125 @@
<?php
namespace App\Http\Controllers\Business;
use App\Abstracts\Http\Controller;
use App\Business\CourierProfileData;
use App\Models\Business\CourierPaymentAccount;
use App\Models\Business\CourierProfile;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
/**
* 快递资料在财务系统的维护:编辑主信息(存覆盖值,不回写工作平台),打款信息新增/变更(保存后跳协议签署推送)。
*/
class CourierProfiles extends Controller
{
public function __construct(private readonly CourierProfileData $profiles)
{
}
public function update(Request $request, string $expcode): RedirectResponse
{
$row = $this->profiles->currentRow($expcode);
abort_if($row === null, 404);
$rules = [];
foreach (CourierProfile::EDITABLE as $field => $label) {
$rules[$field] = match (true) {
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'],
default => ['nullable', 'string', 'max:255'],
};
}
$data = $request->validate($rules, ['expname.required' => '快递公司名称不能为空。'], CourierProfile::EDITABLE);
$count = $this->profiles->update($expcode, $row->expname ?? null, $row, $data, (int) user_id());
return redirect($this->pageUrl($expcode, 'logs'))
->with('success', $count > 0 ? "已保存 {$count} 项修改(财务系统维护,不回写工作平台),修改记录见下方操作日志。" : '没有修改任何字段。');
}
/** 打款信息页签里发起:快递公司代码在表单里填。 */
public function storePaymentAccountForCode(Request $request): RedirectResponse
{
$data = $request->validate(
['expcode' => ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z_\-]+$/']],
['expcode.required' => '请填写快递公司代码。', 'expcode.regex' => '快递公司代码只能是字母、数字、下划线或短横线。'],
);
return $this->storePaymentAccount($request, trim($data['expcode']));
}
public function storePaymentAccount(Request $request, string $expcode): RedirectResponse
{
$row = $this->profiles->currentRow($expcode);
if ($row === null) {
throw \Illuminate\Validation\ValidationException::withMessages(['expcode' => "快递资料里没有快递公司代码「{$expcode}」,请核对。"]);
}
$change = $request->input('action') === CourierPaymentAccount::ACTION_CHANGE;
$number = ['required', 'string', 'max:64', 'regex:/^[0-9A-Za-z\- ]+$/'];
$data = $request->validate([
'action' => ['required', 'in:add,change'],
'account_type' => ['required', 'in:' . implode(',', CourierPaymentAccount::ACCOUNT_TYPES)],
'account_name' => ['required', 'string', 'max:255'],
'bank_name' => ['required', 'string', 'max:255'],
'account_number' => $number,
'effective_date' => ['required', 'date'],
'old_account_name' => [$change ? 'required' : 'nullable', 'string', 'max:255'],
'old_account_number' => $change ? $number : ['nullable', 'string', 'max:64'],
'old_stop_date' => [$change ? 'required' : 'nullable', 'date'],
'change_date' => [$change ? 'required' : 'nullable', 'date'],
'note' => ['nullable', 'string', 'max:500'],
], [
'account_number.regex' => '银行账号只能包含数字、字母和短横线。',
'old_account_number.regex' => '原账号只能包含数字、字母和短横线。',
], [
'account_type' => '账户类型', 'account_name' => $change ? '新开户名称' : '开户名称', 'bank_name' => $change ? '新开户银行' : '开户银行',
'account_number' => $change ? '新银行账号' : '银行账号', 'effective_date' => $change ? '新账户启用日期' : '生效日期',
'old_account_name' => '原开户名称', 'old_account_number' => '原账号', 'old_stop_date' => '原账户停止使用日期', 'change_date' => '账户变更日期',
]);
$strip = static fn (?string $value): ?string => $value === null ? null : (string) preg_replace('/\s+/u', '', $value);
$record = CourierPaymentAccount::query()->create([
'company_id' => company_id(),
'expcode' => $expcode,
'courier_name' => $row->expname ?? null,
'action' => $data['action'],
'account_type' => $data['account_type'],
'account_name' => trim($data['account_name']),
'bank_name' => trim($data['bank_name']),
'account_number' => $strip($data['account_number']),
'effective_date' => $data['effective_date'],
'old_account_name' => $change ? trim((string) $data['old_account_name']) : null,
'old_account_number' => $change ? $strip($data['old_account_number']) : null,
'old_stop_date' => $change ? $data['old_stop_date'] : null,
'change_date' => $change ? $data['change_date'] : null,
'note' => $data['note'] ?? null,
'created_by' => (int) user_id(),
'updated_by' => (int) user_id(),
]);
$summary = $change
? "打款信息变更:{$record->old_account_name} → {$record->account_name}({$record->account_type})"
: "打款信息新增:{$record->account_name}({$record->account_type},{$record->bank_name})";
$this->profiles->log($expcode, $change ? 'account_change' : 'account_add', $summary . ',待推送' . ($change ? '收款账户变更' : '收款账户证明') . '协议', null, (int) user_id());
return redirect()->route('business.pages.show', [
'section' => 'courier-payables',
'page' => 'agreement-signing',
'agreement_view' => 'create',
'payment_account' => $record->id,
])->with('success', $summary . '已保存。请核对下方预填的协议内容,补齐签署人信息后推送给快递签署;签署完成后这条打款信息显示为「已生效」。');
}
private function pageUrl(string $expcode, string $detailTab): string
{
return route('business.pages.show', [
'section' => 'courier-payables',
'page' => 'courier-information',
'selected' => $expcode,
'detail_tab' => $detailTab,
]) . '#courier-detail';
}
}

View File

@ -3,9 +3,12 @@
namespace App\Http\Controllers\Business;
use App\Models\Business\CourierQuoteChange;
use App\Models\Business\CourierStockQuoteEntry;
use App\Services\Esign\EsignClient;
use App\Support\CourierQuoteChangeService;
use App\Support\CourierOnboardingService;
use App\Support\CourierQuoteSignatureService;
use App\Support\CourierRequoteService;
use App\Support\QuoteManagementSnapshot;
use App\Utilities\SystemAccess;
use Illuminate\Http\RedirectResponse;
@ -19,6 +22,7 @@ class CourierQuoteChanges extends Controller
private readonly CourierQuoteChangeService $service,
private readonly QuoteManagementSnapshot $snapshot,
private readonly CourierQuoteSignatureService $signatureService,
private readonly CourierRequoteService $requotes,
) {
}
@ -35,7 +39,7 @@ class CourierQuoteChanges extends Controller
]);
}
public function create(Request $request): View
public function create(Request $request): View|RedirectResponse
{
$quotes = $this->snapshot->load()['quotes'] ?? [];
abort_if($quotes === [], 422, '尚未导入可用于变更的报价版本。');
@ -43,6 +47,11 @@ class CourierQuoteChanges extends Controller
$selectedId = (string) $request->query('source_quote_id', $quotes[0]['id']);
$source = $this->service->findSourceQuote($selectedId);
// 已入驻快递的报价走后台变价页(可改价格,也可改计费方式),推送按入驻资料签署。
if (empty($source['courier_expcode']) && $request->has('source_quote_id') && ($onboarding = $this->requotes->onboardingForCourier($source['company_name'] ?? null))) {
return redirect()->route('business.courier-onboardings.requote', $onboarding);
}
return view('business.pages.courier-payables.quote-change-editor', $this->editorData(null, $quotes, $source));
}
@ -56,20 +65,39 @@ class CourierQuoteChanges extends Controller
public function show(CourierQuoteChange $quoteChange): View
{
$this->refreshSignatures();
$quoteChange->load(['items', 'events.actor', 'version.signature']);
$stockEntry = $quoteChange->isStockQuote() ? CourierStockQuoteEntry::query()->where('source_change_id', $quoteChange->id)->firstOrFail() : null;
$onboarding = $stockEntry === null && $quoteChange->hasQuotePayload() ? $this->requotes->onboardingForCourier($quoteChange->carrier_name) : null;
$requoteDiff = $onboarding !== null
? $this->requotes->diff($onboarding, $this->requotes->basePayload($onboarding, $quoteChange), $quoteChange->quote_payload)
: null;
return view('business.pages.courier-payables.quote-change-show', [
'change' => $quoteChange,
'canReview' => $this->canReview() && $quoteChange->created_by !== user_id(),
'stockEntry' => $stockEntry,
'onboarding' => $onboarding,
'requoteDiff' => $requoteDiff,
'reviewWarnings' => $stockEntry === null && $quoteChange->hasQuotePayload() && $quoteChange->status !== CourierQuoteChange::STATUS_APPROVED
? $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(),
'esignConfigured' => EsignClient::configured(),
'esignEnvironment' => (string) config('services.esign.environment', 'sandbox'),
]);
}
public function edit(CourierQuoteChange $quoteChange): View
public function edit(CourierQuoteChange $quoteChange): View|RedirectResponse
{
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'));
}
if ($quoteChange->hasQuotePayload() && ($onboarding = $this->requotes->onboardingForCourier($quoteChange->carrier_name))) {
return redirect()->route('business.courier-onboardings.requote', $onboarding);
}
$quotes = $this->snapshot->load()['quotes'] ?? [];
$source = $this->service->findSourceQuote($quoteChange->source_quote_id);
$quoteChange->load('items');
@ -79,6 +107,7 @@ class CourierQuoteChanges extends Controller
public function update(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
abort_if($quoteChange->isStockQuote(), 422, '请使用存量报价草稿入口修改。');
$change = $this->service->update($quoteChange, $this->validatedChange($request, false), user_id());
return redirect()->route('business.courier-quote-changes.edit', $change)
@ -93,13 +122,21 @@ class CourierQuoteChanges extends Controller
->with('success', "{$change->number} 已提交审核。");
}
public function approve(CourierQuoteChange $quoteChange): RedirectResponse
public function approve(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
$change = $this->service->approve($quoteChange, user_id());
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'));
$message = "审核完成,已生成新报价版本 {$change->version->version_code}。";
if ($change->isStockQuote()) {
return redirect()->route('business.courier-quote-changes.show', $change)
->with('success', $message . ' ' . $change->version->signature_status . '。原报价已保留,未自动发起电子签署或发送提醒。');
}
try {
$this->signatureService->prepareVersion($change->version, user_id());
$message .= ' 签署 PDF 已生成并固定校验值。';
@ -112,10 +149,84 @@ class CourierQuoteChanges extends Controller
$message .= ' 历史生效已登记,但补差核算尚未执行,请查看核算状态和阻断原因。';
}
// 已入驻快递:按入驻资料直接推送到快递的 e签宝。
if ($change->hasQuotePayload() && ($onboarding = $this->requotes->onboardingForCourier($change->carrier_name))) {
try {
app(CourierOnboardingService::class)->pushVersion($onboarding, $change->version, (int) user_id());
$message .= " 已推送到快递 e签宝({$onboarding->esign_operator_name} {$onboarding->esign_account}),等待签署。";
} catch (\Throwable $exception) {
report($exception);
$reason = $exception instanceof \Illuminate\Validation\ValidationException ? collect($exception->errors())->flatten()->first() : '推送失败';
$message .= " 推送 e签宝失败:{$reason},可在下方重新推送。";
}
}
return redirect()->route('business.courier-quote-changes.show', $change)
->with('success', $message);
}
public function batchApprove(Request $request): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
$input = $request->validate([
'ids' => ['required', 'array', 'min:1', 'max:100'],
'ids.*' => ['required', 'integer', 'min:1', 'distinct'],
'stock_rules_confirmed' => ['accepted'],
], ['stock_rules_confirmed.accepted' => '请先核对选中报价的原报价、计费规则及实际执行日期。']);
$results = [];
// 历史签署资料需要逐份核对,不接受批量标记已经核验。
$singleRequest = $request->duplicate();
$singleRequest->merge(['stock_signature_verified' => false]);
foreach ($input['ids'] as $id) {
$change = CourierQuoteChange::query()->where('company_id', company_id())->find($id);
if ($change === null) {
$results[] = ['number' => '所选记录', 'success' => false, 'message' => '记录已不存在或不属于当前公司。'];
continue;
}
try {
// 复用单条入口,权限、校验、版本、日志及后续签署流程保持一致。
$response = $this->approve($singleRequest, $change);
$results[] = ['number' => $change->number, 'success' => true, 'message' => $response->getSession()->get('success')];
} catch (\Illuminate\Validation\ValidationException $exception) {
$results[] = ['number' => $change->number, 'success' => false, 'message' => collect($exception->errors())->flatten()->implode(';')];
} catch (\Throwable $exception) {
report($exception);
$results[] = ['number' => $change->number, 'success' => false, 'message' => '处理失败,请查看该单状态并重试。'];
}
}
$passed = count(array_filter($results, static fn ($result) => $result['success']));
return redirect()->route('business.courier-quote-changes.index', ['page' => max(1, (int) $request->input('page', 1))])
->with('success', '批量审核完成:成功 ' . $passed . ' 条,未通过 ' . (count($results) - $passed) . ' 条。')
->with('batch_review_results', $results);
}
/** 已入驻快递的变价版本按入驻资料(重新)推送到快递 e签宝。 */
public function pushToCourier(CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
abort_if($quoteChange->isStockQuote(), 422, '存量报价请先核对历史签署资料,补签通过详情页手动发起。');
$onboarding = $this->requotes->onboardingForCourier($quoteChange->carrier_name);
abort_if($onboarding === null || $quoteChange->version === null, 404);
app(CourierOnboardingService::class)->pushVersion($onboarding, $quoteChange->version, (int) user_id());
return redirect()->route('business.courier-quote-changes.show', $quoteChange)
->with('success', "{$quoteChange->version->version_code} 已推送到快递 e签宝,等待签署。");
}
/** 作废发错的报价版本(未签完的同时撤回 e签宝 签署任务)。 */
public function void(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
abort_if($quoteChange->version === null, 404);
$data = $request->validate(
['void_reason' => ['required', 'string', 'min:2', 'max:500']],
['void_reason.required' => '请写明作废原因,例如:江苏面单多打了一位。'],
);
$message = $this->requotes->voidVersion($quoteChange->version, trim($data['void_reason']), (int) user_id());
return redirect()->route('business.courier-quote-changes.show', $quoteChange)->with('success', $message);
}
public function returnForChanges(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
{
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
@ -242,6 +353,15 @@ class CourierQuoteChanges extends Controller
return $name;
}
private function refreshSignatures(): void
{
try {
$this->signatureService->refreshPending();
} catch (\Throwable $exception) {
report($exception);
}
}
private function canReview(): bool
{
return in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true);

View File

@ -11,6 +11,7 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class CourierQuoteSignatures extends Controller
@ -86,6 +87,146 @@ class CourierQuoteSignatures extends Controller
return \Storage::disk('uploads')->download($path, $fileName, ['Content-Type' => 'application/pdf']);
}
/**
* 批量导出已签署的回签单电子档(签署 PDF + 签署完成证书)为 zip。
* codes 为报价版本号,逗号分隔;不传则导出全部已归档的回签单。
*/
public function export(Request $request): BinaryFileResponse
{
$codes = array_values(array_filter(array_map('trim', explode(',', (string) $request->query('codes', '')))));
$signatures = CourierQuoteSignature::query()
->with('version')
->where('status', CourierQuoteSignature::STATUS_ARCHIVED)
->whereNotNull('signed_pdf_path')
->when($codes !== [], fn ($query) => $query->whereHas('version', fn ($version) => $version->whereIn('version_code', $codes)))
->orderBy('id')
->get();
abort_if($signatures->isEmpty(), 404, '没有可导出的已签署回签单。');
$disk = \Storage::disk('uploads');
$zipPath = tempnam(sys_get_temp_dir(), 'quote-signed-');
$zip = new \ZipArchive();
abort_unless($zip->open($zipPath, \ZipArchive::OVERWRITE) === true, 500, '生成压缩包失败。');
$added = 0;
foreach ($signatures as $signature) {
$version = $signature->version;
$base = $this->safeName(($version->company_name ?: $version->carrier_name) . '-' . $version->version_code);
if ($disk->exists($signature->signed_pdf_path)) {
$zip->addFromString("{$base}-回签单.pdf", $disk->get($signature->signed_pdf_path));
$added++;
}
if ($signature->certificate_path && $disk->exists($signature->certificate_path)) {
$zip->addFromString("{$base}-签署完成证书.pdf", $disk->get($signature->certificate_path));
}
}
$zip->close();
abort_if($added === 0, 404, '回签单归档文件不存在。');
$name = $signatures->count() === 1
? $this->safeName($signatures->first()->version->version_code) . '-回签单电子档.zip'
: '快递报价回签单-' . now()->format('Ymd-His') . '.zip';
return response()->download($zipPath, $name, ['Content-Type' => 'application/zip'])->deleteFileAfterSend();
}
/**
* 导出报价电子表格(xlsx,WPS / Excel 都能打开):只保留「省份」表头和各省价格,
* 不带标题、执行时间、计费说明和备注等文字行。
*/
public function sheet(CourierQuoteVersion $quoteVersion): StreamedResponse
{
$values = json_decode((string) $quoteVersion->values_json, true);
$table = self::quoteTable(is_array($values) ? $values : []);
abort_if($table === [], 404, '这份报价没有可导出的价格表。');
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle(mb_substr($this->safeName($quoteVersion->version_code), 0, 31));
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);
} elseif ($value !== null && $value !== '') {
$sheet->setCellValueExplicit($cell, (string) $value, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
}
}
}
$lastColumn = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(count($table[0]));
$range = 'A1:' . $lastColumn . count($table);
$sheet->getStyle($range)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
$sheet->getStyle($range)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER)
->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER)->setWrapText(true);
$header = $sheet->getStyle('A1:' . $lastColumn . '1');
$header->getFont()->setBold(true);
$header->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setRGB('F3EAD7');
$sheet->getColumnDimension('A')->setWidth(12);
for ($i = 2; $i <= count($table[0]); $i++) {
$sheet->getColumnDimension(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($i))->setWidth(16);
}
$sheet->freezePane('B2');
$fileName = $this->safeName(($quoteVersion->company_name ?: $quoteVersion->carrier_name) . '-' . $quoteVersion->version_code) . '-报价.xlsx';
return response()->streamDownload(function () use ($spreadsheet): void {
(new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet))->save('php://output');
}, $fileName, ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
}
/**
* 从报价矩阵里截出价格表:从「省份」表头行开始,到第一行只有一格文字(说明、备注)为止。
*
* @param array<int,mixed> $values
* @return list<list<string|int|float|null>>
*/
public static function quoteTable(array $values): array
{
$rows = array_values(array_filter($values, 'is_array'));
$filled = static fn (array $row): int => count(array_filter($row, static fn ($cell): bool => $cell !== null && trim((string) $cell) !== ''));
$start = null;
foreach ($rows as $index => $row) {
$first = trim((string) ($row[0] ?? ''));
if (preg_match('/^(省份|省市|区域|地区|目的地|目的省份)/u', $first) === 1 && $filled($row) >= 2) {
$start = $index;
break;
}
}
if ($start === null) {
foreach ($rows as $index => $row) {
if ($filled($row) >= 2) {
$start = $index;
break;
}
}
}
if ($start === null) {
return [];
}
$table = [];
for ($i = $start; $i < count($rows) && $filled($rows[$i]) >= 2; $i++) {
$table[] = array_values($rows[$i]);
}
$width = 0;
foreach ($table as $row) {
foreach ($row as $column => $cell) {
if ($cell !== null && trim((string) $cell) !== '') {
$width = max($width, $column + 1);
}
}
}
return array_map(static fn (array $row): array => array_pad(array_slice($row, 0, $width), $width, null), $table);
}
private function safeName(string $name): string
{
return trim(preg_replace('~[\\\\/:*?"<>|\s]+~u', '_', $name), '_') ?: 'quote';
}
private function validateAccountForNotice(string $account, string $noticeType): void
{
$valid = $noticeType === '1'

View File

@ -0,0 +1,214 @@
<?php
namespace App\Http\Controllers\Business;
use App\Models\Business\CourierStockQuoteEntry;
use App\Support\CourierStockQuoteBatchService;
use App\Support\CourierStockQuoteEntryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
use Modules\EcommerceFinance\Repositories\ShippingOrderRepository;
use Symfony\Component\HttpFoundation\StreamedResponse;
class CourierStockQuoteEntries extends Controller
{
public function __construct(private readonly CourierStockQuoteEntryService $service, private readonly CourierStockQuoteBatchService $batches)
{
}
public function create(): View
{
return view('business.pages.courier-payables.stock-quote-batch', ['batch' => null, 'manifest' => null, 'rows' => [], 'couriers' => [], 'templates' => $this->batches->ruleTemplates()]);
}
public function single(): View
{
return view('business.pages.courier-payables.stock-quote-entry', ['entry' => null, 'couriers' => $this->service->courierOptions()]);
}
public function previewBatch(Request $request): RedirectResponse
{
$data = $request->validate([
'source_quote' => ['required', 'file', 'mimes:xlsx,xls', 'max:20480'],
'quote_type' => ['required', 'string', 'max:64'],
'effective_date' => ['nullable', 'date_format:Y-m-d'],
'end_date' => ['nullable', 'date_format:Y-m-d'],
'billing_rules' => ['nullable', 'string', 'max:4000'],
]);
$batch = $this->batches->preview($data['source_quote'], collect($data)->except('source_quote')->all(), (int) user_id());
return redirect()->route('business.courier-stock-quotes.batch', $batch);
}
public function showBatch(string $batch): View
{
$manifest = $this->batches->load($batch, (int) user_id());
$couriers = $manifest['result'] === null ? $this->service->courierOptions() : [];
return view('business.pages.courier-payables.stock-quote-batch', [
'batch' => $batch, 'manifest' => $manifest, 'couriers' => $couriers,
'rows' => $manifest['result'] === null ? $this->batches->rows($manifest, $couriers) : [], 'templates' => [],
]);
}
public function saveBatch(Request $request, string $batch): RedirectResponse|JsonResponse
{
// JSON 请求体不受 max_input_vars 限制,防火墙也可逐字段检查,避免跨字段误匹配。
// 保留旧表单入口,已打开的页面仍由原有防护检查,不豁免任何用户输入。
if ($request->isJson()) {
$selection = $request->json()->all();
} else {
$request->validate(['selection_json' => ['required', 'json', 'max:200000']]);
$selection = json_decode($request->input('selection_json'), true);
}
if (! is_array($selection)) {
throw ValidationException::withMessages(['selection_json' => '请选择本次要录入的工作表。']);
}
foreach (['quote_type', 'summary'] as $field) {
if (is_string($selection[$field] ?? null)) {
$selection[$field] = trim($selection[$field]);
}
}
$data = Validator::make($selection, [
'quote_type' => ['required', 'string', 'max:64'],
'effective_date' => ['nullable', 'date_format:Y-m-d'],
'end_date' => ['nullable', 'date_format:Y-m-d'],
'summary' => ['required', 'string', 'min:2', 'max:2000'],
'rule_groups' => ['required', 'array', 'min:1', 'max:10'],
'rule_groups.*' => ['array'],
'rule_groups.*.name' => ['required', 'string', 'max:100'],
'rule_groups.*.rules' => ['nullable', 'string', 'max:4000'],
'entries' => ['required', 'array', 'max:200'],
'entries.*' => ['array'],
'entries.*.selected' => ['required', 'boolean'],
'entries.*.courier_expcode' => ['nullable', 'string', 'max:64'],
'entries.*.courier_name' => ['nullable', 'string', 'max:255'],
'entries.*.rule_group' => ['required', 'integer', 'min:0', 'max:9'],
'entries.*.effective_date' => ['nullable', 'date_format:Y-m-d'],
'entries.*.end_date' => ['nullable', 'date_format:Y-m-d'],
'submit_for_review' => ['required', 'boolean'],
'confirmed' => ['accepted_if:submit_for_review,true'],
])->validate();
$this->batches->save($batch, (int) user_id(), $data);
if ($request->expectsJson()) {
return response()->json(['redirect' => route('business.courier-stock-quotes.batch', $batch)]);
}
return redirect()->route('business.courier-stock-quotes.batch', $batch);
}
public function store(Request $request): RedirectResponse
{
$data = $request->validate([
...$this->metadataRules(),
'courier_expcode' => ['nullable', 'string', 'max:64'],
'courier_name' => ['required_without:courier_expcode', 'nullable', 'string', 'max:255'],
'quote_type' => ['required', 'string', 'max:64'],
'sheet_name' => ['nullable', 'string', 'max:255'],
...$this->fileRules(true),
]);
$entry = $this->service->create($data, (int) user_id());
return redirect()->route('business.courier-quote-changes.show', $entry->change)
->with('success', '存量报价草稿已保存。请核对原报价、计费规则和实际执行日期后提交审核。');
}
public function edit(CourierStockQuoteEntry $stockQuoteEntry): View
{
$this->ensureEditable($stockQuoteEntry);
return view('business.pages.courier-payables.stock-quote-entry', ['entry' => $stockQuoteEntry, 'couriers' => []]);
}
public function update(Request $request, CourierStockQuoteEntry $stockQuoteEntry): RedirectResponse
{
$this->ensureEditable($stockQuoteEntry);
$data = $request->validate([...$this->metadataRules(), ...$this->fileRules(false), 'sheet_name' => ['nullable', 'string', 'max:255'], 'courier_name' => ['sometimes', 'required', 'string', 'max:255']]);
$this->service->update($stockQuoteEntry, $data, (int) user_id());
return redirect()->route('business.courier-quote-changes.show', $stockQuoteEntry->change)->with('success', '草稿已更新,历次原报价及附件已保留。请重新核对后提交审核。');
}
public function batchImage(Request $request, string $batch, int $sheet, int $file): StreamedResponse
{
$manifest = $this->batches->load($batch, (int) user_id());
$attachment = $manifest['sheets'][$sheet]['signed_images'][$file] ?? null;
return $this->attachmentResponse($attachment, $request->boolean('preview'));
}
public function courierNames(Request $request, ShippingOrderRepository $shipping): JsonResponse
{
$data = $request->validate(['q' => ['required', 'string', 'min:2', 'max:64']]);
try {
return response()->json(['items' => $shipping->recentCourierNames(trim($data['q']), 20)]);
} catch (\Throwable $exception) {
return response()->json(['items' => [], 'message' => '发货名称暂不可用,可直接手填。'], 503);
}
}
public function download(Request $request, CourierStockQuoteEntry $stockQuoteEntry, int $file): StreamedResponse
{
abort_unless($stockQuoteEntry->company_id === (int) company_id(), 404);
$attachment = $stockQuoteEntry->files[$file] ?? null;
return $this->attachmentResponse($attachment, $request->boolean('preview'));
}
private function attachmentResponse(?array $attachment, bool $preview): StreamedResponse
{
$disk = Storage::disk('uploads');
abort_if($attachment === null || ! $disk->exists($attachment['path']), 404, '附件不存在。');
$headers = ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff'];
if ($preview) {
$mime = $attachment['mime_type'] ?? $disk->mimeType($attachment['path']);
abort_unless(in_array($mime, ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'], true), 415, '此格式请下载原文件查看。');
return $disk->response($attachment['path'], $attachment['name'], [...$headers, 'Content-Type' => $mime]);
}
return $disk->download($attachment['path'], $attachment['name'], $headers);
}
private function metadataRules(): array
{
return [
'effective_date' => ['required', 'date_format:Y-m-d'],
'end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:effective_date'],
'billing_rules' => ['required', 'string', 'min:2', 'max:4000'],
'summary' => ['required', 'string', 'min:2', 'max:2000'],
];
}
private function fileRules(bool $requiresSource): array
{
return [
'source_quote' => [$requiresSource ? 'required' : 'nullable', 'file', 'mimes:xlsx,xls', 'max:20480'],
'confirmation_files' => ['nullable', 'array', 'max:10'],
'confirmation_files.*' => ['file', 'mimes:pdf,doc,docx,jpg,jpeg,png,xlsx,xls,eml,msg', 'max:20480'],
'signed_files' => ['nullable', 'array', 'max:10'],
'signed_files.*' => ['file', 'mimes:pdf,doc,docx,jpg,jpeg,png', 'max:20480'],
];
}
private function ensureEditable(CourierStockQuoteEntry $entry): void
{
abort_unless($entry->company_id === (int) company_id() && $entry->change?->isEditable() && $entry->change->created_by === user_id(), 403);
}
public function periodEnd(Request $request, CourierStockQuoteEntry $stockQuoteEntry): RedirectResponse
{
abort_unless(in_array(\App\Utilities\SystemAccess::roleName(user()), [\App\Utilities\SystemAccess::SUPER_ADMIN, \App\Utilities\SystemAccess::ADMIN], true), 403);
abort_unless($stockQuoteEntry->company_id === (int) company_id(), 404);
$data = $request->validate(['end_date' => ['required', 'date_format:Y-m-d'], 'reason' => ['required', 'string', 'min:2', 'max:1000']]);
$this->service->setPeriodEnd($stockQuoteEntry, $data['end_date'], $data['reason'], (int) user_id());
return redirect()->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'quote-management'])->with('success', '执行截止日期已保存,报价原文和签署原件保持不变。');
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use App\Utilities\FinanceLedgerAccess;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Services\FinanceLedgerCalculator;
class FinanceLedger extends Controller
{
public function updateMapping(Request $request, int $id, FinanceLedgerCalculator $calculator): JsonResponse
{
abort_unless(FinanceLedgerAccess::canEditMapping(user()), 403, '只有财务台账管理员可以修改账户映射。');
$data = $request->validate([
'account_short' => ['nullable', 'string', 'max:100'],
]);
$account = trim((string) ($data['account_short'] ?? ''));
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$row = $connection->table('fin_account_map')->where('id', $id)->first();
abort_if($row === null, 404);
if ($account !== '') {
$exists = $connection->table('fin_accounts')->where('account_short', $account)->exists();
abort_unless($exists, 422, '账户简称不存在,请从账户总表中选择。');
}
$old = (string) ($row->account_short ?? '');
$connection->table('fin_account_map')->where('id', $id)->update([
'account_short' => $account !== '' ? $account : null,
'updated_by' => (string) user()->name,
'updated_at' => now(),
]);
$connection->table('fin_account_map_events')->insert([
'source' => (string) $row->source,
'source_value' => (string) $row->source_value,
'old_account_short' => $old !== '' ? $old : null,
'new_account_short' => $account !== '' ? $account : null,
'user_id' => (int) user()->id,
'user_name' => (string) user()->name,
'created_at' => now(),
]);
if ($request->boolean('recalculate', true)) {
$calculator->recalculate();
}
$mapped = $connection->table('fin_account_map')
->whereNotNull('account_short')->where('account_short', '<>', '')->count();
return response()->json([
'ok' => true,
'account_short' => $account,
'mapped' => $mapped,
'total' => $connection->table('fin_account_map')->count(),
], 200, ['Cache-Control' => 'private, no-store']);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -7,6 +7,7 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\PayablesFinalImporter;
use Modules\EcommerceFinance\Services\PayablesFinalImportRunner;
use Modules\EcommerceFinance\Services\PayablesFinalRegistry;
use Modules\EcommerceFinance\Services\PayablesFieldNormalizer;
use Modules\EcommerceFinance\Services\SupplierPayableImportTemplate;
@ -70,6 +71,38 @@ class PayablesFinalActions extends Controller
: back()->with('success', $message);
}
/** 大文件导入第 1 步:上传文件并建立行缓存(前端随后按片拉取处理)。 */
public function importUpload(Request $request, PayablesFinalImportRunner $runner): JsonResponse
{
$request->validate(['import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200']]);
$prepared = $runner->prepare(
$request->file('import'),
$this->fields($request),
$this->storeDataset($request),
(int) (company_id() ?: 1),
user_id() ? (int) user_id() : null,
);
return response()->json($prepared + ['offset' => 0, 'created' => 0, 'updated' => 0, 'done' => false]);
}
/** 大文件导入第 2 步起:每次处理一片,前端拿到进度后继续。 */
public function importChunk(Request $request, PayablesFinalImportRunner $runner): JsonResponse
{
$data = $request->validate([
'token' => ['required', 'string', 'regex:/^[a-f0-9]{32}$/'],
'offset' => ['required', 'integer', 'min:0'],
]);
return response()->json($runner->process(
$data['token'],
(int) $data['offset'],
null,
(int) (company_id() ?: 1),
));
}
public function update(Request $request, string $recordKey): JsonResponse|RedirectResponse
{
$values = $this->normalizer->normalize($this->fields($request), (array) $request->input('values', []));

View File

@ -0,0 +1,84 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\PlantingLossCalculator;
use Modules\EcommerceFinance\View\PlantingLossPageData;
use Modules\EcommerceFinance\View\PlantingReimbursementPageData;
/** 种菜数据汇总:种菜报销 / 种菜损耗 导出(与页面同一筛选口径)。 */
class PlantingWorkOrders extends Controller
{
public function exportReimbursements(PlantingReimbursementPageData $data)
{
$filters = $data->filters();
return $this->csv(
PlantingReimbursementPageData::TITLE . '-' . $filters['month'],
$data->exportColumns(),
static fn () => $data->rows($filters),
);
}
public function exportLoss(PlantingLossPageData $data)
{
$filters = $data->filters();
$suffix = match ($filters['result']) {
PlantingLossCalculator::RESULT_EXEMPT => '-不扣款拍A发B',
PlantingLossCalculator::RESULT_FREE_GOODS => '-不扣款虚拟条码挂钩',
PlantingLossCalculator::RESULT_UNMATCHED => '-未匹配发货',
'all' => '-全部',
default => '-扣款',
};
// 发运营的拍A发B 名单直接按「种菜报销」的字段导出。
if (request()->query('format') === 'reimbursement') {
return $this->csv(
'拍A发B发运营-' . $filters['month'],
PlantingReimbursementPageData::COLUMNS,
static fn () => $data->rows($filters),
);
}
return $this->csv(
PlantingLossPageData::TITLE . '-' . $filters['month'] . $suffix,
$data->exportColumns(),
static fn () => $data->rows($filters),
);
}
/** @param array<string,string> $columns @param callable():iterable<array<string,mixed>> $rows */
private function csv(string $name, array $columns, callable $rows)
{
$file = tmpfile();
abort_if($file === false, 500, '无法创建导出文件。');
try {
fwrite($file, "\xEF\xBB\xBF");
fputcsv($file, array_values($columns));
foreach ($rows() as $row) {
$values = [];
foreach (array_keys($columns) as $key) {
$values[] = $row[$key] ?? '';
}
fputcsv($file, array_map(static function (mixed $value): string {
$value = (string) $value;
// 长数字单号/账号保留文本,避免 Excel 截断;同时阻止公式执行。
return preg_match('/^[=+\-@\t\r\n]|^\d{12,}$/u', $value) ? "'" . $value : $value;
}, $values));
}
rewind($file);
} catch (\Throwable $exception) {
fclose($file);
report($exception);
abort(503, '聚工单镜像或发货数据未就绪,未生成不完整的导出文件,请稍后重试。');
}
return response()->streamDownload(static function () use ($file): void {
fpassthru($file);
fclose($file);
}, $name . '-' . now()->format('YmdHis') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\SupplierAccessoryFreightMatcher;
use Modules\EcommerceFinance\View\SupplierAccessoryFreightPageData;
class SupplierAccessoryFreight extends Controller
{
public function export(SupplierAccessoryFreightPageData $data)
{
$filters = $data->filters();
$columns = $data->exportColumns();
$file = tmpfile();
abort_if($file === false, 500, '无法创建导出文件。');
try {
fwrite($file, "\xEF\xBB\xBF");
fputcsv($file, ['业务月份', '发货记录ID', '仓库', ...array_values($columns)]);
foreach ($data->rows($filters) as $row) {
if ($filters['state'] !== 'all' && $filters['state'] !== $row['state']) continue;
$cells = array_merge($row, ['courier' => ($row['express_name1'] ?? '') ?: ($row['express_name2'] ?? ''),
'freight' => $row['freight_cents'] === null ? '待核实' : number_format($row['freight_cents'] / 100, 2, '.', ''),
'state' => SupplierAccessoryFreightMatcher::STATES[$row['state']], 'deduction' => number_format($row['deduction_cents'] / 100, 2, '.', '')]);
$values = [$filters['month'], $row['source_id'], \Modules\EcommerceFinance\Services\AccessoryReshipMatcher::WAREHOUSE];
foreach ($columns as $key => $label) $values[] = $cells[$key];
fputcsv($file, array_map(static function ($value) {
$value = (string) $value;
// 纯数字标识保留文本,防止 Excel 截断长单号;同时阻止公式执行。
return preg_match('/^[=+\-@\t\r\n]|^\d{12,}$/u', $value) ? "'" . $value : $value;
}, $values));
}
rewind($file);
} catch (\Throwable $exception) {
fclose($file);
report($exception);
abort(503, '资料读取失败,未生成不完整的扣款明细,请稍后重试。');
}
return response()->streamDownload(function () use ($file) { fpassthru($file); fclose($file); }, SupplierAccessoryFreightPageData::TITLE . '-' . $filters['month'] . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\View\SupplierBookkeepingPageData;
class SupplierBookkeeping extends Controller
{
public function export(SupplierBookkeepingPageData $data)
{
$filters = $data->filters();
$columns = $data->exportColumns();
$file = tmpfile();
abort_if($file === false, 500, '无法创建导出文件。');
try {
fwrite($file, "\xEF\xBB\xBF");
fputcsv($file, array_values($columns));
foreach ($data->rows($filters) as $row) {
$values = [];
foreach (array_keys($columns) as $key) {
$values[] = $row[$key] ?? '';
}
fputcsv($file, array_map(static function (mixed $value): string {
$value = (string) $value;
// 长数字单号保留文本,避免 Excel 截断;同时阻止公式执行。
return preg_match('/^[=+\-@\t\r\n]|^\d{12,}$/u', $value) ? "'" . $value : $value;
}, $values));
}
rewind($file);
} catch (\Throwable $exception) {
fclose($file);
report($exception);
abort(503, '聚工单镜像未就绪或读取失败,未生成不完整的厂家记账,请稍后重试。');
}
return response()->streamDownload(static function () use ($file): void {
fpassthru($file);
fclose($file);
}, SupplierBookkeepingPageData::TITLE . '-' . now()->format('YmdHis') . '.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}

View File

@ -0,0 +1,100 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\Rule as ValidationRule;
use Modules\EcommerceFinance\Services\SupplierBookkeepingConfigImporter;
use Modules\EcommerceFinance\Services\SupplierBookkeepingConfigStore;
use Modules\EcommerceFinance\Services\SupplierBookkeepingDeductionRule as Rule;
use Modules\EcommerceFinance\View\SupplierBookkeepingConfigPageData;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class SupplierBookkeepingConfigs extends Controller
{
public function __construct(private readonly SupplierBookkeepingConfigStore $store) {}
public function store(Request $request)
{
$this->store->save($this->validated($request), $this->actor());
return $this->back('厂家记账配置已新增,厂家记账明细按新配置重新判定。');
}
public function update(Request $request, int $configId)
{
$this->store->save($this->validated($request), $this->actor(), $configId);
return $this->back('厂家记账配置已更新,厂家记账明细按新配置重新判定。');
}
public function destroy(int $configId)
{
$this->store->changeDeleted($configId, true, $this->actor());
return $this->back('配置已删除,该供应商视同不在配置表,按正常记账扣款。');
}
public function restore(int $configId)
{
$this->store->changeDeleted($configId, false, $this->actor());
return $this->back('厂家记账配置已恢复。');
}
public function import(Request $request, SupplierBookkeepingConfigImporter $importer)
{
$request->validate(['file' => ['required', 'file', 'mimes:xlsx', 'max:10240']]);
$path = $request->file('file')->getRealPath();
$result = $this->store->import($importer->read($path), $this->actor(), hash_file('sha256', $path));
return $this->back("导入完成:新增{$result['added']}条,更新{$result['updated']}条,未变化{$result['skipped']}条。");
}
public function export(SupplierBookkeepingConfigPageData $data)
{
$rows = $this->store->filtered($data->filters())->get();
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->setTitle('厂家记账配置');
$sheet->fromArray([['供应商', '记账方式', '生效开始日期', '生效结束日期', '原始说明', '创建人', '更新时间', '删除状态']]);
foreach ($rows as $index => $row) {
$values = [$row->supplier_name, Rule::MODES[$row->mode] ?? $row->mode, $row->effective_from, $row->effective_to, $row->source_text, $row->creator, $row->updated_at, $row->deleted_at ? '已删除' : '正常'];
foreach ($values as $column => $value) {
$sheet->setCellValueExplicit([$column + 1, $index + 2], (string) $value, DataType::TYPE_STRING);
}
}
foreach (['A' => 24, 'B' => 20, 'C' => 14, 'D' => 14, 'E' => 44, 'F' => 16, 'G' => 20, 'H' => 10] as $column => $width) {
$sheet->getColumnDimension($column)->setWidth($width);
}
$sheet->freezePane('A2');
return response()->streamDownload(function () use ($book): void {
try { (new Xlsx($book))->save('php://output'); } finally { $book->disconnectWorksheets(); }
}, '厂家记账配置.xlsx', ['Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
}
private function validated(Request $request): array
{
return $request->validate([
'supplier_name' => ['required', 'string', 'max:191'],
'mode' => ['required', ValidationRule::in(array_keys(Rule::MODES))],
'effective_from' => ['nullable', 'date_format:Y-m-d'],
'effective_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:effective_from'],
'source_text' => ['nullable', 'string', 'max:255'],
], [], ['supplier_name' => '供应商', 'mode' => '记账方式', 'effective_from' => '生效开始日期', 'effective_to' => '生效结束日期', 'source_text' => '备注']);
}
private function actor(): string
{
return mb_substr((string) user()->name, 0, 191);
}
private function back(string $message)
{
return redirect()->route('business.pages.show', ['section' => 'supplier-payables', 'page' => 'manufacturer-bookkeeping', 'bk_view' => 'config'])->with('bookkeeping_config_message', $message);
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
use Modules\EcommerceFinance\View\SupplierManagementPageData;
class SupplierManagement extends Controller
{
public function export(Request $request, SupplierManagementMirrorRepository $repository, SupplierManagementPageData $page)
{
abort_unless($repository->ready(), 503, '供应商资料尚未完成首次同步,暂时不能导出。');
$filters = $page->filters($request->query());
return response()->streamDownload(static function () use ($repository, $filters): void {
$csv = fopen('php://output', 'w');
fputs($csv, "\xEF\xBB\xBF");
fputcsv($csv, array_values(SupplierManagementMirrorRepository::COLUMNS));
foreach ($repository->exportRows($filters) as $row) {
$values = [];
foreach (array_keys(SupplierManagementMirrorRepository::COLUMNS) as $column) {
$value = (string) ($row->{$column} ?? '');
if ($column === 'coopersgn') $value = ['1' => '合作', '2' => '不合作'][$value] ?? '未维护';
// Excel 不能执行供应商提供的公式文本,且长编码保留为文本。
if (preg_match('/^[=+\-@\t\r\n]/', ltrim($value)) || preg_match('/^\d{12,}$/', $value)) $value = "'" . $value;
$values[] = $value;
}
fputcsv($csv, $values);
}
fclose($csv);
}, 'supplier_management_' . now()->format('Ymd_His') . '.csv',
['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store']);
}
}

View File

@ -0,0 +1,246 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Services\SupplierComparisonCsvExporter;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
use Modules\EcommerceFinance\Services\SupplierStatementMatcher;
use Modules\EcommerceFinance\Services\SupplierStatementStore;
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
/**
* 供应商对账:对账单模板下载 + 厂家对账单上传(严格按模板校验)。
*/
class SupplierReconciliation extends Controller
{
public function __construct(
private readonly SupplierStatementTemplate $template,
private readonly SupplierStatementStore $statements,
private readonly SupplierReturnConfirmation $returnConfirmations,
private readonly SupplierReconciliationPageData $pageData,
private readonly SupplierReturnCsvExporter $returnCsvExporter,
private readonly SupplierDingTalkNotifier $dingTalkNotifier,
private readonly SupplierComparisonCsvExporter $comparisonCsvExporter,
) {
$this->middleware('auth');
$this->middleware('company.identify');
}
public function template(): BinaryFileResponse
{
$path = $this->template->path();
abort_unless(is_file($path), 404, '对账单模板不存在。');
return response()->download($path, $this->template->filename());
}
public function upload(Request $request): JsonResponse|RedirectResponse
{
$request->validate([
'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200'],
'supplier' => ['required', 'string', 'max:191'],
]);
$supplier = trim((string) $request->input('supplier'));
if ($supplier === '') {
abort(422, '请选择厂家。');
}
$records = $this->template->parse($request->file('import'), $supplier);
$rows = $this->statements->save(
$supplier,
$records,
(string) $request->file('import')->getClientOriginalName(),
(int) (company_id() ?: 1),
user_id() ? (int) user_id() : null,
);
$message = "对账单已保存:{$supplier} 共 {$rows} 行。";
return $request->expectsJson()
? response()->json(['message' => $message, 'rows' => $rows])
: back()->with('success', $message);
}
public function confirmReturn(Request $request): RedirectResponse
{
return $this->markReturn($request, SupplierReturnConfirmation::STATUS_CONFIRMED, '已确认该行退货扣减。');
}
public function disputeReturn(Request $request): RedirectResponse
{
return $this->markReturn($request, SupplierReturnConfirmation::STATUS_DISPUTED, '已提交异议,复核通过前该行暂不扣减。');
}
public function confirmAllReturns(Request $request): RedirectResponse
{
[$supplier, $companyId] = $this->returnTarget($request);
$keys = array_values(array_map(
static fn (array $row): string => (string) ($row['_action_key'] ?? ''),
$this->pageData->returnRowsForFilters($supplier, $companyId, $request->all()),
));
$confirmed = $this->returnConfirmations->confirmAll(
$supplier,
$keys,
$companyId,
user_id() ? (int) user_id() : null,
);
return back()->with('success', "已全部确认:{$confirmed} 行退货扣减生效(异议行保持暂不扣减)。");
}
public function exportReturns(Request $request): StreamedResponse
{
[$supplier, $companyId] = $this->returnTarget($request);
$rows = $this->pageData->returnRowsForFilters($supplier, $companyId, $request->query());
return $this->returnCsvExporter->download($rows, $supplier);
}
public function exportComparison(Request $request): StreamedResponse
{
$request->validate([
'month' => ['nullable', 'string', 'regex:/^\d{4}-\d{2}$/'],
'reconciler' => ['nullable', 'string', 'max:191'],
]);
[$supplier, $companyId] = $this->returnTarget($request);
$detail = $this->pageData->financeDetailForFilters($supplier, $companyId, $request->query());
return $this->comparisonCsvExporter->download(
$detail,
$supplier,
trim((string) $request->query('month', '')),
trim((string) $request->query('reconciler', '')),
);
}
public function saveDingTalkRobot(Request $request): RedirectResponse
{
$request->validate([
'supplier' => ['required', 'string', 'max:191'],
'dingtalk_webhook' => ['nullable', 'string', 'max:2048'],
'dingtalk_secret' => ['nullable', 'string', 'max:256'],
'dingtalk_at_all' => ['nullable', 'boolean'],
]);
[$supplier] = $this->returnTarget($request);
$this->dingTalkNotifier->save(
$supplier,
(string) $request->input('dingtalk_webhook', ''),
(string) $request->input('dingtalk_secret', ''),
$request->boolean('dingtalk_at_all'),
);
return back()->with('success', "{$supplier} 的钉钉群机器人已保存。");
}
public function pushDifferences(Request $request): RedirectResponse
{
$request->validate([
'supplier' => ['required', 'string', 'max:191'],
'month' => ['nullable', 'string', 'regex:/^\d{4}-\d{2}$/'],
'reconciler' => ['nullable', 'string', 'max:191'],
'scope' => ['required', 'in:all,row,selected'],
'purchase_no' => ['nullable', 'string', 'max:191'],
'date' => ['nullable', 'string', 'max:32'],
'barcode' => ['nullable', 'string', 'max:191'],
'difference_type' => ['nullable', 'string', 'max:32'],
'selected_rows' => ['nullable', 'array', 'max:600'],
'selected_rows.*' => ['string', 'max:2048'],
]);
[$supplier, $companyId] = $this->returnTarget($request);
$detail = $this->pageData->financeDetailForFilters($supplier, $companyId, $request->all());
$differences = array_values(array_filter(
$detail['rows'],
static fn (array $row): bool => ($row['type'] ?? '') !== SupplierStatementMatcher::TYPE_MATCH,
));
if ($request->input('scope') === 'row') {
$purchaseNo = trim((string) $request->input('purchase_no'));
$date = trim((string) $request->input('date'));
$barcode = trim((string) $request->input('barcode'));
$type = trim((string) $request->input('difference_type'));
$differences = array_values(array_filter(
$differences,
static fn (array $row): bool => (string) ($row['purchaseNo'] ?? '') === $purchaseNo
&& (string) ($row['date'] ?? '') === $date
&& (string) ($row['barcode'] ?? '') === $barcode
&& (string) ($row['type'] ?? '') === $type
));
} elseif ($request->input('scope') === 'selected') {
$selected = [];
foreach ((array) $request->input('selected_rows', []) as $token) {
$row = json_decode((string) $token, true);
if (is_array($row)) {
$selected[$this->differenceRowKey($row)] = true;
}
}
$differences = array_values(array_filter(
$differences,
fn (array $row): bool => isset($selected[$this->differenceRowKey($row)]),
));
}
if ($differences === []) {
return back()->withErrors(['dingtalk_push' => '当前筛选没有可推送的差异。']);
}
try {
$result = $this->dingTalkNotifier->push($supplier, $differences, [
'month' => (string) $request->input('month', ''),
'reconciler' => (string) $request->input('reconciler', ''),
]);
} catch (Throwable $exception) {
return back()->withErrors(['dingtalk_push' => '推送失败:' . $exception->getMessage()]);
}
return back()->with(
'success',
"已推送 {$result['rows']} 条差异到 {$supplier} 钉钉群({$result['messages']} 条消息)。",
);
}
private function markReturn(Request $request, string $status, string $message): RedirectResponse
{
$request->validate(['key' => ['required', 'string', 'max:191']]);
[$supplier, $companyId] = $this->returnTarget($request);
$this->returnConfirmations->mark(
$supplier,
(string) $request->input('key'),
$status,
$companyId,
user_id() ? (int) user_id() : null,
);
return back()->with('success', $message);
}
/** @return array{0:string,1:int} */
private function returnTarget(Request $request): array
{
$request->validate(['supplier' => ['required', 'string', 'max:191']]);
return [trim((string) $request->input('supplier')), (int) (company_id() ?: 1)];
}
/** @param array<string,mixed> $row */
private function differenceRowKey(array $row): string
{
return implode("\0", [
trim((string) ($row['purchaseNo'] ?? $row['purchase_no'] ?? '')),
trim((string) ($row['date'] ?? '')),
trim((string) ($row['barcode'] ?? '')),
trim((string) ($row['type'] ?? '')),
]);
}
}

View File

@ -0,0 +1,180 @@
<?php
namespace App\Http\Controllers\Onboarding;
use App\Models\Business\CourierOnboarding;
use App\Models\Business\CourierOnboardingFile;
use App\Models\Common\Company;
use App\Support\CourierOnboardingService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
/**
* 快递方扫码打开的免登录入驻填报页。链接里的随机 token 就是凭证,只能读写这一份申请。
*/
class CourierOnboardingForms extends Controller
{
public function __construct(private readonly CourierOnboardingService $service)
{
}
public function show(string $token): View|Response
{
$onboarding = $this->resolve($token);
if ($onboarding === null) {
return $this->unavailable();
}
$onboarding->load('files');
return view('onboarding.courier-form', [
'onboarding' => $onboarding,
'token' => $token,
'provinces' => CourierOnboarding::PROVINCES,
'fileKinds' => CourierOnboardingFile::KINDS,
'requiredKinds' => CourierOnboardingFile::REQUIRED_KINDS,
'personKinds' => CourierOnboardingFile::PERSON_KINDS,
'personRequiredKinds' => CourierOnboardingFile::PERSON_REQUIRED_KINDS,
]);
}
public function update(Request $request, string $token): RedirectResponse|Response
{
$onboarding = $this->resolve($token);
if ($onboarding === null) {
return $this->unavailable();
}
$data = $request->validate($this->rules(), $this->messages());
$files = [];
foreach ((array) $request->file('files', []) as $kind => $uploads) {
$files[(string) $kind] = array_values(array_filter(is_array($uploads) ? $uploads : [$uploads]));
}
$submit = ($data['action'] ?? 'save') === 'submit';
$this->service->saveCourierForm($onboarding, $data, $files, $submit);
return redirect()
->route('courier-onboarding.form', ['token' => $token])
->with('onboarding_success', $submit ? '资料已提交,我们会尽快审核,审核结果请留意对接人通知。' : '资料已暂存,可随时扫码回来继续填写。');
}
private function resolve(string $token): ?CourierOnboarding
{
$onboarding = $this->service->ready() ? $this->service->findByToken($token) : null;
if ($onboarding === null || $onboarding->status === CourierOnboarding::STATUS_CANCELLED) {
return null;
}
// 免登录访问没有当前公司上下文;切到申请所属公司,后续按公司隔离的查询才能命中。
Company::find($onboarding->company_id)?->makeCurrent();
return $onboarding;
}
/**
* 免登录页不走系统的 404 跳转(会跳到登录页),直接给快递方一个能看懂的提示。
*/
private function unavailable(): Response
{
return response()->view('onboarding.courier-unavailable', [], 404);
}
/**
* @return array<string,mixed>
*/
private function rules(): array
{
$text = ['nullable', 'string', 'max:255'];
$phone = ['nullable', 'string', 'regex:/^[0-9+\-\s()]{5,20}$/'];
$money = ['nullable', 'numeric', 'min:0', 'max:100000'];
return [
'remark' => ['nullable', 'string', 'max:2000'],
'action' => ['required', Rule::in(['save', 'submit'])],
'entity_type' => ['nullable', Rule::in(array_keys(CourierOnboarding::ENTITY_TYPES))],
'id_number' => ['nullable', 'string', 'regex:/^\s*\d{17}[\dXx]\s*$/'],
'company_full_name' => $text,
'unified_social_credit_code' => ['nullable', 'string', 'regex:/^[0-9A-Za-z]{18}$/'],
'legal_representative' => ['nullable', 'string', 'max:100'],
'business_address' => $text,
'carrier_brand' => ['nullable', 'string', 'max:50'],
'network_name' => ['nullable', 'string', 'max:100'],
'service_type' => ['nullable', Rule::in(CourierOnboarding::SERVICE_TYPES)],
'contact_name' => ['nullable', 'string', 'max:100'],
'contact_phone' => $phone,
'finance_contact_name' => ['nullable', 'string', 'max:100'],
'finance_contact_phone' => $phone,
'pickup_warehouses' => ['nullable', 'string', 'max:1000'],
'esign_operator_name' => ['nullable', 'string', 'max:100'],
'esign_account' => ['nullable', 'string', 'max:255'],
'bank_account_name' => $text,
'bank_name' => $text,
'bank_account_number' => ['nullable', 'string', 'regex:/^[0-9\s\-]{6,40}$/'],
'private_account_name' => $text,
'private_bank_name' => $text,
'private_account_number' => ['nullable', 'string', 'regex:/^[0-9\s\-]{6,40}$/'],
'invoice_type' => ['nullable', Rule::in(CourierOnboarding::INVOICE_TYPES)],
'tax_rate' => ['nullable', 'numeric', 'min:0', 'max:20'],
'settlement_cycle' => ['nullable', Rule::in(CourierOnboarding::SETTLEMENT_CYCLES)],
...self::quoteRules(),
'remove_files' => ['nullable', 'array'],
'remove_files.*' => ['integer'],
'files' => ['nullable', 'array'],
'files.*' => ['array', 'max:' . CourierOnboardingService::MAX_FILES_PER_KIND],
'files.*.*' => ['file', 'max:10240', 'mimes:jpg,jpeg,png,webp,gif,heic,heif,pdf,xls,xlsx'],
];
}
/**
* 报价部分的校验规则,后台变价页共用。
*
* @return array<string,mixed>
*/
public static function quoteRules(): array
{
$money = ['nullable', 'numeric', 'min:0', 'max:100000'];
return [
'quote_mode' => ['nullable', Rule::in(array_keys(CourierOnboarding::QUOTE_MODES))],
'volumetric_rule' => ['nullable', Rule::in(CourierOnboarding::VOLUMETRIC_RULES)],
'volumetric_divisor' => ['nullable', 'integer', 'min:1000', 'max:20000'],
'quote_effective_date' => ['nullable', 'date'],
'quote_note' => ['nullable', 'string', 'max:2000'],
'quote_rows' => ['nullable', 'array', 'max:80'],
'quote_rows.*.region' => ['nullable', 'string', 'max:50'],
'quote_rows.*.flat' => ['nullable', 'array', 'max:' . \App\Support\CourierQuoteStructure::MAX_BANDS],
'quote_rows.*.flat.*' => $money,
'quote_rows.*.base' => $money,
'quote_rows.*.rates' => ['nullable', 'array', 'max:' . (\App\Support\CourierQuoteStructure::MAX_TIERS + 1)],
'quote_rows.*.rates.*' => $money,
'quote_flat_bands' => ['nullable', 'string', 'max:200'],
'quote_first_weight' => ['nullable', 'numeric', 'min:0', 'max:1000'],
'quote_rate_tiers' => ['nullable', 'string', 'max:200'],
'quote_then_mode' => ['nullable', Rule::in(['waybill_rate', 'first_additional'])],
'min_weight' => ['nullable', 'numeric', 'min:0', 'max:1000'],
'weight_rounding' => ['nullable', Rule::in(array_keys(\App\Support\CourierQuoteStructure::ROUNDING))],
'per_ticket_surcharge' => ['nullable', 'numeric', 'min:0', 'max:1000'],
];
}
/**
* @return array<string,string>
*/
private function messages(): array
{
return [
'unified_social_credit_code.regex' => '统一社会信用代码应为 18 位数字或字母。',
'contact_phone.regex' => '请填写正确的联系电话。',
'id_number.regex' => '身份证号应为 18 位。',
'finance_contact_phone.regex' => '请填写正确的联系电话。',
'bank_account_number.regex' => '银行账号只能包含数字。',
'private_account_number.regex' => '银行卡号只能包含数字。',
'volumetric_divisor.min' => '抛比系数一般为 5000、6000、8000 等。',
'files.*.*.max' => '单个文件不能超过 10MB。',
'files.*.*.mimes' => '请上传照片、PDF 或 Excel 文件。',
];
}
}

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Portal;
use App\Models\Common\Contact;
use App\Models\Document\Document;
use App\Traits\Charts;
use App\Traits\DateTime;
@ -20,6 +21,10 @@ class Dashboard
{
$contact = user()->contact;
if ($contact instanceof Contact && $contact->type === Contact::VENDOR_TYPE) {
return redirect()->route('portal.supplier-reconciliation.index', ['company_id' => company_id()]);
}
// Redirect user redirect landing page..
if (!$contact) {
return redirect(user()->getLandingPageOfUser());

View File

@ -0,0 +1,154 @@
<?php
namespace App\Http\Controllers\Portal;
use App\Models\Common\Contact;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\View\View;
use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter;
use Modules\EcommerceFinance\Services\SupplierReturnConfirmation;
use Modules\EcommerceFinance\Services\SupplierStatementStore;
use Modules\EcommerceFinance\Services\SupplierStatementTemplate;
use Modules\EcommerceFinance\View\SupplierReconciliationPageData;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* 厂家门户:账号绑定供应商后,仅可查看和操作自己的对账数据。
*/
class SupplierReconciliation extends Controller
{
public function __construct(
private readonly SupplierStatementTemplate $template,
private readonly SupplierStatementStore $statements,
private readonly SupplierReturnConfirmation $returnConfirmations,
private readonly SupplierReconciliationPageData $pageData,
private readonly SupplierReturnCsvExporter $returnCsvExporter,
) {
}
public function index(): View
{
[$contact, $supplier, $companyId] = $this->supplierContext();
$data = $this->pageData->portalData($supplier, $companyId);
return view('portal.supplier-reconciliation.index', array_merge($data, [
'contact' => $contact,
'supplier' => $supplier,
'statementTemplateUrl' => route('portal.supplier-reconciliation.template'),
'uploadUrl' => route('portal.supplier-reconciliation.statement.upload'),
'returnConfirmUrl' => route('portal.supplier-reconciliation.return.confirm'),
'returnDisputeUrl' => route('portal.supplier-reconciliation.return.dispute'),
'returnConfirmAllUrl' => route('portal.supplier-reconciliation.return.confirm-all'),
]));
}
public function template(): BinaryFileResponse
{
$this->supplierContext();
$path = $this->template->path();
abort_unless(is_file($path), 404, '对账单模板不存在。');
return response()->download($path, $this->template->filename());
}
public function upload(Request $request): JsonResponse|RedirectResponse
{
$request->validate([
'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:51200'],
]);
[, $supplier, $companyId] = $this->supplierContext();
$records = $this->template->parse($request->file('import'), $supplier);
$rows = $this->statements->save(
$supplier,
$records,
(string) $request->file('import')->getClientOriginalName(),
$companyId,
user_id() ? (int) user_id() : null,
);
$message = "对账单已保存:{$supplier} 共 {$rows} 行。";
return $request->expectsJson()
? response()->json(['message' => $message, 'rows' => $rows])
: redirect()
->route('portal.supplier-reconciliation.index', ['company_id' => $companyId])
->with('success', $message);
}
public function confirmReturn(Request $request): RedirectResponse
{
return $this->markReturn($request, SupplierReturnConfirmation::STATUS_CONFIRMED, '已确认该行退货扣减。');
}
public function disputeReturn(Request $request): RedirectResponse
{
return $this->markReturn($request, SupplierReturnConfirmation::STATUS_DISPUTED, '已提交异议,复核通过前该行暂不扣减。');
}
public function confirmAllReturns(Request $request): RedirectResponse
{
[, $supplier, $companyId] = $this->supplierContext();
$keys = array_values(array_map(
static fn (array $row): string => (string) ($row['_action_key'] ?? ''),
$this->pageData->returnRowsForFilters($supplier, $companyId, $request->all()),
));
$confirmed = $this->returnConfirmations->confirmAll(
$supplier,
$keys,
$companyId,
user_id() ? (int) user_id() : null,
);
return back()->with('success', "已全部确认:{$confirmed} 行退货扣减生效(异议行保持暂不扣减)。");
}
public function exportReturns(Request $request): StreamedResponse
{
[, $supplier, $companyId] = $this->supplierContext();
$rows = $this->pageData->returnRowsForFilters($supplier, $companyId, $request->query());
return $this->returnCsvExporter->download($rows, $supplier);
}
private function markReturn(Request $request, string $status, string $message): RedirectResponse
{
$request->validate(['key' => ['required', 'string', 'max:191']]);
[, $supplier, $companyId] = $this->supplierContext();
$key = (string) $request->input('key');
$owned = collect($this->pageData->returnRows($supplier, $companyId))
->contains(static fn (array $row): bool => (string) ($row['_action_key'] ?? '') === $key);
abort_unless($owned, 403, '该退货明细不属于当前厂家账号。');
$this->returnConfirmations->mark(
$supplier,
$key,
$status,
$companyId,
user_id() ? (int) user_id() : null,
);
return back()->with('success', $message);
}
/** @return array{0:Contact,1:string,2:int} */
private function supplierContext(): array
{
$contact = user()->contact;
abort_unless(
$contact instanceof Contact
&& $contact->type === Contact::VENDOR_TYPE
&& $contact->enabled,
403,
'当前账号未绑定有效的厂家资料,请联系财务人员。',
);
$supplier = trim((string) $contact->name);
abort_if($supplier === '', 403, '当前厂家账号未设置供应商名称,请联系财务人员。');
return [$contact, $supplier, (int) (company_id() ?: 1)];
}
}

View File

@ -49,7 +49,7 @@ class Navigation extends Controller
$titles['sections'][$sectionSlug] = $sectionTitle;
}
foreach ($section['pages'] ?? [] as $page) {
foreach (collect($section['pages'] ?? [])->flatMap(fn (array $page) => [$page, ...($page['children'] ?? [])]) as $page) {
$pageTitle = trim((string) ($pageTitles[$sectionSlug][$page['slug']] ?? ''));
if ($pageTitle !== '') {

View File

@ -5,6 +5,7 @@ namespace App\Http\Controllers\SystemSettings;
use App\Models\Auth\Role;
use App\Models\Auth\User;
use App\Models\Auth\UserAccessGroup;
use App\Utilities\AgreementSigningPermissions;
use App\Utilities\SystemAccess;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
@ -66,6 +67,9 @@ class Users extends Controller
$created->roles()->attach($role->id);
$created->companies()->attach(company_id());
if (array_key_exists('agreement_signing_allowed', $data)) {
AgreementSigningPermissions::setGranted($created, (bool) $data['agreement_signing_allowed']);
}
});
flash('用户已新增。')->success();
@ -122,6 +126,9 @@ class Users extends Controller
$managedUser->update($attributes);
$managedUser->syncRoles([$role->id]);
if (array_key_exists('agreement_signing_allowed', $data)) {
AgreementSigningPermissions::setGranted($managedUser, (bool) $data['agreement_signing_allowed']);
}
});
$managedUser->flushCache();
@ -182,6 +189,7 @@ class Users extends Controller
'role' => ['required', Rule::in($assignable)],
'password' => [$managedUser ? 'nullable' : 'required', 'string', 'min:8', 'confirmed'],
'enabled' => ['nullable', 'boolean'],
'agreement_signing_allowed' => ['sometimes', 'boolean'],
]);
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Http\Controllers\SystemSettings;
use App\Support\CourierOnboardingReviewers;
use App\Utilities\SystemAccess;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class WorkflowReviewers extends Controller
{
public function __construct(private readonly CourierOnboardingReviewers $reviewers)
{
$this->middleware(function ($request, $next) {
abort_unless(SystemAccess::canOpenSettings(), 403);
return $next($request);
});
}
public function index()
{
return view('system_settings.workflow-reviewers.index', [
'reviewers' => $this->reviewers->settings(), 'history' => $this->reviewers->history(),
]);
}
public function search(Request $request)
{
$data = $request->validate(['q' => ['required', 'string', 'min:1', 'max:50']]);
try {
return response()->json(['people' => $this->reviewers->search(trim($data['q']))])->header('Cache-Control', 'no-store');
} catch (\Throwable $e) {
return response()->json(['message' => '钉钉花名册暂时无法查询,请稍后重试。'], 503)->header('Cache-Control', 'no-store');
}
}
public function update(Request $request)
{
$data = $request->validate([
'first' => ['required', 'array', 'min:1', 'max:10'],
'first.*' => ['required', 'string', 'max:100', 'distinct'],
'final' => ['required', 'array', 'min:1', 'max:10'],
'final.*' => ['required', 'string', 'max:100', 'distinct'],
], ['first.required' => '请至少选择一名初审人员。', 'final.required' => '请至少选择一名复审人员。']);
$this->reviewers->save($data, user());
return redirect()->route('system-settings.workflow-reviewers.index')->with('success', '审核人员已保存,立即对待审核申请生效。');
}
}

View File

@ -36,6 +36,7 @@ class Kernel extends HttpKernel
'cookies.response',
'session.start',
\App\Http\Middleware\LogoutIfDingTalkBindingRevoked::class,
\App\Http\Middleware\EnsureLimitedDingTalkPageAccess::class,
// 'session.auth',
'session.errors',
'csrf',

View File

@ -3,21 +3,12 @@
namespace App\Http\Livewire\Business;
use App\Business\ThirdPartyWarehouseQuoteRepository;
use App\Business\ThirdPartyWarehouseStorageFeeCalculator;
use App\Exports\ThirdPartyWarehouseStorageDetailExport;
use App\Exports\ThirdPartyWarehouseStorageSettlementExport;
use App\Models\Business\ThirdPartyWarehouseQuote;
use App\Models\Business\ThirdPartyWarehouseStorageSettlement;
use Illuminate\Contracts\View\View;
use Livewire\Component;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ThirdPartyWarehouseQuotes extends Component
{
/** 固定核算「三方-南昌樵舍仓」,与镜像仓库一致。 */
public const WAREHOUSE_ID = 15045364;
public string $warehouseName = '南昌樵舍仓';
public string $effectiveAt = '';
@ -36,29 +27,9 @@ class ThirdPartyWarehouseQuotes extends Component
public ?string $message = null;
/** 仓储费核算 */
public string $settlementPeriod = '';
/** @var array<string,mixed>|null */
public ?array $settlementSummary = null;
public ?string $settlementMessage = null;
public ?string $settlementError = null;
public ?string $settlementDetailPeriod = null;
public string $settlementDetailDate = '';
/** @var list<string> */
public array $settlementDetailDates = [];
public ?string $settlementDetailMessage = null;
public function mount(): void
{
$this->effectiveAt = now()->toDateString();
$this->settlementPeriod = now()->startOfMonth()->subMonth()->format('Y-m');
}
public function save(): void
@ -94,276 +65,17 @@ class ThirdPartyWarehouseQuotes extends Component
$this->message = '仓储报价状态已更新。';
}
public function calculateStorageFee(): void
{
$this->ensureAuthenticated();
$this->settlementMessage = null;
$this->settlementError = null;
$this->validate([
'settlementPeriod' => ['required', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
], [
'settlementPeriod.regex' => '结算月份格式应为 YYYY-MM。',
]);
try {
$result = app(ThirdPartyWarehouseStorageFeeCalculator::class)
->calculate(self::WAREHOUSE_ID, $this->warehouseName, $this->settlementPeriod);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
$this->settlementError = $e->getMessage();
return;
}
$summary = $result['summary'];
ThirdPartyWarehouseStorageSettlement::query()->updateOrCreate(
[
'company_id' => (int) company_id(),
'warehouse_id' => self::WAREHOUSE_ID,
'period' => $this->settlementPeriod,
],
[
'warehouse_name' => $this->warehouseName,
'quote_id' => $summary['quote_id'] ?? null,
'inbound_rate_per_ton' => $summary['inbound_rate_per_ton'],
'outbound_rate_per_order' => $summary['outbound_rate_per_order'],
'pieces_per_pallet' => $summary['pieces_per_pallet'],
'pallet_area_sqm' => $summary['pallet_area_sqm'],
'storage_rate_per_sqm_month' => $summary['storage_rate_per_sqm_month'],
'days_in_month' => $summary['days_in_month'],
'inbound_tons' => $summary['inbound_tons'],
'outbound_qty' => $summary['outbound_qty'],
'inbound_fee' => $summary['inbound_fee'],
'outbound_fee' => $summary['outbound_fee'],
'storage_fee' => $summary['storage_fee'],
'memo_fee' => $summary['memo_fee'],
'loss_fee' => $summary['loss_fee'],
'compensation_fee' => $summary['compensation_fee'],
'total_fee' => $summary['total_fee'],
'detail_json' => [
'daily' => $result['daily'],
'per_sku' => $result['per_sku'],
'daily_sku' => $result['daily_sku'],
],
'calculated_by' => (int) user_id(),
],
);
$this->settlementSummary = $summary;
$this->settlementMessage = $this->settlementPeriod . ' 仓储费核算完成,已存档。';
}
public function exportSettlement(string $period): ?BinaryFileResponse
{
$this->ensureAuthenticated();
$settlement = ThirdPartyWarehouseStorageSettlement::query()
->where('company_id', (int) company_id())
->where('warehouse_id', self::WAREHOUSE_ID)
->where('period', $period)
->first();
if ($settlement === null) {
$this->settlementError = '未找到 ' . $period . ' 的核算存档,请先核算。';
return null;
}
$detail = $settlement->detail_json ?: ['daily' => [], 'per_sku' => [], 'daily_sku' => []];
$result = [
'summary' => $this->summaryFromSettlement($settlement),
'daily' => $detail['daily'] ?? [],
'per_sku' => $detail['per_sku'] ?? [],
'daily_sku' => $detail['daily_sku'] ?? [],
];
$fileName = $settlement->warehouse_name . '仓储费用_' . $period . '.xlsx';
return Excel::download(new ThirdPartyWarehouseStorageSettlementExport($result), $fileName);
}
public function exportSettlementDetails(string $period): ?BinaryFileResponse
{
$this->ensureAuthenticated();
abort_unless(preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1, 422);
$settlement = $this->settlementForPeriod($period);
if ($settlement === null) {
$this->settlementError = '未找到 ' . $period . ' 的核算存档,请先核算。';
return null;
}
$dailySku = ($settlement->detail_json ?: [])['daily_sku'] ?? [];
if ($dailySku === []) {
$this->showMissingSettlementDetails($period);
return null;
}
$fileName = $settlement->warehouse_name . '每日商品仓储费明细_' . $period . '.xlsx';
return Excel::download(new ThirdPartyWarehouseStorageDetailExport($dailySku), $fileName);
}
public function viewSettlementDetails(string $period): void
{
$this->ensureAuthenticated();
abort_unless(preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1, 422);
$this->settlementDetailPeriod = $period;
$this->settlementDetailDate = '';
$this->settlementDetailDates = [];
$this->settlementDetailMessage = null;
$settlement = $this->settlementForPeriod($period);
if ($settlement === null) {
$this->settlementDetailMessage = '未找到 ' . $period . ' 的核算存档。';
$this->dispatch('warehouse-settlement-details-opened');
return;
}
$detail = $settlement->detail_json ?: [];
$dailySku = $detail['daily_sku'] ?? [];
if ($dailySku === []) {
$this->showMissingSettlementDetails($period);
return;
}
$dates = array_values(array_unique(array_column($dailySku, 'date')));
sort($dates);
$this->settlementDetailDates = $dates;
$this->settlementDetailDate = $dates[0] ?? '';
$this->dispatch('warehouse-settlement-details-opened');
}
public function closeSettlementDetails(): void
{
$this->settlementDetailPeriod = null;
$this->settlementDetailDate = '';
$this->settlementDetailDates = [];
$this->settlementDetailMessage = null;
}
public function render(): View
{
$data = $this->repository()->pageData();
$history = ThirdPartyWarehouseStorageSettlement::query()
->where('company_id', (int) company_id())
->where('warehouse_id', self::WAREHOUSE_ID)
->orderByDesc('period')
->limit(24)
->get()
->map(fn (ThirdPartyWarehouseStorageSettlement $row): array => [
'period' => $row->period,
'total_fee' => (float) $row->total_fee,
'inbound_fee' => (float) $row->inbound_fee,
'outbound_fee' => (float) $row->outbound_fee,
'storage_fee' => (float) $row->storage_fee,
'calculated_at' => optional($row->updated_at)->format('Y-m-d H:i'),
])
->all();
$settlementDetail = $this->settlementDetailData();
return view('business.pages.courier-payables.partials.third-party-warehouse-quotes', [
'warehouseQuotes' => $data['rows'],
'warehouseQuoteSummary' => $data['summary'],
'warehouseQuotesReady' => $data['ready'],
'settlementHistory' => $history,
'settlementDetailRows' => $settlementDetail['rows'],
'settlementDetailSummary' => $settlementDetail['summary'],
]);
}
/** @return array<string,mixed> */
private function summaryFromSettlement(ThirdPartyWarehouseStorageSettlement $s): array
{
return [
'period' => $s->period,
'warehouse_id' => (int) $s->warehouse_id,
'warehouse_name' => $s->warehouse_name,
'quote_id' => $s->quote_id,
'days_in_month' => (int) $s->days_in_month,
'inbound_rate_per_ton' => (float) $s->inbound_rate_per_ton,
'outbound_rate_per_order' => (float) $s->outbound_rate_per_order,
'pieces_per_pallet' => (float) $s->pieces_per_pallet,
'pallet_area_sqm' => (float) $s->pallet_area_sqm,
'storage_rate_per_sqm_month' => (float) $s->storage_rate_per_sqm_month,
'inbound_tons' => (float) $s->inbound_tons,
'inbound_fee' => (float) $s->inbound_fee,
'outbound_qty' => (float) $s->outbound_qty,
'outbound_fee' => (float) $s->outbound_fee,
'storage_fee' => (float) $s->storage_fee,
'memo_fee' => (float) $s->memo_fee,
'loss_fee' => (float) $s->loss_fee,
'compensation_fee' => (float) $s->compensation_fee,
'total_fee' => (float) $s->total_fee,
];
}
/**
* 明细行只参与当前服务端渲染,不进入 Livewire 公共快照,避免日期切换时回传整张表。
*
* @return array{rows:list<array<string,mixed>>,summary:array<string,float|int>|null}
*/
private function settlementDetailData(): array
{
$empty = ['rows' => [], 'summary' => null];
if ($this->settlementDetailPeriod === null
|| ! in_array($this->settlementDetailDate, $this->settlementDetailDates, true)) {
return $empty;
}
$settlement = $this->settlementForPeriod($this->settlementDetailPeriod);
if ($settlement === null) {
return $empty;
}
$detail = $settlement->detail_json ?: [];
$rows = array_values(array_filter(
$detail['daily_sku'] ?? [],
fn (array $row): bool => ($row['date'] ?? null) === $this->settlementDetailDate,
));
usort($rows, static fn (array $left, array $right): int => strcmp(
(string) ($left['sku_code'] ?? ''),
(string) ($right['sku_code'] ?? ''),
));
return [
'rows' => $rows,
'summary' => [
'sku_count' => count($rows),
'opening' => array_sum(array_column($rows, 'opening')),
'net_movement' => array_sum(array_column($rows, 'net_movement')),
'closing' => array_sum(array_column($rows, 'closing')),
'storage_fee' => array_sum(array_column($rows, 'storage_fee')),
],
];
}
private function settlementForPeriod(string $period): ?ThirdPartyWarehouseStorageSettlement
{
return ThirdPartyWarehouseStorageSettlement::query()
->where('company_id', (int) company_id())
->where('warehouse_id', self::WAREHOUSE_ID)
->where('period', $period)
->first();
}
private function showMissingSettlementDetails(string $period): void
{
$this->settlementPeriod = $period;
$this->settlementDetailPeriod = $period;
$this->settlementDetailDate = '';
$this->settlementDetailDates = [];
$this->settlementDetailMessage = $period . ' 的原存档没有每日商品明细,请重新核算该月份后查看和导出。';
$this->dispatch('warehouse-settlement-details-opened');
}
/** @return array<string,array<int,string>> */
protected function rules(): array
{

View File

@ -0,0 +1,323 @@
<?php
namespace App\Http\Livewire\Business;
use App\Business\ThirdPartyWarehouseStorageFeeCalculator;
use App\Exports\ThirdPartyWarehouseStorageDetailExport;
use App\Exports\ThirdPartyWarehouseStorageSettlementExport;
use App\Models\Business\ThirdPartyWarehouseStorageSettlement;
use App\Utilities\SidebarPermissions;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class WarehouseFreight extends Component
{
/** 固定核算「三方-南昌樵舍仓」,与镜像仓库一致。 */
public const WAREHOUSE_ID = 15045364;
#[Locked]
public string $warehouseName = '南昌樵舍仓';
/** 仓储费核算 */
public string $settlementPeriod = '';
/** @var array<string,mixed>|null */
public ?array $settlementSummary = null;
public ?string $settlementMessage = null;
public ?string $settlementError = null;
public ?string $settlementDetailPeriod = null;
public string $settlementDetailDate = '';
/** @var list<string> */
public array $settlementDetailDates = [];
public ?string $settlementDetailMessage = null;
public function mount(): void
{
$this->ensureAuthenticated();
$this->settlementPeriod = now()->startOfMonth()->subMonth()->format('Y-m');
}
public function calculateStorageFee(): void
{
$this->ensureAuthenticated();
$this->settlementMessage = null;
$this->settlementError = null;
$this->validate([
'settlementPeriod' => ['required', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
], [
'settlementPeriod.regex' => '结算月份格式应为 YYYY-MM。',
]);
try {
$result = app(ThirdPartyWarehouseStorageFeeCalculator::class)
->calculate(self::WAREHOUSE_ID, $this->warehouseName, $this->settlementPeriod);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
$this->settlementError = $e->getMessage();
return;
}
$summary = $result['summary'];
ThirdPartyWarehouseStorageSettlement::query()->updateOrCreate(
[
'company_id' => (int) company_id(),
'warehouse_id' => self::WAREHOUSE_ID,
'period' => $this->settlementPeriod,
],
[
'warehouse_name' => $this->warehouseName,
'quote_id' => $summary['quote_id'] ?? null,
'inbound_rate_per_ton' => $summary['inbound_rate_per_ton'],
'outbound_rate_per_order' => $summary['outbound_rate_per_order'],
'pieces_per_pallet' => $summary['pieces_per_pallet'],
'pallet_area_sqm' => $summary['pallet_area_sqm'],
'storage_rate_per_sqm_month' => $summary['storage_rate_per_sqm_month'],
'days_in_month' => $summary['days_in_month'],
'inbound_tons' => $summary['inbound_tons'],
'outbound_qty' => $summary['outbound_qty'],
'inbound_fee' => $summary['inbound_fee'],
'outbound_fee' => $summary['outbound_fee'],
'storage_fee' => $summary['storage_fee'],
'memo_fee' => $summary['memo_fee'],
'loss_fee' => $summary['loss_fee'],
'compensation_fee' => $summary['compensation_fee'],
'total_fee' => $summary['total_fee'],
'detail_json' => [
'daily' => $result['daily'],
'per_sku' => $result['per_sku'],
'daily_sku' => $result['daily_sku'],
],
'calculated_by' => (int) user_id(),
],
);
$this->settlementSummary = $summary;
$this->settlementMessage = $this->settlementPeriod . ' 仓储费核算完成,已存档。';
}
public function exportSettlement(string $period): ?BinaryFileResponse
{
$this->ensureAuthenticated();
$settlement = ThirdPartyWarehouseStorageSettlement::query()
->where('company_id', (int) company_id())
->where('warehouse_id', self::WAREHOUSE_ID)
->where('period', $period)
->first();
if ($settlement === null) {
$this->settlementError = '未找到 ' . $period . ' 的核算存档,请先核算。';
return null;
}
$detail = $settlement->detail_json ?: ['daily' => [], 'per_sku' => [], 'daily_sku' => []];
$result = [
'summary' => $this->summaryFromSettlement($settlement),
'daily' => $detail['daily'] ?? [],
'per_sku' => $detail['per_sku'] ?? [],
'daily_sku' => $detail['daily_sku'] ?? [],
];
$fileName = $settlement->warehouse_name . '仓储费用_' . $period . '.xlsx';
return Excel::download(new ThirdPartyWarehouseStorageSettlementExport($result), $fileName);
}
public function exportSettlementDetails(string $period): ?BinaryFileResponse
{
$this->ensureAuthenticated();
abort_unless(preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1, 422);
$settlement = $this->settlementForPeriod($period);
if ($settlement === null) {
$this->settlementError = '未找到 ' . $period . ' 的核算存档,请先核算。';
return null;
}
$dailySku = ($settlement->detail_json ?: [])['daily_sku'] ?? [];
if ($dailySku === []) {
$this->showMissingSettlementDetails($period);
return null;
}
$fileName = $settlement->warehouse_name . '每日商品仓储费明细_' . $period . '.xlsx';
return Excel::download(new ThirdPartyWarehouseStorageDetailExport($dailySku), $fileName);
}
public function viewSettlementDetails(string $period): void
{
$this->ensureAuthenticated();
abort_unless(preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1, 422);
$this->settlementDetailPeriod = $period;
$this->settlementDetailDate = '';
$this->settlementDetailDates = [];
$this->settlementDetailMessage = null;
$settlement = $this->settlementForPeriod($period);
if ($settlement === null) {
$this->settlementDetailMessage = '未找到 ' . $period . ' 的核算存档。';
$this->dispatch('warehouse-settlement-details-opened');
return;
}
$detail = $settlement->detail_json ?: [];
$dailySku = $detail['daily_sku'] ?? [];
if ($dailySku === []) {
$this->showMissingSettlementDetails($period);
return;
}
$dates = array_values(array_unique(array_column($dailySku, 'date')));
sort($dates);
$this->settlementDetailDates = $dates;
$this->settlementDetailDate = $dates[0] ?? '';
$this->dispatch('warehouse-settlement-details-opened');
}
public function closeSettlementDetails(): void
{
$this->settlementDetailPeriod = null;
$this->settlementDetailDate = '';
$this->settlementDetailDates = [];
$this->settlementDetailMessage = null;
}
public function render(): View
{
$this->ensureAuthenticated();
$history = ThirdPartyWarehouseStorageSettlement::query()
->where('company_id', (int) company_id())
->where('warehouse_id', self::WAREHOUSE_ID)
->orderByDesc('period')
->limit(24)
->get()
->map(fn (ThirdPartyWarehouseStorageSettlement $row): array => [
'period' => $row->period,
'total_fee' => (float) $row->total_fee,
'inbound_fee' => (float) $row->inbound_fee,
'outbound_fee' => (float) $row->outbound_fee,
'storage_fee' => (float) $row->storage_fee,
'calculated_at' => optional($row->updated_at)->format('Y-m-d H:i'),
])
->all();
$settlementDetail = $this->settlementDetailData();
return view('business.pages.courier-payables.partials.warehouse-freight', [
'settlementHistory' => $history,
'settlementDetailRows' => $settlementDetail['rows'],
'settlementDetailSummary' => $settlementDetail['summary'],
]);
}
/** @return array<string,mixed> */
private function summaryFromSettlement(ThirdPartyWarehouseStorageSettlement $s): array
{
return [
'period' => $s->period,
'warehouse_id' => (int) $s->warehouse_id,
'warehouse_name' => $s->warehouse_name,
'quote_id' => $s->quote_id,
'days_in_month' => (int) $s->days_in_month,
'inbound_rate_per_ton' => (float) $s->inbound_rate_per_ton,
'outbound_rate_per_order' => (float) $s->outbound_rate_per_order,
'pieces_per_pallet' => (float) $s->pieces_per_pallet,
'pallet_area_sqm' => (float) $s->pallet_area_sqm,
'storage_rate_per_sqm_month' => (float) $s->storage_rate_per_sqm_month,
'inbound_tons' => (float) $s->inbound_tons,
'inbound_fee' => (float) $s->inbound_fee,
'outbound_qty' => (float) $s->outbound_qty,
'outbound_fee' => (float) $s->outbound_fee,
'storage_fee' => (float) $s->storage_fee,
'memo_fee' => (float) $s->memo_fee,
'loss_fee' => (float) $s->loss_fee,
'compensation_fee' => (float) $s->compensation_fee,
'total_fee' => (float) $s->total_fee,
];
}
/**
* 明细行只参与当前服务端渲染,不进入 Livewire 公共快照,避免日期切换时回传整张表。
*
* @return array{rows:list<array<string,mixed>>,summary:array<string,float|int>|null}
*/
private function settlementDetailData(): array
{
$empty = ['rows' => [], 'summary' => null];
if ($this->settlementDetailPeriod === null
|| ! in_array($this->settlementDetailDate, $this->settlementDetailDates, true)) {
return $empty;
}
$settlement = $this->settlementForPeriod($this->settlementDetailPeriod);
if ($settlement === null) {
return $empty;
}
$detail = $settlement->detail_json ?: [];
$rows = array_values(array_filter(
$detail['daily_sku'] ?? [],
fn (array $row): bool => ($row['date'] ?? null) === $this->settlementDetailDate,
));
usort($rows, static fn (array $left, array $right): int => strcmp(
(string) ($left['sku_code'] ?? ''),
(string) ($right['sku_code'] ?? ''),
));
return [
'rows' => $rows,
'summary' => [
'sku_count' => count($rows),
'opening' => array_sum(array_column($rows, 'opening')),
'net_movement' => array_sum(array_column($rows, 'net_movement')),
'closing' => array_sum(array_column($rows, 'closing')),
'storage_fee' => array_sum(array_column($rows, 'storage_fee')),
],
];
}
private function settlementForPeriod(string $period): ?ThirdPartyWarehouseStorageSettlement
{
return ThirdPartyWarehouseStorageSettlement::query()
->where('company_id', (int) company_id())
->where('warehouse_id', self::WAREHOUSE_ID)
->where('period', $period)
->first();
}
private function showMissingSettlementDetails(string $period): void
{
$this->settlementPeriod = $period;
$this->settlementDetailPeriod = $period;
$this->settlementDetailDate = '';
$this->settlementDetailDates = [];
$this->settlementDetailMessage = $period . ' 的原存档没有每日商品明细,请重新核算该月份后查看和导出。';
$this->dispatch('warehouse-settlement-details-opened');
}
private function ensureAuthenticated(): void
{
abort_unless(auth()->check(), 401);
$section = collect(SidebarPermissions::navigationFor(user()))->firstWhere('slug', 'courier-payables');
abort_unless(collect($section['pages'] ?? [])->contains('slug', 'warehouse-freight'), 403, '当前账号没有该页面权限。');
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace App\Http\Middleware;
use App\Utilities\SidebarPermissions;
use Closure;
use Illuminate\Http\Request;
class EnsureLimitedDingTalkPageAccess
{
public function handle(Request $request, Closure $next): mixed
{
$user = $request->user();
$route = $request->route();
if (! $user || ! $route?->hasParameter('company_id') || ! SidebarPermissions::hasLimitedDingTalkAccess($user)) {
return $next($request);
}
// Keep the application entrance, sign-out and existing self-profile checks.
if ($route->named('dashboard', 'logout', 'profile.edit', 'profile.update')) {
return $next($request);
}
$allowed = SidebarPermissions::allowedKeys($user);
$key = $route->parameter('section').'/'.$route->parameter('page');
if (in_array($key, $allowed, true)) {
return $next($request);
}
// The section and quote group are navigation containers for the three pages.
if ($route->named('business.pages.show') && $route->parameter('section') === 'courier-payables'
&& in_array($route->parameter('page'), [null, 'courier-quote'], true)) {
return $next($request);
}
// Dedicated detail, file and action routes declare their owning business page.
foreach ($route->gatherMiddleware() as $middleware) {
if (is_string($middleware) && str_starts_with($middleware, 'business.page:')
&& in_array(str_replace(',', '/', substr($middleware, strlen('business.page:'))), $allowed, true)) {
return $next($request);
}
}
// Also deny legacy exports/previews that do not declare a page permission.
abort(403, '当前账号没有该页面权限。');
}
}

View File

@ -15,7 +15,7 @@ class LogoutIfDingTalkBindingRevoked
$identityId = $request->session()->get('dingtalk_identity_id');
$user = $request->user();
if (! $identityId) {
if (! $user || $user->created_from !== 'dingtalk_roster') {
if (! $user || ! in_array($user->created_from, ['dingtalk_roster', 'dingtalk_roster_limited'], true)) {
return $next($request);
}
// A password reset must not bypass HR eligibility for provisioned

View File

@ -62,7 +62,7 @@ class ShowInAdmin
public static function groupPayables(array $navigation): array
{
$keys = ['supplier-payables-final', 'courier-payables-final', 'supplier-payables', 'courier-payables', 'raw-board-payables',
$keys = ['supplier-payables-final', 'supplier-reconciliation', 'courier-payables-final', 'supplier-payables', 'courier-payables', 'raw-board-payables',
'lamination-factory-payables', 'paper-materials', 'edge-banding-materials'];
$children = array_values(array_filter($navigation, static fn (array $section): bool => in_array($section['slug'], $keys, true)));
if ($children === []) {
@ -119,6 +119,10 @@ class ShowInAdmin
$order = ($sectionIndex + 1) * 10;
if (empty($pages) || in_array($section['slug'], self::WORKSPACE_SECTION_SLUGS, true)) {
$quoteDirectory = $section['slug'] === 'courier-payables'
? collect($pages)->firstWhere('slug', 'courier-quote')
: null;
$quoteSlugs = array_merge(['courier-quote'], array_column($quoteDirectory['children'] ?? [], 'slug'));
$menu->route(
'business.pages.show',
$section['title'],
@ -126,10 +130,26 @@ class ShowInAdmin
$order,
[
'icon' => $section['icon'],
'active' => fn () => request()->route('section') === $section['slug'],
'active' => fn () => request()->route('section') === $section['slug']
&& (! $quoteDirectory || ! in_array(request()->route('page'), $quoteSlugs, true)),
]
);
if (! empty($quoteDirectory['children'])) {
$menu->route(
'business.pages.show',
$quoteDirectory['title'],
['section' => $section['slug'], 'page' => $quoteDirectory['slug']],
$order + 1,
[
'icon' => '',
'class' => 'ltr:ml-8 rtl:mr-8',
'active' => fn () => request()->route('section') === $section['slug']
&& in_array(request()->route('page'), $quoteSlugs, true),
]
);
}
continue;
}

View File

@ -3,6 +3,7 @@
namespace App\Listeners\Menu;
use App\Events\Menu\PortalCreated as Event;
use App\Models\Common\Contact;
class ShowInPortal
{
@ -16,6 +17,19 @@ class ShowInPortal
{
$user = user();
$menu = $event->menu;
$contact = $user->contact;
if ($contact instanceof Contact && $contact->type === Contact::VENDOR_TYPE) {
$menu->route(
'portal.supplier-reconciliation.index',
'供应商对账',
[],
10,
['icon' => 'fact_check'],
);
return;
}
$inactive = false;

View File

@ -4,6 +4,7 @@ namespace App\Models\Business;
use App\Abstracts\Model;
use App\Support\EsignErrorMessage;
use Illuminate\Contracts\Encryption\DecryptException;
class CourierAgreementSignature extends Model
{
@ -86,6 +87,45 @@ class CourierAgreementSignature extends Model
'operator_account' => 'encrypted',
];
public function partnerTypeLabel(): string
{
// Records created before partner types were introduced are courier tasks.
try {
$partnerType = $this->payload['partner_type'] ?? 'courier';
} catch (DecryptException) {
// Keep legacy rows with unreadable encrypted payloads renderable.
$partnerType = 'courier';
}
return $partnerType === 'supplier' ? '供应商' : '快递公司';
}
/** Only completed archives with a readable courier snapshot belong to contract management. */
public function archivedCourierContractPayload(): ?array
{
if ($this->status !== self::STATUS_ARCHIVED || $this->document_type !== 'cooperation-contract') {
return null;
}
try {
$payload = $this->payload;
} catch (\Throwable) {
return null;
}
// Before partner_type was introduced all signing tasks were courier tasks.
return is_array($payload) && ($payload['partner_type'] ?? 'courier') === 'courier' ? $payload : null;
}
public function credentialDocuments(): array
{
try {
return $this->payload['credential_documents'] ?? [];
} catch (\Throwable) {
return [];
}
}
public function statusLabel(): string
{
return match ($this->status) {
@ -121,6 +161,11 @@ class CourierAgreementSignature extends Model
public function documentLabel(): string
{
foreach (\App\Support\SupplierCooperationTemplates::TEMPLATES as $template) {
if ($this->template_code === $template['code']) {
return $template['name'];
}
}
return self::DOCUMENTS[$this->document_type]['name'] ?? $this->document_type;
}
@ -158,4 +203,13 @@ class CourierAgreementSignature extends Model
return in_array($mode, ['auto', 'manual'], true) ? $mode : 'auto';
}
public function archiveReason(): string
{
try {
return trim((string) data_get($this->payload, 'archive_reason', ''));
} catch (\Throwable) {
return '';
}
}
}

View File

@ -16,6 +16,9 @@ class CourierFreightRow extends Model
'source',
'part',
'transaction_no',
'express_no',
'barcode',
'shop_name',
'freight_amount',
];
@ -29,6 +32,9 @@ class CourierFreightRow extends Model
'source' => '来源',
'part' => '成品配件',
'transaction_no' => '交易单号',
'express_no' => '快递单号',
'barcode' => '条形码',
'shop_name' => '店铺名称',
'freight_amount' => '提供成本运费',
];
}

View File

@ -0,0 +1,340 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* 快递入驻申请:快递方扫码填写资料 → 对接人初审 → 财务复审(生成首版报价)→ 协议签署 → 开通。
*/
class CourierOnboarding extends Model
{
public const STATUS_INVITED = 'invited';
public const STATUS_SUBMITTED = 'submitted';
public const STATUS_RETURNED = 'returned';
public const STATUS_FIRST_APPROVED = 'first_approved';
public const STATUS_APPROVED = 'approved';
public const STATUS_ACTIVATED = 'activated';
public const STATUS_REJECTED = 'rejected';
public const STATUS_CANCELLED = 'cancelled';
public const STATUS_LABELS = [
self::STATUS_INVITED => '待快递填写',
self::STATUS_SUBMITTED => '待初审',
self::STATUS_RETURNED => '已退回补件',
self::STATUS_FIRST_APPROVED => '待财务复审',
self::STATUS_APPROVED => '待签署开通',
self::STATUS_ACTIVATED => '已开通',
self::STATUS_REJECTED => '不予合作',
self::STATUS_CANCELLED => '已作废',
];
/**
* 生成二维码时我方必填的快递资料(快递方看不到),直接对齐到快递资料。
* 字段 => [名称, 可选值(null 为自由填写)]
*/
public const PROFILE_FIELDS = [
'courier_category' => ['快递类型', ['内采快递', '外采快递']],
'cooperation_mode' => ['快递合作方式', ['保丢保损', '保丢不保损', '不保丢不保损']],
'courier_attribute' => ['快递属性', ['简尚', '工厂']],
'deduction_method' => ['扣款方式', ['运费', '损耗+运费', '无']],
'waybill_type' => ['单号类型', ['系统对接', '手填单号']],
'courier_email' => ['快递邮箱', null],
'need_logistics_check' => ['是否需要核对物流点', ['是', '否']],
'shipping_mode' => ['快递发货方式', ['一单一货', '一单多货']],
'workplatform_account' => ['是否已有工作平台账号', ['已有', '新开']],
'network_code' => ['快递网点代码', null],
'network_region' => ['网点所在地区', null],
];
/**
* 校验规则:生成二维码时全部必填;入驻详情里修改时,提交了哪项就校验哪项(不能清空)。
*
* @return array<string,list<string>>
*/
public static function profileRules(bool $onlyPresent = false): array
{
$rules = [];
foreach (self::PROFILE_FIELDS as $field => [$label, $options]) {
$base = $onlyPresent ? ['sometimes', 'required'] : ['required'];
$rules[$field] = [...$base, ...match (true) {
$options !== null => ['in:' . implode(',', $options)],
$field === 'courier_email' => ['email', 'max:191'],
default => ['string', 'max:' . ($field === 'network_code' ? 64 : 191)],
}];
}
return $rules;
}
/** @return array<string,string> 必填提示 */
public static function profileMessages(): array
{
$messages = [];
foreach (self::PROFILE_FIELDS as $field => [$label, $options]) {
$messages[$field . '.required'] = ($options !== null ? '请选择' : '请填写') . $label . '。';
}
return $messages;
}
/** @return array<string,string> 字段名称,用于校验提示 */
public static function profileAttributes(): array
{
return array_map(static fn (array $config): string => $config[0], self::PROFILE_FIELDS);
}
/** 快递方可以继续编辑资料的状态。 */
public const COURIER_EDITABLE = [self::STATUS_INVITED, self::STATUS_RETURNED];
public const ENTITY_COMPANY = 'company';
public const ENTITY_PERSON = 'person';
public const ENTITY_TYPES = [
self::ENTITY_COMPANY => '公司 / 个体户',
self::ENTITY_PERSON => '个人',
];
public const SERVICE_TYPES = ['快递', '快运', '大件专线', '其他'];
public const INVOICE_TYPES = ['增值税专用发票', '增值税普通发票', '不开票'];
public const SETTLEMENT_CYCLES = ['月结', '半月结', '周结', '其他'];
public const QUOTE_MODES = \App\Support\CourierQuoteStructure::MODES;
public const VOLUMETRIC_RULES = ['不计泡', '计泡'];
public const PROVINCES = [
'江苏', '浙江', '上海', '安徽', '北京', '天津', '河北', '山西', '山东', '河南',
'湖北', '湖南', '江西', '福建', '广东', '广西', '海南', '重庆', '四川', '贵州',
'云南', '陕西', '甘肃', '宁夏', '青海', '辽宁', '吉林', '黑龙江', '内蒙古', '新疆', '西藏',
];
protected $table = 'business_courier_onboardings';
protected $fillable = [
'company_id', 'number', 'token', 'status', 'invite_label', 'expires_at',
'entity_type', 'id_number', 'company_full_name', 'unified_social_credit_code', 'legal_representative', 'business_address',
'carrier_brand', 'network_name', 'service_type', 'contact_name', 'contact_phone',
'finance_contact_name', 'finance_contact_phone', 'pickup_warehouses', 'esign_operator_name', 'esign_account',
'bank_account_name', 'bank_name', 'bank_account_number', 'invoice_type', 'tax_rate', 'settlement_cycle',
'private_account_name', 'private_bank_name', 'private_account_number',
'workplatform_expcode', 'erp_account_id', 'erp_opened_at', 'erp_opened_source', 'dingtalk_instance_id',
'courier_category', 'cooperation_mode', 'courier_attribute', 'deduction_method', 'waybill_type', 'courier_email',
'need_logistics_check', 'shipping_mode', 'workplatform_account', 'network_code', 'network_region',
'quote_mode', 'volumetric_rule', 'volumetric_divisor', 'quote_effective_date', 'quote_structure', 'quote_rows',
'min_weight', 'weight_rounding', 'per_ticket_surcharge', 'quote_note', 'remark',
'courier_name', 'reconciler', 'return_reason', 'submitted_at',
'first_reviewed_by', 'first_reviewed_at', 'final_reviewed_by', 'final_reviewed_at',
'quote_change_id', 'quote_version_id', 'activated_by', 'activated_at', 'created_by', 'updated_by',
];
protected $casts = [
'company_id' => 'integer',
'expires_at' => 'datetime',
'submitted_at' => 'datetime',
'first_reviewed_at' => 'datetime',
'final_reviewed_at' => 'datetime',
'activated_at' => 'datetime',
'quote_effective_date' => 'date',
'quote_rows' => 'array',
'quote_structure' => 'array',
'min_weight' => 'float',
'per_ticket_surcharge' => 'float',
'bank_account_number' => 'encrypted',
'private_account_number' => 'encrypted',
'erp_opened_at' => 'datetime',
'id_number' => 'encrypted',
'tax_rate' => 'float',
'volumetric_divisor' => 'integer',
'first_reviewed_by' => 'integer',
'final_reviewed_by' => 'integer',
'activated_by' => 'integer',
'created_by' => 'integer',
'deleted_at' => 'datetime',
];
protected $hidden = ['token', 'bank_account_number', 'private_account_number', 'id_number'];
public function files(): HasMany
{
return $this->hasMany(CourierOnboardingFile::class, 'onboarding_id')->orderBy('id');
}
public function events(): HasMany
{
return $this->hasMany(CourierOnboardingEvent::class, 'onboarding_id')->orderBy('id');
}
public function quoteVersion(): BelongsTo
{
return $this->belongsTo(CourierQuoteVersion::class, 'quote_version_id');
}
public function isPerson(): bool
{
return $this->entity_type === self::ENTITY_PERSON;
}
public function entityLabel(): string
{
return $this->isPerson() ? '个人' : '公司';
}
/** 主体名称:公司为公司全称,个人为姓名。 */
public function subjectLabel(): string
{
return $this->isPerson() ? '姓名' : '公司全称';
}
public function maskedIdNumber(): string
{
$value = (string) ($this->id_number ?? '');
return strlen($value) < 8 ? $value : substr($value, 0, 3) . str_repeat('*', strlen($value) - 7) . substr($value, -4);
}
public function statusLabel(): string
{
return self::STATUS_LABELS[$this->status] ?? $this->status;
}
public function courierCanEdit(): bool
{
return in_array($this->status, self::COURIER_EDITABLE, true) && ! $this->linkExpired();
}
public function linkExpired(): bool
{
return $this->expires_at !== null && $this->expires_at->isPast();
}
public function displayName(): string
{
foreach ([$this->courier_name, $this->network_name, $this->company_full_name, $this->invite_label] as $name) {
if (filled($name)) {
return (string) $name;
}
}
return $this->number;
}
/** e签宝通知方式:1 短信(手机号账号),2 邮件(邮箱账号)。 */
public function esignNoticeType(): string
{
return str_contains((string) $this->esign_account, '@') ? '2' : '1';
}
public function quoteSignature(): ?CourierQuoteSignature
{
return $this->quoteVersion?->signature;
}
public function quoteModeLabel(): string
{
return \App\Support\CourierQuoteStructure::MODES[$this->quote_mode] ?? '';
}
/**
* @return array{mode:string,flat_bands:list<float>,then_mode:string,first_weight:?float,rate_tiers:list<float>}
*/
public function quoteStructure(): array
{
$structure = is_array($this->quote_structure) ? $this->quote_structure : [];
return [
'mode' => (string) ($structure['mode'] ?? $this->quote_mode ?? 'waybill_rate'),
'flat_bands' => array_values($structure['flat_bands'] ?? []),
'then_mode' => (string) ($structure['then_mode'] ?? ''),
'first_weight' => isset($structure['first_weight']) ? (float) $structure['first_weight'] : null,
'rate_tiers' => array_values($structure['rate_tiers'] ?? []),
];
}
/** @return list<array{key:string,label:string}> */
public function quoteColumns(): array
{
return \App\Support\CourierQuoteStructure::columns($this->quoteStructure());
}
/** 附加计费规则的文字(计泡、起算重量、取整、每票加收)。 */
public function quoteRuleLines(): array
{
$kg = static fn ($value): string => \App\Support\CourierQuoteStructure::kg((float) $value);
return array_values(array_filter([
'计费方式:' . \App\Support\CourierQuoteStructure::describe($this->quoteStructure()),
$this->volumetric_rule === '计泡' ? '计泡:长*宽*高/' . ($this->volumetric_divisor ?: 6000) . ',取实重与体积重较大值' : ($this->volumetric_rule ? '不计泡' : null),
$this->min_weight ? '起算重量:不足' . $kg($this->min_weight) . 'kg按' . $kg($this->min_weight) . 'kg计' : null,
$this->weight_rounding && $this->weight_rounding !== 'none' ? '重量取整:' . (\App\Support\CourierQuoteStructure::ROUNDING[$this->weight_rounding] ?? $this->weight_rounding) : null,
$this->per_ticket_surcharge ? '每票加收:' . $kg($this->per_ticket_surcharge) . '元' : null,
]));
}
/** ERP 开通信息来源:钉钉「新建快递」流程同步 / 手动补录 / 工作平台老数据。 */
public const ERP_SOURCES = [
'dingtalk' => '钉钉流程同步',
'manual' => '手动补录',
'workplatform' => '工作平台',
];
/** 开通后等 ERP 专员在钉钉发起「新建快递」流程、开通发货系统账号。 */
public function erpPending(): bool
{
return $this->status === self::STATUS_ACTIVATED && $this->erp_opened_at === null;
}
public function erpSourceLabel(): string
{
return self::ERP_SOURCES[$this->erp_opened_source] ?? '';
}
/** 户名比对:去掉空格,全角括号转半角,英文统一大写。 */
public static function normalizeName(?string $name): string
{
$name = str_replace(['(', ')', ' '], ['(', ')', ''], (string) $name);
return mb_strtoupper((string) preg_replace('/\s+/u', '', $name));
}
/** 对私收款人应为谁:公司入驻是法定代表人,个人入驻是本人。 */
public function expectedPrivatePayee(): ?string
{
return $this->isPerson() ? $this->company_full_name : $this->legal_representative;
}
/**
* 打款账户核对结果:对公户名 = 营业执照公司全称,对私收款人 = 法定代表人(个人为本人)。
*
* @return array{corporate:?bool,private:?bool}
*/
public function accountChecks(): array
{
$same = static fn (?string $a, ?string $b): ?bool => blank($a) || blank($b) ? null : self::normalizeName($a) === self::normalizeName($b);
return [
'corporate' => $this->isPerson() ? null : $same($this->bank_account_name, $this->company_full_name),
'private' => $same($this->private_account_name, $this->expectedPrivatePayee()),
];
}
public function maskedBankAccount(): string
{
$value = (string) ($this->bank_account_number ?? '');
if (mb_strlen($value) <= 8) {
return $value;
}
return mb_substr($value, 0, 4) . str_repeat('*', max(mb_strlen($value) - 8, 4)) . mb_substr($value, -4);
}
/**
* @return list<array{region:string,flat:list<?float>,base:?float,rates:list<?float>}>
*/
public function quoteRowList(): array
{
return array_values(array_filter(
is_array($this->quote_rows) ? $this->quote_rows : [],
static fn ($row): bool => is_array($row) && filled($row['region'] ?? null),
));
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CourierOnboardingEvent extends Model
{
protected $table = 'business_courier_onboarding_events';
protected $fillable = ['company_id', 'onboarding_id', 'event_type', 'from_status', 'to_status', 'note', 'actor_type', 'actor_id'];
protected $casts = [
'company_id' => 'integer',
'onboarding_id' => 'integer',
'actor_id' => 'integer',
'deleted_at' => 'datetime',
];
public function actor(): BelongsTo
{
return $this->belongsTo(user_model_class(), 'actor_id');
}
public function eventLabel(): string
{
return match ($this->event_type) {
'invited' => '生成入驻二维码',
'saved' => '快递方保存资料',
'submitted' => '快递方提交审核',
'first_approved' => '初审通过',
'returned' => '退回补件',
'final_approved' => '财务复审通过',
'activated' => '确认开通',
'rejected' => '不予合作',
'cancelled' => '作废邀请',
'extended' => '延长链接有效期',
'internal_updated' => '更新内部信息',
'quote_pushed' => '推送报价确认单到 e签宝',
'quote_push_failed' => '报价确认单推送失败',
default => $this->event_type,
};
}
public function actorLabel(): string
{
if ($this->actor_type === 'courier') {
return '快递方';
}
return (string) ($this->actor?->name ?? '系统');
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
class CourierOnboardingFile extends Model
{
public const KINDS = [
'business_license' => '营业执照',
'legal_id_card_front' => '法人身份证 · 人像面',
'legal_id_card_back' => '法人身份证 · 国徽面',
'bank_card_front' => '对私银行卡 · 正面',
'bank_card_back' => '对私银行卡 · 反面',
];
/** 计费方式选「其他」时上传的报价表,单独显示在报价区块里。 */
public const QUOTE_SHEET_KIND = 'quote_sheet';
/** @return array<string,string> */
public static function allKinds(): array
{
return self::KINDS + [self::QUOTE_SHEET_KIND => '报价表'];
}
/** 个人入驻时的资料名称。 */
public const PERSON_KINDS = [
'business_license' => '营业执照(有就上传,选填)',
'legal_id_card_front' => '身份证 · 人像面',
'legal_id_card_back' => '身份证 · 国徽面',
'bank_card_front' => '对私银行卡 · 正面',
'bank_card_back' => '对私银行卡 · 反面',
];
/** 提交审核前必须上传的资料(每项一张,重新上传会替换)。 */
public const REQUIRED_KINDS = ['business_license', 'legal_id_card_front', 'legal_id_card_back', 'bank_card_front', 'bank_card_back'];
public const PERSON_REQUIRED_KINDS = ['legal_id_card_front', 'legal_id_card_back', 'bank_card_front', 'bank_card_back'];
/** @return list<string> */
public static function requiredKindsFor(?string $entityType): array
{
return $entityType === CourierOnboarding::ENTITY_PERSON ? self::PERSON_REQUIRED_KINDS : self::REQUIRED_KINDS;
}
public static function labelFor(string $kind, ?string $entityType): string
{
return ($entityType === CourierOnboarding::ENTITY_PERSON ? (self::PERSON_KINDS[$kind] ?? null) : null)
?? self::allKinds()[$kind]
?? $kind;
}
protected $table = 'business_courier_onboarding_files';
protected $fillable = ['company_id', 'onboarding_id', 'kind', 'original_name', 'path', 'mime', 'size'];
protected $casts = [
'company_id' => 'integer',
'onboarding_id' => 'integer',
'size' => 'integer',
'deleted_at' => 'datetime',
];
public function kindLabel(): string
{
return self::KINDS[$this->kind] ?? $this->kind;
}
public function isImage(): bool
{
return str_starts_with((string) $this->mime, 'image/');
}
public function sizeLabel(): string
{
$size = (int) $this->size;
return $size >= 1048576 ? sprintf('%.1f MB', $size / 1048576) : sprintf('%d KB', max(1, (int) ceil($size / 1024)));
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
/**
* 快递资料「打款信息新增 / 变更」。保存后跳到协议签署推送收款账户证明(新增)或收款账户变更(变更),
* 状态按协议签署记录推导:待推送协议 → 签署中 → 已生效。
*/
class CourierPaymentAccount extends Model
{
public const ACTION_ADD = 'add';
public const ACTION_CHANGE = 'change';
public const ACTIONS = [self::ACTION_ADD => '打款信息新增', self::ACTION_CHANGE => '打款信息变更'];
public const ACCOUNT_TYPES = ['对公', '对私'];
/** 对应协议签署里的文件类型。 */
public const DOCUMENT_TYPES = [self::ACTION_ADD => 'account-proof', self::ACTION_CHANGE => 'account-change'];
protected $table = 'business_courier_payment_accounts';
protected $fillable = [
'company_id', 'expcode', 'courier_name', 'action', 'account_type', 'account_name', 'bank_name', 'account_number',
'effective_date', 'old_account_name', 'old_account_number', 'old_stop_date', 'change_date', 'note',
'created_by', 'updated_by',
];
protected $casts = [
'account_number' => 'encrypted',
'old_account_number' => 'encrypted',
'effective_date' => 'date',
'old_stop_date' => 'date',
'change_date' => 'date',
];
public function documentType(): string
{
return self::DOCUMENT_TYPES[$this->action] ?? 'account-proof';
}
public function actionLabel(): string
{
return self::ACTIONS[$this->action] ?? $this->action;
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
/**
* 快递资料在财务系统里的「编辑」覆盖值(按快递公司代码)。工作平台镜像只读,编辑结果存在这里,
* 页面和导出显示时用覆盖值盖在镜像值上。
*/
class CourierProfile extends Model
{
/** 可在财务系统编辑的快递资料字段(键与工作平台 wp_express 列名一致)。 */
public const EDITABLE = [
'expname' => '快递公司名称',
'paymethod' => '运费打款方式',
'status' => '是否启用',
'kuaiyunsgn' => '是否快运',
'stopdate' => '停运时间',
'tradebtime' => '合同开始时间',
'tradeetime' => '合同结束时间',
'linker' => '联系人',
'linkmobile' => '联系电话',
'undefined1' => '自定义1',
'undefined2' => '自定义2',
'undefined3' => '扣款方式',
'dzqzjbr' => '电子签章经办人',
];
public const BOOLEAN_FIELDS = ['status', 'kuaiyunsgn'];
public const DATE_FIELDS = ['stopdate', 'tradebtime', 'tradeetime'];
protected $table = 'business_courier_profiles';
protected $fillable = ['company_id', 'expcode', 'courier_name', 'overrides', 'created_by', 'updated_by'];
protected $casts = ['overrides' => 'array'];
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/** 快递资料操作日志(财务系统侧):编辑、打款信息新增/变更。 */
class CourierProfileEvent extends Model
{
public const ACTIONS = [
'edit' => '编辑快递资料',
'account_add' => '打款信息新增',
'account_change' => '打款信息变更',
];
protected $table = 'business_courier_profile_events';
protected $fillable = ['company_id', 'expcode', 'action', 'summary', 'changes', 'created_by'];
protected $casts = ['changes' => 'array'];
public function creator(): BelongsTo
{
return $this->belongsTo(\App\Models\Auth\User::class, 'created_by');
}
public function actionLabel(): string
{
return self::ACTIONS[$this->action] ?? $this->action;
}
}

View File

@ -21,17 +21,19 @@ class CourierQuoteChange extends Model
protected $fillable = [
'company_id', 'number', 'source_quote_id', 'source_sheet_name', 'carrier_name', 'quote_type',
'change_type', 'status', 'effective_date', 'is_retrospective', 'recalculation_status',
'change_type', 'status', 'effective_date', 'end_date', 'is_retrospective', 'recalculation_status',
'recalculation_note', 'summary', 'created_by', 'submitted_by', 'submitted_at', 'approved_by',
'approved_at', 'new_quote_version_id',
'approved_at', 'new_quote_version_id', 'quote_payload', 'proposed_values_json',
];
protected $casts = [
'company_id' => 'integer',
'effective_date' => 'date',
'end_date' => 'date',
'is_retrospective' => 'boolean',
'submitted_at' => 'datetime',
'approved_at' => 'datetime',
'quote_payload' => 'array',
];
public function items(): HasMany
@ -49,6 +51,30 @@ class CourierQuoteChange extends Model
return $this->hasOne(CourierQuoteVersion::class, 'source_change_id');
}
public function stockEntry(): HasOne
{
return $this->hasOne(CourierStockQuoteEntry::class, 'source_change_id');
}
/** 按完整报价结构提交的变价(快递入驻后的后台变价 / 重新报价)。 */
/** 执行期间文字,如「2026-10-12 至 2026-10-15(临时)」或「2026-10-01 起」。 */
public function periodLabel(): string
{
return $this->end_date !== null
? $this->effective_date?->toDateString() . ' 至 ' . $this->end_date->toDateString() . '(临时)'
: $this->effective_date?->toDateString() . ' 起';
}
public function hasQuotePayload(): bool
{
return is_array($this->quote_payload) && $this->quote_payload !== [];
}
public function isStockQuote(): bool
{
return $this->change_type === '存量报价' && is_numeric(data_get($this->quote_payload, 'stock_quote_entry_id'));
}
public function isEditable(): bool
{
return in_array($this->status, [self::STATUS_DRAFT, self::STATUS_RETURNED], true);

View File

@ -33,6 +33,8 @@ class CourierQuoteChangeEvent extends Model
'submitted' => '提交审核',
'returned' => '退回修改',
'approved' => '审核通过',
'voided' => '版本作废',
'period_end_updated' => '设置执行截止日期',
default => $this->event_type,
};
}

View File

@ -12,15 +12,80 @@ class CourierQuoteVersion extends Model
protected $fillable = [
'company_id', 'version_code', 'source_quote_id', 'source_change_id', 'sheet_name', 'company_name',
'carrier_name', 'quote_type', 'effective_date', 'source_range', 'values_json', 'formulas_json',
'status', 'signature_status', 'created_by', 'approved_by',
'carrier_name', 'courier_expcode', 'billing_rules', 'quote_type', 'effective_date', 'end_date', 'source_range', 'values_json', 'formulas_json',
'status', 'signature_status', 'created_by', 'approved_by', 'void_reason', 'voided_at', 'voided_by',
'billing_structure', 'billing_rows',
];
public const STATUS_APPROVED = 'approved';
/** 发错作废:不再参与生效判断,原件和回签单保留。 */
public const STATUS_VOIDED = 'voided';
protected $casts = [
'company_id' => 'integer',
'effective_date' => 'date',
'end_date' => 'date',
'voided_at' => 'datetime',
'billing_structure' => 'array',
'billing_rows' => 'array',
];
/** 短期(临时)变价:有结束日期,到期后回到原来的长期报价。 */
public function isTemporary(): bool
{
return $this->end_date !== null && !$this->change?->isStockQuote();
}
/** 某一天是否在这一版的执行期间内(开始 ≤ 日期 ≤ 结束;长期版本没有结束)。 */
public function coversDate(\DateTimeInterface $date): bool
{
$day = \Illuminate\Support\Carbon::instance($date)->startOfDay();
return $this->effective_date !== null
&& $this->effective_date->lte($day)
&& ($this->end_date === null || $this->end_date->gte($day));
}
/** 执行期间文字,如「2026-10-12 至 2026-10-15(临时)」或「2026-10-01 起」。 */
public function periodLabel(): string
{
if ($this->effective_date === null) {
return '-';
}
return $this->end_date !== null
? $this->effective_date->toDateString() . ' 至 ' . $this->end_date->toDateString() . ($this->isTemporary() ? '(临时)' : '')
: $this->effective_date->toDateString() . ' 起';
}
/** 是否已有可用于运费核算的结构化计费规则。 */
public function hasBillingRules(): bool
{
$mode = $this->billing_structure['mode'] ?? null;
return is_string($mode) && $mode !== 'other' && is_array($this->billing_rows) && $this->billing_rows !== [];
}
public function isVoided(): bool
{
return $this->status === self::STATUS_VOIDED;
}
/** 存量报价审核后按执行日期生效,不以补签或历史签署资料为前置条件。 */
public function isApprovedStockQuote(): bool
{
return $this->status === self::STATUS_APPROVED
&& $this->change?->status === CourierQuoteChange::STATUS_APPROVED
&& $this->change->isStockQuote();
}
public function signatureLabel(): string
{
return $this->isApprovedStockQuote() && !in_array($this->signature_status, ['历史签署资料已归档', '已签署并归档'], true)
? '存量报价,审核生效(无需签章)' : (string) $this->signature_status;
}
public function change(): BelongsTo
{
return $this->belongsTo(CourierQuoteChange::class, 'source_change_id');

View File

@ -0,0 +1,38 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CourierStockQuoteEntry extends Model
{
protected $table = 'business_courier_stock_quote_entries';
protected $fillable = [
'company_id', 'courier_expcode', 'courier_name', 'courier_name_key', 'quote_type', 'source_change_id',
'sheet_name', 'source_range', 'values_json', 'formulas_json', 'files', 'created_by', 'effective_date', 'end_date',
];
protected $casts = ['company_id' => 'integer', 'files' => 'array', 'effective_date' => 'date', 'end_date' => 'date'];
public function change(): BelongsTo
{
return $this->belongsTo(CourierQuoteChange::class, 'source_change_id');
}
public function sourceQuote(): array
{
return [
'id' => 'STOCK-' . $this->id,
'courier_expcode' => $this->courier_expcode,
'billing_rules' => data_get($this->change?->quote_payload, 'billing_rules'),
'company_name' => $this->courier_name,
'sheet_name' => $this->sheet_name,
'quote_type' => $this->quote_type,
'source_range' => $this->source_range,
'values' => json_decode($this->values_json, true, 512, JSON_THROW_ON_ERROR),
'formulas' => json_decode($this->formulas_json, true, 512, JSON_THROW_ON_ERROR),
];
}
}

View File

@ -17,6 +17,7 @@ class JstOrderLabel extends Model
'shop_name',
'ordered_at',
'label',
'item_code',
'created_from',
];

View File

@ -111,7 +111,8 @@ class DingTalkClosedAccess
'enabled' => true,
'landing_page' => 'dashboard',
'created_by' => 0,
'created_from' => 'dingtalk_roster',
'created_from' => FinanceRoster::isLimitedLoginUser((string) $profile['dingtalk_user_id'])
? 'dingtalk_roster_limited' : 'dingtalk_roster',
]);
$account->roles()->attach($role->id);
// Explicit designation controls the role; ordinary roster users get shell access.

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