Compare commits
483 Commits
fix/system
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| ffe97e458a | |||
| a7e7b067eb | |||
| e6b9775a24 | |||
| 6a1e7678fe | |||
| 6b1ff05fee | |||
| 801264b4b3 | |||
| d967420b08 | |||
| 52181b41d4 | |||
| b601a28e01 | |||
| 3374563c4f | |||
| 79449e4aca | |||
| a8f5e9a188 | |||
| c8dfec5c85 | |||
| 7e23e42a34 | |||
| ddbd018377 | |||
| 506f1e8784 | |||
| 684813d03b | |||
| 79206da614 | |||
| a0e4cc4380 | |||
| e1178f56aa | |||
| 0bb0d895d1 | |||
| 2912814931 | |||
| 5f1348db4b | |||
| e058927cdd | |||
| 5d6412ac44 | |||
| 2d4859f291 | |||
| c7f011fc93 | |||
| 414d4fd3ee | |||
| e0a3b8fd1f | |||
| 773509443d | |||
| 9089d8fb23 | |||
| 85c32fbd7d | |||
| 66639e19c1 | |||
| 92f88fb60b | |||
| 0a7cc700fb | |||
| aa99eb932e | |||
| 6ca0154a22 | |||
| bec7cbdabb | |||
| dcd12eca7b | |||
| e7a73008c7 | |||
| b72b2e12bd | |||
| b6e06e775c | |||
| 4dfed91c92 | |||
| e330d94090 | |||
| 0513146ef9 | |||
| f5b797070b | |||
| cdbaf45f27 | |||
| cc204fbb97 | |||
| 95731bd90b | |||
| 6cfed8ac51 | |||
| 6a6c6f94c1 | |||
| b2f7a072c8 | |||
| 50f5c7bc64 | |||
| 7de0d3370f | |||
| 8df3c3ec36 | |||
| 1954e10b5e | |||
| 56de349bfc | |||
| f8efd97115 | |||
| 2f9fd2ac1d | |||
| f49d32ca8d | |||
| 24c6b7cb51 | |||
| d112d90ed9 | |||
| 12bc2f9efd | |||
| 8b27e3e7aa | |||
| 832fe6399a | |||
| 4539031eb1 | |||
| 2ec2e7410f | |||
| e1efa6812a | |||
| c333497e0b | |||
| e471e2b057 | |||
| cb4fc5af0d | |||
| 8a6e51e031 | |||
| ea0680913e | |||
| 83ab4d4479 | |||
| 73679c55e3 | |||
| 95f7734845 | |||
| 828b5d4412 | |||
| 9edbc0a158 | |||
| 063f5f1a67 | |||
| b4767adb86 | |||
| f0df43e2f2 | |||
| 1e823e299b | |||
| 5a2f4586f7 | |||
| e24b6b8de7 | |||
| 732e6ecd8f | |||
| 593ba3f62c | |||
| 89bfb24e26 | |||
| 29d19aaa34 | |||
| 64c50ba414 | |||
| 939a4e597c | |||
| cb6e10d3b9 | |||
| b1015c7cfb | |||
| 5959ed1311 | |||
| 30e6e6f995 | |||
| 3ce42d564e | |||
| 523b6c2db2 | |||
| 37b9a17b65 | |||
| 671b6b81a8 | |||
| a65b0b41ff | |||
| 2386c92a15 | |||
| aa5950e0c9 | |||
| 79c9b2c3a6 | |||
| cd85ad0f63 | |||
| 0eb439b1e9 | |||
| 365368d032 | |||
| c663a59cf0 | |||
| a026cdc1f0 | |||
| 696327fb38 | |||
| 35c1048880 | |||
| 832d245c8b | |||
| bd07ef1b9a | |||
| 0991391fd7 | |||
| 212f4aa9e6 | |||
| db78e87ea5 | |||
| b9665b6393 | |||
| 24d0bf0a22 | |||
| 9ab3d85a3a | |||
| 0c26491633 | |||
| 1a44a73150 | |||
| 96f0fceab7 | |||
| 9875ced91b | |||
| 31f14cd210 | |||
| 67ce756594 | |||
| a597285e29 | |||
| 02b685bca9 | |||
| 337bee9da1 | |||
| 3f11a171b3 | |||
| ac31ca56ea | |||
| 267d62ee43 | |||
| 6a46a277cb | |||
| 35a98063eb | |||
| a19836d3f3 | |||
| daf50db507 | |||
| b6e984ad30 | |||
| d0dc453139 | |||
| 091cbee965 | |||
| c026f72604 | |||
| 0b5a90456d | |||
| cda29213a1 | |||
| b0319e1cd1 | |||
| fa38374246 | |||
| b1b7710315 | |||
| a14c0d44ca | |||
| 1114349ac7 | |||
| 41080477b8 | |||
| 864f4fe9e8 | |||
| 99e94f7939 | |||
| abe8376f20 | |||
| f0bee2dc22 | |||
| 39769abd26 | |||
| 04aab012b9 | |||
| e8ca07dfd6 | |||
| 6156245335 | |||
| 4fa23a63e3 | |||
| 871793ff29 | |||
| e76e87e4db | |||
| 11637818b9 | |||
| 40ac376760 | |||
| c670272aa2 | |||
| cd8c0511f2 | |||
| f75481633d | |||
| 820de98c29 | |||
| 9e933fa787 | |||
| f053ed8fd0 | |||
| 8bf3acece5 | |||
| 1a592c82a0 | |||
| 6d9a4d2ddd | |||
| 1aed8762b6 | |||
| 23b0beda61 | |||
| cfde5d06c7 | |||
| d2d58276fb | |||
| 1e02737f92 | |||
| 6e092547c0 | |||
| d42bc76404 | |||
| 0e1bac07c0 | |||
| 75f96d8ee4 | |||
| fc6aadc7ff | |||
| 24f11ed0ae | |||
| 765c85af0c | |||
| 841eae6d39 | |||
| c6aeb823ed | |||
| ffd31af3e1 | |||
| add4c912b8 | |||
| 34dfd46e22 | |||
| f0f5b35071 | |||
| bfb668f5db | |||
| e9d5163ca0 | |||
| 7b61be1ed0 | |||
| 1340d24ced | |||
| 17da14981d | |||
| bb0e83da80 | |||
| 205cdfe50e | |||
| d664680aec | |||
| 3e3cb199f7 | |||
| 7d3c2e9605 | |||
| 5bdee2bd8f | |||
| 4041e7351d | |||
| 703940b7b2 | |||
| 2eadd534f9 | |||
| 31dc6b7651 | |||
| ba26a130ae | |||
| b32c7ebf67 | |||
| eba8d5e796 | |||
| fe19763ffd | |||
| 5a27e64aaa | |||
| 8543953752 | |||
| 03dfc70da7 | |||
| da35e00eec | |||
| 606077c0b7 | |||
| 6d85f64d84 | |||
| c713db6fe5 | |||
| 15d34c0de0 | |||
| f594adbba4 | |||
| 082c7f7f38 | |||
| 6518018b9f | |||
| 23fc36c74c | |||
| 97b5824aee | |||
| 9821736dba | |||
| 837e01b164 | |||
| b0693163a6 | |||
| efba0711f6 | |||
| a43d358680 | |||
| 5303994ac3 | |||
| f66cb9fd8f | |||
| cedd6638a1 | |||
| 9de660ae55 | |||
| 27a025a33d | |||
| dddea5b8eb | |||
| 2466c41ba0 | |||
| 8cbd56a4cb | |||
| eed9678abe | |||
| 9d6e2a85d2 | |||
| 7219b4d143 | |||
| d5af967e51 | |||
| c11f363d1a | |||
| 2a37724b8e | |||
| 3dbb09c5d2 | |||
| 556535d643 | |||
| b5ba81add3 | |||
| 02275d064c | |||
| e02d896ad5 | |||
| 00942162ae | |||
| 7f989314ed | |||
| c82b758763 | |||
| 2d53ddc943 | |||
| 5f24bf4fcf | |||
| 10626f0e55 | |||
| e6ce84759e | |||
| 3240342fa4 | |||
| 58506f45a7 | |||
| da503915b3 | |||
| 381c0e0d03 | |||
| 557017b178 | |||
| 160618526e | |||
| 2ea6326bdf | |||
| 039a366717 | |||
| 824e1b0d92 | |||
| 0282fea3fd | |||
| 8b46486b87 | |||
| 4de11d6d95 | |||
| 0188ad18f8 | |||
| 119f52c442 | |||
| 30c4b8cd99 | |||
| a1783bf0eb | |||
| 805fc38cf9 | |||
| 3afbf6320f | |||
| de6a7fbc37 | |||
| 2fc587d2fa | |||
| 5b95620d54 | |||
| 5611491d02 | |||
| bd76d99457 | |||
| 6248d74450 | |||
| 92c7450f8f | |||
| 09a30cd980 | |||
| 018b719257 | |||
| 5baf7a40fb | |||
| b0074bbfa7 | |||
| 691a80e0c3 | |||
| d69d2af66e | |||
| 33d088797f | |||
| 3ad61407f0 | |||
| c1c98f756b | |||
| e4eca2d9af | |||
| 8277d066e8 | |||
| 301caa112d | |||
| 19763659d1 | |||
| 81410eef8d | |||
| 7149bdad1c | |||
| a3a391236f | |||
| 04900e6987 | |||
| cdd08d6357 | |||
| 7a4249d753 | |||
| 941b1acd19 | |||
| 48cb5c956a | |||
| 29e2779c7e | |||
| 5cf63f793a | |||
| 26b9f9432b | |||
| 71c2e0e278 | |||
| f2181e586c | |||
| 1cf6f020c5 | |||
| 8135bd53c8 | |||
| 69ffa43d43 | |||
| 33aa492f7b | |||
| a2fbc66fb7 | |||
| 627216f43e | |||
| 3a298ae3b4 | |||
| f106ef988d | |||
| 957504ac1e | |||
| ceac04e1e0 | |||
| bd3532e140 | |||
| 991d7350b9 | |||
| 30316cdbc9 | |||
| 6cecd87e05 | |||
| 7d9f3d7bd1 | |||
| 1dbcc7794d | |||
| 264423c63f | |||
| a570da3f78 | |||
| 03e5f78d91 | |||
| 4f694f7333 | |||
| b4512c76f2 | |||
| 8a62fdea39 | |||
| 424d7379df | |||
| bf2247640e | |||
| c639b351d8 | |||
| ea6c7c380b | |||
| a7b3e051b5 | |||
| f5371c24f3 | |||
| 81fd0465e4 | |||
| c4157ed7d5 | |||
| 125c6cb003 | |||
| a03405e932 | |||
| 4be7631ae3 | |||
| 28e69e32ed | |||
| 01ef6181d9 | |||
| 0a2646561a | |||
| 65d37c8093 | |||
| 8cdec97df6 | |||
| 92554baf0f | |||
| c43574a92a | |||
| 6dff7620b6 | |||
| b662a340e1 | |||
| 61cfa8a3ff | |||
| db72543cc6 | |||
| 861bc4db71 | |||
| 5cf5a9bd5b | |||
| 921ba9d6a3 | |||
| bd276126c5 | |||
| 395b29aaef | |||
| 494f468b9c | |||
| 256d0ff0f2 | |||
| 167211490b | |||
| e12c9c20ec | |||
| d3532bf0da | |||
| e60095e64d | |||
| 770ddea8a9 | |||
| c658bbed99 | |||
| cad98ba3e9 | |||
| 632e661c8b | |||
| baed64ec3d | |||
| ee871dafc1 | |||
| 68b7e927b1 | |||
| 90fdf33968 | |||
| 16b6c20f73 | |||
| 6c5088e91b | |||
| 3ef2f4d00b | |||
| 9c75c8faad | |||
| cb6e65a6bf | |||
| 9dbabead87 | |||
| d2b3dc3f60 | |||
| 3aab35ac22 | |||
| 10fd8bfdb4 | |||
| 4ca8685324 | |||
| c21a622a16 | |||
| 5645021f89 | |||
| 097525a6ca | |||
| fa2cfe32e1 | |||
| 8b9349282f | |||
| e9302ee420 | |||
| 90a0466220 | |||
| 4592ad5b74 | |||
| efa4193fbd | |||
| f71fa8f669 | |||
| 6fc87fbf24 | |||
| 31ef152cc9 | |||
| f78149e630 | |||
| 2a2c009453 | |||
| c330f35b13 | |||
| 81ef31a657 | |||
| 45dade3c26 | |||
| b4783ae528 | |||
| 8fb8d9487b | |||
| 16e45407b2 | |||
| b66ccf1c43 | |||
| 4c3d382633 | |||
| 951e553fae | |||
| 9831df1ef5 | |||
| bd0b1dd6f4 | |||
| 76407ae5e5 | |||
| e875656c66 | |||
| eb983ecf76 | |||
| 6b40bb3e36 | |||
| f9f92ec65c | |||
| 52ff4999d1 | |||
| 474866b5f8 | |||
| ad6ce5ddf4 | |||
| 7aca023c63 | |||
| 87845baa01 | |||
| eb078cf4ee | |||
| 8563a3f635 | |||
| 886f66293b | |||
| b1e4eb3c72 | |||
| a1498e6134 | |||
| c41681284a | |||
| 2ef723e38d | |||
| b38d3e5b30 | |||
| 2d5da83780 | |||
| 45b88d1528 | |||
| 27021ce55a | |||
| 59485b99f2 | |||
| f4f0d5d7b1 | |||
| c34175c3d1 | |||
| 0f65cb124b | |||
| d88d318e6c | |||
| be1eabfd16 | |||
| 739fff215a | |||
| ecf5b36217 | |||
| 31d66ff89f | |||
| 1e69ca883d | |||
| daca32926d | |||
| d6fe74ad1e | |||
| 4743506504 | |||
| edb0e6c721 | |||
| aa44afe52a | |||
| 7363d01cb2 | |||
| 83ffec8d57 | |||
| 27b8610ef2 | |||
| 6a722a98c6 | |||
| 9bd3778c8f | |||
| 00728c5212 | |||
| 65a7da66f0 | |||
| 9a162b3f0a | |||
| fd07bbba7e | |||
| c93cb2db96 | |||
| 65c774a836 | |||
| a5c536f9dd | |||
| 11c506af89 | |||
| c750f3c09b | |||
| 89a7ee4d3a | |||
| 868a1ec403 | |||
| 59a9d5bf58 | |||
| e5faacd2bf | |||
| dde4531ff4 | |||
| 178bf2840f | |||
| 11db14c758 | |||
| 1f2ac85ab4 | |||
| 0fbbae4b97 | |||
| c5a525695b | |||
| afd6d1ab69 | |||
| bad13f90c5 | |||
| d512e5d9ba | |||
| 6a1a718e89 | |||
| e5e11a25cb | |||
| 394a6838d3 | |||
| 4e76f76b71 | |||
| c32dbe57b2 | |||
| 6cf43d10ae | |||
| fcfc401eff | |||
| 0754045003 | |||
| 80aa79ddc4 | |||
| 78f3bbb2a1 | |||
| b959cef955 | |||
| 1dd1985de2 | |||
| 0c92a3c567 | |||
| 814f9a4520 | |||
| 87292e7959 | |||
| 6e6e3038a1 | |||
| 1c58ba0684 | |||
| 0f4b7d2977 | |||
| d803d97c19 | |||
| 14adc83014 | |||
| 157ceadcad | |||
| e0c57cfafd | |||
| c9f84ccea9 |
@ -10,6 +10,7 @@ runtime
|
||||
*.md
|
||||
JetBrainsMono-字体
|
||||
node_modules
|
||||
outputs
|
||||
**/__pycache__
|
||||
vendor
|
||||
bootstrap/cache/*
|
||||
@ -27,6 +28,7 @@ storage/framework/testing
|
||||
storage/logs/*
|
||||
tests
|
||||
test-data
|
||||
tmp
|
||||
docs
|
||||
scripts
|
||||
npm-debug.log
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -109,6 +109,7 @@ modules/*
|
||||
# 本地私有配置、账号密码和敏感信息文档;禁止使用 git add -f 强制提交。
|
||||
/runtime/private/敏感信息.md
|
||||
/runtime/
|
||||
/tmp/
|
||||
/.caiwu-build/
|
||||
.workbuddy/
|
||||
runtime/.env
|
||||
|
||||
@ -57,13 +57,14 @@
|
||||
|
||||
## 6. 数据、上游与敏感信息
|
||||
|
||||
- 生产网页、后台任务、数据同步和上游网络通道必须运行在服务器或公司管理的固定网络设施上,禁止依赖个人开发机的常驻进程、登录状态或开机状态。生产服务器无法直连上游时,先修复网络或使用公司固定网关,不得在开发机安装生产中继。
|
||||
- 密码、Token、SSH 私钥、数据库连接串、真实财务数据和生产日志不得进入 Git、PR 或公开文档。
|
||||
- 需要长期保存的敏感信息写入被 Git 忽略的 `runtime/private/敏感信息.md`;写入前用 `git check-ignore` 确认。负责人明确要求时,可在当前一对一对话提供指定范围的敏感信息,但不得扩大传播。
|
||||
- 本任务所需的上游只读排查、数据字典刷新、数据集登记和启用、共享镜像建表及索引迁移、首次全量、增量、历史回补和镜像校准,由开发者的 Codex 自主完成,无需负责人逐次授权或代执行。Codex 自行核对来源与范围、备份受影响的配置/镜像及同步状态,使用生产同步节点和现有互斥锁分批执行,并核对源数据、完成状态与真实页面;不把这些工作转交给新人。可从上游重建的镜像修复属于此范围;上游写入、原始业务/财务数据修改、无关数据删除、凭据轮换和覆盖生产连接配置仍需单独授权。
|
||||
- `caiwu_system_config` 保存用户、权限、设置、连接资料、数据字典和同步状态;`caiwu_business_mirror` 保存项目已正式接入的上游业务数据。二者不是 SQL Server 网络代理。
|
||||
- 上游数据库统一按只读黑盒处理。业务查询使用固定、参数化的 Repository/查询执行器,禁止把用户输入拼成 SQL 或执行写操作。
|
||||
- 正式页面优先读取共享业务镜像;尚未迁移的旧页面可继续使用现有快照兼容层。接入新数据时沿用现有镜像数据集、稳定游标、断点同步和同步状态模式,不另造一套链路。
|
||||
- 两个现有来源固定为:`jiansun` 对应 `JianSun` 旧业务库;`operations_replica` 对应 `JSReportReplica` 的 `rpt` 只读视图。不得交换来源或写回历史临时库名。
|
||||
- 当前使用 `operations_replica` 对应 `JSReportReplica` 的 `rpt` 只读视图。`jiansun`(`JianSun` 旧业务库)和 `js_data_middle_platform` 已退役,保留已有镜像与历史标识,不再自动开启连接或恢复其专属同步。新增来源不得复用退役标识或交换来源含义。
|
||||
- 只有涉及上游接入、镜像同步、数据字典或生产刷新时,才读取 `docs/开发与部署SOP.md` 第 8 节及 `docs/上游业务镜像清单.md`。
|
||||
|
||||
## 7. 新人本地开发
|
||||
|
||||
@ -1,6 +1,10 @@
|
||||
# CaiWuXiTong 本地测试环境
|
||||
|
||||
本说明用于开发者在自己的电脑上启动项目。项目使用 Docker,默认访问地址为:
|
||||
本说明用于开发者在自己的电脑上启动项目。项目使用 Docker。
|
||||
|
||||
本地环境只用于开发、测试、构建和发布。生产取数和后台任务不得依赖本机常驻服务;上游网络问题应在生产服务器或公司固定网络设施解决,不安装开发机中继。
|
||||
|
||||
默认访问地址为:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:18088
|
||||
@ -54,6 +58,8 @@ bash deploy/local-init.sh
|
||||
|
||||
这个账号只存在于本机临时数据库中。系统数据库切换完成后,请使用系统数据库里属于自己的账号登录,不要继续把临时账号当作团队共享账号。
|
||||
|
||||
`local-init.sh` 会在本机 `runtime/.env` 写入 `AUTH_PASSWORD_LOGIN_ENABLED=true`,仅用于私有开发库和自动登录助手。代码默认关闭这一开关,并且配置层只允许 `APP_ENV=local` 时生效;正式环境始终只开放钉钉登录。已有开发机拉取本次代码后需重新执行一次 `bash deploy/local-init.sh`。
|
||||
|
||||
初始化中断后,Codex 直接重新执行 `bash deploy/local-init.sh`。脚本会根据 Dockerfile、依赖锁文件、前端源码和静态资源生成镜像指纹:输入未变化时复用镜像,发生变化或缺少必要静态资源时自动重建,并从数据库初始化阶段继续。`--build` 只用于强制重建;`--skip-build` 仅允许镜像指纹和静态资源均已通过校验时使用。
|
||||
|
||||
拉取新代码后再次运行该脚本时,本机临时引导库会自动更新;连接团队共享系统数据库后,这项自动更新会安全跳过。普通开发者任何时候都不需要执行 `php artisan migrate`,也不得对团队共享系统数据库自行迁移。
|
||||
@ -135,10 +141,10 @@ docker compose -f docker-compose.local.yml exec -u www-data app php artisan app:
|
||||
docker compose -f docker-compose.local.yml exec -u www-data app php artisan test --do-not-cache-result
|
||||
|
||||
# 停止容器,但保留本地数据
|
||||
docker compose -f docker-compose.local.yml stop
|
||||
docker compose -f docker-compose.local.yml --profile dev stop
|
||||
|
||||
# 再次启动
|
||||
docker compose -f docker-compose.local.yml start
|
||||
docker compose -f docker-compose.local.yml up -d app mysql
|
||||
```
|
||||
|
||||
不要执行 `docker compose down -v`、删除数据库卷或强制迁移。确需重置本地临时库时,先确认不会影响当前系统数据库配置并找负责人或 Codex处理。
|
||||
@ -147,7 +153,7 @@ docker compose -f docker-compose.local.yml start
|
||||
|
||||
- PHP、配置、模块、页面模板和路由目录已经挂载到容器;开发环境关闭 PHP OPcache 和 Blade 编译缓存,刷新浏览器即可加载最新源码,无需重启 PHP 服务;
|
||||
- 开发环境启动时只执行 `optimize:clear`,不会生成 Laravel 的配置、路由或视图缓存;生产环境仍保留原有缓存构建机制;
|
||||
- 本地 Compose 会同时启动 `frontend` watcher。修改 `resources/assets` 下的 Vue、JavaScript 或 SCSS 后,Laravel Mix 会通过轮询自动重新编译,Apache 使用共享静态资源卷提供最新文件;浏览器刷新即可看到结果。
|
||||
- 普通初始化只启动 PHP 和 MySQL,前端自动编译通过 `dev` profile 按需启动,见下一节。
|
||||
- 如果 watcher 构建失败,查看 `docker compose -f docker-compose.local.yml logs -f frontend`;修复源码后它会继续监听并重新编译。
|
||||
- Composer 依赖、前端依赖、Dockerfile 或构建资源发生变化时,重新执行 `bash deploy/local-init.sh`,脚本会自动重建;
|
||||
- 修改 `runtime/.env` 后,执行:
|
||||
@ -157,7 +163,31 @@ docker compose -f docker-compose.local.yml restart app
|
||||
docker compose -f docker-compose.local.yml exec -u www-data app php artisan optimize:clear
|
||||
```
|
||||
|
||||
停止本地环境时,`app`、`frontend` 和 `mysql` 会一起停止;再次运行初始化脚本会恢复 PHP 服务和前端 watcher。
|
||||
停止本地环境时保留数据卷;再次运行初始化脚本会恢复 PHP 和 MySQL,并停止已有的前端 watcher。
|
||||
|
||||
## 前端自动编译与空闲 CPU
|
||||
|
||||
使用 Docker Compose 2.32 或更新版本。源码仍在 Windows 的项目目录编辑,Compose Watch 使用宿主机文件事件,将 `resources/assets`、`resources/views` 和 `resources/lang` 的变更同步到前端容器的 Linux 文件系统。Laravel Mix 在容器内使用 inotify;`node_modules` 留在镜像中,`public` 和 `storage` 保持现有 named volume。Webpack 不监听依赖、产物、存储和 vendor 目录。
|
||||
|
||||
```powershell
|
||||
# 网页开发:初始化并启动 PHP/MySQL,不启动前端 watcher
|
||||
bash deploy/local-init.sh
|
||||
|
||||
# 需要自动编译 Vue、JS、CSS 或模板中的 Tailwind 类名时,前台运行
|
||||
docker compose -f docker-compose.local.yml --profile dev up --watch frontend
|
||||
|
||||
# 结束前端开发:在上述终端按 Ctrl+C;也可以显式停止 watcher
|
||||
docker compose -f docker-compose.local.yml stop frontend
|
||||
|
||||
# 停止本地网页与 watcher,保留 MySQL 运行和全部数据卷
|
||||
docker compose -f docker-compose.local.yml stop app frontend
|
||||
```
|
||||
|
||||
首次启动会编译一次,之后只有源码变更才重新构建;Apache 通过共享的 `jiangling_public` 卷提供新产物,刷新浏览器即可使用。`frontend` 的重启策略是 `no`,不会随 Docker 重启自动运行。普通 `docker compose up -d` 不会启动 `dev` profile;初始化也不会留下旧的轮询 watcher。
|
||||
|
||||
Windows bind mount 经过 Docker Desktop/WSL2 的 9P 文件共享。高频 poll 会反复请求文件元数据,即使没有编辑也会使宿主机 `dllhost.exe` 中的 `vp9fs.dll` 和 `vmmemWSL` 持续占用 CPU。默认 watcher 因此不再使用 poll;手动兼容命令 `npm run watch-poll` 保留为 5 秒间隔,不作为 Windows 的日常开发入口。
|
||||
|
||||
变更依赖、Webpack/Tailwind 配置或切换分支后,结束 watch 会话并运行 `bash deploy/local-init.sh`,再启动前端自动编译。原生监听与同步只用于本地开发,不改变生产 Compose 或正式构建流程。
|
||||
|
||||
## 相关文档
|
||||
|
||||
|
||||
@ -19,6 +19,8 @@ Codex 的接入验收不能只回答“成功”或“失败”,必须逐个
|
||||
|
||||
完整步骤和排错说明见 [LOCAL_DEPLOY.md](LOCAL_DEPLOY.md)。需要在另一台电脑继续开发时,按 [新电脑开发接续指南](docs/新电脑开发接续指南.md) 操作;所有 Markdown 文档的入口见 [文档索引](docs/README.md)。
|
||||
|
||||
前端自动编译按需运行 `docker compose -f docker-compose.local.yml --profile dev up --watch frontend`。Windows 源码通过文件事件同步到容器内的 Linux 文件系统,再由 Laravel Mix 原生监听;不要对 Windows bind mount 目录开启高频轮询,它会持续扫描 9P 文件共享并占用宿主机 CPU。日常仅启动网页时不运行 watcher,具体启停命令见 [本地开发说明](LOCAL_DEPLOY.md#前端自动编译与空闲-cpu)。
|
||||
|
||||
## 数据库边界
|
||||
|
||||
- 本机 MySQL 只负责第一次启动和临时登录,不是团队业务数据源。
|
||||
|
||||
28
app/Business/ActualTax/ActualTaxPageData.php
Normal file
28
app/Business/ActualTax/ActualTaxPageData.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\ActualTax;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ActualTaxPageData
|
||||
{
|
||||
public function page(Request $request): array
|
||||
{
|
||||
$columns = array_values((array) config('actual_tax.columns', []));
|
||||
$groups = [];
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$label = (string) ($column['group'] ?? '其他');
|
||||
$groups[$label] ??= ['label' => $label, 'columns' => []];
|
||||
$groups[$label]['columns'][] = $column;
|
||||
}
|
||||
|
||||
return [
|
||||
'view' => 'business.pages.company-management.actual-tax',
|
||||
'actualTax' => app(ActualTaxRepository::class)->page($request),
|
||||
'actualTaxColumns' => $columns,
|
||||
'actualTaxGroups' => array_values($groups),
|
||||
'actualTaxSource' => (array) config('actual_tax.source', []),
|
||||
];
|
||||
}
|
||||
}
|
||||
234
app/Business/ActualTax/ActualTaxRepository.php
Normal file
234
app/Business/ActualTax/ActualTaxRepository.php
Normal file
@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\ActualTax;
|
||||
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class ActualTaxRepository
|
||||
{
|
||||
public const TABLE = ActualTaxWorkbookImporter::TABLE;
|
||||
|
||||
public const PER_PAGE = 50;
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
|
||||
public function ready(): bool
|
||||
{
|
||||
return Schema::connection($this->connection->getName())->hasTable(self::TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* rows:LengthAwarePaginator,
|
||||
* filters:array<string,string>,
|
||||
* options:array<string,array<int,mixed>>,
|
||||
* summary:array<string,int|float|null>,
|
||||
* imported_at:mixed,
|
||||
* source_file:?string,
|
||||
* ready:bool
|
||||
* }
|
||||
*/
|
||||
public function page(Request $request): array
|
||||
{
|
||||
$filters = $this->filters($request);
|
||||
|
||||
if (! $this->ready()) {
|
||||
return [
|
||||
'rows' => new Paginator([], 0, self::PER_PAGE, 1, [
|
||||
'path' => $request->url(),
|
||||
'query' => $request->query(),
|
||||
]),
|
||||
'filters' => $filters,
|
||||
'options' => $this->emptyOptions(),
|
||||
'summary' => $this->emptySummary(),
|
||||
'imported_at' => null,
|
||||
'source_file' => null,
|
||||
'ready' => false,
|
||||
];
|
||||
}
|
||||
|
||||
$query = $this->filteredQuery($filters);
|
||||
$summary = $this->summary($query);
|
||||
$sortable = array_values(array_map(
|
||||
static fn (array $column): string => (string) $column['field'],
|
||||
array_filter(
|
||||
(array) config('actual_tax.columns', []),
|
||||
static fn (array $column): bool => ($column['sortable'] ?? true) !== false,
|
||||
),
|
||||
));
|
||||
$sort = (string) $request->query('sort', '');
|
||||
$sort = in_array($sort, $sortable, true) ? $sort : '';
|
||||
$direction = strtolower((string) $request->query('direction', 'asc')) === 'desc' ? 'desc' : 'asc';
|
||||
|
||||
if ($sort !== '') {
|
||||
$query->orderBy($sort, $direction);
|
||||
} else {
|
||||
$query->orderByDesc('period')->orderBy('sort_order');
|
||||
}
|
||||
$query->orderBy('id');
|
||||
|
||||
$rows = $query->paginate(
|
||||
self::PER_PAGE,
|
||||
['*'],
|
||||
'page',
|
||||
max((int) $request->query('page', 1), 1),
|
||||
)->withQueryString();
|
||||
|
||||
$latest = $this->connection->table(self::TABLE)
|
||||
->orderByDesc('imported_at')
|
||||
->first(['imported_at', 'source_file']);
|
||||
|
||||
return [
|
||||
'rows' => $rows,
|
||||
'filters' => $filters,
|
||||
'options' => $this->filterOptions(),
|
||||
'summary' => $summary,
|
||||
'imported_at' => $latest?->imported_at,
|
||||
'source_file' => $latest?->source_file,
|
||||
'ready' => true,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
$period = trim((string) $request->query('period', ''));
|
||||
if (preg_match('/^\d{6}$/', $period) !== 1) {
|
||||
$period = '';
|
||||
}
|
||||
|
||||
return [
|
||||
'period' => $period,
|
||||
'type' => $this->filterText($request->query('type'), 16),
|
||||
'region' => $this->filterText($request->query('region'), 16),
|
||||
'taxpayer_type' => $this->filterText($request->query('taxpayer_type'), 32),
|
||||
'accounting_company' => $this->filterText($request->query('accounting_company'), 191),
|
||||
'contact_person' => $this->filterText($request->query('contact_person'), 64),
|
||||
'company_name' => $this->filterText($request->query('company_name'), 191),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string> $filters
|
||||
*/
|
||||
private function filteredQuery(array $filters): Builder
|
||||
{
|
||||
$query = $this->connection->table(self::TABLE);
|
||||
|
||||
foreach (['period', 'type', 'region', 'taxpayer_type', 'accounting_company', 'contact_person'] as $field) {
|
||||
if (($filters[$field] ?? '') !== '') {
|
||||
$query->where($field, $filters[$field]);
|
||||
}
|
||||
}
|
||||
|
||||
if (($filters['company_name'] ?? '') !== '') {
|
||||
$query->where(
|
||||
'company_name',
|
||||
'like',
|
||||
'%' . addcslashes($filters['company_name'], '%_\\') . '%',
|
||||
);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,int|float|null>
|
||||
*/
|
||||
private function summary(Builder $query): array
|
||||
{
|
||||
$aggregate = (clone $query)
|
||||
->selectRaw('COUNT(*) AS records')
|
||||
->selectRaw('COUNT(DISTINCT company_name) AS companies')
|
||||
->selectRaw('COALESCE(SUM(total_revenue), 0) AS total_revenue')
|
||||
->selectRaw('COALESCE(SUM(total_tax_paid), 0) AS total_tax_paid')
|
||||
->first();
|
||||
|
||||
$revenue = round((float) ($aggregate->total_revenue ?? 0), 2);
|
||||
$tax = round((float) ($aggregate->total_tax_paid ?? 0), 2);
|
||||
|
||||
return [
|
||||
'records' => (int) ($aggregate->records ?? 0),
|
||||
'companies' => (int) ($aggregate->companies ?? 0),
|
||||
'total_revenue' => $revenue,
|
||||
'total_tax_paid' => $tax,
|
||||
'tax_burden_rate' => $revenue > 0 ? $tax / $revenue : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,array<int,mixed>>
|
||||
*/
|
||||
private function filterOptions(): array
|
||||
{
|
||||
$options = [];
|
||||
foreach ([
|
||||
'period',
|
||||
'type',
|
||||
'region',
|
||||
'taxpayer_type',
|
||||
'accounting_company',
|
||||
'contact_person',
|
||||
] as $field) {
|
||||
$direction = $field === 'period' ? 'desc' : 'asc';
|
||||
$options[$field] = $this->connection->table(self::TABLE)
|
||||
->whereNotNull($field)
|
||||
->where($field, '<>', '')
|
||||
->distinct()
|
||||
->orderBy($field, $direction)
|
||||
->pluck($field)
|
||||
->all();
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,array<int,mixed>>
|
||||
*/
|
||||
private function emptyOptions(): array
|
||||
{
|
||||
return [
|
||||
'period' => [],
|
||||
'type' => [],
|
||||
'region' => [],
|
||||
'taxpayer_type' => [],
|
||||
'accounting_company' => [],
|
||||
'contact_person' => [],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,int|float|null>
|
||||
*/
|
||||
private function emptySummary(): array
|
||||
{
|
||||
return [
|
||||
'records' => 0,
|
||||
'companies' => 0,
|
||||
'total_revenue' => 0.0,
|
||||
'total_tax_paid' => 0.0,
|
||||
'tax_burden_rate' => null,
|
||||
];
|
||||
}
|
||||
|
||||
private function filterText(mixed $value, int $limit): string
|
||||
{
|
||||
return mb_substr(trim((string) $value), 0, $limit);
|
||||
}
|
||||
}
|
||||
733
app/Business/ActualTax/ActualTaxWorkbookImporter.php
Normal file
733
app/Business/ActualTax/ActualTaxWorkbookImporter.php
Normal file
@ -0,0 +1,733 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\ActualTax;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
use RuntimeException;
|
||||
use XMLReader;
|
||||
|
||||
class ActualTaxWorkbookImporter
|
||||
{
|
||||
public const TABLE = 'business_actual_tax_records';
|
||||
|
||||
private const HEADER_ROWS = 3;
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
|
||||
public function ready(): bool
|
||||
{
|
||||
return Schema::connection($this->connection->getName())->hasTable(self::TABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{imported:int,skipped:int,source_file:string}
|
||||
*/
|
||||
public function import(string $path, ?string $sourceName = null): array
|
||||
{
|
||||
$realPath = realpath($path);
|
||||
if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) {
|
||||
throw new RuntimeException('实际税金表文件不存在或不可读:' . $path);
|
||||
}
|
||||
|
||||
if (! $this->ready()) {
|
||||
throw new RuntimeException('实际税金数据表尚未创建,请先执行数据库迁移。');
|
||||
}
|
||||
|
||||
[$rows, $skipped] = $this->readRows($realPath);
|
||||
if ($rows === []) {
|
||||
throw new RuntimeException('文件内没有可导入的实际税金数据。');
|
||||
}
|
||||
|
||||
$this->assertUniqueRows($rows);
|
||||
|
||||
$now = Carbon::now();
|
||||
$sourceFile = basename($sourceName ?: $realPath);
|
||||
|
||||
$this->connection->transaction(function () use ($rows, $now, $sourceFile): void {
|
||||
// 链接中的“代办对接表”是完整台账,每次成功导入后整份替换。
|
||||
$this->connection->table(self::TABLE)->delete();
|
||||
|
||||
foreach (array_chunk($rows, 200) as $chunk) {
|
||||
$this->connection->table(self::TABLE)->insert(array_map(
|
||||
static fn (array $row): array => $row + [
|
||||
'source_file' => $sourceFile,
|
||||
'imported_at' => $now,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
],
|
||||
$chunk,
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
return [
|
||||
'imported' => count($rows),
|
||||
'skipped' => $skipped,
|
||||
'source_file' => $sourceFile,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:list<array<string,mixed>>,1:int}
|
||||
*/
|
||||
private function readRows(string $path): array
|
||||
{
|
||||
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
|
||||
|
||||
return match ($extension) {
|
||||
'csv' => $this->readCsv($path),
|
||||
'xlsx' => $this->readXlsxStreaming($path),
|
||||
default => $this->readSpreadsheet($path),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:list<array<string,mixed>>,1:int}
|
||||
*/
|
||||
private function readCsv(string $path): array
|
||||
{
|
||||
$handle = fopen($path, 'rb');
|
||||
if ($handle === false) {
|
||||
throw new RuntimeException('无法读取实际税金 CSV 文件。');
|
||||
}
|
||||
|
||||
try {
|
||||
$header = fgetcsv($handle);
|
||||
if ($header === false) {
|
||||
throw new RuntimeException('实际税金 CSV 文件没有表头。');
|
||||
}
|
||||
|
||||
foreach ($header as $index => $heading) {
|
||||
$heading = trim((string) preg_replace('/^\xEF\xBB\xBF/', '', (string) $heading));
|
||||
if (str_starts_with($heading, '"') && str_ends_with($heading, '"')) {
|
||||
$heading = substr($heading, 1, -1);
|
||||
}
|
||||
$header[$index] = $heading;
|
||||
}
|
||||
$columnMap = $this->flatColumnMap($header);
|
||||
$rows = [];
|
||||
$skipped = 0;
|
||||
$line = 1;
|
||||
|
||||
while (($lineValues = fgetcsv($handle)) !== false) {
|
||||
$line++;
|
||||
$row = $this->normalizeFlatRow($lineValues, $columnMap, $line, $rows);
|
||||
if ($row === null) {
|
||||
$skipped++;
|
||||
} elseif ($row !== []) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return [$rows, $skipped];
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* XLSX 使用 XMLReader 按行读取,避免把整份宽表同时装入内存。
|
||||
*
|
||||
* @return array{0:list<array<string,mixed>>,1:int}
|
||||
*/
|
||||
private function readXlsxStreaming(string $path): array
|
||||
{
|
||||
$zip = new \ZipArchive();
|
||||
if ($zip->open($path) !== true) {
|
||||
throw new RuntimeException('无法打开实际税金 XLSX 文件。');
|
||||
}
|
||||
|
||||
$sheetTemp = null;
|
||||
|
||||
try {
|
||||
$sheetPath = $this->resolveXlsxSheetPath($zip);
|
||||
$sharedStrings = $this->readXlsxSharedStrings($zip);
|
||||
$sheetTemp = $this->extractZipEntry($zip, $sheetPath);
|
||||
|
||||
$reader = new XMLReader();
|
||||
if (! $reader->open($sheetTemp, null, LIBXML_NONET | LIBXML_COMPACT)) {
|
||||
throw new RuntimeException('无法读取实际税金 XLSX 工作表。');
|
||||
}
|
||||
|
||||
$columns = (array) config('actual_tax.columns', []);
|
||||
$headerRows = [];
|
||||
$rows = [];
|
||||
$skipped = 0;
|
||||
$lastRowNumber = 0;
|
||||
$headerValidated = false;
|
||||
|
||||
try {
|
||||
while ($reader->read()) {
|
||||
if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rowNumber = (int) ($reader->getAttribute('r') ?: ($lastRowNumber + 1));
|
||||
$lastRowNumber = $rowNumber;
|
||||
$line = $this->parseXlsxRow($reader->readOuterXml(), $sharedStrings);
|
||||
|
||||
if ($rowNumber <= self::HEADER_ROWS) {
|
||||
$headerRows[$rowNumber] = $line;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $headerValidated) {
|
||||
$this->validateStreamingHeader($headerRows);
|
||||
$headerValidated = true;
|
||||
}
|
||||
|
||||
$values = [];
|
||||
foreach ($columns as $column) {
|
||||
$sourceIndex = (int) ($column['source_index'] ?? -1);
|
||||
if ($sourceIndex < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$values[(string) $column['field']] = $this->normalizeValue(
|
||||
$line[$sourceIndex] ?? null,
|
||||
(string) ($column['type'] ?? 'text'),
|
||||
(string) ($column['label'] ?? $column['field']),
|
||||
$rowNumber,
|
||||
);
|
||||
}
|
||||
|
||||
$row = $this->finalizeRow($values, $rowNumber, count($rows) + 1);
|
||||
if ($row === null) {
|
||||
$skipped++;
|
||||
} else {
|
||||
$rows[] = $row;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$reader->close();
|
||||
}
|
||||
|
||||
if (! $headerValidated) {
|
||||
$this->validateStreamingHeader($headerRows);
|
||||
}
|
||||
|
||||
return [$rows, $skipped];
|
||||
} finally {
|
||||
if ($sheetTemp !== null && is_file($sheetTemp)) {
|
||||
@unlink($sheetTemp);
|
||||
}
|
||||
$zip->close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function readXlsxSharedStrings(\ZipArchive $zip): array
|
||||
{
|
||||
$entry = 'xl/sharedStrings.xml';
|
||||
if ($zip->locateName($entry) === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$temp = $this->extractZipEntry($zip, $entry);
|
||||
$reader = new XMLReader();
|
||||
|
||||
if (! $reader->open($temp, null, LIBXML_NONET | LIBXML_COMPACT)) {
|
||||
@unlink($temp);
|
||||
throw new RuntimeException('无法读取实际税金 XLSX 共享字符串。');
|
||||
}
|
||||
|
||||
$strings = [];
|
||||
|
||||
try {
|
||||
while ($reader->read()) {
|
||||
if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'si') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$node = simplexml_load_string(
|
||||
$reader->readOuterXml(),
|
||||
\SimpleXMLElement::class,
|
||||
LIBXML_NONET | LIBXML_COMPACT,
|
||||
);
|
||||
if ($node === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$texts = $node->xpath('.//*[local-name()="t" and not(ancestor::*[local-name()="rPh"])]') ?: [];
|
||||
$strings[] = implode('', array_map(
|
||||
static fn (\SimpleXMLElement $text): string => (string) $text,
|
||||
$texts,
|
||||
));
|
||||
}
|
||||
} finally {
|
||||
$reader->close();
|
||||
@unlink($temp);
|
||||
}
|
||||
|
||||
return $strings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $sharedStrings
|
||||
* @return list<string|null>
|
||||
*/
|
||||
private function parseXlsxRow(string $rowXml, array $sharedStrings): array
|
||||
{
|
||||
$line = array_fill(0, 79, null);
|
||||
$row = simplexml_load_string(
|
||||
$rowXml,
|
||||
\SimpleXMLElement::class,
|
||||
LIBXML_NONET | LIBXML_COMPACT,
|
||||
);
|
||||
|
||||
if ($row === false) {
|
||||
return $line;
|
||||
}
|
||||
|
||||
$cells = $row->xpath('./*[local-name()="c"]') ?: [];
|
||||
$nextColumn = 0;
|
||||
|
||||
foreach ($cells as $cell) {
|
||||
$reference = (string) ($cell['r'] ?? '');
|
||||
$columnIndex = $nextColumn;
|
||||
|
||||
if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) === 1) {
|
||||
$columnIndex = Coordinate::columnIndexFromString(strtoupper($matches[1])) - 1;
|
||||
}
|
||||
$nextColumn = $columnIndex + 1;
|
||||
|
||||
if ($columnIndex >= count($line)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = (string) ($cell['t'] ?? '');
|
||||
$value = '';
|
||||
|
||||
if ($type === 'inlineStr') {
|
||||
$texts = $cell->xpath('.//*[local-name()="t" and not(ancestor::*[local-name()="rPh"])]') ?: [];
|
||||
$value = implode('', array_map(
|
||||
static fn (\SimpleXMLElement $text): string => (string) $text,
|
||||
$texts,
|
||||
));
|
||||
} else {
|
||||
$values = $cell->xpath('./*[local-name()="v"]') ?: [];
|
||||
$value = isset($values[0]) ? (string) $values[0] : '';
|
||||
}
|
||||
|
||||
if ($type === 's') {
|
||||
$value = $sharedStrings[(int) $value] ?? '';
|
||||
}
|
||||
|
||||
$line[$columnIndex] = $value === '' ? null : $value;
|
||||
}
|
||||
|
||||
return $line;
|
||||
}
|
||||
|
||||
private function resolveXlsxSheetPath(\ZipArchive $zip): string
|
||||
{
|
||||
$workbookXml = $zip->getFromName('xl/workbook.xml');
|
||||
if ($workbookXml === false) {
|
||||
throw new RuntimeException('实际税金 XLSX 缺少 workbook.xml。');
|
||||
}
|
||||
|
||||
$workbook = simplexml_load_string(
|
||||
$workbookXml,
|
||||
\SimpleXMLElement::class,
|
||||
LIBXML_NONET | LIBXML_COMPACT,
|
||||
);
|
||||
if ($workbook === false) {
|
||||
throw new RuntimeException('实际税金 XLSX 工作簿结构无法解析。');
|
||||
}
|
||||
|
||||
$configuredSheet = (string) config('actual_tax.source.sheet', '代办对接表');
|
||||
$sheetNode = null;
|
||||
foreach ($workbook->xpath('//*[local-name()="sheet"]') ?: [] as $candidate) {
|
||||
if ((string) ($candidate['name'] ?? '') === $configuredSheet) {
|
||||
$sheetNode = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (! $sheetNode instanceof \SimpleXMLElement) {
|
||||
throw new RuntimeException('工作簿中未找到“' . $configuredSheet . '”工作表。');
|
||||
}
|
||||
|
||||
$relationshipNamespace = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
|
||||
$relationshipId = (string) ($sheetNode->attributes($relationshipNamespace)['id'] ?? '');
|
||||
$relationshipsXml = $zip->getFromName('xl/_rels/workbook.xml.rels');
|
||||
if ($relationshipId === '' || $relationshipsXml === false) {
|
||||
throw new RuntimeException('实际税金 XLSX 缺少工作表关系信息。');
|
||||
}
|
||||
|
||||
$relationships = simplexml_load_string(
|
||||
$relationshipsXml,
|
||||
\SimpleXMLElement::class,
|
||||
LIBXML_NONET | LIBXML_COMPACT,
|
||||
);
|
||||
if ($relationships === false) {
|
||||
throw new RuntimeException('实际税金 XLSX 工作表关系无法解析。');
|
||||
}
|
||||
|
||||
foreach ($relationships->xpath('//*[local-name()="Relationship"]') ?: [] as $relationship) {
|
||||
if ((string) ($relationship['Id'] ?? '') !== $relationshipId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$target = ltrim((string) ($relationship['Target'] ?? ''), '/');
|
||||
if ($target === '') {
|
||||
break;
|
||||
}
|
||||
|
||||
return str_starts_with($target, 'xl/') ? $target : 'xl/' . $target;
|
||||
}
|
||||
|
||||
throw new RuntimeException('未找到实际税金 XLSX 工作表文件。');
|
||||
}
|
||||
|
||||
private function extractZipEntry(\ZipArchive $zip, string $entry): string
|
||||
{
|
||||
$source = $zip->getStream($entry);
|
||||
if ($source === false) {
|
||||
throw new RuntimeException('无法读取实际税金 XLSX 文件中的 ' . $entry . '。');
|
||||
}
|
||||
|
||||
$temp = tempnam(sys_get_temp_dir(), 'actual-tax-xlsx-');
|
||||
if ($temp === false) {
|
||||
fclose($source);
|
||||
throw new RuntimeException('无法创建实际税金 XLSX 临时文件。');
|
||||
}
|
||||
|
||||
$destination = fopen($temp, 'wb');
|
||||
if ($destination === false) {
|
||||
fclose($source);
|
||||
@unlink($temp);
|
||||
throw new RuntimeException('无法写入实际税金 XLSX 临时文件。');
|
||||
}
|
||||
|
||||
stream_copy_to_stream($source, $destination);
|
||||
fclose($source);
|
||||
fclose($destination);
|
||||
|
||||
return $temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,list<string|null>> $headerRows
|
||||
*/
|
||||
private function validateStreamingHeader(array $headerRows): void
|
||||
{
|
||||
$required = [
|
||||
0 => '期间',
|
||||
4 => '公司名称',
|
||||
7 => '真实业绩(含税)',
|
||||
24 => '合计收入',
|
||||
45 => '税金合计',
|
||||
78 => '备注',
|
||||
];
|
||||
|
||||
foreach ($required as $index => $label) {
|
||||
if ($this->normalizeHeader($headerRows[1][$index] ?? '') !== $this->normalizeHeader($label)) {
|
||||
throw new RuntimeException('实际税金 XLSX 表头与“代办对接表”契约不一致。');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:list<array<string,mixed>>,1:int}
|
||||
*/
|
||||
private function readSpreadsheet(string $path): array
|
||||
{
|
||||
$spreadsheet = IOFactory::load($path);
|
||||
$configuredSheet = (string) config('actual_tax.source.sheet', '代办对接表');
|
||||
$sheet = $spreadsheet->getSheetByName($configuredSheet);
|
||||
|
||||
if (! $sheet instanceof Worksheet) {
|
||||
throw new RuntimeException('工作簿中未找到“' . $configuredSheet . '”工作表。');
|
||||
}
|
||||
|
||||
$grid = $sheet->toArray(null, true, false, false);
|
||||
if ($grid === []) {
|
||||
throw new RuntimeException('“' . $configuredSheet . '”工作表为空。');
|
||||
}
|
||||
|
||||
if ($this->hasThreeRowHeader($grid)) {
|
||||
return $this->readThreeRowHeader($grid);
|
||||
}
|
||||
|
||||
$columnMap = $this->flatColumnMap($grid[0] ?? []);
|
||||
$rows = [];
|
||||
$skipped = 0;
|
||||
|
||||
foreach (array_slice($grid, 1, null, true) as $index => $lineValues) {
|
||||
$row = $this->normalizeFlatRow($lineValues, $columnMap, (int) $index + 1, $rows);
|
||||
if ($row === null) {
|
||||
$skipped++;
|
||||
} elseif ($row !== []) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return [$rows, $skipped];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<list<mixed>> $grid
|
||||
* @return array{0:list<array<string,mixed>>,1:int}
|
||||
*/
|
||||
private function readThreeRowHeader(array $grid): array
|
||||
{
|
||||
$columns = (array) config('actual_tax.columns', []);
|
||||
$rows = [];
|
||||
$skipped = 0;
|
||||
|
||||
foreach (array_slice($grid, self::HEADER_ROWS, null, true) as $index => $lineValues) {
|
||||
$sourceRow = (int) $index + 1;
|
||||
$values = [];
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$sourceIndex = (int) ($column['source_index'] ?? -1);
|
||||
if ($sourceIndex < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$values[(string) $column['field']] = $this->normalizeValue(
|
||||
$lineValues[$sourceIndex] ?? null,
|
||||
(string) ($column['type'] ?? 'text'),
|
||||
(string) ($column['label'] ?? $column['field']),
|
||||
$sourceRow,
|
||||
);
|
||||
}
|
||||
|
||||
$row = $this->finalizeRow($values, $sourceRow, count($rows) + 1);
|
||||
if ($row === null) {
|
||||
$skipped++;
|
||||
} else {
|
||||
$rows[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return [$rows, $skipped];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $values
|
||||
* @param array<int,array<string,mixed>> $columnMap
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
private function normalizeFlatRow(
|
||||
array $values,
|
||||
array $columnMap,
|
||||
int $sourceRow,
|
||||
array $rows,
|
||||
): ?array {
|
||||
$normalized = [];
|
||||
|
||||
foreach ($columnMap as $index => $column) {
|
||||
$normalized[(string) $column['field']] = $this->normalizeValue(
|
||||
$values[$index] ?? null,
|
||||
(string) ($column['type'] ?? 'text'),
|
||||
(string) ($column['label'] ?? $column['field']),
|
||||
$sourceRow,
|
||||
);
|
||||
}
|
||||
|
||||
return $this->finalizeRow($normalized, $sourceRow, count($rows) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $values
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
private function finalizeRow(array $values, int $sourceRow, int $sortOrder): ?array
|
||||
{
|
||||
if (collect($values)->every(static fn ($value): bool => $value === null || $value === '')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$period = trim((string) ($values['period'] ?? ''));
|
||||
$type = trim((string) ($values['type'] ?? ''));
|
||||
$companyName = trim((string) ($values['company_name'] ?? ''));
|
||||
|
||||
if (preg_match('/^\d{6}$/', $period) !== 1) {
|
||||
throw new RuntimeException("第 {$sourceRow} 行期间无效,应为 YYYYMM。");
|
||||
}
|
||||
if ($companyName === '') {
|
||||
throw new RuntimeException("第 {$sourceRow} 行缺少公司名称。");
|
||||
}
|
||||
|
||||
$values['period'] = $period;
|
||||
$values['type'] = $type;
|
||||
$values['company_name'] = $companyName;
|
||||
$values['source_key'] = hash('sha256', implode('|', [$period, $type, $companyName]));
|
||||
$values['source_row'] = $sourceRow;
|
||||
$values['sort_order'] = $sortOrder;
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $rows
|
||||
*/
|
||||
private function assertUniqueRows(array $rows): void
|
||||
{
|
||||
$seen = [];
|
||||
foreach ($rows as $row) {
|
||||
$key = (string) $row['source_key'];
|
||||
if (isset($seen[$key])) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'第 %d 行与第 %d 行的期间、类型、公司名称重复。',
|
||||
$seen[$key],
|
||||
(int) $row['source_row'],
|
||||
));
|
||||
}
|
||||
|
||||
$seen[$key] = (int) $row['source_row'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $header
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
private function flatColumnMap(array $header): array
|
||||
{
|
||||
$lookup = [];
|
||||
foreach ((array) config('actual_tax.columns', []) as $column) {
|
||||
$lookup[$this->normalizeHeader($column['field'] ?? '')] = $column;
|
||||
$lookup[$this->normalizeHeader($column['label'] ?? '')] = $column;
|
||||
}
|
||||
|
||||
$map = [];
|
||||
foreach ($header as $index => $heading) {
|
||||
$field = $lookup[$this->normalizeHeader($heading)] ?? null;
|
||||
if ($field !== null) {
|
||||
$map[$index] = $field;
|
||||
}
|
||||
}
|
||||
|
||||
$required = ['period', 'type', 'company_name'];
|
||||
$mappedFields = array_column($map, 'field');
|
||||
$missing = array_values(array_diff($required, $mappedFields));
|
||||
if ($missing !== []) {
|
||||
throw new RuntimeException('文件表头缺少字段:' . implode('、', $missing) . '。');
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<list<mixed>> $grid
|
||||
*/
|
||||
private function hasThreeRowHeader(array $grid): bool
|
||||
{
|
||||
if (count($grid) < self::HEADER_ROWS + 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$required = [
|
||||
0 => '期间',
|
||||
4 => '公司名称',
|
||||
7 => '真实业绩(含税)',
|
||||
24 => '合计收入',
|
||||
45 => '税金合计',
|
||||
78 => '备注',
|
||||
];
|
||||
|
||||
foreach ($required as $index => $label) {
|
||||
if ($this->normalizeHeader($grid[0][$index] ?? '') !== $this->normalizeHeader($label)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return count($grid[0] ?? []) >= 79;
|
||||
}
|
||||
|
||||
private function normalizeValue(
|
||||
mixed $value,
|
||||
string $type,
|
||||
string $label,
|
||||
int $sourceRow,
|
||||
): mixed {
|
||||
if ($value === null || (is_string($value) && trim($value) === '')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// WPS/Excel 错误值通过内部负数错误码返回,例如 #DIV/0!、#VALUE!。
|
||||
$errorCandidate = is_int($value) || is_float($value)
|
||||
? (float) $value
|
||||
: (is_numeric(str_replace([',', ',', ' '], '', (string) $value))
|
||||
? (float) str_replace([',', ',', ' '], '', (string) $value)
|
||||
: null);
|
||||
if ($errorCandidate !== null
|
||||
&& $errorCandidate <= -2146820000
|
||||
&& $errorCandidate >= -2146830000) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (in_array($type, ['text', 'status', 'mixed_amount'], true)) {
|
||||
if (is_float($value) && floor($value) === $value) {
|
||||
return (string) (int) $value;
|
||||
}
|
||||
|
||||
return trim((string) $value);
|
||||
}
|
||||
|
||||
if (is_int($value) || is_float($value)) {
|
||||
return $this->decimal((float) $value, $type === 'ratio' ? 8 : 2);
|
||||
}
|
||||
|
||||
$text = trim((string) $value);
|
||||
if ($text === '' || in_array($text, ['/', '—', '-', 'N/A'], true) || str_starts_with($text, '#')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$isPercent = str_contains($text, '%');
|
||||
$normalized = str_replace([',', ',', '¥', '¥', '%', ' '], '', $text);
|
||||
if (! is_numeric($normalized)) {
|
||||
throw new RuntimeException("第 {$sourceRow} 行“{$label}”不是有效数字:{$text}");
|
||||
}
|
||||
|
||||
$number = (float) $normalized;
|
||||
if ($type === 'ratio') {
|
||||
if ($isPercent) {
|
||||
$number /= 100;
|
||||
}
|
||||
|
||||
return $this->decimal($number, 8);
|
||||
}
|
||||
|
||||
return $this->decimal($number, $type === 'decimal' ? 2 : 2);
|
||||
}
|
||||
|
||||
private function decimal(float $value, int $precision): string
|
||||
{
|
||||
$formatted = rtrim(rtrim(number_format($value, $precision, '.', ''), '0'), '.');
|
||||
|
||||
return $formatted === '' || $formatted === '-' ? '0' : $formatted;
|
||||
}
|
||||
|
||||
private function normalizeHeader(mixed $value): string
|
||||
{
|
||||
if ($value === null || is_bool($value) || is_array($value)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return mb_strtolower(str_replace(
|
||||
['(', ')', ' ', ' ', '_', '-', "\n", "\r"],
|
||||
['(', ')', '', '', '', '', '', ''],
|
||||
trim((string) $value),
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -281,6 +281,50 @@ SQL);
|
||||
return $statement->fetchAll();
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function allSubjectReferences(int $companyId): array
|
||||
{
|
||||
$statement = $this->pdo()->prepare(
|
||||
'SELECT company_name, company_type, taxpayer_type, business_registration_type, company_status '
|
||||
. 'FROM company_plan_rows '
|
||||
. 'WHERE company_id = :company_id ORDER BY id'
|
||||
);
|
||||
$statement->execute([':company_id' => $companyId]);
|
||||
|
||||
return $statement->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务公司对账从公司盘点读取类型包含“服务公司”的主体。
|
||||
*
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function serviceCompanyRows(int $companyId): array
|
||||
{
|
||||
$statement = $this->pdo()->prepare(<<<'SQL'
|
||||
SELECT
|
||||
id,
|
||||
company_name,
|
||||
company_type,
|
||||
taxpayer_type,
|
||||
business_registration_type,
|
||||
unified_social_credit_code,
|
||||
company_status,
|
||||
sequence_no
|
||||
FROM company_plan_rows
|
||||
WHERE company_id = :company_id
|
||||
AND company_type IS NOT NULL
|
||||
AND TRIM(company_type) LIKE '%服务公司%'
|
||||
ORDER BY
|
||||
CASE WHEN sequence_no IS NULL THEN 1 ELSE 0 END,
|
||||
sequence_no,
|
||||
id
|
||||
SQL);
|
||||
$statement->execute([':company_id' => $companyId]);
|
||||
|
||||
return $statement->fetchAll();
|
||||
}
|
||||
|
||||
public function findForCompany(int $companyId, int $id): ?array
|
||||
{
|
||||
$statement = $this->pdo()->prepare(
|
||||
|
||||
@ -395,6 +395,18 @@ SQL);
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function allShopReferences(int $companyId): array
|
||||
{
|
||||
$statement = $this->pdo()->prepare(
|
||||
'SELECT shop_name, company_name, successor '
|
||||
. 'FROM company_plan_shops WHERE company_id = :company_id ORDER BY id'
|
||||
);
|
||||
$statement->execute([':company_id' => $companyId]);
|
||||
|
||||
return $statement->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个主体下的未完结店铺数量,用于主表徽章与跳转。
|
||||
*
|
||||
|
||||
@ -7,6 +7,7 @@ use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\LazyCollection;
|
||||
use Throwable;
|
||||
|
||||
/** Read the signed snapshot directly: no duplicate contracts, attachment copies or archive backfill. */
|
||||
@ -22,18 +23,9 @@ class CourierContractPageData
|
||||
'unknown' => '期限待核对',
|
||||
];
|
||||
|
||||
public function page(bool $includeRows = true): array
|
||||
public function page(bool $includeRows = true, string $partnerType = 'courier'): array
|
||||
{
|
||||
$search = mb_substr(trim((string) request()->query('contract_search', '')), 0, 255);
|
||||
$status = (string) request()->query('contract_status', '');
|
||||
$status = array_key_exists($status, self::STATUSES) ? $status : '';
|
||||
$from = $this->date(request()->query('contract_end_from'));
|
||||
$to = $this->date(request()->query('contract_end_to'));
|
||||
if ($from && $to && $from > $to) {
|
||||
[$from, $to] = [$to, $from];
|
||||
}
|
||||
$filters = ['contract_search' => $search, 'contract_status' => $status,
|
||||
'contract_end_from' => $from ?? '', 'contract_end_to' => $to ?? ''];
|
||||
$filters = $this->filters();
|
||||
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
|
||||
$page = max((int) request()->query('page', 1), 1);
|
||||
$options = ['path' => request()->url(), 'query' => request()->except('page')];
|
||||
@ -52,39 +44,14 @@ class CourierContractPageData
|
||||
}
|
||||
|
||||
$matched = [];
|
||||
$today = Carbon::today(config('app.timezone'));
|
||||
// Dates and partner types are encrypted. Stream bounded chunks instead of SQL JSON queries
|
||||
// or persisting a second, potentially stale copy of the signed business snapshot.
|
||||
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
|
||||
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
|
||||
->select(['id', 'company_id', 'business_no', 'courier_name', 'payload', 'document_type', 'status',
|
||||
'signed_pdf_path', 'certificate_path', 'archived_at', 'created_by', 'created_at'])
|
||||
->lazyById(250);
|
||||
foreach ($signatures as $signature) {
|
||||
$payload = $signature->archivedCourierContractPayload();
|
||||
if ($payload === null) {
|
||||
try {
|
||||
$signature->payload;
|
||||
} catch (Throwable) {
|
||||
$data['courierContractUnreadable']++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$row = $this->snapshot($signature, $payload, $today);
|
||||
$recordUnreadable = static function () use (&$data): void {
|
||||
$data['courierContractUnreadable']++;
|
||||
};
|
||||
foreach ($this->contractRows($partnerType, $recordUnreadable) as $row) {
|
||||
$data['courierContractCounts'][$row['status']]++;
|
||||
if (! $includeRows || ($status !== '' && $status !== $row['status'])) {
|
||||
continue;
|
||||
if ($includeRows && $this->matchesFilters($row, $filters)) {
|
||||
$matched[] = $row;
|
||||
}
|
||||
if (($from && (! $row['end_date'] || $row['end_date'] < $from))
|
||||
|| ($to && (! $row['end_date'] || $row['end_date'] > $to))) {
|
||||
continue;
|
||||
}
|
||||
if ($search !== '' && ! str_contains(mb_strtolower(implode(' ', [
|
||||
$row['courier_name'], $row['number'], $row['business_no'], $row['party_a'], $row['party_b'],
|
||||
])), mb_strtolower($search))) {
|
||||
continue;
|
||||
}
|
||||
$matched[] = $row;
|
||||
}
|
||||
if ($includeRows) {
|
||||
$priority = ['due' => 0, 'expired' => 1, 'unknown' => 2, 'active' => 3, 'upcoming' => 4];
|
||||
@ -113,6 +80,77 @@ class CourierContractPageData
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function exportRows(string $partnerType): iterable
|
||||
{
|
||||
$filters = $this->filters();
|
||||
$rows = LazyCollection::make(fn () => $this->contractRows($partnerType))
|
||||
->filter(fn (array $row): bool => $this->matchesFilters($row, $filters));
|
||||
foreach ($rows->chunk(250) as $chunk) {
|
||||
$owners = $partnerType === 'courier'
|
||||
? user_model_class()::query()->whereIn('id', $chunk->pluck('created_by')->filter()->unique()->all())->pluck('name', 'id')
|
||||
: [];
|
||||
foreach ($chunk as $row) {
|
||||
$row['creator'] = $owners[$row['created_by']] ?? '未记录';
|
||||
yield $row;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function filters(): array
|
||||
{
|
||||
$search = request()->query('contract_search');
|
||||
$search = is_string($search) ? mb_substr(trim($search), 0, 255) : '';
|
||||
$status = request()->query('contract_status');
|
||||
$status = is_string($status) && array_key_exists($status, self::STATUSES) ? $status : '';
|
||||
$from = $this->date(request()->query('contract_end_from'));
|
||||
$to = $this->date(request()->query('contract_end_to'));
|
||||
if ($from && $to && $from > $to) {
|
||||
[$from, $to] = [$to, $from];
|
||||
}
|
||||
return ['contract_search' => $search, 'contract_status' => $status,
|
||||
'contract_end_from' => $from ?? '', 'contract_end_to' => $to ?? ''];
|
||||
}
|
||||
|
||||
private function matchesFilters(array $row, array $filters): bool
|
||||
{
|
||||
$status = $filters['contract_status'];
|
||||
$from = $filters['contract_end_from'];
|
||||
$to = $filters['contract_end_to'];
|
||||
if (($status !== '' && $status !== $row['status'])
|
||||
|| ($from !== '' && (! $row['end_date'] || $row['end_date'] < $from))
|
||||
|| ($to !== '' && (! $row['end_date'] || $row['end_date'] > $to))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$search = $filters['contract_search'];
|
||||
return $search === '' || str_contains(mb_strtolower(implode(' ', [
|
||||
$row['courier_name'], $row['number'], $row['business_no'], $row['party_a'], $row['party_b'],
|
||||
])), mb_strtolower($search));
|
||||
}
|
||||
|
||||
private function contractRows(string $partnerType, ?callable $recordUnreadable = null): iterable
|
||||
{
|
||||
$today = Carbon::today(config('app.timezone'));
|
||||
// The dates and partner type live in encrypted snapshots.
|
||||
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
|
||||
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
|
||||
->select(['id', 'company_id', 'business_no', 'courier_name', 'payload', 'document_type', 'status',
|
||||
'signed_pdf_path', 'certificate_path', 'archived_at', 'created_by', 'created_at'])
|
||||
->lazyById(250);
|
||||
foreach ($signatures as $signature) {
|
||||
$payload = $signature->archivedContractPayload($partnerType);
|
||||
if ($payload !== null) {
|
||||
yield $this->snapshot($signature, $payload, $today);
|
||||
} elseif ($recordUnreadable !== null) {
|
||||
try {
|
||||
$signature->payload;
|
||||
} catch (Throwable) {
|
||||
$recordUnreadable();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function snapshot(CourierAgreementSignature $signature, array $payload, Carbon $today): array
|
||||
{
|
||||
$start = $this->date($payload['cooperation_start_date'] ?? null);
|
||||
|
||||
196
app/Business/CourierFreightFinancialSummary.php
Normal file
196
app/Business/CourierFreightFinancialSummary.php
Normal file
@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business;
|
||||
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
|
||||
/**
|
||||
* 财务经营分析表 › 快递运费按月、按店铺汇总。
|
||||
*
|
||||
* 每一行快递运费由「结算运费 + 其他附加费汇总 + 退件费」组成:
|
||||
* 结算运费 = 提供成本运费 + 运费差;三份快递应付快照都按交易单号匹配。
|
||||
* 同一交易单号的多条快照金额全部相加;基础运费多行也全部相加,
|
||||
* 但同一月份、同一交易单号的附加费用只挂一次,避免一条订单拆成多行后重复计入。
|
||||
*/
|
||||
class CourierFreightFinancialSummary
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DatabaseManager $databases,
|
||||
private readonly CourierPayableSummaryMap $summaries,
|
||||
) {}
|
||||
|
||||
public function version(int $companyId): int
|
||||
{
|
||||
return (int) cache()->get('courier-freight-financial-version:' . $companyId, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回仅包含有快递运费来源的月份。调用方据此区分「本月无数据」和「金额为 0」。
|
||||
*
|
||||
* @param list<string> $reportMonths YYYY-MM
|
||||
* @return array<string,array<string,float>> 月份 => [店铺 => 快递运费]
|
||||
*/
|
||||
public function monthlyStoreTotals(array $reportMonths, int $companyId): array
|
||||
{
|
||||
$reportMonths = array_values(array_unique(array_filter(
|
||||
$reportMonths,
|
||||
static fn (string $month): bool => preg_match('/^\d{4}-\d{2}$/', $month) === 1,
|
||||
)));
|
||||
$wantedMonths = array_fill_keys($reportMonths, true);
|
||||
if ($wantedMonths === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$cacheKey = 'courier-freight-financial-monthly:v1:'
|
||||
. $companyId . ':' . $this->version($companyId) . ':' . hash('sha256', implode(',', $reportMonths));
|
||||
|
||||
return cache()->remember($cacheKey, now()->addHour(), function () use (
|
||||
$companyId,
|
||||
$wantedMonths,
|
||||
$reportMonths,
|
||||
): array {
|
||||
// 先利用 (company_id, source) 索引找出目标月份对应的来源,
|
||||
// 避免在 100 万级明细上直接分组,也避免没有当月来源时仍扫描全表。
|
||||
$sources = $this->databases->connection()->table('courier_freight_rows')
|
||||
->where('company_id', $companyId)
|
||||
->whereNull('deleted_at')
|
||||
->distinct()
|
||||
->orderBy('source')
|
||||
->pluck('source')
|
||||
->map(static fn ($source): string => trim((string) $source))
|
||||
->filter()
|
||||
->values()
|
||||
->all();
|
||||
$matchingSources = [];
|
||||
foreach ($sources as $source) {
|
||||
$month = $this->sourceMonth($source, $reportMonths);
|
||||
if ($month !== null && isset($wantedMonths[$month])) {
|
||||
$matchingSources[$source] = true;
|
||||
}
|
||||
}
|
||||
if ($matchingSources === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->buildMonthlyStoreTotals($companyId, array_keys($wantedMonths), array_keys($matchingSources));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $reportMonths
|
||||
* @param list<string> $sources
|
||||
* @return array<string,array<string,float>>
|
||||
*/
|
||||
private function buildMonthlyStoreTotals(int $companyId, array $reportMonths, array $sources): array
|
||||
{
|
||||
$differences = $this->summaries->mapByMonth(
|
||||
$companyId,
|
||||
CourierPayableSummaryMap::PAGE_FREIGHT_DIFFERENCE,
|
||||
);
|
||||
$surcharges = $this->summaries->mapByMonth(
|
||||
$companyId,
|
||||
CourierPayableSummaryMap::PAGE_OTHER_SURCHARGE,
|
||||
);
|
||||
$returnFees = $this->summaries->mapByMonth(
|
||||
$companyId,
|
||||
CourierPayableSummaryMap::PAGE_RETURN_FEE,
|
||||
);
|
||||
|
||||
$totals = [];
|
||||
$feeApplied = [];
|
||||
$rows = $this->databases->connection()->table('courier_freight_rows')
|
||||
->where('company_id', $companyId)
|
||||
->whereNull('deleted_at')
|
||||
->whereIn('source', $sources)
|
||||
->select(['source', 'shop_name', 'transaction_no'])
|
||||
->selectRaw('SUM(COALESCE(freight_amount, 0)) AS freight_amount')
|
||||
->groupBy('source', 'shop_name', 'transaction_no')
|
||||
->orderBy('source')
|
||||
->orderBy('shop_name')
|
||||
->orderBy('transaction_no')
|
||||
->cursor();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$month = $this->sourceMonth(
|
||||
(string) $row->source,
|
||||
$reportMonths,
|
||||
);
|
||||
if ($month === null || ! in_array($month, $reportMonths, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 即使店铺为空也保留月份,表示该月已有快递成本来源。
|
||||
$totals[$month] ??= [];
|
||||
$storeName = trim((string) $row->shop_name);
|
||||
if ($storeName === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$transactionNo = trim((string) $row->transaction_no);
|
||||
$amount = (float) $row->freight_amount;
|
||||
$feeKey = $month . "\0" . $transactionNo;
|
||||
if ($transactionNo !== '' && ! isset($feeApplied[$feeKey])) {
|
||||
$amount += $this->numeric($differences[$month][$transactionNo] ?? null);
|
||||
$amount += $this->numeric($surcharges[$month][$transactionNo] ?? null);
|
||||
$amount += $this->numeric($returnFees[$month][$transactionNo] ?? null);
|
||||
$feeApplied[$feeKey] = true;
|
||||
}
|
||||
|
||||
$totals[$month][$storeName] = round(
|
||||
($totals[$month][$storeName] ?? 0.0) + $amount,
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
return $totals;
|
||||
}
|
||||
|
||||
/**
|
||||
* 来源通常为「提供成本9月汇总」。优先取来源里的年份;没有年份时,
|
||||
* 用当前报表年份补齐。若来源是「5-7月」范围,取最后月份作为该汇总的账期。
|
||||
*
|
||||
* @param list<string> $reportMonths
|
||||
*/
|
||||
private function sourceMonth(string $source, array $reportMonths): ?string
|
||||
{
|
||||
$source = trim($source);
|
||||
if ($source === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match(
|
||||
'/(?<!\d)((?:19|20)\d{2})\D{0,4}(1[0-2]|0?[1-9])(?!\d)/u',
|
||||
$source,
|
||||
$matches,
|
||||
) === 1) {
|
||||
return $matches[1] . '-' . str_pad((string) (int) $matches[2], 2, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
if (preg_match(
|
||||
'/(?:1[0-2]|0?[1-9])\s*[-~至]\s*(1[0-2]|0?[1-9])\s*月/u',
|
||||
$source,
|
||||
$range,
|
||||
) === 1) {
|
||||
$month = (int) $range[1];
|
||||
} elseif (preg_match('/(1[0-2]|0?[1-9])\s*月/u', $source, $single) === 1) {
|
||||
$month = (int) $single[1];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
$year = $reportMonths !== [] ? substr($reportMonths[0], 0, 4) : null;
|
||||
|
||||
return $year === null
|
||||
? null
|
||||
: $year . '-' . str_pad((string) $month, 2, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
private function numeric(mixed $value): float
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
return is_numeric($value) ? (float) $value : 0.0;
|
||||
}
|
||||
}
|
||||
@ -3,6 +3,7 @@
|
||||
namespace App\Business;
|
||||
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
@ -110,6 +111,7 @@ class CourierFreightImporter
|
||||
|
||||
$flush();
|
||||
arsort($sources);
|
||||
Cache::increment('courier-freight-financial-version:' . $companyId);
|
||||
|
||||
return [
|
||||
'file' => basename($path),
|
||||
|
||||
@ -7,7 +7,7 @@ use Illuminate\Support\Facades\Storage;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 快递应付的两个汇总页 → 「交易单号 ⇒ 金额类取值」映射。
|
||||
* 快递应付的三个汇总页 → 「交易单号 ⇒ 金额类取值」映射。
|
||||
*
|
||||
* 这些数据都是财务在「应付款项 › 快递应付 › 运费差 / 其他附加费汇总 / 退件费」页面上传的汇总快照
|
||||
* (JSON 文件,不是数据库表),快递运费页面按交易单号把对应金额带出来展示。
|
||||
@ -37,6 +37,7 @@ class CourierPayableSummaryMap
|
||||
];
|
||||
|
||||
private const CACHE_MINUTES = 10;
|
||||
private const AMOUNT_SCALE = 10;
|
||||
|
||||
public function __construct(private readonly CourierPayableSummaryStore $store) {}
|
||||
|
||||
@ -57,7 +58,7 @@ class CourierPayableSummaryMap
|
||||
}
|
||||
|
||||
// 文件时间戳进缓存键:财务重新导入运费差后不用等缓存过期。
|
||||
$key = sprintf('courier-payable-summary-map:v1:%s:%d:%d', $page, $companyId, (int) $disk->lastModified($path));
|
||||
$key = sprintf('courier-payable-summary-map:v3:%s:%d:%d', $page, $companyId, (int) $disk->lastModified($path));
|
||||
|
||||
return Cache::remember($key, now()->addMinutes(self::CACHE_MINUTES), function () use ($companyId, $page): array {
|
||||
try {
|
||||
@ -70,6 +71,43 @@ class CourierPayableSummaryMap
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总快照按原始日期拆成月份,供财务经营分析表按月匹配。
|
||||
*
|
||||
* 同一交易单号在同一月份可以出现多行,所有金额都累加,不做去重。
|
||||
*
|
||||
* @return array<string,array<string,string>> 月份 => [交易单号 => 金额]
|
||||
*/
|
||||
public function mapByMonth(int $companyId, string $page): array
|
||||
{
|
||||
if (! isset(self::PAGES[$page])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$disk = Storage::disk('uploads');
|
||||
$path = $this->store->path($companyId, $page);
|
||||
if (! $disk->exists($path)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$key = sprintf(
|
||||
'courier-payable-summary-month-map:v1:%s:%d:%d',
|
||||
$page,
|
||||
$companyId,
|
||||
(int) $disk->lastModified($path),
|
||||
);
|
||||
|
||||
return Cache::remember($key, now()->addMinutes(self::CACHE_MINUTES), function () use ($companyId, $page): array {
|
||||
try {
|
||||
return $this->buildByMonth($companyId, $page);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function build(int $companyId, string $page): array
|
||||
{
|
||||
@ -86,7 +124,8 @@ class CourierPayableSummaryMap
|
||||
return [];
|
||||
}
|
||||
|
||||
$map = [];
|
||||
$totals = [];
|
||||
$fallbacks = [];
|
||||
foreach ((array) $snapshot['rows'] as $row) {
|
||||
$orderNos = trim((string) ($row[$orderColumn] ?? ''));
|
||||
if ($orderNos === '') {
|
||||
@ -99,17 +138,123 @@ class CourierPayableSummaryMap
|
||||
}
|
||||
|
||||
// 源表一个格子可能放多个交易单号(逗号分隔),逐个挂到同一个金额上。
|
||||
foreach (explode(',', $orderNos) as $orderNo) {
|
||||
foreach (preg_split('/[,,]/u', $orderNos) ?: [] as $orderNo) {
|
||||
$orderNo = trim($orderNo);
|
||||
if ($orderNo !== '' && ! isset($map[$orderNo])) {
|
||||
$map[$orderNo] = $value;
|
||||
if ($orderNo === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 同一交易单号可能拆成多条运费差、附加费或退件费,按单号汇总,
|
||||
// 避免页面只取第一条而漏计同一订单的后续金额。
|
||||
$numericValue = $this->numericDecimal($value);
|
||||
if ($numericValue !== null && function_exists('bcadd')) {
|
||||
$totals[$orderNo] = bcadd(
|
||||
$totals[$orderNo] ?? '0',
|
||||
$numericValue,
|
||||
self::AMOUNT_SCALE,
|
||||
);
|
||||
} else {
|
||||
$fallbacks[$orderNo] ??= $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$map = [];
|
||||
foreach ($totals as $orderNo => $total) {
|
||||
$map[$orderNo] = $this->decimalString($total);
|
||||
}
|
||||
foreach ($fallbacks as $orderNo => $value) {
|
||||
if (! isset($map[$orderNo])) {
|
||||
$map[$orderNo] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/** @return array<string,array<string,string>> */
|
||||
private function buildByMonth(int $companyId, string $page): array
|
||||
{
|
||||
$snapshot = $this->store->snapshot($companyId, $page);
|
||||
if ($snapshot === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
[$orderHeaders, $valueHeaders] = self::PAGES[$page];
|
||||
$headers = array_map(static fn ($value): string => trim((string) $value), (array) $snapshot['headers']);
|
||||
$orderColumn = $this->columnIndex($headers, $orderHeaders);
|
||||
$valueColumn = $this->columnIndex($headers, $valueHeaders);
|
||||
$dateColumn = $this->columnIndex($headers, ['日期', '结算月份', '结算月', '月份']);
|
||||
if ($orderColumn === null || $valueColumn === null || $dateColumn === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$totals = [];
|
||||
foreach ((array) $snapshot['rows'] as $row) {
|
||||
$month = $this->month((string) ($row[$dateColumn] ?? ''));
|
||||
$orderNos = trim((string) ($row[$orderColumn] ?? ''));
|
||||
$value = trim((string) ($row[$valueColumn] ?? ''));
|
||||
$numericValue = $this->numericDecimal($value);
|
||||
if ($month === null || $orderNos === '' || $numericValue === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$totals[$month] ??= [];
|
||||
foreach (preg_split('/[,,]/u', $orderNos) ?: [] as $orderNo) {
|
||||
$orderNo = trim($orderNo);
|
||||
if ($orderNo === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$totals[$month][$orderNo] = function_exists('bcadd')
|
||||
? bcadd($totals[$month][$orderNo] ?? '0', $numericValue, self::AMOUNT_SCALE)
|
||||
: (string) ((float) ($totals[$month][$orderNo] ?? 0) + (float) $numericValue);
|
||||
}
|
||||
}
|
||||
|
||||
$map = [];
|
||||
foreach ($totals as $month => $orders) {
|
||||
foreach ($orders as $orderNo => $total) {
|
||||
$map[$month][$orderNo] = $this->decimalString($total);
|
||||
}
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
private function month(string $value): ?string
|
||||
{
|
||||
if (preg_match(
|
||||
'/(?<!\d)((?:19|20)\d{2})\D{0,4}(1[0-2]|0?[1-9])(?!\d)/u',
|
||||
trim($value),
|
||||
$matches,
|
||||
) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $matches[1] . '-' . str_pad((string) (int) $matches[2], 2, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
private function numericDecimal(string $value): ?string
|
||||
{
|
||||
if (! is_numeric($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (stripos($value, 'e') === false) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return sprintf('%.' . self::AMOUNT_SCALE . 'F', (float) $value);
|
||||
}
|
||||
|
||||
private function decimalString(string $value): string
|
||||
{
|
||||
$value = rtrim(rtrim($value, '0'), '.');
|
||||
|
||||
return $value === '' || $value === '-0' ? '0' : $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按表头名定位:候选顺序优先,每个候选先找完全相等的表头,再退化成包含匹配
|
||||
* (例如「差异(结算运费-提供成本运费)」只能靠包含匹配)。
|
||||
|
||||
@ -9,6 +9,7 @@ use App\Models\Business\CourierProfile;
|
||||
use App\Models\Business\CourierProfileEvent;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@ -33,7 +34,7 @@ final class CourierProfileData
|
||||
/** 把覆盖值盖到快递资料行上,`_overridden` 记下改过的字段。 */
|
||||
public function apply(object $row, array $overrides): object
|
||||
{
|
||||
$row = clone $row;
|
||||
$row = $this->fillFromOnboarding(clone $row);
|
||||
$changed = [];
|
||||
foreach ($overrides as $field => $value) {
|
||||
if (array_key_exists($field, CourierProfile::EDITABLE)) {
|
||||
@ -155,11 +156,16 @@ final class CourierProfileData
|
||||
/** 工作平台的行:扣款方式没填时用入驻里我方填的。 */
|
||||
public function fillFromOnboarding(object $row): object
|
||||
{
|
||||
$row = clone $row;
|
||||
$onboarding = $row->_info['onboarding'] ?? null;
|
||||
if ($onboarding !== null && blank($row->undefined3 ?? null) && filled($onboarding->deduction_method)) {
|
||||
$row = clone $row;
|
||||
$row->undefined3 = $onboarding->deduction_method;
|
||||
}
|
||||
foreach (['entity_type', 'company_full_name', ...self::APPENDED_PROFILE_FIELDS] as $field) {
|
||||
if (! property_exists($row, $field)) {
|
||||
$row->{$field} = $onboarding?->{$field};
|
||||
}
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
@ -187,36 +193,38 @@ final class CourierProfileData
|
||||
/** 保存编辑:只记和当前显示值不同的字段,并写一条操作日志。 */
|
||||
public function update(string $expcode, ?string $courierName, object $current, array $values, int $userId): int
|
||||
{
|
||||
$profile = CourierProfile::query()->firstOrNew(['company_id' => company_id(), 'expcode' => $expcode]);
|
||||
$overrides = (array) ($profile->overrides ?? []);
|
||||
$changes = [];
|
||||
foreach (CourierProfile::EDITABLE as $field => $label) {
|
||||
if (! array_key_exists($field, $values)) {
|
||||
continue;
|
||||
return DB::transaction(function () use ($expcode, $courierName, $current, $values, $userId): int {
|
||||
$profile = CourierProfile::query()->firstOrNew(['company_id' => company_id(), 'expcode' => $expcode]);
|
||||
$overrides = (array) ($profile->overrides ?? []);
|
||||
$changes = [];
|
||||
foreach (CourierProfile::EDITABLE as $field => $label) {
|
||||
if (! array_key_exists($field, $values)) {
|
||||
continue;
|
||||
}
|
||||
$new = $this->normalize($field, $values[$field]);
|
||||
$old = $this->normalize($field, $current->{$field} ?? null);
|
||||
if ($new === $old) {
|
||||
continue;
|
||||
}
|
||||
$overrides[$field] = $new;
|
||||
$changes[$field] = ['label' => $label, 'old' => $old, 'new' => $new];
|
||||
}
|
||||
$new = $this->normalize($field, $values[$field]);
|
||||
$old = $this->normalize($field, $current->{$field} ?? null);
|
||||
if ($new === $old) {
|
||||
continue;
|
||||
if ($changes === []) {
|
||||
return 0;
|
||||
}
|
||||
$overrides[$field] = $new;
|
||||
$changes[$field] = ['label' => $label, 'old' => $old, 'new' => $new];
|
||||
}
|
||||
if ($changes === []) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$profile->fill([
|
||||
'courier_name' => $courierName ?: $profile->courier_name,
|
||||
'overrides' => $overrides,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$profile->created_by ??= $userId;
|
||||
$profile->save();
|
||||
$profile->fill([
|
||||
'courier_name' => $courierName ?: $profile->courier_name,
|
||||
'overrides' => $overrides,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$profile->created_by ??= $userId;
|
||||
$profile->save();
|
||||
|
||||
$this->log($expcode, 'edit', '修改 ' . implode('、', array_column($changes, 'label')), $changes, $userId);
|
||||
$this->log($expcode, 'edit', '修改 ' . implode('、', array_column($changes, 'label')), $changes, $userId);
|
||||
|
||||
return count($changes);
|
||||
return count($changes);
|
||||
});
|
||||
}
|
||||
|
||||
public function log(string $expcode, string $action, string $summary, ?array $changes, int $userId): void
|
||||
|
||||
378
app/Business/InvoiceQuotaPageData.php
Normal file
378
app/Business/InvoiceQuotaPageData.php
Normal file
@ -0,0 +1,378 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business;
|
||||
|
||||
use App\Business\Piaoju\PiaojuSellerQuotaRepository;
|
||||
use App\Models\Business\InvoiceBasic;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Throwable;
|
||||
|
||||
class InvoiceQuotaPageData
|
||||
{
|
||||
private const PER_PAGE = 50;
|
||||
private const QUOTA_WARNING_DAYS = 5;
|
||||
|
||||
public function __construct(
|
||||
private readonly PiaojuSellerQuotaRepository $piaojuQuotas,
|
||||
) {
|
||||
}
|
||||
|
||||
public function page(): array
|
||||
{
|
||||
try {
|
||||
$data = $this->buildData();
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return $this->errorPayload();
|
||||
}
|
||||
|
||||
$rows = $data['allRows'];
|
||||
$total = $rows->count();
|
||||
$lastPage = max(1, (int) ceil($total / self::PER_PAGE));
|
||||
$currentPage = min(max((int) request()->query('page', 1), 1), $lastPage);
|
||||
$pageRows = $rows
|
||||
->slice(($currentPage - 1) * self::PER_PAGE, self::PER_PAGE)
|
||||
->values();
|
||||
|
||||
$paginator = new LengthAwarePaginator(
|
||||
$pageRows,
|
||||
$total,
|
||||
self::PER_PAGE,
|
||||
$currentPage,
|
||||
[
|
||||
'path' => request()->url(),
|
||||
'query' => request()->query(),
|
||||
]
|
||||
);
|
||||
|
||||
return [
|
||||
'view' => 'business.pages.invoice_quota',
|
||||
'title' => '发票额度',
|
||||
'period' => $data['period'],
|
||||
'periodOptions' => $data['periodOptions'],
|
||||
'sellerEntity' => $data['sellerEntity'],
|
||||
'rows' => $paginator,
|
||||
'summary' => $data['summary'],
|
||||
'loadError' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回当前筛选条件下的全部行,供 CSV 导出使用。
|
||||
*
|
||||
* @return array{period:string, sellerEntity:string, allRows:Collection, summary:array}
|
||||
*/
|
||||
public function exportData(): array
|
||||
{
|
||||
return $this->buildData();
|
||||
}
|
||||
|
||||
private function buildData(): array
|
||||
{
|
||||
$periodOptions = InvoiceBasic::query()
|
||||
->select('period')
|
||||
->whereNotNull('period')
|
||||
->where('period', '<>', '')
|
||||
->distinct()
|
||||
->orderByDesc('period')
|
||||
->pluck('period')
|
||||
->map(static fn ($period): string => trim((string) $period))
|
||||
->filter(fn (string $period): bool => $this->normalizePeriod($period) !== null)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
$requestedPeriod = $this->normalizePeriod(
|
||||
trim((string) request()->query('period', ''))
|
||||
);
|
||||
$period = $requestedPeriod ?? $periodOptions->first() ?? '';
|
||||
$forecastContext = $this->forecastContext($period);
|
||||
$sellerEntity = mb_substr(
|
||||
trim((string) request()->query('seller_entity', '')),
|
||||
0,
|
||||
100
|
||||
);
|
||||
|
||||
$query = InvoiceBasic::query()->select([
|
||||
'id',
|
||||
'store_entity',
|
||||
'invoice_issuer',
|
||||
'output_amount',
|
||||
'period',
|
||||
]);
|
||||
|
||||
if ($period !== '') {
|
||||
$query->where('period', $period);
|
||||
} else {
|
||||
$query->where(function ($query): void {
|
||||
$query->whereNull('period')->orWhere('period', '');
|
||||
});
|
||||
}
|
||||
|
||||
if ($sellerEntity !== '') {
|
||||
$needle = '%' . addcslashes($sellerEntity, '%_\\') . '%';
|
||||
$query->where('store_entity', 'like', $needle);
|
||||
}
|
||||
|
||||
$snapshots = $this->piaojuQuotas->byNormalizedName();
|
||||
$rows = $query
|
||||
->orderBy('store_entity')
|
||||
->orderByDesc('id')
|
||||
->get()
|
||||
->map(fn (InvoiceBasic $row): object => $this->presentRow(
|
||||
$row,
|
||||
$snapshots->get(PiaojuSellerQuotaRepository::normalizeName((string) $row->store_entity)),
|
||||
$forecastContext,
|
||||
))
|
||||
->sortBy(static fn (object $row): string => sprintf(
|
||||
'%02d|%s',
|
||||
$row->status_rank,
|
||||
(string) $row->store_entity
|
||||
))
|
||||
->values();
|
||||
|
||||
$total = $rows->count();
|
||||
$usedAmount = $rows->sum(static fn (object $row): float => (float) $row->output_amount);
|
||||
$usedTotal = round($usedAmount, 2);
|
||||
$forecastTotal = (int) ($forecastContext['elapsed_days'] ?? 0) > 0
|
||||
? round(
|
||||
$usedAmount
|
||||
* (int) ($forecastContext['days_in_month'] ?? 0)
|
||||
/ (int) $forecastContext['elapsed_days'],
|
||||
2
|
||||
)
|
||||
: 0.0;
|
||||
$availableRows = $rows->filter(
|
||||
static fn (object $row): bool => $row->available_amount !== null
|
||||
);
|
||||
$availableTotal = round($availableRows->sum(
|
||||
static fn (object $row): float => (float) $row->available_amount
|
||||
), 2);
|
||||
$matchedCount = $rows->where('snapshot_matched', true)->count();
|
||||
$unmatchedCount = $rows->where('snapshot_matched', false)->count();
|
||||
$unavailableCount = $rows->where('snapshot_unavailable', true)->count();
|
||||
$insufficientCount = $rows->where('insufficient', true)->count();
|
||||
$warningCount = $rows->where('quota_warning', true)->count();
|
||||
|
||||
return [
|
||||
'period' => $period,
|
||||
'periodOptions' => $periodOptions,
|
||||
'sellerEntity' => $sellerEntity,
|
||||
'allRows' => $rows,
|
||||
'summary' => [
|
||||
'record_count' => $total,
|
||||
'used_total' => $usedTotal,
|
||||
'forecast_total' => $forecastTotal,
|
||||
'available_total' => $availableTotal,
|
||||
'matched_count' => $matchedCount,
|
||||
'unmatched_count' => $unmatchedCount,
|
||||
'unavailable_count' => $unavailableCount,
|
||||
'insufficient_count' => $insufficientCount,
|
||||
'warning_count' => $warningCount,
|
||||
'forecast_elapsed_days' => $forecastContext['elapsed_days'],
|
||||
'forecast_days_in_month' => $forecastContext['days_in_month'],
|
||||
'forecast_is_current' => $forecastContext['is_current'],
|
||||
'latest_quota_updated_at' => $this->latestDateTime(
|
||||
$rows->pluck('quota_updated_at')
|
||||
),
|
||||
'latest_source_fetched_at' => $this->latestDateTime(
|
||||
$rows->pluck('source_fetched_at')
|
||||
),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function presentRow(
|
||||
InvoiceBasic $row,
|
||||
?object $snapshot,
|
||||
array $forecastContext,
|
||||
): object
|
||||
{
|
||||
$outputAmount = round((float) $row->output_amount, 2);
|
||||
$availableAmount = $snapshot !== null && is_numeric($snapshot->invoice_limit)
|
||||
? round((float) $snapshot->invoice_limit, 2)
|
||||
: null;
|
||||
$authStatus = strtoupper(trim((string) ($snapshot->auth_status ?? '')));
|
||||
$elapsedDays = (int) ($forecastContext['elapsed_days'] ?? 0);
|
||||
$daysInMonth = (int) ($forecastContext['days_in_month'] ?? 0);
|
||||
$dailyAverageRaw = $elapsedDays > 0
|
||||
? $outputAmount / $elapsedDays
|
||||
: null;
|
||||
$dailyAverage = $dailyAverageRaw !== null ? round($dailyAverageRaw, 2) : null;
|
||||
$forecastMonthly = $dailyAverageRaw !== null && $daysInMonth > 0
|
||||
? round($outputAmount * $daysInMonth / $elapsedDays, 2)
|
||||
: null;
|
||||
$coverageDaysRaw = $dailyAverageRaw !== null && $dailyAverageRaw > 0 && $availableAmount !== null
|
||||
? max($availableAmount, 0) / $dailyAverageRaw
|
||||
: null;
|
||||
$coverageDays = $coverageDaysRaw !== null ? round($coverageDaysRaw, 2) : null;
|
||||
$quotaWarning = (bool) ($forecastContext['is_current'] ?? false)
|
||||
&& $authStatus === 'AUTHENTICATED'
|
||||
&& $availableAmount !== null
|
||||
&& $availableAmount > 0
|
||||
&& $coverageDaysRaw !== null
|
||||
&& $coverageDaysRaw < self::QUOTA_WARNING_DAYS;
|
||||
|
||||
if ($snapshot === null) {
|
||||
$status = '未匹配';
|
||||
$statusTone = 'muted';
|
||||
$statusIcon = 'link_off';
|
||||
$statusRank = 0;
|
||||
} elseif ($authStatus === 'AUTHENTICATED_EXPIRED') {
|
||||
$status = '授权过期';
|
||||
$statusTone = 'warning';
|
||||
$statusIcon = 'schedule';
|
||||
$statusRank = 1;
|
||||
} elseif ($authStatus !== 'AUTHENTICATED') {
|
||||
$status = '不可查看';
|
||||
$statusTone = 'muted';
|
||||
$statusIcon = 'visibility_off';
|
||||
$statusRank = 1;
|
||||
} elseif ($availableAmount === null) {
|
||||
$status = '未获取额度';
|
||||
$statusTone = 'muted';
|
||||
$statusIcon = 'cloud_off';
|
||||
$statusRank = 1;
|
||||
} elseif ($availableAmount <= 0) {
|
||||
$status = '额度不足';
|
||||
$statusTone = 'danger';
|
||||
$statusIcon = 'error';
|
||||
$statusRank = 2;
|
||||
} elseif ($quotaWarning) {
|
||||
$status = '5天内预警';
|
||||
$statusTone = 'danger';
|
||||
$statusIcon = 'notification_important';
|
||||
$statusRank = 2;
|
||||
} else {
|
||||
$status = '正常';
|
||||
$statusTone = 'success';
|
||||
$statusIcon = 'check_circle_outline';
|
||||
$statusRank = 3;
|
||||
}
|
||||
|
||||
return (object) [
|
||||
'id' => $row->id,
|
||||
'store_entity' => $row->store_entity,
|
||||
'invoice_issuer' => $row->invoice_issuer,
|
||||
'output_amount' => $outputAmount,
|
||||
'daily_average' => $dailyAverage,
|
||||
'forecast_monthly' => $forecastMonthly,
|
||||
'available_amount' => $availableAmount,
|
||||
'coverage_days' => $coverageDays,
|
||||
'quota_updated_at' => $this->formatDateTime($snapshot->invoice_limit_updated_at ?? null),
|
||||
'source_fetched_at' => $this->formatDateTime($snapshot->source_fetched_at ?? null),
|
||||
'snapshot_matched' => $snapshot !== null,
|
||||
'snapshot_unavailable' => $snapshot !== null
|
||||
&& ($authStatus !== 'AUTHENTICATED' || $availableAmount === null),
|
||||
'insufficient' => $snapshot !== null
|
||||
&& $authStatus === 'AUTHENTICATED'
|
||||
&& $availableAmount !== null
|
||||
&& $availableAmount <= 0,
|
||||
'quota_warning' => $quotaWarning,
|
||||
'status' => $status,
|
||||
'status_tone' => $statusTone,
|
||||
'status_icon' => $statusIcon,
|
||||
'status_rank' => $statusRank,
|
||||
'period' => $row->period,
|
||||
];
|
||||
}
|
||||
|
||||
private function formatDateTime(mixed $value): ?string
|
||||
{
|
||||
$text = trim((string) ($value ?? ''));
|
||||
if ($text === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Carbon::parse($text, 'Asia/Shanghai')->format('Y-m-d H:i');
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function latestDateTime(Collection $values): ?string
|
||||
{
|
||||
return $values
|
||||
->filter(static fn (mixed $value): bool => trim((string) $value) !== '')
|
||||
->sortDesc()
|
||||
->first();
|
||||
}
|
||||
|
||||
private function normalizePeriod(string $period): ?string
|
||||
{
|
||||
return preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1
|
||||
? $period
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{elapsed_days:int,days_in_month:int,is_current:bool}
|
||||
*/
|
||||
private function forecastContext(string $period): array
|
||||
{
|
||||
if ($period === '') {
|
||||
return ['elapsed_days' => 0, 'days_in_month' => 0, 'is_current' => false];
|
||||
}
|
||||
|
||||
try {
|
||||
$month = Carbon::createFromFormat('!Y-m-d', $period . '-01', 'Asia/Shanghai');
|
||||
$today = Carbon::now('Asia/Shanghai')->startOfDay();
|
||||
} catch (Throwable) {
|
||||
return ['elapsed_days' => 0, 'days_in_month' => 0, 'is_current' => false];
|
||||
}
|
||||
|
||||
$daysInMonth = $month->daysInMonth;
|
||||
if ($month->format('Y-m') === $today->format('Y-m')) {
|
||||
return [
|
||||
'elapsed_days' => min($today->day, $daysInMonth),
|
||||
'days_in_month' => $daysInMonth,
|
||||
'is_current' => true,
|
||||
];
|
||||
}
|
||||
|
||||
if ($month->lt($today->copy()->startOfMonth())) {
|
||||
return [
|
||||
'elapsed_days' => $daysInMonth,
|
||||
'days_in_month' => $daysInMonth,
|
||||
'is_current' => false,
|
||||
];
|
||||
}
|
||||
|
||||
return ['elapsed_days' => 0, 'days_in_month' => $daysInMonth, 'is_current' => false];
|
||||
}
|
||||
|
||||
private function errorPayload(): array
|
||||
{
|
||||
return [
|
||||
'view' => 'business.pages.invoice_quota',
|
||||
'title' => '发票额度',
|
||||
'period' => '',
|
||||
'periodOptions' => collect(),
|
||||
'sellerEntity' => '',
|
||||
'rows' => new LengthAwarePaginator([], 0, self::PER_PAGE, 1, [
|
||||
'path' => request()->url(),
|
||||
'query' => request()->query(),
|
||||
]),
|
||||
'summary' => [
|
||||
'record_count' => 0,
|
||||
'used_total' => 0.0,
|
||||
'forecast_total' => 0.0,
|
||||
'available_total' => 0.0,
|
||||
'matched_count' => 0,
|
||||
'unmatched_count' => 0,
|
||||
'unavailable_count' => 0,
|
||||
'insufficient_count' => 0,
|
||||
'warning_count' => 0,
|
||||
'forecast_elapsed_days' => 0,
|
||||
'forecast_days_in_month' => 0,
|
||||
'forecast_is_current' => false,
|
||||
'latest_quota_updated_at' => null,
|
||||
'latest_source_fetched_at' => null,
|
||||
],
|
||||
'loadError' => '发票额度数据暂时无法读取,请稍后重试。',
|
||||
];
|
||||
}
|
||||
}
|
||||
198
app/Business/InvoiceReportsPageData.php
Normal file
198
app/Business/InvoiceReportsPageData.php
Normal file
@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business;
|
||||
|
||||
use App\Models\Business\InputInvoiceReport;
|
||||
use App\Models\Business\OutputInvoiceReport;
|
||||
use Illuminate\Support\Collection;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 发票数据报表:发票情况汇总在前,进项/销项明细在后。
|
||||
*
|
||||
* 汇总按公司名称合并进项报表与销项报表,金额均使用两张报表的合计口径;
|
||||
* 差额 = 销项 − 进项,正数表示销项大于进项。
|
||||
*/
|
||||
class InvoiceReportsPageData
|
||||
{
|
||||
private const TABS = ['summary', 'input', 'output'];
|
||||
|
||||
public function page(?string $tab): array
|
||||
{
|
||||
$tab = in_array($tab, self::TABS, true) ? $tab : 'summary';
|
||||
|
||||
$inputRows = $this->reportRows(InputInvoiceReport::class);
|
||||
$outputRows = $this->reportRows(OutputInvoiceReport::class);
|
||||
|
||||
if ($tab === 'summary') {
|
||||
$allRows = $this->summaryRows($inputRows, $outputRows);
|
||||
$filters = $this->summaryFilters();
|
||||
$summaryRows = $this->filterSummaryRows($allRows, $filters);
|
||||
|
||||
return [
|
||||
'view' => 'business.pages.invoice_reports',
|
||||
'summaryRows' => $summaryRows,
|
||||
'summaryTotals' => $this->summaryTotals($summaryRows),
|
||||
'summaryFilters' => $filters,
|
||||
'companyOptions' => $allRows->pluck('company_name')
|
||||
->filter(static fn ($name): bool => (string) $name !== '')
|
||||
->unique()
|
||||
->sort()
|
||||
->values(),
|
||||
'taxpayerTypeOptions' => $allRows->pluck('taxpayer_type')
|
||||
->filter(static fn ($type): bool => (string) $type !== '' && (string) $type !== '—')
|
||||
->unique()
|
||||
->sort()
|
||||
->values(),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'view' => 'business.pages.invoice_reports',
|
||||
'items' => $tab === 'output' ? $outputRows : $inputRows,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 报表表在部分老环境可能尚未迁移,缺失时保持页面可用并展示空表。
|
||||
*
|
||||
* @param class-string $model
|
||||
*/
|
||||
private function reportRows(string $model): Collection
|
||||
{
|
||||
try {
|
||||
return $model::query()
|
||||
->orderBy('company_name')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
|
||||
private function summaryRows(Collection $inputRows, Collection $outputRows): Collection
|
||||
{
|
||||
$inputs = $inputRows->groupBy(fn ($row): string => trim((string) $row->company_name));
|
||||
$outputs = $outputRows->groupBy(fn ($row): string => trim((string) $row->company_name));
|
||||
|
||||
$companyNames = $inputs->keys()
|
||||
->merge($outputs->keys())
|
||||
->filter(static fn ($name): bool => $name !== '')
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
|
||||
$taxpayerTypes = $this->taxpayerTypes($companyNames);
|
||||
|
||||
return $companyNames->map(function (string $companyName) use ($inputs, $outputs, $taxpayerTypes): object {
|
||||
$inputRows = $inputs->get($companyName, collect());
|
||||
$outputRows = $outputs->get($companyName, collect());
|
||||
|
||||
$inputAmount = $this->sumField($inputRows, 'input_total_amount');
|
||||
$inputTax = $this->sumField($inputRows, 'input_total_tax');
|
||||
$outputAmount = $this->sumField($outputRows, 'output_total_amount');
|
||||
$outputTax = $this->sumField($outputRows, 'output_total_tax');
|
||||
$ratio = $outputAmount > 0 ? $inputAmount / $outputAmount : null;
|
||||
|
||||
return (object) [
|
||||
'company_name' => $companyName,
|
||||
'taxpayer_type' => $taxpayerTypes->get($companyName, '—'),
|
||||
'input_total_amount' => $inputAmount,
|
||||
'input_total_tax' => $inputTax,
|
||||
'output_total_amount' => $outputAmount,
|
||||
'output_total_tax' => $outputTax,
|
||||
'input_output_ratio' => $ratio,
|
||||
'is_warning' => $ratio !== null && $ratio < 0.8,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
private function summaryTotals(Collection $rows): object
|
||||
{
|
||||
return (object) [
|
||||
'input_total_amount' => round((float) $rows->sum('input_total_amount'), 2),
|
||||
'input_total_tax' => round((float) $rows->sum('input_total_tax'), 2),
|
||||
'output_total_amount' => round((float) $rows->sum('output_total_amount'), 2),
|
||||
'output_total_tax' => round((float) $rows->sum('output_total_tax'), 2),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{company:string,taxpayer_type:string,warning:string}
|
||||
*/
|
||||
private function summaryFilters(): array
|
||||
{
|
||||
$warning = strtolower(trim((string) request()->query('warning', '')));
|
||||
|
||||
return [
|
||||
'company' => trim((string) request()->query('company', '')),
|
||||
'taxpayer_type' => trim((string) request()->query('taxpayer_type', '')),
|
||||
'warning' => in_array($warning, ['yes', 'no'], true) ? $warning : '',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{company:string,taxpayer_type:string,warning:string} $filters
|
||||
*/
|
||||
private function filterSummaryRows(Collection $rows, array $filters): Collection
|
||||
{
|
||||
return $rows->filter(function (object $row) use ($filters): bool {
|
||||
if ($filters['company'] !== '' && $row->company_name !== $filters['company']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($filters['taxpayer_type'] !== '' && $row->taxpayer_type !== $filters['taxpayer_type']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($filters['warning'] === 'yes' && ! $row->is_warning) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($filters['warning'] === 'no' && $row->is_warning) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
})->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* 纳税人类型取公司基础信息共享镜像;镜像未就绪或公司未登记时显示「—」。
|
||||
*/
|
||||
private function taxpayerTypes(Collection $companyNames): Collection
|
||||
{
|
||||
$names = $companyNames
|
||||
->map(static fn ($name): string => trim((string) $name))
|
||||
->filter(static fn (string $name): bool => $name !== '')
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
if ($names === []) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
try {
|
||||
$rows = app(\Modules\EcommerceFinance\Repositories\BusinessInformationMirrorRepository::class)
|
||||
->allCompaniesForClassification(['_company_names' => $names]);
|
||||
|
||||
return collect($rows)
|
||||
->mapWithKeys(static fn (array $row): array => [
|
||||
trim((string) ($row['company_name'] ?? '')) => trim((string) ($row['taxpayer_category'] ?? '')),
|
||||
])
|
||||
->filter(static fn ($value, $key): bool => $key !== '' && (string) $value !== '');
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
|
||||
private function sumField(Collection $rows, string $field): float
|
||||
{
|
||||
return round($rows->sum(static fn ($row): float => (float) $row->{$field}), 2);
|
||||
}
|
||||
}
|
||||
@ -30,6 +30,7 @@ class KukaPostingBaseImporter
|
||||
* store_count: int,
|
||||
* order_count: int,
|
||||
* skipped_store_rows: int,
|
||||
* skipped_cancelled_rows: int,
|
||||
* file_sha256: string
|
||||
* }
|
||||
*/
|
||||
@ -59,12 +60,18 @@ class KukaPostingBaseImporter
|
||||
throw new RuntimeException('顾家过账基础数据字段或店铺范围未配置。');
|
||||
}
|
||||
|
||||
$sourceColumns = array_values(array_filter(array_map(
|
||||
static fn (array $field): string => trim((string) ($field['source'] ?? '')),
|
||||
$fields,
|
||||
)));
|
||||
if (count($sourceColumns) !== count($fields)) {
|
||||
throw new RuntimeException('顾家过账基础数据字段配置不完整。');
|
||||
$requiredSourceColumns = [];
|
||||
$optionalSourceColumns = [];
|
||||
foreach ($fields as $field) {
|
||||
$source = trim((string) ($field['source'] ?? ''));
|
||||
if ($source === '') {
|
||||
throw new RuntimeException('顾家过账基础数据字段配置不完整。');
|
||||
}
|
||||
if (($field['optional'] ?? false) === true) {
|
||||
$optionalSourceColumns[] = $source;
|
||||
} else {
|
||||
$requiredSourceColumns[] = $source;
|
||||
}
|
||||
}
|
||||
|
||||
$sheetName = trim((string) ($sheetName ?: config('kuka_posting.source_sheet', '发货明细表')));
|
||||
@ -77,6 +84,7 @@ class KukaPostingBaseImporter
|
||||
$orders = [];
|
||||
$rowCount = 0;
|
||||
$skippedStoreRows = 0;
|
||||
$skippedCancelledRows = 0;
|
||||
$sourceRowNumber = 1;
|
||||
$now = now();
|
||||
|
||||
@ -87,12 +95,14 @@ class KukaPostingBaseImporter
|
||||
$sheetName,
|
||||
$companyId,
|
||||
$fields,
|
||||
$sourceColumns,
|
||||
$requiredSourceColumns,
|
||||
$optionalSourceColumns,
|
||||
$allowedStores,
|
||||
&$storeCounts,
|
||||
&$orders,
|
||||
&$rowCount,
|
||||
&$skippedStoreRows,
|
||||
&$skippedCancelledRows,
|
||||
&$sourceRowNumber,
|
||||
$fileHash,
|
||||
$now,
|
||||
@ -114,7 +124,12 @@ class KukaPostingBaseImporter
|
||||
$batch = [];
|
||||
};
|
||||
|
||||
foreach ($this->reader->rows($path, $sourceColumns, [], $sheetName) as $sourceValues) {
|
||||
foreach ($this->reader->rows(
|
||||
$path,
|
||||
$requiredSourceColumns,
|
||||
$optionalSourceColumns,
|
||||
$sheetName,
|
||||
) as $sourceValues) {
|
||||
$sourceRowNumber++;
|
||||
$storeName = trim((string) ($sourceValues['店铺'] ?? ''));
|
||||
if ($storeName === '' || ! in_array($storeName, $allowedStores, true)) {
|
||||
@ -122,6 +137,11 @@ class KukaPostingBaseImporter
|
||||
|
||||
continue;
|
||||
}
|
||||
if (trim((string) ($sourceValues['订单状态'] ?? '')) === '已取消') {
|
||||
$skippedCancelledRows++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$payload = [];
|
||||
foreach ($fields as $field) {
|
||||
@ -231,6 +251,7 @@ class KukaPostingBaseImporter
|
||||
'store_count' => count(array_filter($storeCounts)),
|
||||
'order_count' => count($orders),
|
||||
'skipped_store_rows' => $skippedStoreRows,
|
||||
'skipped_cancelled_rows' => $skippedCancelledRows,
|
||||
'file_sha256' => strtolower($fileHash),
|
||||
];
|
||||
}
|
||||
|
||||
@ -28,7 +28,15 @@ class KukaPostingBasePageData
|
||||
public function build(Request $request, int $companyId): array
|
||||
{
|
||||
$stores = array_values((array) config('kuka_posting.stores', []));
|
||||
$fields = array_values((array) config('kuka_posting.fields', []));
|
||||
$fieldDefinitions = collect((array) config('kuka_posting.fields', []))->keyBy('name');
|
||||
$displayFieldNames = array_values((array) config('kuka_posting.shipment_display_fields', []));
|
||||
$fields = $displayFieldNames === []
|
||||
? $fieldDefinitions->values()->all()
|
||||
: collect($displayFieldNames)
|
||||
->map(static fn (string $name): ?array => $fieldDefinitions->get($name))
|
||||
->filter()
|
||||
->values()
|
||||
->all();
|
||||
$available = $this->repository->available();
|
||||
$periods = $available ? $this->repository->periods($companyId) : [];
|
||||
$latest = $available ? $this->repository->latestImport($companyId) : null;
|
||||
@ -67,13 +75,98 @@ class KukaPostingBasePageData
|
||||
'path' => $request->url(),
|
||||
'query' => $request->query(),
|
||||
]);
|
||||
$rows->setCollection($rows->getCollection()->map(function (object $row): object {
|
||||
$decodedRows = $rows->getCollection()->map(function (object $row): array {
|
||||
$values = json_decode((string) $row->source_values, true);
|
||||
if (! is_array($values)) {
|
||||
$values = [];
|
||||
}
|
||||
$values['_row_id'] = $row->id;
|
||||
|
||||
return [
|
||||
'item_number' => trim((string) ($values['货号'] ?? '')),
|
||||
'style_code' => trim((string) ($values['款式编码'] ?? '')),
|
||||
'values' => $values,
|
||||
];
|
||||
});
|
||||
$maps = $this->repository->materialMaps(
|
||||
$companyId,
|
||||
$decodedRows->pluck('item_number')->filter()->unique()->values()->all(),
|
||||
);
|
||||
$brandItems = $this->repository->brandItemMaps(
|
||||
$companyId,
|
||||
$decodedRows->pluck('style_code')->filter()->unique()->values()->all(),
|
||||
);
|
||||
$itemBrandItems = $this->repository->itemBrandItemMaps(
|
||||
$companyId,
|
||||
$decodedRows->pluck('item_number')->filter()->unique()->values()->all(),
|
||||
);
|
||||
$repairedMaterialNumbers = $decodedRows
|
||||
->filter(static fn (array $row): bool => trim((string) (
|
||||
$row['values']['物料信息修正'] ?? ''
|
||||
)) === '是')
|
||||
->map(static fn (array $row): string => trim((string) (
|
||||
$row['values']['物料编号'] ?? ''
|
||||
)))
|
||||
->filter();
|
||||
$quotations = $this->repository->effectiveQuotations(
|
||||
$companyId,
|
||||
collect($maps)
|
||||
->pluck('material_number')
|
||||
->filter()
|
||||
->merge($repairedMaterialNumbers)
|
||||
->unique()
|
||||
->values()
|
||||
->all(),
|
||||
);
|
||||
$rows->setCollection($decodedRows->map(function (array $row) use ($maps, $brandItems, $itemBrandItems, $quotations): object {
|
||||
$values = $row['values'];
|
||||
$usesRepairedMaterial = trim((string) ($values['物料信息修正'] ?? '')) === '是';
|
||||
$storedMaterialNumber = trim((string) ($values['物料编号'] ?? ''));
|
||||
$storedMaterialDescription = trim((string) ($values['型号'] ?? ''));
|
||||
if (in_array($storedMaterialNumber, ['', '—', '-'], true)) {
|
||||
$storedMaterialNumber = '';
|
||||
}
|
||||
if (in_array($storedMaterialDescription, ['', '—', '-'], true)) {
|
||||
$storedMaterialDescription = '';
|
||||
}
|
||||
$mappedMaterialNumber = trim((string) ($maps[$row['item_number']]->material_number ?? ''));
|
||||
$materialNumber = $usesRepairedMaterial && $storedMaterialNumber !== ''
|
||||
? $storedMaterialNumber
|
||||
: $mappedMaterialNumber;
|
||||
$quotation = $materialNumber === '' ? null : ($quotations[$materialNumber] ?? null);
|
||||
$brandItemNumber = trim((string) (
|
||||
$brandItems[$row['style_code']]->brand_item_number ?? ''
|
||||
));
|
||||
if ($brandItemNumber === '') {
|
||||
$brandItemNumber = trim((string) (
|
||||
$itemBrandItems[$row['item_number']]->brand_item_number ?? ''
|
||||
));
|
||||
}
|
||||
|
||||
if ($brandItemNumber !== '') {
|
||||
$values['货号'] = $brandItemNumber;
|
||||
}
|
||||
|
||||
$values['物料编号'] = '';
|
||||
$values['型号'] = '';
|
||||
$values['成本'] = '';
|
||||
$values['发货金额'] = '';
|
||||
|
||||
if ($quotation !== null) {
|
||||
$cost = $this->decimal($quotation->price_including_tax);
|
||||
$quantity = $this->decimal($values['实发数量'] ?? null);
|
||||
|
||||
$values['物料编号'] = $materialNumber;
|
||||
$values['型号'] = (string) ($quotation->material_desc ?? '');
|
||||
$values['成本'] = $cost ?? '';
|
||||
$values['发货金额'] = $cost !== null && $quantity !== null
|
||||
? $this->multiplyDecimal($cost, $quantity)
|
||||
: '';
|
||||
} elseif ($mappedMaterialNumber === '' && $usesRepairedMaterial) {
|
||||
$values['物料编号'] = $storedMaterialNumber;
|
||||
$values['型号'] = $storedMaterialDescription;
|
||||
}
|
||||
|
||||
return (object) $values;
|
||||
}));
|
||||
$statuses = $available ? $this->repository->statuses($companyId, $period) : [];
|
||||
@ -128,4 +221,20 @@ class KukaPostingBasePageData
|
||||
'error' => $error,
|
||||
];
|
||||
}
|
||||
|
||||
private function decimal(mixed $value): ?string
|
||||
{
|
||||
$normalized = str_replace(',', '', trim((string) $value));
|
||||
|
||||
return $normalized !== '' && is_numeric($normalized) ? $normalized : null;
|
||||
}
|
||||
|
||||
private function multiplyDecimal(string $cost, string $quantity): string
|
||||
{
|
||||
if (function_exists('bcmul')) {
|
||||
return bcmul($cost, $quantity, 4);
|
||||
}
|
||||
|
||||
return number_format((float) $cost * (float) $quantity, 4, '.', '');
|
||||
}
|
||||
}
|
||||
|
||||
@ -87,6 +87,107 @@ class KukaPostingBaseRepository
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $itemNumbers
|
||||
* @return array<string,object>
|
||||
*/
|
||||
public function materialMaps(int $companyId, array $itemNumbers): array
|
||||
{
|
||||
$itemNumbers = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $value): string => trim((string) $value),
|
||||
$itemNumbers,
|
||||
))));
|
||||
if ($itemNumbers === []
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_material_map_rows')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->connection()
|
||||
->table('kuka_posting_material_map_rows')
|
||||
->where('company_id', $companyId)
|
||||
->where('match_status', 'matched')
|
||||
->whereIn('item_number', $itemNumbers)
|
||||
->get(['item_number', 'material_number'])
|
||||
->filter(static fn (object $row): bool => trim((string) $row->material_number) !== '')
|
||||
->keyBy(static fn (object $row): string => (string) $row->item_number)
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $lookupCodes
|
||||
* @return array<string,object>
|
||||
*/
|
||||
public function brandItemMaps(int $companyId, array $lookupCodes): array
|
||||
{
|
||||
$lookupCodes = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $value): string => trim((string) $value),
|
||||
$lookupCodes,
|
||||
))));
|
||||
if ($lookupCodes === []
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_brand_item_map_rows')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->connection()
|
||||
->table('kuka_posting_brand_item_map_rows')
|
||||
->where('company_id', $companyId)
|
||||
->whereIn('product_code', $lookupCodes)
|
||||
->get(['product_code', 'brand_item_number'])
|
||||
->filter(static fn (object $row): bool => trim((string) $row->brand_item_number) !== '')
|
||||
->keyBy(static fn (object $row): string => (string) $row->product_code)
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $itemNumbers
|
||||
* @return array<string,object>
|
||||
*/
|
||||
public function itemBrandItemMaps(int $companyId, array $itemNumbers): array
|
||||
{
|
||||
$itemNumbers = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $value): string => trim((string) $value),
|
||||
$itemNumbers,
|
||||
))));
|
||||
if ($itemNumbers === []
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_item_brand_item_map_rows')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->connection()
|
||||
->table('kuka_posting_item_brand_item_map_rows')
|
||||
->where('company_id', $companyId)
|
||||
->whereIn('item_number', $itemNumbers)
|
||||
->get(['item_number', 'brand_item_number'])
|
||||
->filter(static fn (object $row): bool => trim((string) $row->brand_item_number) !== '')
|
||||
->keyBy(static fn (object $row): string => (string) $row->item_number)
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $materialNumbers
|
||||
* @return array<string,object>
|
||||
*/
|
||||
public function effectiveQuotations(int $companyId, array $materialNumbers): array
|
||||
{
|
||||
$materialNumbers = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $value): string => trim((string) $value),
|
||||
$materialNumbers,
|
||||
))));
|
||||
if ($materialNumbers === []
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->connection()
|
||||
->table('kuka_posting_quotation_rows')
|
||||
->where('company_id', $companyId)
|
||||
->where('record_status', '生效')
|
||||
->whereIn('material_number', $materialNumbers)
|
||||
->get(['material_number', 'material_desc', 'price_including_tax'])
|
||||
->keyBy(static fn (object $row): string => (string) $row->material_number)
|
||||
->all();
|
||||
}
|
||||
|
||||
public function paginate(
|
||||
int $companyId,
|
||||
string $period,
|
||||
|
||||
434
app/Business/KukaPostingBase/KukaPostingLabelImporter.php
Normal file
434
app/Business/KukaPostingBase/KukaPostingLabelImporter.php
Normal file
@ -0,0 +1,434 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\KukaPostingBase;
|
||||
|
||||
use App\Business\XlsxSheetReader;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
class KukaPostingLabelImporter
|
||||
{
|
||||
private const LABEL_FIELD = '过账标签';
|
||||
|
||||
private const ALLOWED_LABELS = [
|
||||
'是',
|
||||
'补单(订单四组)',
|
||||
];
|
||||
|
||||
private const IDENTITY_FIELDS = [
|
||||
'店铺',
|
||||
'内部订单号',
|
||||
'线上订单号',
|
||||
'商品编码',
|
||||
'原始线上订单号',
|
||||
];
|
||||
|
||||
private const UPDATE_CHUNK = 500;
|
||||
|
||||
public function __construct(
|
||||
private readonly DatabaseManager $databases,
|
||||
private readonly XlsxSheetReader $reader,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* period: string,
|
||||
* dry_run: bool,
|
||||
* label_column: string,
|
||||
* rows: int,
|
||||
* stores: array<string, int>,
|
||||
* store_count: int,
|
||||
* labels: array<string, int>,
|
||||
* updated: int,
|
||||
* unchanged: int,
|
||||
* file_sha256: string
|
||||
* }
|
||||
*/
|
||||
public function import(
|
||||
string $path,
|
||||
string $period,
|
||||
?string $sheetName = null,
|
||||
?string $labelColumn = null,
|
||||
int $companyId = 1,
|
||||
bool $dryRun = false,
|
||||
): array {
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
||||
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
|
||||
}
|
||||
if (! is_file($path) || ! is_readable($path)) {
|
||||
throw new InvalidArgumentException('月度过账标签文件不存在或不可读。');
|
||||
}
|
||||
|
||||
$connection = $this->connection();
|
||||
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) {
|
||||
throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。');
|
||||
}
|
||||
|
||||
$allowedStores = array_values(array_filter(array_map(
|
||||
static fn (mixed $store): string => trim((string) $store),
|
||||
(array) config('kuka_posting.stores', []),
|
||||
)));
|
||||
if ($allowedStores === []) {
|
||||
throw new RuntimeException('顾家过账基础数据店铺范围未配置。');
|
||||
}
|
||||
|
||||
$labelColumn = trim((string) ($labelColumn ?? ''));
|
||||
if ($labelColumn === '') {
|
||||
$labelColumn = CarbonImmutable::createFromFormat('!Y-m', $period)
|
||||
->format('Y年n月过账');
|
||||
}
|
||||
|
||||
$sheetName = trim((string) ($sheetName ?? ''));
|
||||
if ($sheetName === '') {
|
||||
$sheetName = 'Sheet1';
|
||||
}
|
||||
$fileHash = hash_file('sha256', $path);
|
||||
if (! is_string($fileHash)) {
|
||||
throw new RuntimeException('无法计算月度过账标签文件摘要。');
|
||||
}
|
||||
|
||||
$records = $this->readRecords(
|
||||
$path,
|
||||
$sheetName,
|
||||
$labelColumn,
|
||||
$allowedStores,
|
||||
);
|
||||
|
||||
if ($dryRun) {
|
||||
return $this->validateRows(
|
||||
$connection,
|
||||
$records,
|
||||
$period,
|
||||
$labelColumn,
|
||||
$companyId,
|
||||
false,
|
||||
) + [
|
||||
'dry_run' => true,
|
||||
'file_sha256' => strtolower($fileHash),
|
||||
];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$connection->transaction(function () use (
|
||||
&$result,
|
||||
$connection,
|
||||
$records,
|
||||
$period,
|
||||
$labelColumn,
|
||||
$companyId,
|
||||
): void {
|
||||
$result = $this->validateRows(
|
||||
$connection,
|
||||
$records,
|
||||
$period,
|
||||
$labelColumn,
|
||||
$companyId,
|
||||
true,
|
||||
);
|
||||
$this->applyLabels($connection, $records, $period, $companyId);
|
||||
});
|
||||
|
||||
return $result + [
|
||||
'dry_run' => false,
|
||||
'file_sha256' => strtolower($fileHash),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $allowedStores
|
||||
* @return list<array{excel_row_number: int, label: string, identity: array<string, string>}>
|
||||
*/
|
||||
private function readRecords(
|
||||
string $path,
|
||||
string $sheetName,
|
||||
string $labelColumn,
|
||||
array $allowedStores,
|
||||
): array {
|
||||
$records = [];
|
||||
$excelRowNumber = 1;
|
||||
|
||||
foreach ($this->reader->rows(
|
||||
$path,
|
||||
array_merge([$labelColumn], self::IDENTITY_FIELDS),
|
||||
[],
|
||||
$sheetName,
|
||||
) as $values) {
|
||||
$excelRowNumber++;
|
||||
|
||||
$label = trim((string) ($values[$labelColumn] ?? ''));
|
||||
if (! in_array($label, self::ALLOWED_LABELS, true)) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Excel 第 %d 行的“%s”只能为“%s”,当前值为“%s”。',
|
||||
$excelRowNumber,
|
||||
$labelColumn,
|
||||
implode('”或“', self::ALLOWED_LABELS),
|
||||
$label,
|
||||
));
|
||||
}
|
||||
|
||||
$identity = [];
|
||||
foreach (self::IDENTITY_FIELDS as $field) {
|
||||
$identity[$field] = trim((string) ($values[$field] ?? ''));
|
||||
}
|
||||
if (! in_array($identity['店铺'], $allowedStores, true)) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Excel 第 %d 行的店铺“%s”不在顾家过账基础数据范围内。',
|
||||
$excelRowNumber,
|
||||
$identity['店铺'],
|
||||
));
|
||||
}
|
||||
|
||||
$records[] = [
|
||||
'excel_row_number' => $excelRowNumber,
|
||||
'label' => $label,
|
||||
'identity' => $identity,
|
||||
];
|
||||
}
|
||||
|
||||
if ($records === []) {
|
||||
throw new RuntimeException('月度过账标签文件没有数据行。');
|
||||
}
|
||||
|
||||
return $records;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{excel_row_number: int, label: string, identity: array<string, string>}> $records
|
||||
* @return array{
|
||||
* period: string,
|
||||
* label_column: string,
|
||||
* rows: int,
|
||||
* stores: array<string, int>,
|
||||
* store_count: int,
|
||||
* labels: array<string, int>,
|
||||
* updated: int,
|
||||
* unchanged: int
|
||||
* }
|
||||
*/
|
||||
private function validateRows(
|
||||
ConnectionInterface $connection,
|
||||
array $records,
|
||||
string $period,
|
||||
string $labelColumn,
|
||||
int $companyId,
|
||||
bool $lockRows,
|
||||
): array {
|
||||
$expectedRows = count($records);
|
||||
$databaseRows = $this->baseRowsQuery($connection, $period, $companyId)
|
||||
->count();
|
||||
if ($databaseRows !== $expectedRows) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'月度过账标签文件有 %s 行,但共享镜像 %s 有 %s 行,行数不一致,未写入任何标签。',
|
||||
number_format($expectedRows),
|
||||
$period,
|
||||
number_format($databaseRows),
|
||||
));
|
||||
}
|
||||
|
||||
$labels = array_fill_keys(self::ALLOWED_LABELS, 0);
|
||||
$stores = [];
|
||||
$updated = 0;
|
||||
$unchanged = 0;
|
||||
$index = 0;
|
||||
$query = $this->baseRowsQuery($connection, $period, $companyId)
|
||||
->orderBy('source_row_number');
|
||||
if ($lockRows) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
foreach ($query->cursor() as $row) {
|
||||
$record = $records[$index] ?? null;
|
||||
if ($record === null) {
|
||||
throw new RuntimeException('共享镜像行数多于月度过账标签文件,未写入任何标签。');
|
||||
}
|
||||
|
||||
$sourceValues = $this->decodeSourceValues($row);
|
||||
$this->assertIdentity($row, $sourceValues, $record);
|
||||
|
||||
$label = $record['label'];
|
||||
$labels[$label]++;
|
||||
$store = $record['identity']['店铺'];
|
||||
$stores[$store] = ($stores[$store] ?? 0) + 1;
|
||||
|
||||
if (trim((string) ($sourceValues[self::LABEL_FIELD] ?? '')) === $label) {
|
||||
$unchanged++;
|
||||
} else {
|
||||
$updated++;
|
||||
}
|
||||
|
||||
$index++;
|
||||
}
|
||||
|
||||
if ($index !== $expectedRows) {
|
||||
throw new RuntimeException('共享镜像行数少于月度过账标签文件,未写入任何标签。');
|
||||
}
|
||||
|
||||
ksort($stores);
|
||||
|
||||
return [
|
||||
'period' => $period,
|
||||
'label_column' => $labelColumn,
|
||||
'rows' => $expectedRows,
|
||||
'stores' => $stores,
|
||||
'store_count' => count($stores),
|
||||
'labels' => $labels,
|
||||
'updated' => $updated,
|
||||
'unchanged' => $unchanged,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{excel_row_number: int, label: string, identity: array<string, string>}> $records
|
||||
*/
|
||||
private function applyLabels(
|
||||
ConnectionInterface $connection,
|
||||
array $records,
|
||||
string $period,
|
||||
int $companyId,
|
||||
): void {
|
||||
$index = 0;
|
||||
$batch = [];
|
||||
$flush = static function () use (&$batch, $connection): void {
|
||||
if ($batch === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection->table('kuka_posting_base_rows')->upsert(
|
||||
$batch,
|
||||
['company_id', 'period', 'source_row_number'],
|
||||
['source_values', 'row_hash'],
|
||||
);
|
||||
$batch = [];
|
||||
};
|
||||
|
||||
foreach ($this->baseRowsQuery($connection, $period, $companyId)
|
||||
->orderBy('source_row_number')
|
||||
->cursor() as $row) {
|
||||
$record = $records[$index] ?? null;
|
||||
if ($record === null) {
|
||||
throw new RuntimeException('共享镜像行数多于月度过账标签文件,标签写入已回滚。');
|
||||
}
|
||||
|
||||
$sourceValues = $this->decodeSourceValues($row);
|
||||
$this->assertIdentity($row, $sourceValues, $record);
|
||||
$index++;
|
||||
|
||||
if (trim((string) ($sourceValues[self::LABEL_FIELD] ?? '')) === $record['label']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sourceValues[self::LABEL_FIELD] = $record['label'];
|
||||
$encoded = json_encode(
|
||||
$sourceValues,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
);
|
||||
$batch[] = [
|
||||
'company_id' => $companyId,
|
||||
'period' => $period,
|
||||
'source_row_number' => (int) $row->source_row_number,
|
||||
'store_name' => $row->store_name,
|
||||
'internal_order_no' => $row->internal_order_no,
|
||||
'online_order_no' => $row->online_order_no,
|
||||
'product_code' => $row->product_code,
|
||||
'source_values' => $encoded,
|
||||
'row_hash' => hash('sha256', $encoded),
|
||||
'imported_at' => $row->imported_at,
|
||||
];
|
||||
|
||||
if (count($batch) >= self::UPDATE_CHUNK) {
|
||||
$flush();
|
||||
}
|
||||
}
|
||||
|
||||
if ($index !== count($records)) {
|
||||
throw new RuntimeException('共享镜像行数少于月度过账标签文件,标签写入已回滚。');
|
||||
}
|
||||
|
||||
$flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function decodeSourceValues(object $row): array
|
||||
{
|
||||
$values = json_decode(
|
||||
(string) $row->source_values,
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR,
|
||||
);
|
||||
if (! is_array($values)) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'共享镜像 source_row_number=%d 的源数据不是有效对象。',
|
||||
(int) $row->source_row_number,
|
||||
));
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $sourceValues
|
||||
* @param array{excel_row_number: int, label: string, identity: array<string, string>} $record
|
||||
*/
|
||||
private function assertIdentity(object $row, array $sourceValues, array $record): void
|
||||
{
|
||||
$databaseIdentity = [
|
||||
'店铺' => trim((string) ($sourceValues['店铺'] ?? '')),
|
||||
'内部订单号' => trim((string) ($sourceValues['内部订单号'] ?? '')),
|
||||
'线上订单号' => trim((string) ($sourceValues['线上订单号'] ?? '')),
|
||||
'商品编码' => trim((string) ($sourceValues['商品编码'] ?? '')),
|
||||
'原始线上订单号' => trim((string) ($sourceValues['原始线上订单号'] ?? '')),
|
||||
];
|
||||
|
||||
foreach ($databaseIdentity as $field => $value) {
|
||||
if ($value !== $record['identity'][$field]) {
|
||||
throw new RuntimeException(sprintf(
|
||||
'Excel 第 %d 行与共享镜像 source_row_number=%d 的“%s”不一致,未写入任何标签。',
|
||||
$record['excel_row_number'],
|
||||
(int) $row->source_row_number,
|
||||
$field,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// 顶层订单字段是页面搜索用的冗余索引,历史数据可能保留旧值。
|
||||
// 行身份以 source_values 中的业务源字段为准,本命令不会改动这些索引字段。
|
||||
}
|
||||
|
||||
private function baseRowsQuery(
|
||||
ConnectionInterface $connection,
|
||||
string $period,
|
||||
int $companyId,
|
||||
) {
|
||||
return $connection->table('kuka_posting_base_rows')
|
||||
->where('company_id', $companyId)
|
||||
->where('period', $period)
|
||||
->select([
|
||||
'id',
|
||||
'source_row_number',
|
||||
'store_name',
|
||||
'internal_order_no',
|
||||
'online_order_no',
|
||||
'product_code',
|
||||
'source_values',
|
||||
'imported_at',
|
||||
]);
|
||||
}
|
||||
|
||||
private function connection(): ConnectionInterface
|
||||
{
|
||||
return $this->databases->connection($this->connectionName());
|
||||
}
|
||||
|
||||
private function connectionName(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,505 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\KukaPostingBase;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class KukaPostingMaterialMapSynchronizer
|
||||
{
|
||||
public const SOURCE_KEY = 'furniture3d';
|
||||
public const DATASET_KEY = 'furniture3d.kuka-material-map';
|
||||
|
||||
private const INSERT_CHUNK = 500;
|
||||
private const SOURCE_ITEM_CHUNK = 200;
|
||||
|
||||
public function __construct(
|
||||
private readonly DatabaseManager $databases,
|
||||
private readonly UpstreamReadOnlyQueryFactory $queries,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* dry_run: bool,
|
||||
* items: int,
|
||||
* matched: int,
|
||||
* unmatched: int,
|
||||
* ambiguous: int,
|
||||
* direct: int,
|
||||
* archive: int,
|
||||
* brand_sku: int,
|
||||
* brand_item_mappings: int,
|
||||
* brand_sku_mappings: int,
|
||||
* item_brand_mappings: int
|
||||
* }
|
||||
*/
|
||||
public function sync(int $companyId = 1, ?string $period = null, bool $dryRun = false): array
|
||||
{
|
||||
$connection = $this->connection();
|
||||
|
||||
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_material_map_rows')
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_brand_item_map_rows')
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_item_brand_item_map_rows')
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) {
|
||||
throw new RuntimeException('顾家物料匹配所需的数据表尚未建立,请先执行数据库迁移。');
|
||||
}
|
||||
|
||||
$started = microtime(true);
|
||||
$this->markState('running', 0, null, $started);
|
||||
|
||||
try {
|
||||
$identifiers = $this->sourceIdentifiers($connection, $companyId, $period);
|
||||
$items = $identifiers['items'];
|
||||
if ($items === []) {
|
||||
throw new RuntimeException('当前账期没有可用于匹配的货号。');
|
||||
}
|
||||
|
||||
$quotations = $this->activeQuotations($connection, $companyId);
|
||||
[$direct, $archive, $brandSku] = $this->sourceCandidates($items);
|
||||
$rows = $this->resolveRows($companyId, $items, $quotations, $direct, $archive, $brandSku);
|
||||
$stats = $this->stats($rows);
|
||||
$displayItemResult = $this->displayItemRows(
|
||||
$companyId,
|
||||
$identifiers['style_codes'],
|
||||
$items,
|
||||
);
|
||||
|
||||
if (! $dryRun) {
|
||||
$connection->transaction(function () use ($connection, $companyId, $rows, $displayItemResult): void {
|
||||
$connection->table('kuka_posting_material_map_rows')
|
||||
->where('company_id', $companyId)
|
||||
->delete();
|
||||
$connection->table('kuka_posting_brand_item_map_rows')
|
||||
->where('company_id', $companyId)
|
||||
->delete();
|
||||
$connection->table('kuka_posting_item_brand_item_map_rows')
|
||||
->where('company_id', $companyId)
|
||||
->delete();
|
||||
|
||||
foreach (array_chunk($rows, self::INSERT_CHUNK) as $chunk) {
|
||||
$connection->table('kuka_posting_material_map_rows')->insert($chunk);
|
||||
}
|
||||
foreach (array_chunk($displayItemResult['style_rows'], self::INSERT_CHUNK) as $chunk) {
|
||||
$connection->table('kuka_posting_brand_item_map_rows')->insert($chunk);
|
||||
}
|
||||
foreach (array_chunk($displayItemResult['item_rows'], self::INSERT_CHUNK) as $chunk) {
|
||||
$connection->table('kuka_posting_item_brand_item_map_rows')->insert($chunk);
|
||||
}
|
||||
});
|
||||
|
||||
$this->markState('succeeded', count($rows), null, $started);
|
||||
}
|
||||
|
||||
return ['dry_run' => $dryRun] + $stats + [
|
||||
'brand_item_mappings' => count($displayItemResult['style_rows'])
|
||||
+ count($displayItemResult['item_rows']),
|
||||
'brand_sku_mappings' => count($displayItemResult['style_rows']),
|
||||
'item_brand_mappings' => count($displayItemResult['item_rows']),
|
||||
];
|
||||
} catch (Throwable $exception) {
|
||||
if (! $dryRun) {
|
||||
$this->markState('failed', 0, $exception::class, $started);
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{items:list<string>,style_codes:list<string>} */
|
||||
private function sourceIdentifiers(ConnectionInterface $connection, int $companyId, ?string $period): array
|
||||
{
|
||||
$items = [];
|
||||
$styleCodes = [];
|
||||
$query = $connection->table('kuka_posting_base_rows')
|
||||
->where('company_id', $companyId)
|
||||
->when($period !== null, fn ($builder) => $builder->where('period', $period));
|
||||
|
||||
$query->select(['id', 'source_values'])
|
||||
->orderBy('id')
|
||||
->chunkById(1000, function ($rows) use (&$items, &$styleCodes): void {
|
||||
foreach ($rows as $row) {
|
||||
$values = json_decode((string) $row->source_values, true);
|
||||
if (! is_array($values)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$itemNumber = trim((string) ($values['货号'] ?? ''));
|
||||
if ($itemNumber !== '') {
|
||||
$items[$itemNumber] = true;
|
||||
}
|
||||
$styleCode = trim((string) ($values['款式编码'] ?? ''));
|
||||
if ($styleCode !== '') {
|
||||
$styleCodes[$styleCode] = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$items = array_keys($items);
|
||||
sort($items, SORT_STRING);
|
||||
$styleCodes = array_keys($styleCodes);
|
||||
sort($styleCodes, SORT_STRING);
|
||||
|
||||
return ['items' => $items, 'style_codes' => $styleCodes];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $styleCodes
|
||||
* @param list<string> $itemNumbers
|
||||
* @return array{
|
||||
* style_rows:list<array<string,mixed>>,
|
||||
* item_rows:list<array<string,mixed>>
|
||||
* }
|
||||
*/
|
||||
private function displayItemRows(int $companyId, array $styleCodes, array $itemNumbers): array
|
||||
{
|
||||
$query = $this->queries->forSourceWithTimeout(self::SOURCE_KEY, 15);
|
||||
$styleRows = [];
|
||||
$itemRows = [];
|
||||
$now = now();
|
||||
|
||||
foreach (array_chunk($styleCodes, self::SOURCE_ITEM_CHUNK) as $chunk) {
|
||||
foreach ($query->select($this->brandItemSql(count($chunk)), $chunk) as $sourceRow) {
|
||||
$styleCode = trim((string) ($sourceRow['lookup_code'] ?? ''));
|
||||
$brandItemNumber = trim((string) ($sourceRow['brand_item_number'] ?? ''));
|
||||
if ($styleCode === '' || $brandItemNumber === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sourceImportedAt = trim((string) ($sourceRow['source_imported_at'] ?? ''));
|
||||
$styleRows[] = [
|
||||
'company_id' => $companyId,
|
||||
'product_code' => $styleCode,
|
||||
'brand_item_number' => $brandItemNumber,
|
||||
'source_imported_at' => $sourceImportedAt === '' ? null : $sourceImportedAt,
|
||||
'synced_at' => $now,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
foreach (array_chunk($itemNumbers, self::SOURCE_ITEM_CHUNK) as $chunk) {
|
||||
foreach ($query->select($this->brandItemSql(count($chunk)), $chunk) as $sourceRow) {
|
||||
$itemNumber = trim((string) ($sourceRow['lookup_code'] ?? ''));
|
||||
$brandItemNumber = trim((string) ($sourceRow['brand_item_number'] ?? ''));
|
||||
if ($itemNumber === '' || $brandItemNumber === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sourceImportedAt = trim((string) ($sourceRow['source_imported_at'] ?? ''));
|
||||
$itemRows[] = [
|
||||
'company_id' => $companyId,
|
||||
'item_number' => $itemNumber,
|
||||
'brand_item_number' => $brandItemNumber,
|
||||
'source_imported_at' => $sourceImportedAt === '' ? null : $sourceImportedAt,
|
||||
'synced_at' => $now,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'style_rows' => $styleRows,
|
||||
'item_rows' => $itemRows,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function activeQuotations(ConnectionInterface $connection, int $companyId): array
|
||||
{
|
||||
return $connection->table('kuka_posting_quotation_rows')
|
||||
->where('company_id', $companyId)
|
||||
->where('record_status', '生效')
|
||||
->get(['material_number', 'material_desc'])
|
||||
->mapWithKeys(static function (object $row): array {
|
||||
$materialNumber = trim((string) $row->material_number);
|
||||
|
||||
return $materialNumber === ''
|
||||
? []
|
||||
: [$materialNumber => trim((string) $row->material_desc)];
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $items
|
||||
* @return array{
|
||||
* 0:array<string,array<string,true>>,
|
||||
* 1:array<string,array<string,true>>,
|
||||
* 2:array<string,array<string,true>>
|
||||
* }
|
||||
*/
|
||||
private function sourceCandidates(array $items): array
|
||||
{
|
||||
$direct = [];
|
||||
$archive = [];
|
||||
$brandSku = [];
|
||||
$query = $this->queries->forSourceWithTimeout(self::SOURCE_KEY, 15);
|
||||
|
||||
foreach (array_chunk($items, self::SOURCE_ITEM_CHUNK) as $chunk) {
|
||||
$directRows = $query->select($this->directSql(count($chunk)), $chunk);
|
||||
$this->collectCandidates(
|
||||
$direct,
|
||||
$directRows,
|
||||
);
|
||||
$this->collectCandidates($brandSku, $directRows, 'brand_sku');
|
||||
$this->collectCandidates(
|
||||
$archive,
|
||||
$query->select($this->archiveSql(count($chunk)), $chunk),
|
||||
);
|
||||
}
|
||||
|
||||
return [$direct, $archive, $brandSku];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,array<string,true>> $target
|
||||
* @param list<array<string,mixed>> $rows
|
||||
*/
|
||||
private function collectCandidates(
|
||||
array &$target,
|
||||
array $rows,
|
||||
string $materialField = 'material_number',
|
||||
): void
|
||||
{
|
||||
foreach ($rows as $row) {
|
||||
$itemNumber = trim((string) ($row['item_number'] ?? ''));
|
||||
$materialNumber = trim((string) ($row[$materialField] ?? ''));
|
||||
if ($itemNumber === '' || $materialNumber === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$target[$itemNumber][$materialNumber] = true;
|
||||
}
|
||||
}
|
||||
|
||||
private function directSql(int $count): string
|
||||
{
|
||||
$placeholders = implode(', ', array_fill(0, $count, '?'));
|
||||
|
||||
return 'SELECT "normalizedSku" AS item_number, '
|
||||
. 'TRIM(updates->>\'materialNo\') AS material_number, '
|
||||
. 'TRIM(updates->>\'brandSkuCode\') AS brand_sku '
|
||||
. 'FROM public."BarcodePrintImportRecord" '
|
||||
. 'WHERE "normalizedSku" IN (' . $placeholders . ') '
|
||||
. 'AND (COALESCE(updates->>\'materialNo\', \'\') <> \'\' '
|
||||
. 'OR COALESCE(updates->>\'brandSkuCode\', \'\') <> \'\') '
|
||||
. 'GROUP BY "normalizedSku", updates->>\'materialNo\', updates->>\'brandSkuCode\' '
|
||||
. 'LIMIT 5000';
|
||||
}
|
||||
|
||||
private function archiveSql(int $count): string
|
||||
{
|
||||
$placeholders = implode(', ', array_fill(0, $count, '?'));
|
||||
|
||||
return 'SELECT TRIM(sku) AS item_number, TRIM(barcode) AS material_number '
|
||||
. 'FROM public."SupplyChainProductArchive" '
|
||||
. 'WHERE sku IN (' . $placeholders . ') '
|
||||
. 'AND COALESCE(TRIM(barcode), \'\') <> \'\' '
|
||||
. 'GROUP BY sku, barcode '
|
||||
. 'LIMIT 5000';
|
||||
}
|
||||
|
||||
private function brandItemSql(int $count): string
|
||||
{
|
||||
$placeholders = implode(', ', array_fill(0, $count, '?'));
|
||||
|
||||
return 'SELECT DISTINCT ON ("normalizedSku") '
|
||||
. '"normalizedSku" AS lookup_code, '
|
||||
. 'TRIM(updates->>\'brandSkuCode\') AS brand_item_number, '
|
||||
. '"importedAt" AS source_imported_at '
|
||||
. 'FROM public."BarcodePrintImportRecord" '
|
||||
. 'WHERE "normalizedSku" IN (' . $placeholders . ') '
|
||||
. 'AND COALESCE(TRIM(updates->>\'brandSkuCode\'), \'\') <> \'\' '
|
||||
. 'ORDER BY "normalizedSku", "importedAt" DESC NULLS LAST, id DESC '
|
||||
. 'LIMIT 5000';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $items
|
||||
* @param array<string,true> $quoteMaterials
|
||||
* @param array<string,array<string,true>> $direct
|
||||
* @param array<string,array<string,true>> $archive
|
||||
* @param array<string,array<string,true>> $brandSku
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function resolveRows(
|
||||
int $companyId,
|
||||
array $items,
|
||||
array $quotations,
|
||||
array $direct,
|
||||
array $archive,
|
||||
array $brandSku,
|
||||
): array {
|
||||
$quoteKeys = array_keys($quotations);
|
||||
$brandMaterials = $this->quoteBrandMaterials($quotations);
|
||||
$rows = [];
|
||||
$now = now();
|
||||
|
||||
foreach ($items as $itemNumber) {
|
||||
$directMatches = array_values(array_unique(array_intersect(
|
||||
array_keys($direct[$itemNumber] ?? []),
|
||||
$quoteKeys,
|
||||
)));
|
||||
$archiveMatches = array_values(array_unique(array_intersect(
|
||||
array_keys($archive[$itemNumber] ?? []),
|
||||
$quoteKeys,
|
||||
)));
|
||||
$brandMatches = [];
|
||||
foreach (array_keys($brandSku[$itemNumber] ?? []) as $brand) {
|
||||
foreach (array_keys($brandMaterials[$brand] ?? []) as $materialNumber) {
|
||||
$brandMatches[] = $materialNumber;
|
||||
}
|
||||
}
|
||||
$brandMatches = array_values(array_unique($brandMatches));
|
||||
$matches = array_values(array_unique(array_merge(
|
||||
$directMatches,
|
||||
$archiveMatches,
|
||||
$brandMatches,
|
||||
)));
|
||||
|
||||
$materialNumber = null;
|
||||
$matchSource = null;
|
||||
if (count($directMatches) === 1) {
|
||||
$materialNumber = $directMatches[0];
|
||||
$matchSource = 'barcode_material_no';
|
||||
} elseif ($directMatches === [] && count($archiveMatches) === 1) {
|
||||
$materialNumber = $archiveMatches[0];
|
||||
$matchSource = 'archive_barcode';
|
||||
} elseif ($directMatches === [] && $archiveMatches === [] && count($brandMatches) === 1) {
|
||||
$materialNumber = $brandMatches[0];
|
||||
$matchSource = 'brand_sku';
|
||||
}
|
||||
|
||||
$status = match (true) {
|
||||
$materialNumber !== null => 'matched',
|
||||
count($matches) > 1 => 'ambiguous',
|
||||
default => 'unmatched',
|
||||
};
|
||||
|
||||
$rows[] = [
|
||||
'company_id' => $companyId,
|
||||
'item_number' => $itemNumber,
|
||||
'material_number' => $materialNumber,
|
||||
'match_status' => $status,
|
||||
'match_source' => $matchSource,
|
||||
'candidate_count' => count($matches),
|
||||
'candidate_materials' => json_encode(
|
||||
$matches,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
),
|
||||
'synced_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string> $quotations
|
||||
* @return array<string,array<string,true>>
|
||||
*/
|
||||
private function quoteBrandMaterials(array $quotations): array
|
||||
{
|
||||
$materials = [];
|
||||
|
||||
foreach ($quotations as $materialNumber => $description) {
|
||||
$brand = trim(explode('~', $description, 2)[0]);
|
||||
if ($brand !== '') {
|
||||
$materials[$brand][$materialNumber] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $materials;
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $rows */
|
||||
private function stats(array $rows): array
|
||||
{
|
||||
$counts = ['matched' => 0, 'unmatched' => 0, 'ambiguous' => 0];
|
||||
$sources = ['barcode_material_no' => 0, 'archive_barcode' => 0, 'brand_sku' => 0];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$counts[$row['match_status']]++;
|
||||
if ($row['match_source'] !== null) {
|
||||
$sources[$row['match_source']]++;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'items' => count($rows),
|
||||
'matched' => $counts['matched'],
|
||||
'unmatched' => $counts['unmatched'],
|
||||
'ambiguous' => $counts['ambiguous'],
|
||||
'direct' => $sources['barcode_material_no'],
|
||||
'archive' => $sources['archive_barcode'],
|
||||
'brand_sku' => $sources['brand_sku'],
|
||||
];
|
||||
}
|
||||
|
||||
private function markState(
|
||||
string $status,
|
||||
int $rowCount,
|
||||
?string $errorCode,
|
||||
float $started,
|
||||
): void {
|
||||
if (! Schema::connection($this->connectionName())->hasTable('business_mirror_table_states')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $this->connection();
|
||||
$now = now();
|
||||
$existing = $connection->table('business_mirror_table_states')
|
||||
->where('dataset_key', self::DATASET_KEY)
|
||||
->first();
|
||||
$values = [
|
||||
'source_key' => self::SOURCE_KEY,
|
||||
'source_object' => 'public.SupplyChainProductArchive + public.BarcodePrintImportRecord',
|
||||
'target_table' => 'kuka_posting_material_map_rows',
|
||||
'status' => $status,
|
||||
'run_mode' => 'targeted',
|
||||
'last_attempted_at' => $now,
|
||||
'last_error_code' => $errorCode === null ? null : mb_substr($errorCode, 0, 120),
|
||||
'updated_at' => $now,
|
||||
];
|
||||
|
||||
if ($status === 'succeeded') {
|
||||
$values += [
|
||||
'initial_completed_at' => $existing?->initial_completed_at ?? $now,
|
||||
'last_succeeded_at' => $now,
|
||||
'last_upserted_rows' => $rowCount,
|
||||
'mirror_row_count' => $rowCount,
|
||||
];
|
||||
if (Schema::connection($this->connectionName())
|
||||
->hasColumn('business_mirror_table_states', 'mirror_row_count_is_exact')) {
|
||||
$values['mirror_row_count_is_exact'] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($existing !== null) {
|
||||
$connection->table('business_mirror_table_states')
|
||||
->where('dataset_key', self::DATASET_KEY)
|
||||
->update($values);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$connection->table('business_mirror_table_states')->insert($values + [
|
||||
'dataset_key' => self::DATASET_KEY,
|
||||
'created_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
private function connection(): ConnectionInterface
|
||||
{
|
||||
return $this->databases->connection($this->connectionName());
|
||||
}
|
||||
|
||||
private function connectionName(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
}
|
||||
1034
app/Business/KukaPostingBase/KukaPostingMaterialRepairImporter.php
Normal file
1034
app/Business/KukaPostingBase/KukaPostingMaterialRepairImporter.php
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,314 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\KukaPostingPerformance;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Throwable;
|
||||
|
||||
class KukaPostingPerformancePageData
|
||||
{
|
||||
private const EXCLUDED_PLATFORMS = ['京东网银钱包'];
|
||||
|
||||
private const INCOME_SQL = 'COALESCE(income_amount, 0)'
|
||||
. ' + COALESCE(discount_amount, 0)'
|
||||
. ' + COALESCE(offset_amount, 0)'
|
||||
. ' + COALESCE(refund_amount, 0)'
|
||||
. ' + COALESCE(default_compensation_amount, 0)';
|
||||
|
||||
/**
|
||||
* 业绩明细的 12 家店铺月度收入汇总。
|
||||
*
|
||||
* 收入口径:账单收入 + 优惠金额 + 冲减金额 + 退款金额 + 违约赔付(冲减收入)。
|
||||
*
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function build(Request $request): array
|
||||
{
|
||||
$stores = array_values(array_unique(array_filter(array_map(
|
||||
static fn (mixed $store): string => trim((string) $store),
|
||||
(array) config('kuka_posting.stores', []),
|
||||
))));
|
||||
|
||||
if ($stores === []) {
|
||||
return $this->emptyResult($stores, '尚未配置灵珊店铺业绩的店铺范围。');
|
||||
}
|
||||
|
||||
try {
|
||||
$months = $this->availableMonths();
|
||||
$month = $this->selectedMonth((string) $request->query('month', ''), $months);
|
||||
if ($month === null) {
|
||||
return $this->emptyResult($stores, '业绩明细暂时没有可汇总的月份。');
|
||||
}
|
||||
|
||||
$storeRows = cache()->remember(
|
||||
$this->cacheKey('stores', $month, $stores),
|
||||
now()->addMinutes(10),
|
||||
fn (): array => $this->storeRows($month, $stores),
|
||||
);
|
||||
|
||||
$monthlyTotals = cache()->remember(
|
||||
$this->cacheKey('months', implode('|', $months), $stores),
|
||||
now()->addMinutes(10),
|
||||
fn (): array => $this->monthlyTotals($months, $stores),
|
||||
);
|
||||
|
||||
$summary = $this->summary($storeRows);
|
||||
|
||||
return [
|
||||
'stores' => $storeRows,
|
||||
'months' => $months,
|
||||
'month' => $month,
|
||||
'month_label' => $this->monthLabel($month),
|
||||
'summary' => $summary,
|
||||
'monthly_totals' => $monthlyTotals,
|
||||
'error' => null,
|
||||
];
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return $this->emptyResult(
|
||||
$stores,
|
||||
'灵珊店铺业绩暂时无法读取,请稍后重试;这不代表该月收入为 0。',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function availableMonths(): array
|
||||
{
|
||||
return cache()->remember(
|
||||
$this->cacheKey('available-months'),
|
||||
now()->addMinutes(10),
|
||||
function (): array {
|
||||
$range = $this->connection()
|
||||
->table('store_receipt_order_match_rows')
|
||||
->whereNotIn('platform', self::EXCLUDED_PLATFORMS)
|
||||
->whereNotNull('report_month')
|
||||
->selectRaw('MIN(report_month) as min_month, MAX(report_month) as max_month')
|
||||
->first();
|
||||
|
||||
if (($range->min_month ?? null) === null || ($range->max_month ?? null) === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$end = CarbonImmutable::parse((string) $range->max_month)->startOfMonth();
|
||||
$start = CarbonImmutable::parse((string) $range->min_month)->startOfMonth();
|
||||
$earliest = now()->startOfMonth()->subMonthsNoOverflow(11);
|
||||
if ($start->lt($earliest)) {
|
||||
$start = $earliest;
|
||||
}
|
||||
|
||||
$months = [];
|
||||
for ($cursor = $end; $cursor->gte($start); $cursor = $cursor->subMonthNoOverflow()) {
|
||||
$months[] = $cursor->format('Y-m');
|
||||
}
|
||||
|
||||
return $months;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $months
|
||||
*/
|
||||
private function selectedMonth(string $requested, array $months): ?string
|
||||
{
|
||||
if (preg_match('/^\d{4}-\d{2}$/', $requested) === 1 && in_array($requested, $months, true)) {
|
||||
return $requested;
|
||||
}
|
||||
|
||||
$previousMonth = now()->subMonthNoOverflow()->format('Y-m');
|
||||
|
||||
return in_array($previousMonth, $months, true) ? $previousMonth : ($months[0] ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $stores
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function storeRows(string $month, array $stores): array
|
||||
{
|
||||
$aggregates = $this->connection()
|
||||
->table('store_receipt_order_match_rows')
|
||||
->where('report_month', $month . '-01')
|
||||
->whereIn('store_name', $stores)
|
||||
->whereNotIn('platform', self::EXCLUDED_PLATFORMS)
|
||||
->selectRaw(
|
||||
'store_name,
|
||||
COUNT(*) as row_count,
|
||||
SUM(COALESCE(income_amount, 0)) as income_amount,
|
||||
SUM(COALESCE(discount_amount, 0)) as discount_amount,
|
||||
SUM(COALESCE(offset_amount, 0)) as offset_amount,
|
||||
SUM(COALESCE(refund_amount, 0)) as refund_amount,
|
||||
SUM(COALESCE(default_compensation_amount, 0)) as default_compensation_amount,
|
||||
SUM(' . self::INCOME_SQL . ') as total_income,
|
||||
MAX(imported_at) as imported_at'
|
||||
)
|
||||
->groupBy('store_name')
|
||||
->get()
|
||||
->keyBy('store_name');
|
||||
|
||||
return array_map(static function (string $store) use ($aggregates): array {
|
||||
$row = $aggregates->get($store);
|
||||
|
||||
return [
|
||||
'store_name' => $store,
|
||||
'row_count' => (int) ($row->row_count ?? 0),
|
||||
'income_amount' => round((float) ($row->income_amount ?? 0), 2),
|
||||
'discount_amount' => round((float) ($row->discount_amount ?? 0), 2),
|
||||
'offset_amount' => round((float) ($row->offset_amount ?? 0), 2),
|
||||
'refund_amount' => round((float) ($row->refund_amount ?? 0), 2),
|
||||
'default_compensation_amount' => round((float) ($row->default_compensation_amount ?? 0), 2),
|
||||
'total_income' => round((float) ($row->total_income ?? 0), 2),
|
||||
'imported_at' => $row->imported_at ?? null,
|
||||
'has_data' => $row !== null,
|
||||
];
|
||||
}, $stores);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $months
|
||||
* @param list<string> $stores
|
||||
* @return list<array{month:string,label:string,total_income:float,row_count:int}>
|
||||
*/
|
||||
private function monthlyTotals(array $months, array $stores): array
|
||||
{
|
||||
$totals = [];
|
||||
foreach ($months as $month) {
|
||||
$row = $this->connection()
|
||||
->table('store_receipt_order_match_rows')
|
||||
->where('report_month', $month . '-01')
|
||||
->whereIn('store_name', $stores)
|
||||
->whereNotIn('platform', self::EXCLUDED_PLATFORMS)
|
||||
->selectRaw(
|
||||
'COUNT(*) as row_count,
|
||||
SUM(' . self::INCOME_SQL . ') as total_income'
|
||||
)
|
||||
->first();
|
||||
|
||||
$totals[] = [
|
||||
'month' => $month,
|
||||
'label' => $this->monthLabel($month),
|
||||
'total_income' => round((float) ($row->total_income ?? 0), 2),
|
||||
'row_count' => (int) ($row->row_count ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
return $totals;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function summary(array $rows): array
|
||||
{
|
||||
$summary = [
|
||||
'row_count' => 0,
|
||||
'stores_with_data' => 0,
|
||||
'income_amount' => 0.0,
|
||||
'discount_amount' => 0.0,
|
||||
'offset_amount' => 0.0,
|
||||
'refund_amount' => 0.0,
|
||||
'default_compensation_amount' => 0.0,
|
||||
'total_income' => 0.0,
|
||||
'imported_at' => null,
|
||||
];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$summary['row_count'] += (int) $row['row_count'];
|
||||
$summary['stores_with_data'] += $row['has_data'] ? 1 : 0;
|
||||
foreach ([
|
||||
'income_amount',
|
||||
'discount_amount',
|
||||
'offset_amount',
|
||||
'refund_amount',
|
||||
'default_compensation_amount',
|
||||
'total_income',
|
||||
] as $field) {
|
||||
$summary[$field] += (float) $row[$field];
|
||||
}
|
||||
|
||||
if ($row['imported_at'] !== null
|
||||
&& ($summary['imported_at'] === null || $row['imported_at'] > $summary['imported_at'])) {
|
||||
$summary['imported_at'] = $row['imported_at'];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'income_amount',
|
||||
'discount_amount',
|
||||
'offset_amount',
|
||||
'refund_amount',
|
||||
'default_compensation_amount',
|
||||
'total_income',
|
||||
] as $field) {
|
||||
$summary[$field] = round((float) $summary[$field], 2);
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $stores
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function emptyResult(array $stores, string $error): array
|
||||
{
|
||||
return [
|
||||
'stores' => array_map(static fn (string $store): array => [
|
||||
'store_name' => $store,
|
||||
'row_count' => 0,
|
||||
'income_amount' => 0.0,
|
||||
'discount_amount' => 0.0,
|
||||
'offset_amount' => 0.0,
|
||||
'refund_amount' => 0.0,
|
||||
'default_compensation_amount' => 0.0,
|
||||
'total_income' => 0.0,
|
||||
'imported_at' => null,
|
||||
'has_data' => false,
|
||||
], $stores),
|
||||
'months' => [],
|
||||
'month' => null,
|
||||
'month_label' => '—',
|
||||
'summary' => [
|
||||
'row_count' => 0,
|
||||
'stores_with_data' => 0,
|
||||
'income_amount' => 0.0,
|
||||
'discount_amount' => 0.0,
|
||||
'offset_amount' => 0.0,
|
||||
'refund_amount' => 0.0,
|
||||
'default_compensation_amount' => 0.0,
|
||||
'total_income' => 0.0,
|
||||
'imported_at' => null,
|
||||
],
|
||||
'monthly_totals' => [],
|
||||
'error' => $error,
|
||||
];
|
||||
}
|
||||
|
||||
private function connection()
|
||||
{
|
||||
return DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
||||
}
|
||||
|
||||
private function monthLabel(string $month): string
|
||||
{
|
||||
return substr($month, 0, 4) . '年' . (int) substr($month, 5, 2) . '月';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $stores
|
||||
*/
|
||||
private function cacheKey(string $scope, string $period = '', array $stores = []): string
|
||||
{
|
||||
return 'kuka-posting-performance-v1:' . $scope . ':' . md5(json_encode([
|
||||
$period,
|
||||
$stores,
|
||||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,251 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\KukaPostingQuotation;
|
||||
|
||||
use App\Business\XlsxSheetReader;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class KukaPostingQuotationImporter
|
||||
{
|
||||
private const INSERT_CHUNK = 500;
|
||||
|
||||
public function __construct(
|
||||
private readonly DatabaseManager $databases,
|
||||
private readonly XlsxSheetReader $reader,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* dry_run: bool,
|
||||
* rows: int,
|
||||
* material_count: int,
|
||||
* status_counts: array<string, int>,
|
||||
* file_sha256: string
|
||||
* }
|
||||
*/
|
||||
public function import(
|
||||
string $path,
|
||||
?string $sheetName = null,
|
||||
int $companyId = 1,
|
||||
bool $dryRun = false,
|
||||
): array {
|
||||
if (! is_file($path) || ! is_readable($path)) {
|
||||
throw new InvalidArgumentException('顾家报价单文件不存在或不可读。');
|
||||
}
|
||||
|
||||
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_imports')
|
||||
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) {
|
||||
throw new RuntimeException('顾家报价单表尚未建立,请先执行数据库迁移。');
|
||||
}
|
||||
|
||||
$fields = (array) config('kuka_posting.quotation_fields', []);
|
||||
$sourceColumns = array_values(array_filter(array_map(
|
||||
static fn (array $field): string => trim((string) ($field['source'] ?? '')),
|
||||
$fields,
|
||||
)));
|
||||
if ($fields === [] || count($sourceColumns) !== count($fields)) {
|
||||
throw new RuntimeException('顾家报价单字段配置不完整。');
|
||||
}
|
||||
|
||||
$keyField = (string) config('kuka_posting.quotation_key_field', 'MaterialNumber');
|
||||
$statusField = (string) config('kuka_posting.quotation_status_field', 'RecordStatus');
|
||||
if (! in_array($keyField, $sourceColumns, true) || ! in_array($statusField, $sourceColumns, true)) {
|
||||
throw new RuntimeException('顾家报价单缺少物料编码或状态字段配置。');
|
||||
}
|
||||
|
||||
$sheetName = trim((string) ($sheetName ?: config('kuka_posting.quotation_source_sheet', 'Sheet1')));
|
||||
$fileHash = hash_file('sha256', $path);
|
||||
if (! is_string($fileHash)) {
|
||||
throw new RuntimeException('无法计算顾家报价单文件摘要。');
|
||||
}
|
||||
|
||||
$connection = $this->connection();
|
||||
$rows = [];
|
||||
$materials = [];
|
||||
$statusCounts = [];
|
||||
$sourceRowNumber = 1;
|
||||
$now = now();
|
||||
|
||||
foreach ($this->reader->rows($path, $sourceColumns, [], $sheetName) as $sourceValues) {
|
||||
$sourceRowNumber++;
|
||||
|
||||
// 前两行分别是系统字段名和中文表名,真实报价记录从第 3 行开始。
|
||||
if ($sourceRowNumber < 3) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (count(array_filter(
|
||||
$sourceValues,
|
||||
static fn (mixed $value): bool => trim((string) $value) !== '',
|
||||
)) === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$payload = [];
|
||||
foreach ($fields as $field) {
|
||||
$source = (string) $field['source'];
|
||||
$value = trim((string) ($sourceValues[$source] ?? ''));
|
||||
if (($field['kind'] ?? null) === 'date' && $value !== '') {
|
||||
$value = $this->normalizeDate($value);
|
||||
}
|
||||
$payload[(string) $field['name']] = $value;
|
||||
}
|
||||
|
||||
$materialNumber = trim((string) ($payload['material_number'] ?? ''));
|
||||
if ($materialNumber === '') {
|
||||
throw new RuntimeException('顾家报价单第 ' . $sourceRowNumber . ' 行缺少物料编码。');
|
||||
}
|
||||
if (isset($materials[$materialNumber])) {
|
||||
throw new RuntimeException('顾家报价单存在重复物料编码:' . $materialNumber);
|
||||
}
|
||||
$materials[$materialNumber] = true;
|
||||
|
||||
$status = trim((string) ($payload['record_status'] ?? ''));
|
||||
if ($status !== '') {
|
||||
$statusCounts[$status] = ($statusCounts[$status] ?? 0) + 1;
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'company_id' => $companyId,
|
||||
'material_number' => $materialNumber,
|
||||
'material_desc' => $this->limit((string) ($payload['material_desc'] ?? ''), 500),
|
||||
'supplier_account' => $this->limit((string) ($payload['supplier_account'] ?? ''), 191),
|
||||
'supplier_name' => $this->limit((string) ($payload['supplier_name'] ?? ''), 500),
|
||||
'record_status' => $this->limit($status, 64),
|
||||
'price_including_tax' => $this->decimal((string) ($payload['price_including_tax'] ?? '')),
|
||||
'price_excluding_tax' => $this->decimal((string) ($payload['price_excluding_tax'] ?? '')),
|
||||
'price_valid_date' => $this->nullableValue((string) ($payload['price_valid_date'] ?? '')),
|
||||
'price_expiry_date' => $this->nullableValue((string) ($payload['price_expiry_date'] ?? '')),
|
||||
'row_hash' => hash(
|
||||
'sha256',
|
||||
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
|
||||
),
|
||||
'source_values' => json_encode(
|
||||
$payload,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
),
|
||||
'source_row_number' => $sourceRowNumber,
|
||||
'imported_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
if ($rows === []) {
|
||||
throw new RuntimeException('顾家报价单中没有可导入的报价记录。');
|
||||
}
|
||||
|
||||
ksort($statusCounts);
|
||||
|
||||
$write = function () use (
|
||||
$connection,
|
||||
$companyId,
|
||||
&$rows,
|
||||
$statusCounts,
|
||||
$sheetName,
|
||||
$path,
|
||||
$fileHash,
|
||||
$now,
|
||||
$dryRun,
|
||||
): void {
|
||||
if ($dryRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection->table('kuka_posting_quotation_rows')
|
||||
->where('company_id', $companyId)
|
||||
->delete();
|
||||
|
||||
foreach (array_chunk($rows, self::INSERT_CHUNK) as $chunk) {
|
||||
$connection->table('kuka_posting_quotation_rows')->insert($chunk);
|
||||
}
|
||||
|
||||
$connection->table('kuka_posting_quotation_imports')->upsert(
|
||||
[[
|
||||
'company_id' => $companyId,
|
||||
'row_count' => count($rows),
|
||||
'material_count' => count($rows),
|
||||
'status_counts' => json_encode($statusCounts, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||||
'file_name' => basename($path),
|
||||
'file_sha256' => strtolower($fileHash),
|
||||
'source_sheet' => $sheetName,
|
||||
'completed_at' => $now,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]],
|
||||
['company_id'],
|
||||
[
|
||||
'row_count',
|
||||
'material_count',
|
||||
'status_counts',
|
||||
'file_name',
|
||||
'file_sha256',
|
||||
'source_sheet',
|
||||
'completed_at',
|
||||
'updated_at',
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
if ($dryRun) {
|
||||
$write();
|
||||
} else {
|
||||
$connection->transaction($write);
|
||||
}
|
||||
|
||||
return [
|
||||
'dry_run' => $dryRun,
|
||||
'rows' => count($rows),
|
||||
'material_count' => count($materials),
|
||||
'status_counts' => $statusCounts,
|
||||
'file_sha256' => strtolower($fileHash),
|
||||
];
|
||||
}
|
||||
|
||||
private function connection(): ConnectionInterface
|
||||
{
|
||||
return $this->databases->connection($this->connectionName());
|
||||
}
|
||||
|
||||
private function connectionName(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
|
||||
private function normalizeDate(string $value): string
|
||||
{
|
||||
if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) {
|
||||
return gmdate('Y-m-d H:i:s', (int) round(((float) $value - 25569) * 86400));
|
||||
}
|
||||
|
||||
try {
|
||||
return CarbonImmutable::parse($value, 'Asia/Shanghai')->format('Y-m-d H:i:s');
|
||||
} catch (Throwable) {
|
||||
throw new InvalidArgumentException('顾家报价单日期格式无法识别:' . $value);
|
||||
}
|
||||
}
|
||||
|
||||
private function decimal(string $value): ?string
|
||||
{
|
||||
$value = str_replace(',', '', trim($value));
|
||||
|
||||
return $value !== '' && is_numeric($value) ? $value : null;
|
||||
}
|
||||
|
||||
private function nullableValue(string $value): ?string
|
||||
{
|
||||
return $value === '' ? null : $value;
|
||||
}
|
||||
|
||||
private function limit(string $value, int $length): ?string
|
||||
{
|
||||
$value = trim($value);
|
||||
|
||||
return $value === '' ? null : mb_substr($value, 0, $length);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\KukaPostingQuotation;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Throwable;
|
||||
|
||||
class KukaPostingQuotationPageData
|
||||
{
|
||||
/**
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function build(Request $request, int $companyId): array
|
||||
{
|
||||
$fields = array_values((array) config('kuka_posting.quotation_fields', []));
|
||||
$perPage = (int) $request->integer('per_page', 50);
|
||||
if (! in_array($perPage, [50, 100, 200], true)) {
|
||||
$perPage = 50;
|
||||
}
|
||||
$page = max(1, (int) $request->integer('page', 1));
|
||||
$keyword = mb_substr(trim((string) $request->query('keyword', '')), 0, 120);
|
||||
$status = mb_substr(trim((string) $request->query('status', '')), 0, 64);
|
||||
$empty = new LengthAwarePaginator([], 0, $perPage, $page, [
|
||||
'path' => $request->url(),
|
||||
'query' => $request->query(),
|
||||
]);
|
||||
|
||||
if ($fields === []) {
|
||||
return $this->result($empty, [], $keyword, $status, $perPage, '顾家报价单字段配置不完整。');
|
||||
}
|
||||
|
||||
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
$schema = Schema::connection($connectionName);
|
||||
if (! $schema->hasTable('kuka_posting_quotation_rows')
|
||||
|| ! $schema->hasTable('kuka_posting_quotation_imports')) {
|
||||
return $this->result($empty, $fields, $keyword, $status, $perPage, '顾家报价单镜像尚未建立,请先执行数据库迁移和报价单导入。');
|
||||
}
|
||||
|
||||
try {
|
||||
$connection = DB::connection($connectionName);
|
||||
$import = $connection->table('kuka_posting_quotation_imports')
|
||||
->where('company_id', $companyId)
|
||||
->first();
|
||||
$statuses = $connection->table('kuka_posting_quotation_rows')
|
||||
->where('company_id', $companyId)
|
||||
->whereNotNull('record_status')
|
||||
->where('record_status', '!=', '')
|
||||
->distinct()
|
||||
->orderBy('record_status')
|
||||
->pluck('record_status')
|
||||
->map(static fn (mixed $value): string => (string) $value)
|
||||
->all();
|
||||
if ($status !== '' && ! in_array($status, $statuses, true)) {
|
||||
$status = '';
|
||||
}
|
||||
|
||||
$query = $connection->table('kuka_posting_quotation_rows')
|
||||
->where('company_id', $companyId);
|
||||
if ($keyword !== '') {
|
||||
$like = '%' . addcslashes($keyword, '\\%_') . '%';
|
||||
$query->where(static function ($nested) use ($like): void {
|
||||
$nested->where('material_number', 'like', $like)
|
||||
->orWhere('material_desc', 'like', $like)
|
||||
->orWhere('supplier_account', 'like', $like)
|
||||
->orWhere('supplier_name', 'like', $like);
|
||||
});
|
||||
}
|
||||
if ($status !== '') {
|
||||
$query->where('record_status', $status);
|
||||
}
|
||||
|
||||
$rows = $query
|
||||
->orderBy('material_number')
|
||||
->paginate($perPage, ['*'], 'page', $page)
|
||||
->withQueryString();
|
||||
$rows->setCollection($rows->getCollection()->map(static function (object $row): object {
|
||||
$values = json_decode((string) $row->source_values, true);
|
||||
|
||||
return (object) (is_array($values) ? $values : []);
|
||||
}));
|
||||
|
||||
$range = $connection->table('kuka_posting_quotation_rows')
|
||||
->where('company_id', $companyId)
|
||||
->selectRaw('MIN(price_valid_date) as min_valid, MAX(price_expiry_date) as max_expiry')
|
||||
->first();
|
||||
$statusCounts = json_decode((string) ($import->status_counts ?? ''), true);
|
||||
|
||||
return $this->result(
|
||||
$rows,
|
||||
$fields,
|
||||
$keyword,
|
||||
$status,
|
||||
$perPage,
|
||||
null,
|
||||
[
|
||||
'rows' => (int) ($import->row_count ?? 0),
|
||||
'materials' => (int) ($import->material_count ?? 0),
|
||||
'statuses' => is_array($statusCounts) ? $statusCounts : [],
|
||||
'valid_from' => $range->min_valid ?? null,
|
||||
'valid_to' => $range->max_expiry ?? null,
|
||||
'file_name' => (string) ($import->file_name ?? ''),
|
||||
'file_sha256' => (string) ($import->file_sha256 ?? ''),
|
||||
'source_sheet' => (string) ($import->source_sheet ?? ''),
|
||||
'completed_at' => (string) ($import->completed_at ?? ''),
|
||||
],
|
||||
$statuses,
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return $this->result(
|
||||
$empty,
|
||||
$fields,
|
||||
$keyword,
|
||||
$status,
|
||||
$perPage,
|
||||
'顾家报价单暂时无法读取,请稍后重试;这不代表报价数据为 0。',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $fields
|
||||
* @param list<string> $statuses
|
||||
* @param array<string,mixed> $import
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function result(
|
||||
LengthAwarePaginator $rows,
|
||||
array $fields,
|
||||
string $keyword,
|
||||
string $status,
|
||||
int $perPage,
|
||||
?string $error,
|
||||
array $import = [],
|
||||
array $statuses = [],
|
||||
): array {
|
||||
$directoryFields = array_map(static fn (array $field): array => [
|
||||
'name' => (string) $field['name'],
|
||||
'source' => (string) $field['name'],
|
||||
'label' => (string) $field['label'],
|
||||
'kind' => (string) ($field['kind'] ?? 'text'),
|
||||
'tones' => (array) ($field['tones'] ?? []),
|
||||
], $fields);
|
||||
|
||||
return [
|
||||
'directory' => [
|
||||
'title' => '顾家报价单 · 价格明细',
|
||||
'icon' => 'request_quote',
|
||||
'status' => '顾家报价单',
|
||||
'description' => '顾家 SRM 报价数据原始字段;当前数据集共 '
|
||||
. number_format((int) ($import['rows'] ?? 0)) . ' 条,物料编码唯一。',
|
||||
'empty' => '顾家报价单尚未导入。',
|
||||
'fields' => $directoryFields,
|
||||
],
|
||||
'rows' => $rows,
|
||||
'filters' => [
|
||||
'keyword' => $keyword,
|
||||
'status' => $status,
|
||||
'per_page' => $perPage,
|
||||
],
|
||||
'statuses' => $statuses,
|
||||
'import' => $import,
|
||||
'summary' => [
|
||||
'filtered_rows' => $rows->total(),
|
||||
'rows' => (int) ($import['rows'] ?? 0),
|
||||
'materials' => (int) ($import['materials'] ?? 0),
|
||||
'valid_from' => $import['valid_from'] ?? null,
|
||||
'valid_to' => $import['valid_to'] ?? null,
|
||||
'completed_at' => $import['completed_at'] ?? null,
|
||||
],
|
||||
'error' => $error,
|
||||
];
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
170
app/Business/Piaoju/PiaojuSellerQuotaClient.php
Normal file
170
app/Business/Piaoju/PiaojuSellerQuotaClient.php
Normal file
@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\Piaoju;
|
||||
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
|
||||
class PiaojuSellerQuotaClient
|
||||
{
|
||||
/**
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function fetchAll(): array
|
||||
{
|
||||
$this->prepare();
|
||||
|
||||
$rows = [];
|
||||
$total = null;
|
||||
$pageSize = max((int) config('piaoju.page_size', 100), 1);
|
||||
$maxPages = max((int) config('piaoju.max_pages', 20), 1);
|
||||
|
||||
for ($page = 1; $page <= $maxPages; $page++) {
|
||||
[$batch, $pageTotal] = $this->fetchPage($page, $pageSize);
|
||||
$total ??= $pageTotal;
|
||||
|
||||
foreach ($batch as $row) {
|
||||
if (! is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = trim((string) ($row['id'] ?? $row['sellerCode'] ?? ''));
|
||||
if ($key === '') {
|
||||
throw new RuntimeException('piaoju_seller_key_missing');
|
||||
}
|
||||
$rows[$key] = $row;
|
||||
}
|
||||
|
||||
if ($batch === []
|
||||
|| ($total !== null && count($rows) >= $total)
|
||||
|| ($total === null && count($batch) < $pageSize)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($total !== null && count($rows) !== $total) {
|
||||
throw new RuntimeException('piaoju_seller_count_mismatch');
|
||||
}
|
||||
|
||||
return array_values($rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:list<array<string,mixed>>,1:?int}
|
||||
*/
|
||||
private function fetchPage(int $page, int $pageSize): array
|
||||
{
|
||||
$response = Http::acceptJson()
|
||||
->withHeaders([
|
||||
'Cookie' => $this->cookieHeader(),
|
||||
'Origin' => 'https://fp.erp321.com',
|
||||
'Referer' => 'https://fp.erp321.com/setting/companyBodyManage',
|
||||
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
. '(KHTML, like Gecko) Chrome/157.0.0.0 Safari/537.36 Edg/157.0.0.0',
|
||||
])
|
||||
->connectTimeout(10)
|
||||
->timeout(max((int) config('piaoju.timeout_seconds', 30), 1))
|
||||
->retry(2, 300, throw: false)
|
||||
->post(
|
||||
rtrim((string) config('piaoju.api_base_url'), '/') . '/fp/fms/company/seller/page',
|
||||
[
|
||||
'data' => [
|
||||
'coid' => (string) config('piaoju.coid'),
|
||||
'uid' => (string) config('piaoju.uid'),
|
||||
'ssProjectType' => (string) config('piaoju.project_type'),
|
||||
'sellerNames' => [],
|
||||
'status' => null,
|
||||
'authStatus' => null,
|
||||
],
|
||||
'page' => [
|
||||
'pageNum' => $page,
|
||||
'pageSize' => $pageSize,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
return $this->parseResponse($response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:list<array<string,mixed>>,1:?int}
|
||||
*/
|
||||
private function parseResponse(Response $response): array
|
||||
{
|
||||
if (! $response->successful()) {
|
||||
throw new RuntimeException('piaoju_api_http_error');
|
||||
}
|
||||
|
||||
$payload = $response->json();
|
||||
if (! is_array($payload)) {
|
||||
throw new RuntimeException('piaoju_api_invalid_response');
|
||||
}
|
||||
|
||||
$code = $payload['code'] ?? null;
|
||||
if ($code !== null && ! in_array((string) $code, ['0', '0000', '200'], true)) {
|
||||
throw new RuntimeException(
|
||||
in_array((string) $code, ['-1', '1006', '403'], true)
|
||||
? 'piaoju_api_auth_failed'
|
||||
: 'piaoju_api_error'
|
||||
);
|
||||
}
|
||||
|
||||
if (($payload['success'] ?? null) === false) {
|
||||
throw new RuntimeException('piaoju_api_error');
|
||||
}
|
||||
|
||||
$data = $payload['data'] ?? null;
|
||||
$rows = null;
|
||||
$total = null;
|
||||
|
||||
if (is_array($data)) {
|
||||
if (array_is_list($data)) {
|
||||
$rows = $data;
|
||||
$total = isset($payload['total']) ? (int) $payload['total'] : null;
|
||||
} else {
|
||||
$rows = $data['list'] ?? $data['records'] ?? null;
|
||||
$total = $data['total'] ?? $payload['total'] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
if (! is_array($rows)) {
|
||||
throw new RuntimeException('piaoju_api_invalid_response');
|
||||
}
|
||||
|
||||
return [
|
||||
array_values(array_filter($rows, 'is_array')),
|
||||
$total === null ? null : max((int) $total, 0),
|
||||
];
|
||||
}
|
||||
|
||||
private function prepare(): void
|
||||
{
|
||||
$this->cookieHeader();
|
||||
|
||||
if (trim((string) config('piaoju.coid')) === ''
|
||||
|| trim((string) config('piaoju.uid')) === '') {
|
||||
throw new RuntimeException('piaoju_api_context_missing');
|
||||
}
|
||||
}
|
||||
|
||||
private function cookieHeader(): string
|
||||
{
|
||||
$cookie = trim((string) config('piaoju.cookie', ''));
|
||||
if ($cookie !== '') {
|
||||
return $cookie;
|
||||
}
|
||||
|
||||
$path = trim((string) config('piaoju.cookie_file', ''));
|
||||
if ($path === '' || ! is_file($path)) {
|
||||
throw new RuntimeException('piaoju_cookie_not_configured');
|
||||
}
|
||||
|
||||
$cookie = trim((string) file_get_contents($path));
|
||||
if ($cookie === '' || preg_match('/[\r\n]/', $cookie) === 1) {
|
||||
throw new RuntimeException('piaoju_cookie_invalid');
|
||||
}
|
||||
|
||||
return $cookie;
|
||||
}
|
||||
}
|
||||
128
app/Business/Piaoju/PiaojuSellerQuotaImporter.php
Normal file
128
app/Business/Piaoju/PiaojuSellerQuotaImporter.php
Normal file
@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\Piaoju;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class PiaojuSellerQuotaImporter
|
||||
{
|
||||
public const TABLE = 'piaoju_seller_quota_snapshots';
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $rows
|
||||
*/
|
||||
public function replace(array $rows, ?DateTimeInterface $fetchedAt = null): int
|
||||
{
|
||||
$values = $this->values($rows, $fetchedAt);
|
||||
if ($values === []) {
|
||||
throw new RuntimeException('piaoju_seller_rows_empty');
|
||||
}
|
||||
|
||||
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
foreach (array_chunk($values, 200) as $chunk) {
|
||||
$connection->table(self::TABLE)->upsert(
|
||||
$chunk,
|
||||
['seller_key'],
|
||||
[
|
||||
'seller_name',
|
||||
'tax_number',
|
||||
'seller_status',
|
||||
'auth_status',
|
||||
'auth_status_desc',
|
||||
'invoice_limit',
|
||||
'invoice_limit_updated_at',
|
||||
'source_fetched_at',
|
||||
'synced_at',
|
||||
'updated_at',
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
$connection->table(self::TABLE)
|
||||
->whereNotIn('seller_key', array_column($values, 'seller_key'))
|
||||
->delete();
|
||||
$connection->commit();
|
||||
} catch (Throwable $exception) {
|
||||
$connection->rollBack();
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return count($values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function values(array $rows, ?DateTimeInterface $fetchedAt = null): array
|
||||
{
|
||||
$fetchedAt ??= now();
|
||||
$sourceFetchedAt = Carbon::instance($fetchedAt)
|
||||
->setTimezone('Asia/Shanghai')
|
||||
->format('Y-m-d H:i:s');
|
||||
$values = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$taxNumber = $this->text($row['taxNumber'] ?? null, 64);
|
||||
$sellerKey = $taxNumber
|
||||
?? trim((string) ($row['id'] ?? $row['sellerCode'] ?? ''));
|
||||
$sellerName = trim((string) ($row['sellerName'] ?? ''));
|
||||
if ($sellerKey === '' || $sellerName === '') {
|
||||
throw new RuntimeException('piaoju_seller_row_invalid');
|
||||
}
|
||||
|
||||
if (isset($values[$sellerKey])) {
|
||||
throw new RuntimeException('piaoju_seller_key_duplicated');
|
||||
}
|
||||
|
||||
$values[$sellerKey] = [
|
||||
'seller_key' => mb_substr($sellerKey, 0, 64),
|
||||
'seller_name' => mb_substr($sellerName, 0, 191),
|
||||
'tax_number' => $taxNumber,
|
||||
'seller_status' => $row['status'] === null ? null : (bool) $row['status'],
|
||||
'auth_status' => $this->text($row['authStatus'] ?? null, 32),
|
||||
'auth_status_desc' => $this->text($row['authStatusDesc'] ?? null, 64),
|
||||
'invoice_limit' => $this->decimal($row['invoiceLimit'] ?? null),
|
||||
'invoice_limit_updated_at' => $this->dateTime($row['invoiceLimitUpdated'] ?? null),
|
||||
'source_fetched_at' => $sourceFetchedAt,
|
||||
'synced_at' => now(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
];
|
||||
}
|
||||
|
||||
return array_values($values);
|
||||
}
|
||||
|
||||
private function text(mixed $value, int $length): ?string
|
||||
{
|
||||
$text = trim((string) ($value ?? ''));
|
||||
|
||||
return $text === '' ? null : mb_substr($text, 0, $length);
|
||||
}
|
||||
|
||||
private function decimal(mixed $value): ?float
|
||||
{
|
||||
return is_numeric($value) ? round((float) $value, 2) : null;
|
||||
}
|
||||
|
||||
private function dateTime(mixed $value): ?string
|
||||
{
|
||||
$text = trim((string) ($value ?? ''));
|
||||
if ($text === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Carbon::parse($text, 'Asia/Shanghai')->format('Y-m-d H:i:s');
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
57
app/Business/Piaoju/PiaojuSellerQuotaRepository.php
Normal file
57
app/Business/Piaoju/PiaojuSellerQuotaRepository.php
Normal file
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\Piaoju;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Throwable;
|
||||
|
||||
class PiaojuSellerQuotaRepository
|
||||
{
|
||||
/**
|
||||
* @return Collection<string,object>
|
||||
*/
|
||||
public function byNormalizedName(): Collection
|
||||
{
|
||||
try {
|
||||
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
if (! Schema::connection($connectionName)->hasTable(PiaojuSellerQuotaImporter::TABLE)) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$rows = DB::connection($connectionName)
|
||||
->table(PiaojuSellerQuotaImporter::TABLE)
|
||||
->select([
|
||||
'seller_key',
|
||||
'seller_name',
|
||||
'tax_number',
|
||||
'seller_status',
|
||||
'auth_status',
|
||||
'auth_status_desc',
|
||||
'invoice_limit',
|
||||
'invoice_limit_updated_at',
|
||||
'source_fetched_at',
|
||||
'synced_at',
|
||||
])
|
||||
->get();
|
||||
|
||||
return $rows
|
||||
->groupBy(fn (object $row): string => self::normalizeName((string) $row->seller_name))
|
||||
->filter(fn (Collection $group): bool => $group->count() === 1)
|
||||
->map(static fn (Collection $group): object => $group->first());
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
|
||||
public static function normalizeName(string $name): string
|
||||
{
|
||||
$name = str_replace(['(', ')'], ['(', ')'], trim($name));
|
||||
$name = preg_replace('/\s+/u', '', $name) ?? $name;
|
||||
|
||||
return mb_strtoupper($name);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business\ServiceCompanyReconciliation;
|
||||
|
||||
use App\Business\XlsxSheetReader;
|
||||
use RuntimeException;
|
||||
|
||||
class CustomerServiceMappingWorkbookImporter
|
||||
{
|
||||
public function __construct(private readonly XlsxSheetReader $reader) {}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* rows:list<array{service_company_name:string,store_company_name:string,fee_rate:float,source_row:int}>,
|
||||
* total_rows:int,
|
||||
* assigned_rows:int,
|
||||
* unassigned_rows:int,
|
||||
* unassigned:list<array{store_company_name:string,fee_rate:float,source_row:int}>,
|
||||
* invalid_rows:list<string>
|
||||
* }
|
||||
*/
|
||||
public function rows(string $path): array
|
||||
{
|
||||
if (! is_file($path)) {
|
||||
throw new RuntimeException('客服公司映射文件不存在:' . $path);
|
||||
}
|
||||
|
||||
$result = [
|
||||
'rows' => [],
|
||||
'total_rows' => 0,
|
||||
'assigned_rows' => 0,
|
||||
'unassigned_rows' => 0,
|
||||
'unassigned' => [],
|
||||
'invalid_rows' => [],
|
||||
];
|
||||
foreach ($this->reader->rows(
|
||||
$path,
|
||||
['公司名称', '结算比例', '对应客服公司'],
|
||||
sheetName: '公司盘点',
|
||||
) as $row) {
|
||||
$result['total_rows']++;
|
||||
$sourceRow = $result['total_rows'] + 1;
|
||||
$storeName = trim((string) ($row['公司名称'] ?? ''));
|
||||
$serviceName = trim((string) ($row['对应客服公司'] ?? ''));
|
||||
if ($storeName === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$feeRate = $this->feeRate((string) ($row['结算比例'] ?? ''));
|
||||
if ($feeRate === null) {
|
||||
$result['invalid_rows'][] = "第 {$sourceRow} 行结算比例无效。";
|
||||
continue;
|
||||
}
|
||||
if ($serviceName === '') {
|
||||
$result['unassigned_rows']++;
|
||||
$result['unassigned'][] = [
|
||||
'store_company_name' => $storeName,
|
||||
'fee_rate' => $feeRate,
|
||||
'source_row' => $sourceRow,
|
||||
];
|
||||
continue;
|
||||
}
|
||||
|
||||
$result['rows'][] = [
|
||||
'service_company_name' => $serviceName,
|
||||
'store_company_name' => $storeName,
|
||||
'fee_rate' => $feeRate,
|
||||
'source_row' => $sourceRow,
|
||||
];
|
||||
$result['assigned_rows']++;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function feeRate(string $value): ?float
|
||||
{
|
||||
$normalized = trim(str_replace(['%', ',', ','], ['', '', ''], $value));
|
||||
if ($normalized === '' || ! is_numeric($normalized)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$rate = (float) $normalized;
|
||||
if ($rate > 1) {
|
||||
$rate /= 100;
|
||||
}
|
||||
|
||||
return $rate > 0 && $rate <= 1 ? round($rate, 6) : null;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -466,7 +466,7 @@ class SupplierSummaryInboundImporter
|
||||
|
||||
if (
|
||||
preg_match(
|
||||
'/^=?\s*\$?([A-Z]{1,3})\$?(\d+)\s*\*\s*\$?([A-Z]{1,3})\$?(\d+)\s*$/i',
|
||||
'/^[=+]?\s*\$?([A-Z]{1,3})\$?(\d+)\s*\*\s*\$?([A-Z]{1,3})\$?(\d+)\s*$/i',
|
||||
$formula,
|
||||
$matches,
|
||||
) !== 1
|
||||
|
||||
@ -17,7 +17,7 @@ class SystemizationTodoAuditLogger
|
||||
|
||||
public const ACTION_LABELS = [
|
||||
'create' => '新增',
|
||||
'update' => '修改',
|
||||
'update' => '改动',
|
||||
'delete' => '删除',
|
||||
'import' => '导入',
|
||||
];
|
||||
@ -149,18 +149,6 @@ class SystemizationTodoAuditLogger
|
||||
}
|
||||
|
||||
DB::table(self::TABLE)->insert($rows);
|
||||
$companyIds = array_values(array_unique(array_column($rows, 'company_id')));
|
||||
foreach ($companyIds as $companyId) {
|
||||
$maxId = (int) DB::table(self::TABLE)
|
||||
->where('company_id', $companyId)
|
||||
->max('id');
|
||||
if ($maxId > self::HISTORY_LIMIT) {
|
||||
DB::table(self::TABLE)
|
||||
->where('company_id', $companyId)
|
||||
->where('id', '<=', $maxId - self::HISTORY_LIMIT)
|
||||
->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -170,6 +158,7 @@ class SystemizationTodoAuditLogger
|
||||
int $companyId,
|
||||
int $limit = self::HISTORY_LIMIT,
|
||||
?string $from = null,
|
||||
?string $date = null,
|
||||
): array
|
||||
{
|
||||
if (! $this->tableReady()) {
|
||||
@ -179,6 +168,10 @@ class SystemizationTodoAuditLogger
|
||||
return DB::table(self::TABLE)
|
||||
->where('company_id', $companyId)
|
||||
->when($from !== null && $from !== '', fn ($query) => $query->where('at', '>=', $from))
|
||||
->when($date !== null && $date !== '', function ($query) use ($date): void {
|
||||
$query->where('at', '>=', $date . ' 00:00:00')
|
||||
->where('at', '<', Carbon::parse($date)->addDay()->toDateString() . ' 00:00:00');
|
||||
})
|
||||
->orderByDesc('id')
|
||||
->limit(max(1, min($limit, self::HISTORY_LIMIT)))
|
||||
->get()
|
||||
|
||||
@ -275,25 +275,14 @@ class UpstreamBusinessInformation
|
||||
}
|
||||
|
||||
$references ??= $this->companyPlanClassificationReferences($rows);
|
||||
$byCreditCode = [];
|
||||
$byCompanyName = [];
|
||||
|
||||
foreach ($references as $reference) {
|
||||
$creditCode = $this->normalizeCreditCode($reference['unified_social_credit_code'] ?? null);
|
||||
if ($creditCode !== '' && ! isset($byCreditCode[$creditCode])) {
|
||||
$byCreditCode[$creditCode] = $reference;
|
||||
}
|
||||
|
||||
$companyName = $this->normalizeCompanyName($reference['company_name'] ?? null);
|
||||
if ($companyName !== '' && ! isset($byCompanyName[$companyName])) {
|
||||
$byCompanyName[$companyName] = $reference;
|
||||
}
|
||||
}
|
||||
$index = $this->companyPlanClassificationIndex($references);
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
$creditCode = $this->normalizeCreditCode($row['unified_social_credit_code'] ?? null);
|
||||
$companyName = $this->normalizeCompanyName($row['company_name'] ?? null);
|
||||
$reference = $byCreditCode[$creditCode] ?? $byCompanyName[$companyName] ?? null;
|
||||
$reference = $this->matchedCompanyPlanClassification(
|
||||
$index,
|
||||
$row['company_name'] ?? null,
|
||||
[$row],
|
||||
);
|
||||
|
||||
$planTaxType = trim((string) ($reference['taxpayer_type'] ?? ''));
|
||||
$row['taxpayer_category'] = $this->normalizeTaxType(
|
||||
@ -319,6 +308,10 @@ class UpstreamBusinessInformation
|
||||
*/
|
||||
private function companyPlanClassificationReferences(array $rows = [], bool $all = false): array
|
||||
{
|
||||
if ($this->companyPlans === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
if ($all) {
|
||||
@ -337,6 +330,61 @@ class UpstreamBusinessInformation
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $references
|
||||
* @return array{
|
||||
* by_credit_code:array<string,array<string,mixed>>,
|
||||
* by_company_name:array<string,array<string,mixed>>
|
||||
* }
|
||||
*/
|
||||
private function companyPlanClassificationIndex(array $references): array
|
||||
{
|
||||
$byCreditCode = [];
|
||||
$byCompanyName = [];
|
||||
|
||||
foreach ($references as $reference) {
|
||||
$creditCode = $this->normalizeCreditCode($reference['unified_social_credit_code'] ?? null);
|
||||
if ($creditCode !== '' && ! isset($byCreditCode[$creditCode])) {
|
||||
$byCreditCode[$creditCode] = $reference;
|
||||
}
|
||||
|
||||
$companyName = $this->normalizeCompanyName($reference['company_name'] ?? null);
|
||||
if ($companyName !== '' && ! isset($byCompanyName[$companyName])) {
|
||||
$byCompanyName[$companyName] = $reference;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'by_credit_code' => $byCreditCode,
|
||||
'by_company_name' => $byCompanyName,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* by_credit_code:array<string,array<string,mixed>>,
|
||||
* by_company_name:array<string,array<string,mixed>>
|
||||
* } $index
|
||||
* @param list<array<string,mixed>> $companyRows
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
private function matchedCompanyPlanClassification(
|
||||
array $index,
|
||||
mixed $companyName,
|
||||
array $companyRows = [],
|
||||
): ?array {
|
||||
foreach ($companyRows as $companyRow) {
|
||||
$creditCode = $this->normalizeCreditCode($companyRow['unified_social_credit_code'] ?? null);
|
||||
if ($creditCode !== '' && isset($index['by_credit_code'][$creditCode])) {
|
||||
return $index['by_credit_code'][$creditCode];
|
||||
}
|
||||
}
|
||||
|
||||
$normalizedCompanyName = $this->normalizeCompanyName($companyName);
|
||||
|
||||
return $index['by_company_name'][$normalizedCompanyName] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string|list<string>> $filters
|
||||
*/
|
||||
@ -481,7 +529,7 @@ SQL);
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺基础信息页每次读取时把负责人字段覆盖为店铺账号镜像中的值。
|
||||
* 店铺基础信息页从店铺账号镜像关联负责人;部门负责人不使用旧档案兜底。
|
||||
* 账号店铺名与 ERP 店铺名只差下划线/空格,因此统一归一后关联。
|
||||
*
|
||||
* @param list<array<string,mixed>> $rows
|
||||
@ -494,16 +542,16 @@ SQL);
|
||||
$key = StoreAccountMirrorRepository::storeNameKey($row['erp_store_name'] ?? '');
|
||||
$match = $ownership[$key] ?? null;
|
||||
if ($match === null) {
|
||||
// 部门负责人只认店铺账号密码镜像,不能沿用可能属于其他口径的旧档案值。
|
||||
$row['department_manager'] = null;
|
||||
continue;
|
||||
}
|
||||
foreach ([
|
||||
'store_manager' => $match['operation_owner'],
|
||||
'department_manager' => $match['operation_department_head'],
|
||||
] as $field => $value) {
|
||||
if ($value !== '') {
|
||||
$row[$field] = $value;
|
||||
}
|
||||
|
||||
if ($match['operation_owner'] !== '') {
|
||||
$row['store_manager'] = $match['operation_owner'];
|
||||
}
|
||||
$departmentManager = trim((string) $match['operation_department_head']);
|
||||
$row['department_manager'] = $departmentManager !== '' ? $departmentManager : null;
|
||||
}
|
||||
unset($row);
|
||||
|
||||
@ -789,6 +837,7 @@ SQL);
|
||||
'entity' => $entity,
|
||||
'company_type' => $row['company_type'] ?? null,
|
||||
'rolling_12m_income' => null,
|
||||
'previous_month_settlement_income' => null,
|
||||
'can_change_entity' => null,
|
||||
'plan' => null,
|
||||
'new_entity' => null,
|
||||
@ -799,6 +848,11 @@ SQL);
|
||||
}
|
||||
|
||||
$this->sumNullable($entities[$entity], 'rolling_12m_income', $row['rolling_12m_income'] ?? null);
|
||||
$this->sumNullable(
|
||||
$entities[$entity],
|
||||
'previous_month_settlement_income',
|
||||
$row['previous_month_settlement_income'] ?? null,
|
||||
);
|
||||
for ($month = 1; $month <= 12; $month++) {
|
||||
$key = sprintf('income_%02d', $month);
|
||||
$entities[$entity][$key] ??= null;
|
||||
@ -813,15 +867,29 @@ SQL);
|
||||
} catch (Throwable) {
|
||||
$classifications = [];
|
||||
}
|
||||
$planClassifications = $this->companyPlanClassificationIndex(
|
||||
$this->companyPlanClassificationReferences(all: true),
|
||||
);
|
||||
foreach ($rows as &$row) {
|
||||
$row['company_details'] = $details[$row['entity']] ?? [];
|
||||
$row['city'] = $this->cityFromDetails($row['company_details']);
|
||||
$row['company_status'] = $row['company_details'][0]['company_status'] ?? null;
|
||||
$classification = $classifications[$row['entity']] ?? [];
|
||||
$taxType = $classification['tax_type']
|
||||
$planClassification = $this->matchedCompanyPlanClassification(
|
||||
$planClassifications,
|
||||
$row['entity'],
|
||||
$row['company_details'],
|
||||
);
|
||||
$planTaxType = trim((string) ($planClassification['taxpayer_type'] ?? ''));
|
||||
$planBusinessType = trim((string) ($planClassification['business_registration_type'] ?? ''));
|
||||
$taxType = $planTaxType !== ''
|
||||
? $planTaxType
|
||||
: $classification['tax_type']
|
||||
?? $row['company_details'][0]['taxpayer_category']
|
||||
?? null;
|
||||
$businessType = $classification['business_registration_type']
|
||||
$businessType = $planBusinessType !== ''
|
||||
? $planBusinessType
|
||||
: $classification['business_registration_type']
|
||||
?? $row['company_details'][0]['business_registration_type']
|
||||
?? null;
|
||||
$classificationStatus = trim((string) ($classification['status'] ?? ''));
|
||||
@ -833,16 +901,19 @@ SQL);
|
||||
$row['tax_type'] = $this->normalizeTaxType($taxType) ?? '/';
|
||||
$businessType = trim((string) $businessType);
|
||||
$row['business_registration_type'] = $retained
|
||||
&& in_array($businessType, ['核定', '个人独资企业'], true)
|
||||
&& ($planBusinessType !== '' || in_array($businessType, ['核定', '个人独资企业'], true))
|
||||
? $businessType
|
||||
: '/';
|
||||
}
|
||||
unset($row);
|
||||
|
||||
// 整列为空的月份默认隐藏;金额 0 仍视为有账单,不隐藏。
|
||||
// 服务公司结算收入列按业务要求默认隐藏;整列为空的月份也默认隐藏,金额 0 仍视为有账单。
|
||||
request()->attributes->set(
|
||||
'subject-operating-report.default_hidden_columns',
|
||||
$this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true),
|
||||
array_values(array_unique([
|
||||
'previous_month_settlement_income',
|
||||
...$this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true),
|
||||
])),
|
||||
);
|
||||
|
||||
$rows = array_values(array_filter($rows, fn (array $row): bool => $this->subjectMatchesFilters($row, $filters)));
|
||||
@ -1049,7 +1120,7 @@ SQL);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (['rolling_12m_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
|
||||
foreach (['rolling_12m_income', 'previous_month_settlement_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
|
||||
$needle = str_replace(',', '', trim((string) ($filters[$key] ?? '')));
|
||||
if ($needle !== '' && (! is_numeric($needle) || ! is_numeric($row[$key] ?? null)
|
||||
|| abs((float) $row[$key] - (float) $needle) > 0.000001)) {
|
||||
@ -1067,6 +1138,7 @@ SQL);
|
||||
$key = (string) ($filters['_sort'] ?? 'entity');
|
||||
$allowed = [
|
||||
'city', 'entity', 'company_type', 'tax_type', 'business_registration_type', 'rolling_12m_income',
|
||||
'previous_month_settlement_income',
|
||||
...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12)),
|
||||
'can_change_entity', 'plan', 'new_entity',
|
||||
];
|
||||
|
||||
169
app/Console/Commands/AssignFinanceLedgerCompanyPlans.php
Normal file
169
app/Console/Commands/AssignFinanceLedgerCompanyPlans.php
Normal file
@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Utilities\FinanceLedgerAccountShouldKeep;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use Throwable;
|
||||
|
||||
class AssignFinanceLedgerCompanyPlans extends Command
|
||||
{
|
||||
private const PRESERVED_ACCOUNT_TYPES = ['支付宝', '网商银行'];
|
||||
|
||||
protected $signature = 'finance-ledger:assign-company-plans
|
||||
{path : 公司保留名单 XLSX/XLS 文件}
|
||||
{--dry-run : 只核对公司和账户数量,不写入数据}';
|
||||
|
||||
protected $description = '按公司保留名单设置账户公司规划与是否保留';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$companies = $this->companyNames((string) $this->argument('path'));
|
||||
if ($companies === []) {
|
||||
throw new \RuntimeException('公司保留名单中没有可识别的公司名称。');
|
||||
}
|
||||
|
||||
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
||||
$accounts = $connection->table('fin_accounts')
|
||||
->orderBy('id')
|
||||
->get(['id', 'company_name', 'account_type']);
|
||||
|
||||
$retainedIds = [];
|
||||
$temporaryIds = [];
|
||||
$preservedIds = [];
|
||||
$matchedKeys = [];
|
||||
foreach ($accounts as $account) {
|
||||
$key = $this->normalizeCompanyName((string) ($account->company_name ?? ''));
|
||||
$accountId = (int) $account->id;
|
||||
if ($key !== '' && isset($companies[$key])) {
|
||||
$matchedKeys[$key] = true;
|
||||
}
|
||||
|
||||
if (in_array(trim((string) ($account->account_type ?? '')), self::PRESERVED_ACCOUNT_TYPES, true)) {
|
||||
$preservedIds[] = $accountId;
|
||||
} elseif ($key !== '' && isset($companies[$key])) {
|
||||
$retainedIds[] = $accountId;
|
||||
} else {
|
||||
$temporaryIds[] = $accountId;
|
||||
}
|
||||
}
|
||||
|
||||
$unmatchedCompanies = array_values(array_diff_key($companies, $matchedKeys));
|
||||
$this->table(
|
||||
['名单公司', '匹配名单公司', '账户总数', '更新为保留', '更新为暂时保留', '保持原状'],
|
||||
[[
|
||||
count($companies),
|
||||
count($matchedKeys),
|
||||
$accounts->count(),
|
||||
count($retainedIds),
|
||||
count($temporaryIds),
|
||||
count($preservedIds),
|
||||
]],
|
||||
);
|
||||
|
||||
if ($unmatchedCompanies !== []) {
|
||||
$this->warn('以下名单公司没有匹配到账户:' . implode('、', $unmatchedCompanies));
|
||||
}
|
||||
|
||||
if ((bool) $this->option('dry-run')) {
|
||||
$this->info('核对完成,未写入数据。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$connection->transaction(function () use (
|
||||
$connection,
|
||||
$retainedIds,
|
||||
$temporaryIds,
|
||||
$now,
|
||||
): void {
|
||||
foreach (array_chunk($retainedIds, 500) as $ids) {
|
||||
$connection->table('fin_accounts')
|
||||
->whereIn('id', $ids)
|
||||
->update([
|
||||
'company_plan' => '保留',
|
||||
'account_should_keep' => '是',
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
foreach (array_chunk($temporaryIds, 500) as $ids) {
|
||||
$connection->table('fin_accounts')
|
||||
->whereIn('id', $ids)
|
||||
->update([
|
||||
'company_plan' => '不保留',
|
||||
'account_should_keep' => FinanceLedgerAccountShouldKeep::TEMPORARY,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
$this->info(sprintf(
|
||||
'已更新 %d 个账户:保留 %d 个,暂时保留 %d 个;另有 %d 个支付宝或网商银行账户保持原状。',
|
||||
count($retainedIds) + count($temporaryIds),
|
||||
count($retainedIds),
|
||||
count($temporaryIds),
|
||||
count($preservedIds),
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private function companyNames(string $path): array
|
||||
{
|
||||
if (! is_file($path)) {
|
||||
throw new \RuntimeException('公司保留名单文件不存在:' . $path);
|
||||
}
|
||||
|
||||
$worksheet = IOFactory::load($path)->getActiveSheet();
|
||||
$rows = $worksheet->toArray(null, true, true, false);
|
||||
if ($rows === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$header = array_map(
|
||||
fn (mixed $value): string => $this->normalizeCompanyName((string) $value),
|
||||
$rows[0],
|
||||
);
|
||||
$column = array_search('公司名称', $header, true);
|
||||
if ($column === false) {
|
||||
$column = 0;
|
||||
} else {
|
||||
array_shift($rows);
|
||||
}
|
||||
|
||||
$companies = [];
|
||||
foreach ($rows as $row) {
|
||||
$name = trim((string) ($row[$column] ?? ''));
|
||||
$key = $this->normalizeCompanyName($name);
|
||||
if ($key !== '') {
|
||||
$companies[$key] = $name;
|
||||
}
|
||||
}
|
||||
|
||||
return $companies;
|
||||
}
|
||||
|
||||
private function normalizeCompanyName(string $name): string
|
||||
{
|
||||
$name = str_replace(
|
||||
['(', ')', '【', '】', ' '],
|
||||
['(', ')', '[', ']', ' '],
|
||||
trim($name),
|
||||
);
|
||||
$name = (string) preg_replace('/\s+/u', '', $name);
|
||||
|
||||
return mb_strtolower($name, 'UTF-8');
|
||||
}
|
||||
}
|
||||
98
app/Console/Commands/AuditBillSyncWindow.php
Normal file
98
app/Console/Commands/AuditBillSyncWindow.php
Normal file
@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Console\Command;
|
||||
use InvalidArgumentException;
|
||||
use Modules\EcommerceFinance\Services\BillSyncWindowAuditor;
|
||||
|
||||
class AuditBillSyncWindow extends Command
|
||||
{
|
||||
protected $signature = 'bill-sync:audit-window
|
||||
{--from= : 开始日期 YYYY-MM-DD;默认以前一自然日结束的最近 7 天}
|
||||
{--to= : 结束日期 YYYY-MM-DD;默认前一自然日}
|
||||
{--days=7 : 未指定 --from 时回看的自然日数,最大 93}
|
||||
{--json : 输出 JSON,供每日账单自动化读取}';
|
||||
|
||||
protected $description = '核对最近账单窗口的日期、行数、店铺数和收支,识别漏日及异常低量';
|
||||
|
||||
public function handle(BillSyncWindowAuditor $auditor): int
|
||||
{
|
||||
try {
|
||||
[$from, $to] = $this->window();
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$result = $auditor->audit($from, $to);
|
||||
|
||||
if ((bool) $this->option('json')) {
|
||||
$this->line(json_encode(
|
||||
$result,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
|
||||
));
|
||||
} else {
|
||||
$this->renderText($result);
|
||||
}
|
||||
|
||||
return $result['has_gaps'] || $result['has_anomalies']
|
||||
? self::FAILURE
|
||||
: self::SUCCESS;
|
||||
}
|
||||
|
||||
/** @return array{0:string,1:string} */
|
||||
private function window(): array
|
||||
{
|
||||
$to = trim((string) $this->option('to'));
|
||||
$to = $to !== ''
|
||||
? $this->date($to, '--to')
|
||||
: now('Asia/Shanghai')->subDay()->toDateString();
|
||||
|
||||
$from = trim((string) $this->option('from'));
|
||||
if ($from !== '') {
|
||||
$from = $this->date($from, '--from');
|
||||
} else {
|
||||
$days = max(1, (int) $this->option('days'));
|
||||
if ($days > 93) {
|
||||
throw new InvalidArgumentException('--days 最大为 93。');
|
||||
}
|
||||
$from = (new DateTimeImmutable($to))->modify('-' . ($days - 1) . ' days')->format('Y-m-d');
|
||||
}
|
||||
|
||||
if ($from > $to) {
|
||||
throw new InvalidArgumentException('开始日期不能晚于结束日期。');
|
||||
}
|
||||
|
||||
return [$from, $to];
|
||||
}
|
||||
|
||||
private function date(string $value, string $option): string
|
||||
{
|
||||
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||||
if (! $parsed || $parsed->format('Y-m-d') !== $value) {
|
||||
throw new InvalidArgumentException("{$option} 日期格式必须为 YYYY-MM-DD。");
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $result */
|
||||
private function renderText(array $result): void
|
||||
{
|
||||
$this->line("账单窗口:{$result['window']['from']} 至 {$result['window']['to']}");
|
||||
foreach ($result['platforms'] as $platform) {
|
||||
if (($platform['status'] ?? '') === 'failed') {
|
||||
$this->line("{$platform['label']} | FAILED | {$platform['error']}");
|
||||
continue;
|
||||
}
|
||||
$missing = $platform['missing_dates'] !== [] ? implode(',', $platform['missing_dates']) : '-';
|
||||
$suspicious = $platform['suspicious_dates'] !== [] ? implode(',', $platform['suspicious_dates']) : '-';
|
||||
$this->line(
|
||||
"{$platform['label']} | {$platform['status']} | missing={$missing} | suspicious={$suspicious}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Concerns;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
|
||||
use Throwable;
|
||||
|
||||
trait QueuesBillPerformanceResync
|
||||
{
|
||||
protected function queueBillPerformanceResync(
|
||||
BillPerformanceResyncDispatcher $dispatcher,
|
||||
string $platform,
|
||||
array $result,
|
||||
bool $periodEndExclusive = false,
|
||||
): bool {
|
||||
try {
|
||||
$periodEnd = (string) ($result['period_end'] ?? '');
|
||||
if ($periodEndExclusive && $periodEnd !== '') {
|
||||
$periodEnd = Carbon::parse($periodEnd)->subDay()->toDateString();
|
||||
}
|
||||
$queued = $dispatcher->dispatch(
|
||||
$platform,
|
||||
(string) ($result['period_start'] ?? ''),
|
||||
$periodEnd,
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('账单已导入,但业绩明细重算任务排队失败;请重新执行本导入命令以重试排队。');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->line(
|
||||
'业绩明细重算已排队:'
|
||||
. implode('、', $queued['months'])
|
||||
. '(新增 ' . $queued['jobs'] . ' 个任务)'
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
59
app/Console/Commands/ImportAccountShortRenames.php
Normal file
59
app/Console/Commands/ImportAccountShortRenames.php
Normal file
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerAccountEditor;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ImportAccountShortRenames extends Command
|
||||
{
|
||||
protected $signature = 'finance-ledger:import-account-short-renames
|
||||
{path : 账户简称批量修改 JSON 文件}
|
||||
{--apply : 实际写入;未指定时只校验}';
|
||||
|
||||
protected $description = '按账户 ID 批量修改账户简称,并同步所有关联数据';
|
||||
|
||||
public function handle(FinanceLedgerAccountEditor $editor): int
|
||||
{
|
||||
try {
|
||||
$path = (string) $this->argument('path');
|
||||
if (! is_file($path) || ! is_readable($path)) {
|
||||
throw new RuntimeException('账户简称批量修改文件不存在或不可读取。');
|
||||
}
|
||||
if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'json') {
|
||||
throw new RuntimeException('账户简称批量修改文件必须为 JSON。');
|
||||
}
|
||||
if (filesize($path) > 10 * 1024 * 1024) {
|
||||
throw new RuntimeException('账户简称批量修改文件不能超过 10 MB。');
|
||||
}
|
||||
|
||||
$content = file_get_contents($path);
|
||||
if (! is_string($content)) {
|
||||
throw new RuntimeException('无法读取账户简称批量修改文件。');
|
||||
}
|
||||
$mappings = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (! is_array($mappings) || ! array_is_list($mappings)) {
|
||||
throw new RuntimeException('账户简称批量修改文件必须是 JSON 数组。');
|
||||
}
|
||||
|
||||
$apply = (bool) $this->option('apply');
|
||||
$result = $editor->renameShorts($mappings, $apply);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'%s账户简称:共 %d 户,计划修改 %d 户,未变化 %d 户。',
|
||||
$result['dry_run'] ? '校验完成,' : '已完成',
|
||||
$result['requested'],
|
||||
$result['changed'],
|
||||
$result['unchanged'],
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
36
app/Console/Commands/ImportActualTax.php
Normal file
36
app/Console/Commands/ImportActualTax.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\ActualTax\ActualTaxWorkbookImporter;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class ImportActualTax extends Command
|
||||
{
|
||||
protected $signature = 'actual-tax:import
|
||||
{path : 实际税金表工作簿或 CSV 路径}';
|
||||
|
||||
protected $description = '导入实际税金表,整份替换共享业务镜像中的上一版数据';
|
||||
|
||||
public function handle(ActualTaxWorkbookImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import((string) $this->argument('path'));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('实际税金表导入失败:' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'实际税金表导入完成:%s 条,跳过空行 %s 条,来源文件 %s。',
|
||||
number_format($result['imported']),
|
||||
number_format($result['skipped']),
|
||||
$result['source_file'],
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
42
app/Console/Commands/ImportBankBillHeaders.php
Normal file
42
app/Console/Commands/ImportBankBillHeaders.php
Normal file
@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BankBillHeaderImporter;
|
||||
use Throwable;
|
||||
|
||||
class ImportBankBillHeaders extends Command
|
||||
{
|
||||
protected $signature = 'finance-ledger:import-bank-bill-headers
|
||||
{path : 银行批量明细 XLSX/XLS 文件}
|
||||
{--bank= : 招商银行或华夏银行}
|
||||
{--dry-run : 只检查,不写入表头配置}';
|
||||
|
||||
protected $description = '导入银行原始账单表头并生成银行账单列配置';
|
||||
|
||||
public function handle(BankBillHeaderImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
(string) $this->option('bank'),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'%s%s:%d 列。',
|
||||
$result['dry_run'] ? '校验完成,' : '表头已导入,',
|
||||
$result['bank'],
|
||||
$result['columns'],
|
||||
));
|
||||
$this->line(implode(' | ', $result['labels']));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
59
app/Console/Commands/ImportBankBills.php
Normal file
59
app/Console/Commands/ImportBankBills.php
Normal file
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BankBillStatementImporter;
|
||||
use Throwable;
|
||||
|
||||
class ImportBankBills extends Command
|
||||
{
|
||||
protected $signature = 'finance-ledger:import-bank-bills
|
||||
{path : 银行批量账单 XLSX/XLS/CSV 文件}
|
||||
{--bank= : 账单所属银行模板}
|
||||
{--scope=direct : direct(银企直连)或 non_direct(非银企直连)}
|
||||
{--dry-run : 只校验,不写入账单数据}
|
||||
{--replace : 先清空该银行旧账单,再导入本次文件}';
|
||||
|
||||
protected $description = '按已导入的银行表头导入原始账单明细';
|
||||
|
||||
public function handle(BankBillStatementImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
(string) $this->option('bank'),
|
||||
(bool) $this->option('dry-run'),
|
||||
(bool) $this->option('replace'),
|
||||
true,
|
||||
(string) $this->option('scope'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'%s%s:%d 条,新增 %d 条,更新 %d 条,跳过 %d 条;涉及 %d 个账户。',
|
||||
$result['dry_run'] ? '校验完成,' : '账单已导入,',
|
||||
$result['bank'],
|
||||
$result['rows'],
|
||||
$result['inserted'],
|
||||
$result['updated'],
|
||||
$result['skipped'],
|
||||
$result['accounts'],
|
||||
));
|
||||
$this->line(sprintf(
|
||||
'账务日期:%s 至 %s。',
|
||||
$result['first_date'] ?? '无',
|
||||
$result['last_date'] ?? '无',
|
||||
));
|
||||
$this->line(sprintf(
|
||||
'已同步 %d 个账户的当前余额。',
|
||||
$result['synced_accounts'],
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
57
app/Console/Commands/ImportBankBillsDirectory.php
Normal file
57
app/Console/Commands/ImportBankBillsDirectory.php
Normal file
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BankBillStatementDirectoryImporter;
|
||||
use Throwable;
|
||||
|
||||
class ImportBankBillsDirectory extends Command
|
||||
{
|
||||
protected $signature = 'finance-ledger:import-bank-bills-directory
|
||||
{path : 已解压的银行账单目录}
|
||||
{--bank= : 招商银行、华夏银行或网商银行}
|
||||
{--dry-run : 只校验,不写入账单数据}';
|
||||
|
||||
protected $description = '一次导入目录中的多份银行账单,并统一同步余额';
|
||||
|
||||
public function handle(BankBillStatementDirectoryImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
(string) $this->option('bank'),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'%s%s:%d 个文件,成功 %d 个,失败 %d 个,共 %d 条;新增 %d 条,更新 %d 条,跳过 %d 条。',
|
||||
$result['dry_run'] ? '校验完成,' : '账单已导入,',
|
||||
$result['bank'],
|
||||
$result['files'],
|
||||
$result['imported_files'],
|
||||
$result['failed_files'],
|
||||
$result['rows'],
|
||||
$result['inserted'],
|
||||
$result['updated'],
|
||||
$result['skipped'],
|
||||
));
|
||||
$this->line(sprintf(
|
||||
'账务日期:%s 至 %s;涉及 %d 个账户,已同步 %d 个账户余额。',
|
||||
$result['first_date'] ?? '无',
|
||||
$result['last_date'] ?? '无',
|
||||
$result['accounts'],
|
||||
$result['synced_accounts'],
|
||||
));
|
||||
foreach ($result['failures'] as $failure) {
|
||||
$this->error($failure);
|
||||
}
|
||||
|
||||
return $result['failed_files'] === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
48
app/Console/Commands/ImportBankDirectBalances.php
Normal file
48
app/Console/Commands/ImportBankDirectBalances.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BankDirectBalanceWorkbookImporter;
|
||||
use Throwable;
|
||||
|
||||
class ImportBankDirectBalances extends Command
|
||||
{
|
||||
protected $signature = 'finance-ledger:import-bank-direct-balances
|
||||
{path : 银企直联余额 XLSX/XLS 文件}
|
||||
{--balance-date= : 指定余额日期,格式 YYYY-MM-DD}
|
||||
{--dry-run : 只校验和统计,不写入共享业务库}';
|
||||
|
||||
protected $description = '导入银企直联账户可用余额及期末余额快照';
|
||||
|
||||
public function handle(BankDirectBalanceWorkbookImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
$this->option('balance-date') === null
|
||||
? null
|
||||
: (string) $this->option('balance-date'),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->table(['项目', '值'], [
|
||||
['余额日期', $result['balance_date']],
|
||||
['账户数', $result['total']],
|
||||
['银行数', $result['bank_count']],
|
||||
['可用余额合计', number_format($result['available_total'], 2, '.', '')],
|
||||
['替换原快照', $result['replaced']],
|
||||
['模式', $result['dry_run'] ? '校验' : '写入'],
|
||||
]);
|
||||
$this->info($result['dry_run']
|
||||
? '银企直联余额校验完成,未写入共享业务库。'
|
||||
: '银企直联余额导入完成,期末余额已接入账户总览。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -2,13 +2,17 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\DewuSettlementBillImporter;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ImportDewuSettlementBills extends Command
|
||||
{
|
||||
use QueuesBillPerformanceResync;
|
||||
|
||||
protected $signature = 'dewu-bills:import-authoritative
|
||||
{path : 聚胜算导出的得物完整账单 XLSX}
|
||||
{--from= : 账期开始日期,格式 YYYY-MM-DD}
|
||||
@ -20,7 +24,10 @@ class ImportDewuSettlementBills extends Command
|
||||
|
||||
protected $description = '导入并核验聚胜算得物完整账单(保留全部渠道)';
|
||||
|
||||
public function handle(DewuSettlementBillImporter $importer): int
|
||||
public function handle(
|
||||
DewuSettlementBillImporter $importer,
|
||||
BillPerformanceResyncDispatcher $performanceResync,
|
||||
): int
|
||||
{
|
||||
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
|
||||
if (trim((string) $this->option($option)) === '') {
|
||||
@ -67,6 +74,10 @@ class ImportDewuSettlementBills extends Command
|
||||
->implode(';'));
|
||||
$this->line('SHA-256: ' . $result['source_sha256']);
|
||||
|
||||
if (! $this->queueBillPerformanceResync($performanceResync, 'dewu', $result)) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,12 +2,16 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\DouyinAuthoritativeBillImporter;
|
||||
use Throwable;
|
||||
|
||||
class ImportDouyinAuthoritativeBills extends Command
|
||||
{
|
||||
use QueuesBillPerformanceResync;
|
||||
|
||||
protected $signature = 'business-mirror:import-douyin-authoritative
|
||||
{path : 胜算原始明细 UTF-8 CSV} {month : 所属月份 YYYY-MM}
|
||||
{--count= : 核对笔数} {--income= : 核对收入合计} {--expense= : 核对支出合计}
|
||||
@ -15,7 +19,10 @@ class ImportDouyinAuthoritativeBills extends Command
|
||||
|
||||
protected $description = '校验并原子启用指定月份或月初至截止日的胜算抖音明细,保留旧版本用于回滚';
|
||||
|
||||
public function handle(DouyinAuthoritativeBillImporter $importer): int
|
||||
public function handle(
|
||||
DouyinAuthoritativeBillImporter $importer,
|
||||
BillPerformanceResyncDispatcher $performanceResync,
|
||||
): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'),
|
||||
@ -25,6 +32,10 @@ class ImportDouyinAuthoritativeBills extends Command
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->info('胜算抖音明细已启用,范围:[' . $result['period_start'] . ', ' . $result['period_end'] . '),笔数:' . $result['row_count']);
|
||||
if (! $this->queueBillPerformanceResync($performanceResync, 'douyin', $result, true)) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,20 +2,27 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\JdDailyBillImporter;
|
||||
use Throwable;
|
||||
|
||||
class ImportJdDailyBills extends Command
|
||||
{
|
||||
use QueuesBillPerformanceResync;
|
||||
|
||||
protected $signature = 'business-mirror:import-jd-daily
|
||||
{path : 胜算京东日账单指定月份月初至截止日期 UTF-8 CSV} {month : YYYY-MM}
|
||||
{--through= : 截止日期 YYYY-MM-DD,默认月末} {--count= : 核对笔数} {--income= : 核对收入} {--expense= : 核对支出}';
|
||||
|
||||
protected $description = '核对并启用胜算京东日账单月份镜像,保留旧版本';
|
||||
|
||||
public function handle(JdDailyBillImporter $importer): int
|
||||
public function handle(
|
||||
JdDailyBillImporter $importer,
|
||||
BillPerformanceResyncDispatcher $performanceResync,
|
||||
): int
|
||||
{
|
||||
$lock = Cache::lock('jd-daily-bill-import', 21600);
|
||||
if (! $lock->get()) {
|
||||
@ -26,7 +33,20 @@ class ImportJdDailyBills extends Command
|
||||
$result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'),
|
||||
(int) $this->option('count'), (string) $this->option('income'), (string) $this->option('expense'), $this->option('through'));
|
||||
$this->info('京东日账单已启用,笔数:' . $result['row_count']);
|
||||
return self::SUCCESS;
|
||||
$queuedJd = $this->queueBillPerformanceResync(
|
||||
$performanceResync,
|
||||
'jd-transactions',
|
||||
$result,
|
||||
true,
|
||||
);
|
||||
$queuedJingxi = $this->queueBillPerformanceResync(
|
||||
$performanceResync,
|
||||
'jingxi',
|
||||
$result,
|
||||
true,
|
||||
);
|
||||
|
||||
return $queuedJd && $queuedJingxi ? self::SUCCESS : self::FAILURE;
|
||||
} catch (Throwable $e) {
|
||||
$this->error('京东日账单未启用,保留上一版本。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件、重复记录及镜像连接。'));
|
||||
return self::FAILURE;
|
||||
|
||||
@ -4,6 +4,7 @@ namespace App\Console\Commands;
|
||||
|
||||
use App\Business\WithdrawalBalanceAlertSynchronizer;
|
||||
use App\Models\Business\StoreReceivingAccount;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\FinanceBillShopBalanceFallback;
|
||||
use Modules\EcommerceFinance\Services\JushuitanShopBalanceImporter;
|
||||
@ -14,6 +15,7 @@ class ImportJushuitanShopBalances extends Command
|
||||
protected $signature = 'business:import-jushuitan-shop-balances
|
||||
{path : 聚水潭店铺余额接口 JSON 或 XLSX/XLS 导出文件}
|
||||
{--balance-date= : 导入日期,格式 YYYY-MM-DD;多日期导出必须指定}
|
||||
{--date-range= : 连续日期范围 YYYY-MM-DD:YYYY-MM-DD;一次导入多天余额}
|
||||
{--scope=all : 来源范围,同一日期同一范围会被原子替换}
|
||||
{--dry-run : 只校验和统计,不写入共享业务库}';
|
||||
|
||||
@ -25,13 +27,31 @@ class ImportJushuitanShopBalances extends Command
|
||||
FinanceBillShopBalanceFallback $financeFallback,
|
||||
): int
|
||||
{
|
||||
$dateRange = trim((string) ($this->option('date-range') ?? ''));
|
||||
$balanceDate = $this->option('balance-date');
|
||||
$allDates = $dateRange !== '';
|
||||
if ($allDates && $balanceDate !== null) {
|
||||
$this->error('--date-range 与 --balance-date 不能同时使用。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
$this->option('balance-date') === null ? null : (string) $this->option('balance-date'),
|
||||
(string) $this->option('scope'),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
if ($allDates) {
|
||||
$result = $importer->importMany(
|
||||
(string) $this->argument('path'),
|
||||
$this->rangeDates($dateRange),
|
||||
(string) $this->option('scope'),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} else {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
$balanceDate === null ? null : (string) $balanceDate,
|
||||
(string) $this->option('scope'),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error($exception->getMessage());
|
||||
@ -39,38 +59,54 @@ class ImportJushuitanShopBalances extends Command
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'%s:%s 共 %d 条,替换原有 %d 条。',
|
||||
$result['dry_run'] ? '校验完成' : '导入完成',
|
||||
$result['balance_date'],
|
||||
$result['total'],
|
||||
$result['replaced'],
|
||||
));
|
||||
|
||||
$financeFallbackFailed = false;
|
||||
try {
|
||||
$fallback = $financeFallback->fillMissing(
|
||||
$result['balance_date'],
|
||||
(string) $this->option('scope'),
|
||||
(bool) $result['dry_run'],
|
||||
);
|
||||
if (! $fallback['supported']) {
|
||||
$this->warn('账单余额回填:当前来源的店铺收款账户账单没有累计账户余额字段,跳过回填。');
|
||||
} elseif ($fallback['missing'] === 0) {
|
||||
$this->info('账单余额回填:聚水潭余额没有缺失店铺。');
|
||||
} else {
|
||||
if ($allDates) {
|
||||
foreach ($result['dates'] as $daily) {
|
||||
$this->info(sprintf(
|
||||
'账单余额回填:缺失 %d 家,匹配 %d 家,写入 %d 条,仍有 %d 家待补。',
|
||||
$fallback['missing'],
|
||||
$fallback['resolved'],
|
||||
$fallback['filled'],
|
||||
$fallback['unresolved'],
|
||||
'%s:%s 共 %d 条,替换原有 %d 条。',
|
||||
$daily['dry_run'] ? '校验完成' : '导入完成',
|
||||
$daily['balance_date'],
|
||||
$daily['total'],
|
||||
$daily['replaced'],
|
||||
));
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('财务系统店铺收款账户账单余额回填失败,聚水潭余额已保留,财务回填未覆盖。');
|
||||
$financeFallbackFailed = true;
|
||||
} else {
|
||||
$this->info(sprintf(
|
||||
'%s:%s 共 %d 条,替换原有 %d 条。',
|
||||
$result['dry_run'] ? '校验完成' : '导入完成',
|
||||
$result['balance_date'],
|
||||
$result['total'],
|
||||
$result['replaced'],
|
||||
));
|
||||
}
|
||||
|
||||
$financeFallbackFailed = false;
|
||||
if ($allDates) {
|
||||
$this->warn('多日期历史导入未执行财务账单回填,聚水潭原始快照已按日期写入。');
|
||||
} else {
|
||||
try {
|
||||
$fallback = $financeFallback->fillMissing(
|
||||
$result['balance_date'],
|
||||
(string) $this->option('scope'),
|
||||
(bool) $result['dry_run'],
|
||||
);
|
||||
if (! $fallback['supported']) {
|
||||
$this->warn('账单余额回填:当前来源的店铺收款账户账单没有累计账户余额字段,跳过回填。');
|
||||
} elseif ($fallback['missing'] === 0) {
|
||||
$this->info('账单余额回填:聚水潭余额没有缺失店铺。');
|
||||
} else {
|
||||
$this->info(sprintf(
|
||||
'账单余额回填:缺失 %d 家,匹配 %d 家,写入 %d 条,仍有 %d 家待补。',
|
||||
$fallback['missing'],
|
||||
$fallback['resolved'],
|
||||
$fallback['filled'],
|
||||
$fallback['unresolved'],
|
||||
));
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('财务系统店铺收款账户账单余额回填失败,聚水潭余额已保留,财务回填未覆盖。');
|
||||
$financeFallbackFailed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (! $result['dry_run']) {
|
||||
@ -103,4 +139,33 @@ class ImportJushuitanShopBalances extends Command
|
||||
|
||||
return $financeFallbackFailed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function rangeDates(string $range): array
|
||||
{
|
||||
$parts = explode(':', $range);
|
||||
if (count($parts) !== 2) {
|
||||
throw new \InvalidArgumentException('日期范围格式应为 YYYY-MM-DD:YYYY-MM-DD。');
|
||||
}
|
||||
|
||||
$start = CarbonImmutable::createFromFormat('!Y-m-d', trim($parts[0]), 'Asia/Shanghai');
|
||||
$end = CarbonImmutable::createFromFormat('!Y-m-d', trim($parts[1]), 'Asia/Shanghai');
|
||||
if (! $start instanceof CarbonImmutable
|
||||
|| $start->format('Y-m-d') !== trim($parts[0])
|
||||
|| ! $end instanceof CarbonImmutable
|
||||
|| $end->format('Y-m-d') !== trim($parts[1])
|
||||
|| $end->lt($start)) {
|
||||
throw new \InvalidArgumentException('日期范围格式应为 YYYY-MM-DD:YYYY-MM-DD,且结束日期不能早于开始日期。');
|
||||
}
|
||||
if ($start->diffInDays($end) > 366) {
|
||||
throw new \InvalidArgumentException('单次多日期导入不能超过 366 天。');
|
||||
}
|
||||
|
||||
$dates = [];
|
||||
for ($date = $start; $date->lte($end); $date = $date->addDay()) {
|
||||
$dates[] = $date->format('Y-m-d');
|
||||
}
|
||||
|
||||
return $dates;
|
||||
}
|
||||
}
|
||||
|
||||
164
app/Console/Commands/ImportKukaErpRecipients.php
Normal file
164
app/Console/Commands/ImportKukaErpRecipients.php
Normal file
@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ImportKukaErpRecipients extends Command
|
||||
{
|
||||
protected $signature = 'kuka-posting:import-erp-recipients
|
||||
{file : 工作簿5.xlsx 路径}
|
||||
{--company=1 : 公司 ID}
|
||||
{--sheet=Sheet1 : 工作表名称}';
|
||||
|
||||
protected $description = '导入顾家ERP商品导入使用的收货人池';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$path = (string) $this->argument('file');
|
||||
if (! is_file($path)) {
|
||||
throw new RuntimeException('导入文件不存在。');
|
||||
}
|
||||
|
||||
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
if (! Schema::connection($connectionName)->hasTable('kuka_posting_erp_recipient_rows')) {
|
||||
throw new RuntimeException('ERP收货人池表尚未建立。');
|
||||
}
|
||||
|
||||
$rows = $this->readRows($path, (string) $this->option('sheet'));
|
||||
if ($rows === []) {
|
||||
throw new RuntimeException('工作簿中没有可导入的收货人数据。');
|
||||
}
|
||||
|
||||
$companyId = max(1, (int) $this->option('company'));
|
||||
$now = now();
|
||||
DB::connection($connectionName)->transaction(function () use ($connectionName, $companyId, $now, $rows): void {
|
||||
$connection = DB::connection($connectionName);
|
||||
$connection->table('kuka_posting_erp_recipient_rows')
|
||||
->where('company_id', $companyId)
|
||||
->delete();
|
||||
$connection->table('kuka_posting_erp_recipient_rows')->insert(array_map(
|
||||
fn (array $row, int $index): array => $row + [
|
||||
'company_id' => $companyId,
|
||||
'sort_order' => $index + 1,
|
||||
'imported_at' => $now,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
],
|
||||
$rows,
|
||||
array_keys($rows),
|
||||
));
|
||||
});
|
||||
|
||||
$this->info('已导入 ERP 收货人池:'.count($rows).' 条。');
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{receiver_name:string,receiver_mobile:string,receiver_state:string,receiver_city:string,receiver_district:string,receiver_address:string,buyer_nick:string,source_row_number:int,row_hash:string}>
|
||||
*/
|
||||
private function readRows(string $path, string $sheetName): array
|
||||
{
|
||||
$spreadsheet = IOFactory::load($path);
|
||||
$sheet = $sheetName === ''
|
||||
? $spreadsheet->getActiveSheet()
|
||||
: $spreadsheet->getSheetByName($sheetName);
|
||||
if ($sheet === null) {
|
||||
throw new RuntimeException('工作簿中没有指定工作表:'.$sheetName);
|
||||
}
|
||||
|
||||
$data = $sheet->toArray(null, false, false, false);
|
||||
$headers = [
|
||||
'收货人(必填)',
|
||||
'收货人手机(必填)',
|
||||
'收货人的所在省份(必填)',
|
||||
'收货人的所在城市(必填)',
|
||||
'收货人的所在区(县)(必填)',
|
||||
'收货地址(必填)',
|
||||
'买家昵称(必填)',
|
||||
];
|
||||
$headerIndex = null;
|
||||
$columns = [];
|
||||
foreach (array_slice($data, 0, 20, true) as $rowIndex => $row) {
|
||||
$candidate = [];
|
||||
foreach ($row as $columnIndex => $value) {
|
||||
$label = trim((string) $value);
|
||||
if (in_array($label, $headers, true)) {
|
||||
$candidate[$label] = $columnIndex;
|
||||
}
|
||||
}
|
||||
if (count($candidate) === count($headers)) {
|
||||
$headerIndex = (int) $rowIndex;
|
||||
$columns = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($headerIndex === null) {
|
||||
throw new RuntimeException('未找到工作簿5的标准表头。');
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
foreach (array_slice($data, $headerIndex + 1, null, true) as $rowIndex => $row) {
|
||||
$values = [];
|
||||
foreach ($headers as $header) {
|
||||
$values[$header] = trim((string) ($row[$columns[$header]] ?? ''));
|
||||
}
|
||||
if ($values['收货人(必填)'] === 'clientName'
|
||||
|| $values['收货人手机(必填)'] === 'clientMobile') {
|
||||
continue;
|
||||
}
|
||||
foreach ($headers as $header) {
|
||||
if ($values[$header] === '') {
|
||||
throw new RuntimeException('第 '.($rowIndex + 1).' 行存在必填字段为空。');
|
||||
}
|
||||
}
|
||||
|
||||
$mobile = $this->normalizeMobile($values['收货人手机(必填)']);
|
||||
if ($mobile === '') {
|
||||
throw new RuntimeException('第 '.($rowIndex + 1).' 行收货人手机无效。');
|
||||
}
|
||||
$normalized = [
|
||||
'receiver_name' => $values['收货人(必填)'],
|
||||
'receiver_mobile' => $mobile,
|
||||
'receiver_state' => $values['收货人的所在省份(必填)'],
|
||||
'receiver_city' => $values['收货人的所在城市(必填)'],
|
||||
'receiver_district' => $values['收货人的所在区(县)(必填)'],
|
||||
'receiver_address' => $values['收货地址(必填)'],
|
||||
'buyer_nick' => $values['买家昵称(必填)'],
|
||||
'source_row_number' => (int) $rowIndex + 1,
|
||||
];
|
||||
$normalized['row_hash'] = hash('sha256', json_encode(
|
||||
$normalized,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
));
|
||||
$rows[] = $normalized;
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
private function normalizeMobile(mixed $value): string
|
||||
{
|
||||
$mobile = trim((string) $value);
|
||||
if ($mobile === '') {
|
||||
return '';
|
||||
}
|
||||
if (is_numeric($mobile) && preg_match('/^\d+(?:\.0+)?$/', $mobile) === 1) {
|
||||
return number_format((float) $mobile, 0, '', '');
|
||||
}
|
||||
|
||||
return preg_replace('/\s+/u', '', $mobile) ?? '';
|
||||
}
|
||||
}
|
||||
@ -52,6 +52,7 @@ class ImportKukaPostingBase extends Command
|
||||
['店铺数', number_format($result['store_count'])],
|
||||
['订单数', number_format($result['order_count'])],
|
||||
['非指定店铺跳过', number_format($result['skipped_store_rows'])],
|
||||
['已取消状态跳过', number_format($result['skipped_cancelled_rows'])],
|
||||
['文件 SHA-256', $result['file_sha256']],
|
||||
]);
|
||||
$this->table(['店铺', '行数'], $storeRows);
|
||||
|
||||
71
app/Console/Commands/ImportKukaPostingLabels.php
Normal file
71
app/Console/Commands/ImportKukaPostingLabels.php
Normal file
@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\KukaPostingBase\KukaPostingLabelImporter;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class ImportKukaPostingLabels extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:import-kuka-posting-labels
|
||||
{path : 带月度过账标签列的 XLSX 文件}
|
||||
{--month= : 账期 YYYY-MM}
|
||||
{--sheet=Sheet1 : 工作表名称}
|
||||
{--column= : 标签列名,默认按账期生成“YYYY年M月过账”}
|
||||
{--company=1 : 公司 ID}
|
||||
{--dry-run : 只校验文件和共享镜像,不写入过账标签}';
|
||||
|
||||
protected $description = '按源表行序更新顾家过账基础数据的过账标签';
|
||||
|
||||
public function handle(KukaPostingLabelImporter $importer): int
|
||||
{
|
||||
$period = trim((string) $this->option('month'));
|
||||
if ($period === '') {
|
||||
$this->error('必须指定 --month=YYYY-MM。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
$period,
|
||||
(string) ($this->option('sheet') ?: 'Sheet1'),
|
||||
$this->option('column') ? (string) $this->option('column') : null,
|
||||
max(1, (int) $this->option('company')),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('顾家过账标签未导入,原有数据未改变。' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$labelRows = [];
|
||||
foreach ($result['labels'] as $label => $count) {
|
||||
$labelRows[] = [$label, number_format($count)];
|
||||
}
|
||||
|
||||
$storeRows = [];
|
||||
foreach ($result['stores'] as $store => $count) {
|
||||
$storeRows[] = [$store, number_format($count)];
|
||||
}
|
||||
|
||||
$this->table(['项目', '值'], [
|
||||
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
|
||||
['账期', $result['period']],
|
||||
['标签列', $result['label_column']],
|
||||
['数据行数', number_format($result['rows'])],
|
||||
['店铺数', number_format($result['store_count'])],
|
||||
['需要更新', number_format($result['updated'])],
|
||||
['已一致', number_format($result['unchanged'])],
|
||||
['文件 SHA-256', $result['file_sha256']],
|
||||
]);
|
||||
$this->table(['过账标签', '行数'], $labelRows);
|
||||
$this->table(['店铺', '行数'], $storeRows);
|
||||
$this->info($result['dry_run'] ? '顾家过账标签校验完成。' : '顾家过账标签已更新。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
66
app/Console/Commands/ImportKukaPostingMaterialRepair.php
Normal file
66
app/Console/Commands/ImportKukaPostingMaterialRepair.php
Normal file
@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\KukaPostingBase\KukaPostingMaterialRepairImporter;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class ImportKukaPostingMaterialRepair extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:import-kuka-posting-material-repair
|
||||
{abnormalPath : 表一,缺少物料信息的异常数据 XLSX 文件}
|
||||
{mappingPath : 表二,包含完整物料信息的发货明细 XLSX 文件}
|
||||
{--month= : 账期 YYYY-MM}
|
||||
{--sheet=Sheet1 : 两个工作表共用的工作表名称}
|
||||
{--company=1 : 公司 ID}
|
||||
{--dry-run : 只校验异常清单、表二和生产镜像,不写入}';
|
||||
|
||||
protected $description = '仅修正顾家过账异常发货明细行的物料编号和物料描述';
|
||||
|
||||
public function handle(KukaPostingMaterialRepairImporter $importer): int
|
||||
{
|
||||
$period = trim((string) $this->option('month'));
|
||||
if ($period === '') {
|
||||
$this->error('必须指定 --month=YYYY-MM。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('abnormalPath'),
|
||||
(string) $this->argument('mappingPath'),
|
||||
$period,
|
||||
(string) ($this->option('sheet') ?: 'Sheet1'),
|
||||
max(1, (int) $this->option('company')),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('顾家过账物料修正未导入,原有数据未改变。' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$storeRows = [];
|
||||
foreach ($result['stores'] as $store => $count) {
|
||||
$storeRows[] = [$store, number_format($count)];
|
||||
}
|
||||
|
||||
$this->table(['项目', '值'], [
|
||||
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
|
||||
['账期', $result['period']],
|
||||
['异常数据行数', number_format($result['rows'])],
|
||||
['业务记录数', number_format($result['identities'])],
|
||||
['物料组合数', number_format($result['material_pairs'])],
|
||||
['需要更新', number_format($result['updated'])],
|
||||
['已一致', number_format($result['unchanged'])],
|
||||
['表一 SHA-256', $result['abnormal_file_sha256']],
|
||||
['表二 SHA-256', $result['mapping_file_sha256']],
|
||||
]);
|
||||
$this->table(['店铺', '异常行数'], $storeRows);
|
||||
$this->info($result['dry_run'] ? '顾家过账异常物料校验完成。' : '顾家过账异常物料已修正。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
64
app/Console/Commands/ImportKukaPostingMaterialSource.php
Normal file
64
app/Console/Commands/ImportKukaPostingMaterialSource.php
Normal file
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\KukaPostingBase\KukaPostingMaterialRepairImporter;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class ImportKukaPostingMaterialSource extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:import-kuka-posting-material-source
|
||||
{path : 包含完整发货明细和物料信息的 XLSX 文件}
|
||||
{--month= : 账期 YYYY-MM}
|
||||
{--sheet=Sheet1 : 工作表名称}
|
||||
{--company=1 : 公司 ID}
|
||||
{--dry-run : 只校验文件、物料报价和共享镜像,不写入}';
|
||||
|
||||
protected $description = '按整表物料源文件修正顾家过账发货明细的物料、成本和金额';
|
||||
|
||||
public function handle(KukaPostingMaterialRepairImporter $importer): int
|
||||
{
|
||||
$period = trim((string) $this->option('month'));
|
||||
if ($period === '') {
|
||||
$this->error('必须指定 --month=YYYY-MM。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $importer->importSource(
|
||||
(string) $this->argument('path'),
|
||||
$period,
|
||||
(string) ($this->option('sheet') ?: 'Sheet1'),
|
||||
max(1, (int) $this->option('company')),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('顾家过账物料源修正未导入,原有数据未改变。' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$storeRows = [];
|
||||
foreach ($result['stores'] as $store => $count) {
|
||||
$storeRows[] = [$store, number_format($count)];
|
||||
}
|
||||
|
||||
$this->table(['项目', '值'], [
|
||||
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
|
||||
['账期', $result['period']],
|
||||
['源文件行数', number_format($result['rows'])],
|
||||
['有效物料行数', number_format($result['valid_rows'])],
|
||||
['#N/A 等跳过行数', number_format($result['skipped_unmapped_rows'])],
|
||||
['物料编号数', number_format($result['materials'])],
|
||||
['需要更新', number_format($result['updated'])],
|
||||
['已一致', number_format($result['unchanged'])],
|
||||
['文件 SHA-256', $result['file_sha256']],
|
||||
]);
|
||||
$this->table(['店铺', '有效物料行数'], $storeRows);
|
||||
$this->info($result['dry_run'] ? '顾家过账整表物料校验完成。' : '顾家过账整表物料已修正。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
52
app/Console/Commands/ImportKukaPostingQuotation.php
Normal file
52
app/Console/Commands/ImportKukaPostingQuotation.php
Normal file
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\KukaPostingQuotation\KukaPostingQuotationImporter;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class ImportKukaPostingQuotation extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:import-kuka-posting-quotation
|
||||
{path : 顾家报价单 XLSX 文件}
|
||||
{--sheet= : 工作表名称,默认 Sheet1}
|
||||
{--company=1 : 公司 ID}
|
||||
{--dry-run : 只校验文件、字段和物料编码,不写入共享镜像}';
|
||||
|
||||
protected $description = '导入顾家过账报价单';
|
||||
|
||||
public function handle(KukaPostingQuotationImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
$this->option('sheet') ?: null,
|
||||
max(1, (int) $this->option('company')),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('顾家报价单未导入,原有数据未改变。' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$statuses = [];
|
||||
foreach ($result['status_counts'] as $status => $count) {
|
||||
$statuses[] = [$status, number_format($count)];
|
||||
}
|
||||
|
||||
$this->table(['项目', '值'], [
|
||||
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
|
||||
['报价记录', number_format($result['rows'])],
|
||||
['唯一物料', number_format($result['material_count'])],
|
||||
['文件 SHA-256', $result['file_sha256']],
|
||||
]);
|
||||
if ($statuses !== []) {
|
||||
$this->table(['状态', '记录数'], $statuses);
|
||||
}
|
||||
$this->info($result['dry_run'] ? '顾家报价单校验完成。' : '顾家报价单已导入共享镜像。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
118
app/Console/Commands/ImportPayablesFinal.php
Normal file
118
app/Console/Commands/ImportPayablesFinal.php
Normal file
@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Modules\EcommerceFinance\Services\PayablesFinalImportRunner;
|
||||
use Modules\EcommerceFinance\Services\PayablesFinalRegistry;
|
||||
use Throwable;
|
||||
|
||||
class ImportPayablesFinal extends Command
|
||||
{
|
||||
protected $signature = 'payables:final-import
|
||||
{--directory= : 已解压 CSV 文件目录}
|
||||
{--section=supplier-payables-final : 终版目录}
|
||||
{--dataset=payment-reconciliation : 数据集页面}
|
||||
{--company=1 : 公司 ID}
|
||||
{--user= : 操作人 ID}';
|
||||
|
||||
protected $description = '将终版页面的 CSV 文件分片导入业务数据库';
|
||||
|
||||
public function handle(
|
||||
PayablesFinalRegistry $registry,
|
||||
PayablesFinalImportRunner $runner,
|
||||
): int {
|
||||
$directory = trim((string) $this->option('directory'));
|
||||
$section = trim((string) $this->option('section'));
|
||||
$dataset = trim((string) $this->option('dataset'));
|
||||
$companyId = max(1, (int) $this->option('company'));
|
||||
$userId = $this->option('user') === null ? null : max(1, (int) $this->option('user'));
|
||||
|
||||
if ($directory === '' || ! is_dir($directory)) {
|
||||
$this->error('导入目录不存在。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (! $registry->supports($section, $dataset)) {
|
||||
$this->error('不支持的终版页面。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$files = glob(rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*.csv') ?: [];
|
||||
sort($files, SORT_NATURAL);
|
||||
if ($files === []) {
|
||||
$this->error('导入目录中没有 CSV 文件。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$fields = $registry->fields($section, $dataset);
|
||||
$storeDataset = 'final:'
|
||||
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
|
||||
. ':'
|
||||
. $dataset;
|
||||
$totalCreated = 0;
|
||||
$totalUpdated = 0;
|
||||
$totalRows = 0;
|
||||
|
||||
try {
|
||||
foreach ($files as $index => $path) {
|
||||
$file = new UploadedFile(
|
||||
$path,
|
||||
basename($path),
|
||||
'text/csv',
|
||||
null,
|
||||
true,
|
||||
);
|
||||
$prepared = $runner->prepare(
|
||||
$file,
|
||||
$fields,
|
||||
$storeDataset,
|
||||
$companyId,
|
||||
$userId,
|
||||
);
|
||||
$token = $prepared['token'];
|
||||
$offset = 0;
|
||||
$created = 0;
|
||||
$updated = 0;
|
||||
|
||||
do {
|
||||
$progress = $runner->process($token, $offset, null, $companyId);
|
||||
$offset = $progress['offset'];
|
||||
$created = $progress['created'];
|
||||
$updated = $progress['updated'];
|
||||
} while (! $progress['done']);
|
||||
|
||||
$totalCreated += $created;
|
||||
$totalUpdated += $updated;
|
||||
$totalRows += (int) $prepared['total'];
|
||||
$this->line(sprintf(
|
||||
'[%d/%d] %s:%s 行,新增 %s,更新 %s',
|
||||
$index + 1,
|
||||
count($files),
|
||||
basename($path),
|
||||
number_format((int) $prepared['total']),
|
||||
number_format($created),
|
||||
number_format($updated),
|
||||
));
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'导入完成:文件 %s 个,读取 %s 行,新增 %s,更新 %s。',
|
||||
number_format(count($files)),
|
||||
number_format($totalRows),
|
||||
number_format($totalCreated),
|
||||
number_format($totalUpdated),
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -11,16 +11,19 @@ use Throwable;
|
||||
class ImportPinduoduoPlatformBalances extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:import-pdd-platform-balances
|
||||
{path : 拼多多平台实际期末余额 XLSX/XLS/CSV}
|
||||
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD}';
|
||||
{path : 聚水潭平台资金账户余额 XLSX/XLS/CSV}
|
||||
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD;文件名含 YYYY-MM 时可省略}';
|
||||
|
||||
protected $description = '导入拼多多平台实际期末余额,作为后续月份期初余额的滚动基准';
|
||||
protected $description = '导入拼多多“期初余额”和“平台实际期末余额”,并自动维护待补期初队列';
|
||||
|
||||
public function handle(PinduoduoPlatformBalanceImporter $importer): int
|
||||
{
|
||||
$periodEnd = trim((string) $this->option('period-end'));
|
||||
if ($periodEnd === '') {
|
||||
$this->error('缺少 --period-end。');
|
||||
$periodEnd = $this->periodEndFromFilename((string) $this->argument('path'));
|
||||
}
|
||||
if ($periodEnd === '') {
|
||||
$this->error('无法从文件名识别账期,请使用 --period-end=YYYY-MM-DD 指定月末。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
@ -38,9 +41,11 @@ class ImportPinduoduoPlatformBalances extends Command
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->table(['截止日期', '店铺数', '余额合计', '替换旧行数', '来源文件'], [[
|
||||
$this->table(['截止日期', '店铺数', '期初行数', '期初合计', '期末余额合计', '替换旧行数', '来源文件'], [[
|
||||
$result['period_end'],
|
||||
$result['total'],
|
||||
$result['opening_total'],
|
||||
$result['opening_balance_total'],
|
||||
$result['balance_total'],
|
||||
$result['replaced'],
|
||||
$result['source_filename'],
|
||||
@ -48,4 +53,23 @@ class ImportPinduoduoPlatformBalances extends Command
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function periodEndFromFilename(string $path): string
|
||||
{
|
||||
$filename = basename($path);
|
||||
if (preg_match('/(20\d{2})[-_年](\d{1,2})/u', $filename, $matches) !== 1) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$month = (int) $matches[2];
|
||||
if ($month < 1 || $month > 12) {
|
||||
return '';
|
||||
}
|
||||
$date = \DateTimeImmutable::createFromFormat(
|
||||
'!Y-n-j',
|
||||
sprintf('%d-%d-1', (int) $matches[1], $month),
|
||||
);
|
||||
|
||||
return $date === false ? '' : $date->format('Y-m-t');
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,13 +2,17 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\PinduoduoSettlementBillImporter;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ImportPinduoduoSettlementBills extends Command
|
||||
{
|
||||
use QueuesBillPerformanceResync;
|
||||
|
||||
protected $signature = 'pinduoduo-bills:import-authoritative
|
||||
{path : 聚胜算导出的拼多多完整账单 XLSX}
|
||||
{--from= : 账期开始日期,格式 YYYY-MM-DD}
|
||||
@ -20,7 +24,10 @@ class ImportPinduoduoSettlementBills extends Command
|
||||
|
||||
protected $description = '导入并核验聚胜算拼多多完整账单(保留全部账户类型)';
|
||||
|
||||
public function handle(PinduoduoSettlementBillImporter $importer): int
|
||||
public function handle(
|
||||
PinduoduoSettlementBillImporter $importer,
|
||||
BillPerformanceResyncDispatcher $performanceResync,
|
||||
): int
|
||||
{
|
||||
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
|
||||
if (trim((string) $this->option($option)) === '') {
|
||||
@ -67,6 +74,10 @@ class ImportPinduoduoSettlementBills extends Command
|
||||
->implode(';'));
|
||||
$this->line('SHA-256: ' . $result['source_sha256']);
|
||||
|
||||
if (! $this->queueBillPerformanceResync($performanceResync, 'pinduoduo', $result)) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
111
app/Console/Commands/ImportServiceCompanyCustomerMapping.php
Normal file
111
app/Console/Commands/ImportServiceCompanyCustomerMapping.php
Normal file
@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\ServiceCompanyReconciliation\CustomerServiceMappingWorkbookImporter;
|
||||
use App\Business\ServiceCompanyReconciliation\ServiceCompanyReconciliationRepository;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class ImportServiceCompanyCustomerMapping extends Command
|
||||
{
|
||||
protected $signature = 'service-company:import-customer-mapping
|
||||
{file : 客服公司映射 Excel 路径}
|
||||
{--company-id=1 : 租户公司 ID}
|
||||
{--effective-from=2026-10-01 : 结算关系生效日期}
|
||||
{--auto-assign-period= : 未分配店铺按该月收入自动平衡,默认上一个完整月}
|
||||
{--deactivate-empty-auto : 校正错误自动分配,停用报表当前月份无收入的自动来源关系}
|
||||
{--actor=客服公司映射导入 : 导入操作人}
|
||||
{--dry-run : 只解析和校验,不写入数据库}';
|
||||
|
||||
protected $description = '导入客服公司与店铺公司的配置映射';
|
||||
|
||||
public function handle(
|
||||
CustomerServiceMappingWorkbookImporter $importer,
|
||||
ServiceCompanyReconciliationRepository $repository,
|
||||
): int {
|
||||
$companyId = (int) $this->option('company-id');
|
||||
$effectiveFrom = trim((string) $this->option('effective-from'));
|
||||
$autoAssignPeriod = trim((string) $this->option('auto-assign-period'));
|
||||
if ($autoAssignPeriod === '') {
|
||||
$autoAssignPeriod = now()->startOfMonth()->subMonthNoOverflow()->format('Y-m');
|
||||
}
|
||||
try {
|
||||
$parsed = $importer->rows((string) $this->argument('file'));
|
||||
} catch (\Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->table(['指标', '数量'], [
|
||||
['店铺公司行数', $parsed['total_rows']],
|
||||
['已分配客服公司', $parsed['assigned_rows']],
|
||||
['暂不分配', $parsed['unassigned_rows']],
|
||||
['无效行', count($parsed['invalid_rows'])],
|
||||
]);
|
||||
if ($parsed['invalid_rows'] !== []) {
|
||||
$this->error(implode(PHP_EOL, $parsed['invalid_rows']));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ((bool) $this->option('dry-run')) {
|
||||
$this->info('校验通过,未写入数据库。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$result = $repository->syncCustomerServiceMappings(
|
||||
$companyId,
|
||||
$parsed['rows'],
|
||||
$effectiveFrom,
|
||||
trim((string) $this->option('actor')) ?: '客服公司映射导入',
|
||||
$parsed['unassigned'],
|
||||
$autoAssignPeriod,
|
||||
);
|
||||
if ($result['errors'] !== []) {
|
||||
$this->error(implode(PHP_EOL, $result['errors']));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->table(['结果', '数量'], [
|
||||
['新增', $result['created']],
|
||||
['更新', $result['updated']],
|
||||
['无变化', $result['unchanged']],
|
||||
['停用', $result['inactive']],
|
||||
['自动补分配', $result['auto_assigned']],
|
||||
['有收入但无法分配', count($result['auto_errors'])],
|
||||
]);
|
||||
if ($result['auto_totals'] !== []) {
|
||||
$this->table(
|
||||
['客服公司', '自动补分配后收入'],
|
||||
collect($result['auto_totals'])
|
||||
->map(static fn (float $amount, string $name): array => [$name, number_format($amount, 2, '.', '')])
|
||||
->values()
|
||||
->all(),
|
||||
);
|
||||
}
|
||||
if ($result['auto_errors'] !== []) {
|
||||
$this->warn(implode(PHP_EOL, $result['auto_errors']));
|
||||
}
|
||||
if ((bool) $this->option('deactivate-empty-auto')) {
|
||||
$cleanup = $repository->deactivateAutoMappingsWithoutReportIncome(
|
||||
$companyId,
|
||||
$autoAssignPeriod,
|
||||
trim((string) $this->option('actor')) ?: '客服公司映射导入',
|
||||
);
|
||||
if ($cleanup['errors'] !== []) {
|
||||
$this->error(implode(PHP_EOL, $cleanup['errors']));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->table(['自动分配校正', '数量'], [
|
||||
['停用无收入关系', $cleanup['deactivated']],
|
||||
['保留有收入关系', $cleanup['kept']],
|
||||
]);
|
||||
}
|
||||
$this->info("客服公司映射已同步,生效日期:{$effectiveFrom}");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -2,13 +2,17 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\TaobaoAlipaySettlementBillImporter;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ImportTaobaoAlipaySettlementBills extends Command
|
||||
{
|
||||
use QueuesBillPerformanceResync;
|
||||
|
||||
protected $signature = 'taobao-alipay-bills:import-authoritative
|
||||
{path : 聚胜算导出的淘系支付宝完整账单 XLSX}
|
||||
{--from= : 账期开始日期,格式 YYYY-MM-DD}
|
||||
@ -20,7 +24,10 @@ class ImportTaobaoAlipaySettlementBills extends Command
|
||||
|
||||
protected $description = '导入并核验聚胜算淘系支付宝完整账单';
|
||||
|
||||
public function handle(TaobaoAlipaySettlementBillImporter $importer): int
|
||||
public function handle(
|
||||
TaobaoAlipaySettlementBillImporter $importer,
|
||||
BillPerformanceResyncDispatcher $performanceResync,
|
||||
): int
|
||||
{
|
||||
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
|
||||
if (trim((string) $this->option($option)) === '') {
|
||||
@ -66,6 +73,10 @@ class ImportTaobaoAlipaySettlementBills extends Command
|
||||
->implode(';'));
|
||||
$this->line('SHA-256: ' . $result['source_sha256']);
|
||||
|
||||
if (! $this->queueBillPerformanceResync($performanceResync, 'taobao-alipay', $result)) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,13 +2,17 @@
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\TaobaoWechatSettlementBillImporter;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ImportTaobaoWechatSettlementBills extends Command
|
||||
{
|
||||
use QueuesBillPerformanceResync;
|
||||
|
||||
protected $signature = 'taobao-wechat-bills:import-authoritative
|
||||
{path : 聚胜算导出的淘系微信完整账单 XLSX}
|
||||
{--from= : 账期开始日期,格式 YYYY-MM-DD}
|
||||
@ -20,7 +24,10 @@ class ImportTaobaoWechatSettlementBills extends Command
|
||||
|
||||
protected $description = '导入并核验聚胜算淘系微信完整账单';
|
||||
|
||||
public function handle(TaobaoWechatSettlementBillImporter $importer): int
|
||||
public function handle(
|
||||
TaobaoWechatSettlementBillImporter $importer,
|
||||
BillPerformanceResyncDispatcher $performanceResync,
|
||||
): int
|
||||
{
|
||||
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
|
||||
if (trim((string) $this->option($option)) === '') {
|
||||
@ -67,6 +74,10 @@ class ImportTaobaoWechatSettlementBills extends Command
|
||||
->implode(';'));
|
||||
$this->line('SHA-256: ' . $result['source_sha256']);
|
||||
|
||||
if (! $this->queueBillPerformanceResync($performanceResync, 'taobao-wechat', $result)) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
@ -13,7 +13,7 @@ class ImportWangshangBankBills extends Command
|
||||
{--date= : 账单日期 YYYY-MM-DD,默认前一天}
|
||||
{--dry-run : 只校验,不写入财务台账}';
|
||||
|
||||
protected $description = '批量导入网商银行交易明细到财务台账动账明细';
|
||||
protected $description = '批量导入网商银行影刀账单到银行账单';
|
||||
|
||||
public function handle(WangshangBankBillImporter $importer): int
|
||||
{
|
||||
@ -26,7 +26,7 @@ class ImportWangshangBankBills extends Command
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('网商银行账单未导入,保留原有动账明细。' . $exception->getMessage());
|
||||
$this->error('网商银行影刀账单未导入,保留原有银行账单。' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
@ -45,12 +45,16 @@ class ImportWangshangBankBills extends Command
|
||||
|
||||
$this->info(sprintf(
|
||||
'%s网商银行账单:%d 个账户,%d 笔,收入 %.2f,支出 %.2f。',
|
||||
$result['dry_run'] ? '校验完成,' : '已接入财务台账动账明细,',
|
||||
$result['dry_run'] ? '校验完成,' : '已写入银行账单,',
|
||||
count($result['accounts']),
|
||||
$result['rows'],
|
||||
$result['income'],
|
||||
$result['expense'],
|
||||
));
|
||||
$this->line(sprintf(
|
||||
'已同步 %d 个账户的当前余额。',
|
||||
$result['synced_accounts'],
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
384
app/Console/Commands/LockFinanceLedgerMonthlyOpening.php
Normal file
384
app/Console/Commands/LockFinanceLedgerMonthlyOpening.php
Normal file
@ -0,0 +1,384 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
class LockFinanceLedgerMonthlyOpening extends Command
|
||||
{
|
||||
protected $signature = 'finance-ledger:lock-monthly-opening
|
||||
{date? : 锁定日期,必须为每月 1 日;默认当月}
|
||||
{--apply : 正式写入;不传时只预览}
|
||||
{--json : 以 JSON 输出结果}';
|
||||
|
||||
protected $description = '按上月末最后一笔真实银行余额锁定账户月度期初';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$date = $this->date();
|
||||
$previousEnd = $date->subDay();
|
||||
$nextMonth = $date->addMonthNoOverflow();
|
||||
$result = $this->lock($date, $previousEnd, $nextMonth, (bool) $this->option('apply'));
|
||||
if ((bool) $this->option('json')) {
|
||||
$this->line(json_encode(
|
||||
$result,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
|
||||
));
|
||||
} else {
|
||||
$this->line(($result['applied'] ? '已锁定' : '预览') . ' ' . $result['opening_date'] . ' 月度期初');
|
||||
$this->line(
|
||||
'可锁定账户:' . $result['eligible_accounts']
|
||||
. ';写入账户:' . $result['unique_account_shorts']
|
||||
. ';新增:' . $result['created']
|
||||
. ';更新:' . $result['updated']
|
||||
. ';无变化:' . $result['unchanged']
|
||||
. ';保留手工期初:' . $result['preserved_existing']
|
||||
);
|
||||
$this->line(
|
||||
'跳过:无真实余额 ' . $result['skipped_no_basis']
|
||||
. ';同名账户余额冲突 ' . $result['skipped_conflicts']
|
||||
);
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (\Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
private function date(): CarbonImmutable
|
||||
{
|
||||
$value = trim((string) ($this->argument('date') ?: now('Asia/Shanghai')->toDateString()));
|
||||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
|
||||
if (! $date instanceof CarbonImmutable
|
||||
|| $date->format('Y-m-d') !== $value
|
||||
|| $date->day !== 1) {
|
||||
throw new RuntimeException('锁定日期必须使用 YYYY-MM-01 格式。');
|
||||
}
|
||||
|
||||
return $date;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function lock(
|
||||
CarbonImmutable $date,
|
||||
CarbonImmutable $previousEnd,
|
||||
CarbonImmutable $nextMonth,
|
||||
bool $apply,
|
||||
): array {
|
||||
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
||||
$accounts = $connection->table('fin_accounts')
|
||||
->whereNotNull('account_short')
|
||||
->where('account_short', '<>', '')
|
||||
->orderBy('account_short')
|
||||
->orderBy('account_no')
|
||||
->get(['id', 'account_short', 'account_no']);
|
||||
$bankStatementBefore = [];
|
||||
foreach ($connection->table('fin_transactions')
|
||||
->where('source', 'bank_statement')
|
||||
->whereNotNull('balance')
|
||||
->orderBy('txn_date')
|
||||
->orderBy('id')
|
||||
->get(['txn_date', 'source_value', 'income', 'expense', 'balance']) as $row) {
|
||||
$accountNo = $this->accountNo($row->source_value);
|
||||
if ($accountNo === '') {
|
||||
continue;
|
||||
}
|
||||
if ($row->txn_date <= $previousEnd->toDateString()) {
|
||||
$bankStatementBefore[$accountNo] = $row;
|
||||
}
|
||||
}
|
||||
$bankBillBefore = [];
|
||||
foreach ($connection->table('fin_bank_direct_bills')
|
||||
->whereNotNull('balance')
|
||||
->orderBy('txn_date')
|
||||
->orderBy('txn_at')
|
||||
->orderBy('id')
|
||||
->get(['account_no', 'txn_date', 'income', 'expense', 'balance']) as $row) {
|
||||
$accountNo = $this->accountNo($row->account_no);
|
||||
if ($accountNo === '') {
|
||||
continue;
|
||||
}
|
||||
if ($row->txn_date <= $previousEnd->toDateString()) {
|
||||
$bankBillBefore[$accountNo] = $row;
|
||||
}
|
||||
}
|
||||
$snapshotBefore = [];
|
||||
foreach ($connection->table('fin_bank_direct_balance_snapshots')
|
||||
->where('balance_date', '<=', $previousEnd->toDateString())
|
||||
->orderBy('balance_date')
|
||||
->orderBy('balance_at')
|
||||
->orderBy('id')
|
||||
->get(['account_no', 'account_balance', 'available_balance']) as $row) {
|
||||
$accountNo = $this->accountNo($row->account_no);
|
||||
if ($accountNo !== '') {
|
||||
$snapshotBefore[$accountNo] = $row;
|
||||
}
|
||||
}
|
||||
$openingBefore = $connection->table('fin_account_opening')
|
||||
->where('opening_date', '<', $date->toDateString())
|
||||
->orderBy('opening_date')
|
||||
->orderBy('id')
|
||||
->get(['account_short', 'opening_date', 'opening_balance'])
|
||||
->keyBy('account_short');
|
||||
$latestTransactionByShort = [];
|
||||
$latestTransactionByAccountNo = [];
|
||||
foreach ($connection->table('fin_transactions')
|
||||
->whereNull('deleted_at')
|
||||
->where('txn_date', '<=', $previousEnd->toDateString())
|
||||
->cursor() as $row) {
|
||||
$transactionDate = substr((string) $row->txn_date, 0, 10);
|
||||
$short = trim((string) ($row->account_short ?? ''));
|
||||
if ($short !== ''
|
||||
&& ($latestTransactionByShort[$short] ?? '') < $transactionDate) {
|
||||
$latestTransactionByShort[$short] = $transactionDate;
|
||||
}
|
||||
$accountNo = $this->accountNo($row->source_value ?? null);
|
||||
if ($accountNo !== ''
|
||||
&& ($latestTransactionByAccountNo[$accountNo] ?? '') < $transactionDate) {
|
||||
$latestTransactionByAccountNo[$accountNo] = $transactionDate;
|
||||
}
|
||||
}
|
||||
$existingOpenings = $connection->table('fin_account_opening')
|
||||
->where('opening_date', $date->toDateString())
|
||||
->get()
|
||||
->keyBy('account_short');
|
||||
|
||||
$byShort = [];
|
||||
foreach ($accounts as $account) {
|
||||
$short = trim((string) $account->account_short);
|
||||
$accountNo = $this->accountNo($account->account_no);
|
||||
[$balance, $source, $sourceDate] = $this->actualOpening(
|
||||
$accountNo,
|
||||
$bankStatementBefore,
|
||||
$bankBillBefore,
|
||||
$snapshotBefore,
|
||||
);
|
||||
[$carriedBalance, $carriedSource, $carriedSourceDate] = $this->carriedOpening(
|
||||
$short,
|
||||
$accountNo,
|
||||
$openingBefore,
|
||||
$latestTransactionByShort,
|
||||
$latestTransactionByAccountNo,
|
||||
);
|
||||
$opening = $openingBefore->get($short);
|
||||
$latestOpeningDate = $opening === null
|
||||
? ''
|
||||
: substr((string) $opening->opening_date, 0, 10);
|
||||
if ($carriedBalance !== null
|
||||
&& ($balance === null || $carriedSourceDate > $sourceDate)) {
|
||||
$balance = $carriedBalance;
|
||||
$source = $carriedSource;
|
||||
$sourceDate = $carriedSourceDate;
|
||||
} elseif ($balance !== null
|
||||
&& $latestOpeningDate !== ''
|
||||
&& $sourceDate < $latestOpeningDate) {
|
||||
// 新期初比旧账单余额更晚;若期初后还有未定价动账,不能回退使用旧余额。
|
||||
$balance = null;
|
||||
$source = '';
|
||||
$sourceDate = '';
|
||||
}
|
||||
if ($balance === null) {
|
||||
$byShort[$short][] = [
|
||||
'account_id' => (int) $account->id,
|
||||
'balance' => null,
|
||||
'source' => '',
|
||||
'source_date' => '',
|
||||
];
|
||||
continue;
|
||||
}
|
||||
$byShort[$short][] = [
|
||||
'account_id' => (int) $account->id,
|
||||
'balance' => $balance,
|
||||
'source' => $source,
|
||||
'source_date' => $sourceDate,
|
||||
];
|
||||
}
|
||||
|
||||
$eligibleAccounts = 0;
|
||||
$skippedNoBasis = 0;
|
||||
$skippedConflicts = 0;
|
||||
$candidates = [];
|
||||
foreach ($byShort as $short => $items) {
|
||||
$missing = array_filter($items, static fn (array $item): bool => $item['balance'] === null);
|
||||
if ($missing !== []) {
|
||||
$skippedNoBasis += count($items);
|
||||
continue;
|
||||
}
|
||||
$balances = array_values(array_unique(array_map(
|
||||
static fn (array $item): string => number_format((float) $item['balance'], 2, '.', ''),
|
||||
$items,
|
||||
)));
|
||||
if (count($balances) !== 1) {
|
||||
$skippedConflicts += count($items);
|
||||
continue;
|
||||
}
|
||||
$eligibleAccounts += count($items);
|
||||
$candidates[$short] = [
|
||||
'opening_balance' => (float) $balances[0],
|
||||
'source' => (string) $items[0]['source'],
|
||||
'source_date' => (string) $items[0]['source_date'],
|
||||
];
|
||||
}
|
||||
|
||||
$created = 0;
|
||||
$updated = 0;
|
||||
$unchanged = 0;
|
||||
$preservedExisting = 0;
|
||||
if ($apply) {
|
||||
$connection->transaction(function () use (
|
||||
$connection,
|
||||
$date,
|
||||
$candidates,
|
||||
$existingOpenings,
|
||||
&$created,
|
||||
&$updated,
|
||||
&$unchanged,
|
||||
&$preservedExisting,
|
||||
): void {
|
||||
foreach ($candidates as $short => $candidate) {
|
||||
$existing = $existingOpenings->get($short);
|
||||
$remark = '系统锁定:' . $candidate['source_date'] . ' 最后一笔实际余额';
|
||||
if ($existing === null) {
|
||||
$connection->table('fin_account_opening')->insert([
|
||||
'account_short' => $short,
|
||||
'opening_date' => $date->toDateString(),
|
||||
'opening_balance' => $candidate['opening_balance'],
|
||||
'remark' => $remark,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
$created++;
|
||||
continue;
|
||||
}
|
||||
if (! str_starts_with((string) $existing->remark, '系统锁定:')) {
|
||||
$preservedExisting++;
|
||||
continue;
|
||||
}
|
||||
if (abs((float) $existing->opening_balance - (float) $candidate['opening_balance']) < 0.005
|
||||
&& (string) $existing->remark === $remark) {
|
||||
$unchanged++;
|
||||
continue;
|
||||
}
|
||||
$connection->table('fin_account_opening')
|
||||
->where('id', $existing->id)
|
||||
->update([
|
||||
'opening_balance' => $candidate['opening_balance'],
|
||||
'remark' => $remark,
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
$updated++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return [
|
||||
'applied' => $apply,
|
||||
'opening_date' => $date->toDateString(),
|
||||
'previous_period_end' => $previousEnd->toDateString(),
|
||||
'eligible_accounts' => $eligibleAccounts,
|
||||
'unique_account_shorts' => count($candidates),
|
||||
'created' => $created,
|
||||
'updated' => $updated,
|
||||
'unchanged' => $unchanged,
|
||||
'preserved_existing' => $preservedExisting,
|
||||
'skipped_no_basis' => $skippedNoBasis,
|
||||
'skipped_conflicts' => $skippedConflicts,
|
||||
'candidates' => array_map(
|
||||
static fn (string $short, array $candidate): array => [
|
||||
'account_short' => $short,
|
||||
...$candidate,
|
||||
],
|
||||
array_keys($candidates),
|
||||
array_values($candidates),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:?float,1:string,2:string}
|
||||
*/
|
||||
private function actualOpening(
|
||||
string $accountNo,
|
||||
array $bankStatementBefore,
|
||||
array $bankBillBefore,
|
||||
array $snapshotBefore,
|
||||
): array {
|
||||
if ($accountNo === '') {
|
||||
return [null, '', ''];
|
||||
}
|
||||
if (isset($bankStatementBefore[$accountNo])) {
|
||||
$row = $bankStatementBefore[$accountNo];
|
||||
|
||||
return [
|
||||
round((float) $row->balance, 2),
|
||||
'bank_statement',
|
||||
substr((string) $row->txn_date, 0, 10),
|
||||
];
|
||||
}
|
||||
if (isset($bankBillBefore[$accountNo])) {
|
||||
$row = $bankBillBefore[$accountNo];
|
||||
|
||||
return [
|
||||
round((float) $row->balance, 2),
|
||||
'bank_bill',
|
||||
substr((string) $row->txn_date, 0, 10),
|
||||
];
|
||||
}
|
||||
if (isset($snapshotBefore[$accountNo])) {
|
||||
$row = $snapshotBefore[$accountNo];
|
||||
|
||||
return [
|
||||
round((float) ($row->account_balance ?? $row->available_balance), 2),
|
||||
'balance_snapshot',
|
||||
substr((string) $row->balance_date, 0, 10),
|
||||
];
|
||||
}
|
||||
|
||||
return [null, '', ''];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:?float,1:string,2:string}
|
||||
*/
|
||||
private function carriedOpening(
|
||||
string $accountShort,
|
||||
string $accountNo,
|
||||
mixed $openingBefore,
|
||||
array $latestTransactionByShort,
|
||||
array $latestTransactionByAccountNo,
|
||||
): array {
|
||||
$opening = $openingBefore->get($accountShort);
|
||||
if ($opening === null) {
|
||||
return [null, '', ''];
|
||||
}
|
||||
|
||||
$openingDate = substr((string) $opening->opening_date, 0, 10);
|
||||
$latestTransactionDate = max(
|
||||
(string) ($latestTransactionByShort[$accountShort] ?? ''),
|
||||
$accountNo !== '' ? (string) ($latestTransactionByAccountNo[$accountNo] ?? '') : '',
|
||||
);
|
||||
if ($latestTransactionDate !== '' && $latestTransactionDate >= $openingDate) {
|
||||
return [null, '', ''];
|
||||
}
|
||||
|
||||
return [
|
||||
round((float) $opening->opening_balance, 2),
|
||||
'opening_carry_forward',
|
||||
$openingDate,
|
||||
];
|
||||
}
|
||||
|
||||
private function accountNo(mixed $value): string
|
||||
{
|
||||
return preg_replace('/\D+/', '', trim((string) $value)) ?? '';
|
||||
}
|
||||
}
|
||||
104
app/Console/Commands/PlantingReimbursementDailyDigest.php
Normal file
104
app/Console/Commands/PlantingReimbursementDailyDigest.php
Normal file
@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\EcommerceFinance\Repositories\PlantingReimbursementRepository as Repository;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementAuditor as Auditor;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
|
||||
use Throwable;
|
||||
|
||||
/** 每天 10:25 生成当天种菜报销批次,把核对数、可报销合计、要取消的单和自检结果推到钉钉群并 @ 报销人。只读,不改聚工单。 */
|
||||
class PlantingReimbursementDailyDigest extends Command
|
||||
{
|
||||
protected $signature = 'planting-reimbursement:daily-digest
|
||||
{--date= : 报销日期 Y-m-d,默认今天}
|
||||
{--dry-run : 只打印消息,不发送}
|
||||
{--force : 忽略当天已推送标记}';
|
||||
|
||||
protected $description = '推送当天种菜报销批次汇总到钉钉群';
|
||||
|
||||
public function handle(Workbench $workbench, Robot $robot, Repository $repository): int
|
||||
{
|
||||
$date = trim((string) $this->option('date')) ?: Workbench::defaultDate();
|
||||
try {
|
||||
Workbench::parseDate($date);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$failed = false;
|
||||
foreach (Company::enabled()->orderBy('id')->get() as $company) {
|
||||
$company->makeCurrent();
|
||||
if (! $robot->enabled()) {
|
||||
$this->line("#{$company->id}: 未配置种菜报销群机器人,跳过");
|
||||
continue;
|
||||
}
|
||||
$lock = "planting-reimbursement:digest:{$company->id}:{$date}";
|
||||
if (! $this->option('dry-run') && ! $this->option('force') && ! Cache::add($lock, now()->toDateTimeString(), now()->addDay())) {
|
||||
$this->line("#{$company->id}: {$date} 已推送过");
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
[$title, $text] = $this->message($workbench, $repository, (int) $company->id, $date);
|
||||
if ($this->option('dry-run')) {
|
||||
$this->line($title . "\n" . $text);
|
||||
continue;
|
||||
}
|
||||
$robot->sendDigest($title, $text);
|
||||
$this->info("#{$company->id}: 已推送 {$date} 汇总");
|
||||
} catch (Throwable $exception) {
|
||||
Cache::forget($lock);
|
||||
report($exception);
|
||||
$this->error("#{$company->id}: 推送失败:" . $exception->getMessage());
|
||||
$failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
/** @return array{0:string,1:string} */
|
||||
private function message(Workbench $workbench, Repository $repository, int $companyId, string $date): array
|
||||
{
|
||||
$sync = $repository->syncStatus();
|
||||
$url = route('business.pages.show', ['company_id' => $companyId, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench', 'date' => $date]);
|
||||
$title = '种菜报销 ' . $date . ' 批次';
|
||||
$lines = ['#### ' . $title];
|
||||
|
||||
$stale = $sync['code'] !== 'ready' || $sync['last_succeeded_at'] === null
|
||||
|| now()->diffInMinutes(\Illuminate\Support\Carbon::parse($sync['last_succeeded_at']), true) > 20;
|
||||
if ($stale) {
|
||||
$lines[] = '> **聚工单数据不是最新的**(最后同步成功:' . ($sync['last_succeeded_at'] ? substr($sync['last_succeeded_at'], 0, 16) : '无') . '),先别按下面结果报销。';
|
||||
}
|
||||
if (! in_array($sync['code'], ['ready', 'failed'], true)) {
|
||||
$lines[] = '- 聚工单镜像未就绪,暂时无法生成批次。';
|
||||
$lines[] = '- [打开工作台](' . $url . ')';
|
||||
|
||||
return [$title, implode("\n", $lines)];
|
||||
}
|
||||
|
||||
$result = $workbench->build($companyId, $date);
|
||||
$s = $result['summary'];
|
||||
$lines[] = '- 待处理(付款 ' . substr($result['window']['from'], 0, 10) . ' ~ ' . substr($result['window']['to'], 0, 10) . '):**' . $s['source']['count'] . ' 条 / ' . number_format((float) $s['source']['amount'], 2) . ' 元**,请先在聚工单核对';
|
||||
$lines[] = '- 可报销:' . $s['counts'][Auditor::DECISION_PASS] . ' 条 / **' . number_format((float) $s['total'], 2) . ' 元**(三大天猫 ' . number_format((float) $s['group_amounts'][Auditor::GROUP_BIG_TMALL], 2) . ',其他 ' . number_format((float) $s['group_amounts'][Auditor::GROUP_OTHER], 2) . ')';
|
||||
$lines[] = '- 取消工单:' . $s['counts'][Auditor::DECISION_CANCEL] . ' 条;待复查:' . $s['counts'][Auditor::DECISION_RECHECK] . ' 条';
|
||||
$bad = array_column(array_filter($s['checks'], static fn (array $check): bool => ! $check['ok']), 'label');
|
||||
$lines[] = '- 自检:' . ($bad === [] ? '全部通过' : '未通过 ' . implode('、', $bad));
|
||||
if (($result['uploads']['monitor'] ?? null) === null || substr((string) ($result['uploads']['monitor']['uploaded_at'] ?? ''), 0, 10) !== $date) {
|
||||
$lines[] = '- 今天还没上传种菜监控看板,超额尚未校验';
|
||||
}
|
||||
if (($result['roster_source'] ?? '') === 'none') {
|
||||
$lines[] = '- 取不到在职名单,收款人在职未校验';
|
||||
}
|
||||
$lines[] = '- [打开工作台核对](' . $url . ')';
|
||||
|
||||
return [$title, implode("\n", $lines)];
|
||||
}
|
||||
}
|
||||
38
app/Console/Commands/ProcessPayablesUnpricedCycle.php
Normal file
38
app/Console/Commands/ProcessPayablesUnpricedCycle.php
Normal file
@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\PayablesUnpricedCycleProcessor;
|
||||
|
||||
class ProcessPayablesUnpricedCycle extends Command
|
||||
{
|
||||
protected $signature = 'payables:unpriced-cycle
|
||||
{price-file : 工作平台定价/变价文件路径}
|
||||
{--period= : 货款账期,格式 YYYY-MM,默认上月}
|
||||
{--cutoff= : 定价快照截止日,格式 YYYY-MM-DD,默认今天}
|
||||
{--company=1 : 公司 ID}
|
||||
{--user= : 操作用户 ID}';
|
||||
|
||||
protected $description = '匹配历史未定价并补入当月新增未定价';
|
||||
|
||||
public function handle(PayablesUnpricedCycleProcessor $processor): int
|
||||
{
|
||||
$period = (string) ($this->option('period') ?: now()->subMonthNoOverflow()->format('Y-m'));
|
||||
$cutoff = (string) ($this->option('cutoff') ?: now()->format('Y-m-d'));
|
||||
$companyId = max(1, (int) $this->option('company'));
|
||||
$userId = $this->option('user') !== null ? (int) $this->option('user') : null;
|
||||
|
||||
$result = $processor->process(
|
||||
(string) $this->argument('price-file'),
|
||||
$period,
|
||||
$cutoff,
|
||||
$companyId,
|
||||
$userId,
|
||||
);
|
||||
|
||||
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -9,8 +9,8 @@ use Modules\EcommerceFinance\Repositories\DewuSettlementBillRepository;
|
||||
use Modules\EcommerceFinance\Repositories\JdDailyBillRepository;
|
||||
use Modules\EcommerceFinance\Repositories\PinduoduoSettlementBillRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingDewuAlipayBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
|
||||
@ -150,6 +150,7 @@ class RunAccountBillsExportTask extends Command
|
||||
'taobao-wechat' => app(TaobaoWechatSettlementBillRepository::class)->exportAccountBills($filters, $sort, $dir),
|
||||
'pinduoduo' => app(PinduoduoSettlementBillRepository::class)->exportAccountBills($filters, $sort, $dir),
|
||||
'dewu' => app(DewuSettlementBillRepository::class)->exportAccountBills($filters, $sort, $dir),
|
||||
'dewu-alipay' => app(StoreReceivingDewuAlipayBillMirrorRepository::class)->exportRows($filters, $sort, $dir),
|
||||
'jd-transactions', 'jingxi' => JdBillPlatform::isJdBillTab($tab)
|
||||
? app(JdDailyBillRepository::class)->forPlatform(JdBillPlatform::platformForBillType($tab))->exportRows($filters, $sort, $dir)
|
||||
: [],
|
||||
|
||||
@ -11,7 +11,7 @@ use Symfony\Component\Process\Process;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 科目映射表变更后的业绩明细自动重跑队列。
|
||||
* 科目映射表或原始账单变化后的业绩明细自动重跑队列。
|
||||
*
|
||||
* 每轮按预算处理队列里的「平台 × 月份」;实际同步放在独立 PHP 子进程中,
|
||||
* 避免大平台重跑时的内存累积,并让其它同步有机会取得全局锁。
|
||||
@ -20,7 +20,7 @@ class RunAccountMappingResync extends Command
|
||||
{
|
||||
protected $signature = 'store-receipt:auto-resync {--max-jobs=1 : 每轮最多任务数,0为不限} {--max-seconds=300 : 单个任务结束后检查本轮时间预算}';
|
||||
|
||||
protected $description = '处理科目映射表变更触发的业绩明细重跑队列';
|
||||
protected $description = '处理科目映射表或原始账单变化触发的业绩明细重跑队列';
|
||||
|
||||
public function handle(AccountMappingResyncDispatcher $dispatcher): int
|
||||
{
|
||||
@ -79,7 +79,7 @@ class RunAccountMappingResync extends Command
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('科目映射表自动重跑失败:' . $exception->getMessage());
|
||||
Log::error('业绩明细自动重跑失败:' . $exception->getMessage());
|
||||
DB::table(AccountMappingResyncDispatcher::JOBS_TABLE)
|
||||
->where('id', $job->id)
|
||||
->where('status', 'running')
|
||||
|
||||
52
app/Console/Commands/SeedUnshippedHistory.php
Normal file
52
app/Console/Commands/SeedUnshippedHistory.php
Normal file
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Support\UnshippedWaybills;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
final class SeedUnshippedHistory extends Command
|
||||
{
|
||||
protected $signature = 'courier:seed-unshipped-history {cutoff : 历史明细截止日期} {--apply : 确认写入共享镜像}';
|
||||
protected $description = '从标准输入读取核对后的分来源单号清单,补录历史未发出明细';
|
||||
|
||||
public function handle(UnshippedWaybills $service): int
|
||||
{
|
||||
$data = json_decode(stream_get_contents(STDIN, 1048577), true);
|
||||
$cutoff = $this->argument('cutoff');
|
||||
$validator = Validator::make(['data' => $data, 'cutoff' => $cutoff], [
|
||||
'cutoff' => ['required', 'date_format:Y-m-d', 'after_or_equal:'.UnshippedWaybills::START, 'before:today'],
|
||||
'data' => ['required', 'array:intercept,replacement,warehouse', 'size:3'],
|
||||
'data.*' => ['required', 'array', 'max:10000'],
|
||||
'data.*.*' => ['required', 'string', 'regex:/^[a-zA-Z0-9-]{7,96}$/', 'not_regex:/^\d+(?:\.\d+)?e[+-]?\d+$/i'],
|
||||
'data.intercept.*' => ['max:15'],
|
||||
]);
|
||||
if ($validator->fails()) {
|
||||
$this->error('清单格式、快递单号或截止日期校验失败。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$marker = UnshippedWaybills::HISTORY_PREFIX.$cutoff;
|
||||
foreach ($data as $source => $numbers) {
|
||||
$data[$source] = array_values(array_unique($numbers));
|
||||
$this->info(UnshippedWaybills::label($source).':'.count($data[$source]).' 条。');
|
||||
}
|
||||
if (!$this->option('apply')) return self::SUCCESS;
|
||||
|
||||
$service->connection()->transaction(function () use ($service, $data, $marker, $cutoff): void {
|
||||
foreach ($data as $source => $numbers) {
|
||||
foreach (array_chunk($numbers, 500) as $chunk) {
|
||||
$service->results()->upsert(array_map(fn ($waybill) => [
|
||||
'source' => $source, 'waybill_no' => $waybill, 'evidence_no' => $marker,
|
||||
'evidence_time' => $cutoff.' 00:00:00', 'evidence_text' => '历史导出补录,文件仅含单号和来源;日期为覆盖截止日。',
|
||||
], $chunk), ['source', 'evidence_no', 'waybill_no'], ['evidence_text']);
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
170
app/Console/Commands/SendCmbMailFailureNotification.php
Normal file
170
app/Console/Commands/SendCmbMailFailureNotification.php
Normal file
@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class SendCmbMailFailureNotification extends Command
|
||||
{
|
||||
protected $signature = 'cmb-mail:notify-failure
|
||||
{--date= : 账单日期 YYYY-MM-DD;默认前一天}
|
||||
{--type=unknown : 失败类型}
|
||||
{--reason= : 已脱敏的简短失败原因}
|
||||
{--recipient= : 接收人的钉钉企业昵称}
|
||||
{--test : 发送通道测试消息}';
|
||||
|
||||
protected $description = '由生产服务器向指定钉钉成员发送招商银行邮件任务失败提醒';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$date = $this->date();
|
||||
$recipient = trim((string) $this->option('recipient'));
|
||||
if ($recipient === '') {
|
||||
throw new RuntimeException('未配置钉钉提醒接收人。');
|
||||
}
|
||||
|
||||
$userIds = DB::table('dingtalk_identities')
|
||||
->where('nickname', $recipient)
|
||||
->whereNotNull('dingtalk_user_id')
|
||||
->pluck('dingtalk_user_id')
|
||||
->map(static fn ($value): string => trim((string) $value))
|
||||
->filter()
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
if ($userIds->count() !== 1) {
|
||||
throw new RuntimeException(
|
||||
$userIds->isEmpty()
|
||||
? '没有找到对应的钉钉企业成员。'
|
||||
: '该昵称对应多个钉钉企业成员,无法安全确定接收人。'
|
||||
);
|
||||
}
|
||||
|
||||
[$title, $text] = $this->message(
|
||||
$date,
|
||||
trim((string) $this->option('type')) ?: 'unknown',
|
||||
$this->safeReason((string) $this->option('reason')),
|
||||
(bool) $this->option('test'),
|
||||
);
|
||||
$this->sendToDingTalk([$userIds->first()], $title, $text);
|
||||
$this->info($this->option('test') ? '钉钉通知通道测试已发送。' : '钉钉失败提醒已发送。');
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
private function date(): string
|
||||
{
|
||||
$value = trim((string) $this->option('date'));
|
||||
$value = $value !== '' ? $value : now('Asia/Shanghai')->subDay()->toDateString();
|
||||
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||||
if (! $parsed || $parsed->format('Y-m-d') !== $value) {
|
||||
throw new RuntimeException('--date 必须使用 YYYY-MM-DD 格式。');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @return array{0:string,1:string} */
|
||||
private function message(string $date, string $type, string $reason, bool $test): array
|
||||
{
|
||||
if ($test) {
|
||||
return [
|
||||
'招商银行邮件任务通知通道测试',
|
||||
implode("\n", [
|
||||
'### 招商银行邮件任务通知通道测试',
|
||||
'- 接收方式:生产服务器直接发送至钉钉',
|
||||
'- 用途:仅发送招商银行邮件任务异常提醒',
|
||||
'- 结果:通道已接通',
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
$labels = [
|
||||
'auth' => '邮箱授权失效或登录失败',
|
||||
'config' => '任务配置缺失',
|
||||
'not_found' => '未找到当天招商银行账单邮件',
|
||||
'download' => '账单下载失败',
|
||||
'archive' => '账单解压或安全校验失败',
|
||||
'import' => '银行账单导入失败',
|
||||
'unknown' => '任务执行失败',
|
||||
];
|
||||
|
||||
return [
|
||||
'招商银行邮件任务失败',
|
||||
implode("\n", [
|
||||
'### 招商银行邮件任务失败',
|
||||
'- 账单日期:' . $date,
|
||||
'- 失败类型:' . ($labels[$type] ?? $labels['unknown']),
|
||||
'- 执行结果:07:00、07:10 两次均失败',
|
||||
'- 原因:' . $reason,
|
||||
'请检查服务器任务日志及 163 邮箱授权状态。',
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
private function safeReason(string $reason): string
|
||||
{
|
||||
$reason = preg_replace('/[\r\n\t]+/u', ' ', trim($reason)) ?? '';
|
||||
$reason = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu', '[邮箱已隐藏]', $reason) ?? $reason;
|
||||
$reason = mb_substr($reason, 0, 200);
|
||||
|
||||
return $reason !== '' ? $reason : '服务器日志已记录具体错误。';
|
||||
}
|
||||
|
||||
/** @param list<string> $userIds */
|
||||
private function sendToDingTalk(array $userIds, string $title, string $text): void
|
||||
{
|
||||
$clientId = trim((string) config('dingtalk.client_id'));
|
||||
$clientSecret = trim((string) config('dingtalk.client_secret'));
|
||||
$robotCode = trim((string) config('dingtalk.robot.code'));
|
||||
if ($clientId === '' || $clientSecret === '' || $robotCode === '') {
|
||||
throw new RuntimeException('钉钉应用通知凭据不完整。');
|
||||
}
|
||||
|
||||
$timeout = max(3, min(30, (int) config('dingtalk.timeout', 10)));
|
||||
$tokenResponse = Http::asJson()
|
||||
->acceptJson()
|
||||
->timeout($timeout)
|
||||
->post((string) config('dingtalk.robot.access_token_url'), [
|
||||
'appKey' => $clientId,
|
||||
'appSecret' => $clientSecret,
|
||||
]);
|
||||
$accessToken = trim((string) $tokenResponse->json('accessToken'));
|
||||
if (! $tokenResponse->successful() || $accessToken === '') {
|
||||
throw new RuntimeException('钉钉应用访问令牌获取失败。');
|
||||
}
|
||||
|
||||
$response = Http::asJson()
|
||||
->acceptJson()
|
||||
->withHeaders(['x-acs-dingtalk-access-token' => $accessToken])
|
||||
->timeout($timeout)
|
||||
->post((string) config('dingtalk.robot.send_url'), [
|
||||
'robotCode' => $robotCode,
|
||||
'userIds' => $userIds,
|
||||
'msgKey' => 'sampleMarkdown',
|
||||
'msgParam' => json_encode([
|
||||
'title' => $title,
|
||||
'text' => $text,
|
||||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
|
||||
if (! $response->successful()) {
|
||||
$code = trim((string) $response->json('code'));
|
||||
throw new RuntimeException(
|
||||
'钉钉消息发送失败:HTTP ' . $response->status()
|
||||
. ($code !== '' ? ' ' . mb_substr($code, 0, 120) : '')
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
99
app/Console/Commands/SendSupplierStatementReminders.php
Normal file
99
app/Console/Commands/SendSupplierStatementReminders.php
Normal file
@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\EcommerceFinance\Services\SupplierStatementReminder;
|
||||
use Throwable;
|
||||
|
||||
class SendSupplierStatementReminders extends Command
|
||||
{
|
||||
protected $signature = 'supplier-statement:send-reminders
|
||||
{--date= : 执行日期,格式 Y-m-d,默认今天}
|
||||
{--supplier= : 仅检查指定供应商}
|
||||
{--dry-run : 只预览,不发送也不记录}';
|
||||
|
||||
protected $description = '在每月 1-14 日提醒上月有入库数据但尚未上传对账单的供应商';
|
||||
|
||||
public function handle(SupplierStatementReminder $reminder): int
|
||||
{
|
||||
$timezone = (string) config('app.platform_timezone', 'Asia/Shanghai');
|
||||
$dateValue = trim((string) $this->option('date')) ?: now($timezone)->toDateString();
|
||||
try {
|
||||
$date = Carbon::createFromFormat('!Y-m-d', $dateValue, $timezone)->startOfDay();
|
||||
} catch (Throwable) {
|
||||
$this->error('执行日期格式无效。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($date->format('Y-m-d') !== $dateValue) {
|
||||
$this->error('执行日期格式无效。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$failed = false;
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
foreach (Company::enabled()->orderBy('id')->get() as $company) {
|
||||
$company->makeCurrent();
|
||||
$lock = Cache::lock(sprintf(
|
||||
'supplier-statement-reminder:%d:%s',
|
||||
$company->id,
|
||||
$date->toDateString(),
|
||||
), 900);
|
||||
if (! $dryRun && ! $lock->get()) {
|
||||
$this->warn("#{$company->id} {$company->name}: 已有催办任务运行");
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $reminder->send(
|
||||
$date,
|
||||
(int) $company->id,
|
||||
$dryRun,
|
||||
trim((string) $this->option('supplier')),
|
||||
);
|
||||
if (! $result['reminder_day']) {
|
||||
$this->line("#{$company->id} {$company->name}: 今天不在 1-14 日催办窗口");
|
||||
continue;
|
||||
}
|
||||
if ($result['source_suppliers'] === 0) {
|
||||
$this->warn("#{$company->id} {$company->name}: 上月对账入库数据尚未导入或没有入库供应商");
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->line(sprintf(
|
||||
'#%d %s %s: 入库供应商 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,今日已提醒 %d 家,未配置机器人 %d 家,失败 %d 家',
|
||||
$company->id,
|
||||
$company->name,
|
||||
$result['accounting_month'],
|
||||
$result['source_suppliers'],
|
||||
$result['configured'],
|
||||
$dryRun ? '将提醒' : '已发送',
|
||||
count($dryRun ? $result['previewed'] : $result['sent']),
|
||||
count($result['uploaded']),
|
||||
count($result['already_sent']),
|
||||
count($result['missing_robot']),
|
||||
count($result['failed']),
|
||||
));
|
||||
foreach ($result['failed'] as $supplier => $message) {
|
||||
$this->error("{$supplier}: {$message}");
|
||||
$failed = true;
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error("#{$company->id} {$company->name}: 催办任务失败:" . $exception->getMessage());
|
||||
$failed = true;
|
||||
} finally {
|
||||
if (! $dryRun) {
|
||||
$lock->release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -13,9 +13,10 @@ use Throwable;
|
||||
|
||||
class SyncBusinessFilesToQiniu extends Command
|
||||
{
|
||||
private const PROBE_CLEANUP_MAX_ATTEMPTS = 10;
|
||||
// Qiniu can briefly report a deleted object as present; keep the wait bounded.
|
||||
private const PROBE_CLEANUP_MAX_ATTEMPTS = 20;
|
||||
|
||||
private const PROBE_CLEANUP_RETRY_DELAY_MICROSECONDS = 500_000;
|
||||
private const PROBE_CLEANUP_RETRY_DELAY_MICROSECONDS = 1_000_000;
|
||||
|
||||
protected $signature = 'storage:business-files:sync
|
||||
{--require-qiniu : Fail unless the private Qiniu backend is enabled}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\DingInvoiceSyncService;
|
||||
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
|
||||
use Throwable;
|
||||
|
||||
@ -12,12 +13,15 @@ class SyncDingProcessDetailMirror extends Command
|
||||
{--full : 从配置起始日期完整重建明细和付款事实}
|
||||
{--business-id= : 只同步指定审批编号,多个用逗号分隔(最多 50 个)}
|
||||
{--skip-approval-api : 定向同步时不调用钉钉官方审批接口}
|
||||
{--skip-invoices : 不执行同轮发票增量识别}
|
||||
{--dry-run : 只读取上游并校验,不写入镜像}';
|
||||
|
||||
protected $description = '从结构化审批镜像同步流程明细,并用钉钉官方接口补取缺失付款';
|
||||
protected $description = '同步 OA 流程结构化明细,并在同一批处理中增量识别发票';
|
||||
|
||||
public function handle(DingProcessDetailMirrorSynchronizer $synchronizer): int
|
||||
{
|
||||
public function handle(
|
||||
DingProcessDetailMirrorSynchronizer $synchronizer,
|
||||
DingInvoiceSyncService $invoiceSync,
|
||||
): int {
|
||||
$businessIds = array_values(array_filter(array_map(
|
||||
'trim',
|
||||
explode(',', (string) $this->option('business-id')),
|
||||
@ -61,6 +65,31 @@ class SyncDingProcessDetailMirror extends Command
|
||||
$result['bank_amount_total'],
|
||||
));
|
||||
|
||||
if ($businessIds === []
|
||||
&& ! (bool) $this->option('dry-run')
|
||||
&& ! (bool) $this->option('skip-invoices')
|
||||
&& (bool) config('ding_invoice_data.sync_with_oa_process', true)) {
|
||||
try {
|
||||
$month = $invoiceSync->latestPendingMonth();
|
||||
if ($month !== null) {
|
||||
$invoiceResult = $invoiceSync->syncMonth(
|
||||
$month,
|
||||
(int) config('ding_invoice_data.auto_scan_limit', 5),
|
||||
);
|
||||
$this->info(sprintf(
|
||||
'发票增量识别完成:%d 个流程,新识别 %d 张,保留 %d 张,剩余 %d 个流程。',
|
||||
$invoiceResult['processed_flows'],
|
||||
$invoiceResult['recognized_invoices'],
|
||||
$invoiceResult['preserved_invoices'],
|
||||
$invoiceResult['remaining_flows'],
|
||||
));
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->warn('发票增量识别失败,OA 流程镜像已正常更新:' . $exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,7 +39,11 @@ class SyncDingWorklogs extends Command
|
||||
|
||||
$days = max((int) ($this->option('days') ?: config('dingtalk.worklog.lookback_days', 35)), 1);
|
||||
$templates = $this->templates();
|
||||
$to = now();
|
||||
$timezone = (string) config(
|
||||
'dingtalk.worklog.timezone',
|
||||
config('app.platform_timezone', config('app.timezone', 'Asia/Shanghai')),
|
||||
);
|
||||
$to = now($timezone);
|
||||
$from = $to->copy()->subDays($days)->startOfDay();
|
||||
|
||||
try {
|
||||
|
||||
@ -13,6 +13,8 @@ class SyncFinanceLedgerRpt extends Command
|
||||
{--to= : 业务日期止,默认读取配置或当天}
|
||||
{--days= : 只拉取最近 N 天并合并到现有明细}
|
||||
{--merge : 合并到现有明细,不删除历史}
|
||||
{--dingtalk-only : 只同步钉钉付款明细,用于高频增量}
|
||||
{--sources= : 只同步指定来源,逗号分隔:dingtalk,payable,store,withdrawal}
|
||||
{--no-recalculate : 只同步明细,不重算流水}';
|
||||
|
||||
protected $description = '从 AI 库 rpt 同步财务台账动账明细,并重算每日流水';
|
||||
@ -22,18 +24,34 @@ class SyncFinanceLedgerRpt extends Command
|
||||
$days = (int) ($this->option('days') ?: 0);
|
||||
$from = $this->option('from') ?: null;
|
||||
$merge = (bool) $this->option('merge');
|
||||
$dingtalkOnly = (bool) $this->option('dingtalk-only');
|
||||
$sources = array_values(array_filter(array_map(
|
||||
'trim',
|
||||
explode(',', (string) $this->option('sources')),
|
||||
)));
|
||||
if ($dingtalkOnly) {
|
||||
$sources = ['dingtalk'];
|
||||
}
|
||||
if ($days > 0) {
|
||||
$from = now()->subDays(max(1, $days) - 1)->toDateString();
|
||||
$merge = true;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $synchronizer->sync(
|
||||
! $this->option('no-recalculate'),
|
||||
$from,
|
||||
$this->option('to') ?: null,
|
||||
$merge,
|
||||
);
|
||||
$result = $sources !== []
|
||||
? $synchronizer->syncSources(
|
||||
$sources,
|
||||
! $this->option('no-recalculate'),
|
||||
$from,
|
||||
$this->option('to') ?: null,
|
||||
$merge,
|
||||
)
|
||||
: $synchronizer->sync(
|
||||
! $this->option('no-recalculate'),
|
||||
$from,
|
||||
$this->option('to') ?: null,
|
||||
$merge,
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
|
||||
@ -32,8 +32,23 @@ class SyncFinanceLedgerShopData extends Command
|
||||
$this->option('to') ?: null,
|
||||
(bool) $this->option('rebuild'),
|
||||
);
|
||||
$directoryMappings = $synchronizer->syncAccountMappings();
|
||||
$publicAccountDefaults = $synchronizer->syncDefaultPublicAccounts();
|
||||
$result = [
|
||||
'balance' => $balance,
|
||||
'account_mappings' => [
|
||||
'defaulted' => $publicAccountDefaults['defaulted'],
|
||||
'directory_shops' => $directoryMappings['shops'],
|
||||
'shop_rows_updated' => $directoryMappings['shop_rows_updated']
|
||||
+ $publicAccountDefaults['shop_rows_updated'],
|
||||
'mappings_inserted' => $directoryMappings['mappings_inserted']
|
||||
+ $publicAccountDefaults['mappings_inserted'],
|
||||
'mappings_updated' => $directoryMappings['mappings_updated']
|
||||
+ $publicAccountDefaults['mappings_updated'],
|
||||
'account_missing' => $publicAccountDefaults['account_missing'],
|
||||
'ambiguous' => $directoryMappings['ambiguous']
|
||||
+ $publicAccountDefaults['ambiguous'],
|
||||
],
|
||||
'withdrawals' => [
|
||||
'processed' => 0,
|
||||
'written' => 0,
|
||||
@ -68,6 +83,8 @@ class SyncFinanceLedgerShopData extends Command
|
||||
['重建店铺台账', $result['balance']['rebuilt']],
|
||||
['已更新店铺余额', $result['balance']['matched']],
|
||||
['店铺余额合计', number_format((float) $result['balance']['amount'], 2)],
|
||||
['默认公户补齐店铺', $result['account_mappings']['defaulted']],
|
||||
['多公户待确认', $result['account_mappings']['ambiguous']],
|
||||
['提现处理笔数', $result['withdrawals']['processed']],
|
||||
['提现新增或更新', $result['withdrawals']['written']],
|
||||
['上游已存在提现', $result['withdrawals']['upstream_duplicates']],
|
||||
|
||||
35
app/Console/Commands/SyncInternalFlowCompanies.php
Normal file
35
app/Console/Commands/SyncInternalFlowCompanies.php
Normal file
@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\InternalFlowWorkbookImporter;
|
||||
use Throwable;
|
||||
|
||||
class SyncInternalFlowCompanies extends Command
|
||||
{
|
||||
protected $signature = 'internal-flow:sync-companies';
|
||||
|
||||
protected $description = '将内部流转配置公司补齐到当前数据集,并同步其固定标签';
|
||||
|
||||
public function handle(InternalFlowWorkbookImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->syncConfiguredCompanies();
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('内部流转公司标签同步失败:' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'内部流转公司标签同步完成:新增 %s 家,更新 %s 家,配置共 %s 家。',
|
||||
number_format($result['inserted']),
|
||||
number_format($result['updated']),
|
||||
number_format($result['total']),
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
58
app/Console/Commands/SyncKukaPostingMaterialMap.php
Normal file
58
app/Console/Commands/SyncKukaPostingMaterialMap.php
Normal file
@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\KukaPostingBase\KukaPostingMaterialMapSynchronizer;
|
||||
use Illuminate\Console\Command;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class SyncKukaPostingMaterialMap extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:sync-kuka-posting-material-map
|
||||
{--company=1 : 公司 ID}
|
||||
{--period= : 只匹配指定账期,格式 YYYY-MM}
|
||||
{--dry-run : 只读取和校验,不覆盖镜像}
|
||||
{--json : 输出 JSON}';
|
||||
|
||||
protected $description = '按货号匹配物料编号,并按款式编码匹配品牌货号及货号回退';
|
||||
|
||||
public function handle(KukaPostingMaterialMapSynchronizer $synchronizer): int
|
||||
{
|
||||
$companyId = (int) $this->option('company');
|
||||
if ($companyId <= 0) {
|
||||
throw new InvalidArgumentException('公司 ID 必须为正整数。');
|
||||
}
|
||||
|
||||
$period = trim((string) $this->option('period'));
|
||||
if ($period !== '' && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
||||
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
|
||||
}
|
||||
|
||||
$result = $synchronizer->sync(
|
||||
$companyId,
|
||||
$period === '' ? null : $period,
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
|
||||
if ((bool) $this->option('json')) {
|
||||
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
} else {
|
||||
$this->info(sprintf(
|
||||
'物料映射%s完成:货号 %d,唯一匹配 %d,未匹配 %d,冲突 %d;直接物料编号 %d,档案条码 %d,品牌SKU %d;页面货号映射 %d(款式品牌 %d,货号品牌回退 %d)。',
|
||||
$result['dry_run'] ? '校验' : '同步',
|
||||
$result['items'],
|
||||
$result['matched'],
|
||||
$result['unmatched'],
|
||||
$result['ambiguous'],
|
||||
$result['direct'],
|
||||
$result['archive'],
|
||||
$result['brand_sku'],
|
||||
$result['brand_item_mappings'],
|
||||
$result['brand_sku_mappings'],
|
||||
$result['item_brand_mappings'],
|
||||
));
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
81
app/Console/Commands/SyncPiaojuSellerQuotas.php
Normal file
81
app/Console/Commands/SyncPiaojuSellerQuotas.php
Normal file
@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Business\Piaoju\PiaojuSellerQuotaClient;
|
||||
use App\Business\Piaoju\PiaojuSellerQuotaImporter;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
class SyncPiaojuSellerQuotas extends Command
|
||||
{
|
||||
protected $signature = 'piaoju:sync-invoice-quotas
|
||||
{--file= : 票聚销方列表 JSON 文件;省略时调用票聚接口}
|
||||
{--stdin : 从标准输入读取票聚销方列表 JSON}
|
||||
{--dry-run : 只读取并校验票聚响应,不写共享镜像}';
|
||||
|
||||
protected $description = '同步票聚销方管理的最新可用发票额度到共享业务镜像';
|
||||
|
||||
public function handle(PiaojuSellerQuotaClient $client, PiaojuSellerQuotaImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$rows = $this->inputRows($client);
|
||||
$values = $importer->values($rows);
|
||||
|
||||
if ((bool) $this->option('dry-run')) {
|
||||
$this->info(sprintf('票聚销方额度读取成功:%d 条,未写入镜像。', count($values)));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$written = $importer->replace($rows);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('票聚销方额度同步失败,已保留上一版镜像。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info(sprintf('票聚销方额度同步完成:%d 条。', $written));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function inputRows(PiaojuSellerQuotaClient $client): array
|
||||
{
|
||||
$fromStdin = (bool) $this->option('stdin');
|
||||
$path = trim((string) $this->option('file'));
|
||||
if (! $fromStdin && $path === '') {
|
||||
return $client->fetchAll();
|
||||
}
|
||||
|
||||
$raw = $fromStdin ? stream_get_contents(STDIN) : file_get_contents($path);
|
||||
if (! is_string($raw) || trim($raw) === '') {
|
||||
throw new \RuntimeException('piaoju_input_empty');
|
||||
}
|
||||
|
||||
$decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
|
||||
$rows = null;
|
||||
if (is_array($decoded)) {
|
||||
if (array_is_list($decoded)) {
|
||||
$rows = $decoded;
|
||||
} else {
|
||||
$data = $decoded['data'] ?? null;
|
||||
if (is_array($data)) {
|
||||
$rows = array_is_list($data)
|
||||
? $data
|
||||
: ($data['list'] ?? $data['records'] ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (! is_array($rows)) {
|
||||
throw new \RuntimeException('piaoju_input_invalid');
|
||||
}
|
||||
|
||||
return array_values(array_filter($rows, 'is_array'));
|
||||
}
|
||||
}
|
||||
74
app/Console/Commands/SyncPromotionExpenses.php
Normal file
74
app/Console/Commands/SyncPromotionExpenses.php
Normal file
@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\EcommerceFinance\Services\PromotionExpenseMirrorSynchronizer;
|
||||
use Throwable;
|
||||
|
||||
class SyncPromotionExpenses extends Command
|
||||
{
|
||||
private const HISTORY_START = '2026-01-01';
|
||||
|
||||
protected $signature = 'business-mirror:sync-promotion-expenses
|
||||
{--from= : 开始日期(含)}
|
||||
{--to= : 结束日期(含)}
|
||||
{--days=7 : 未指定 from/to 时同步最近多少天}
|
||||
{--full : 从 2026-01-01 开始完整校准}';
|
||||
|
||||
protected $description = '按日期、平台和店铺自动汇总聚水潭推广费用到共享镜像';
|
||||
|
||||
public function handle(PromotionExpenseMirrorSynchronizer $synchronizer): int
|
||||
{
|
||||
try {
|
||||
[$from, $to] = $this->dateRange();
|
||||
$result = $synchronizer->sync($from, $to);
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('推广费用共享镜像同步失败。', ['exception' => $exception::class]);
|
||||
$this->error('推广费用同步失败,页面继续显示上一版数据。');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($result['days'] === 0) {
|
||||
$this->warn('上游暂无推广费用数据,未写入镜像。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->info(sprintf(
|
||||
'推广费用同步完成:%s 至 %s(源数据截至 %s),%d 天,源记录 %d 条,汇总镜像 %d 行。',
|
||||
$result['from'],
|
||||
$result['to'],
|
||||
$result['effective_to'] ?? '无',
|
||||
$result['days'],
|
||||
$result['source_rows'],
|
||||
$result['stored_rows'],
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/** @return array{0:Carbon,1:Carbon} */
|
||||
private function dateRange(): array
|
||||
{
|
||||
$toInput = trim((string) $this->option('to'));
|
||||
$fromInput = trim((string) $this->option('from'));
|
||||
$to = $toInput === ''
|
||||
? now('Asia/Shanghai')->startOfDay()
|
||||
: Carbon::createFromFormat('Y-m-d', $toInput, 'Asia/Shanghai')->startOfDay();
|
||||
$from = $fromInput !== ''
|
||||
? Carbon::createFromFormat('Y-m-d', $fromInput, 'Asia/Shanghai')->startOfDay()
|
||||
: ($this->option('full')
|
||||
? Carbon::parse(self::HISTORY_START, 'Asia/Shanghai')->startOfDay()
|
||||
: $to->copy()->subDays(max(1, (int) $this->option('days')) - 1));
|
||||
|
||||
if ($from->gt($to)) {
|
||||
throw new \InvalidArgumentException('开始日期不能晚于结束日期。');
|
||||
}
|
||||
|
||||
return [$from, $to];
|
||||
}
|
||||
}
|
||||
@ -12,6 +12,7 @@ use App\Business\PlantingOrderLabelLookup;
|
||||
use Modules\EcommerceFinance\Services\AccountLedgerRemarkMap;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||
use Modules\EcommerceFinance\Services\LedgerRemarkFilter;
|
||||
use Modules\EcommerceFinance\Services\ProductCostAutoRefresh;
|
||||
use Modules\EcommerceFinance\Services\StoreReportMirrorSynchronizer;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
@ -27,7 +28,8 @@ use Throwable;
|
||||
* 再按「店铺 + 完整线上单号」汇总收入金额与收款笔数
|
||||
* - 订单侧:销售全量按「店铺 + 线上订单号」先聚合求和(一单多品/多子订单在此合并),金额取 goods_count > 0 的有效行
|
||||
* - 单号匹配:优先完整线上单号精确匹配;仅当核心号唯一时允许兼容回退,多个完整单号共用核心号时禁止合并
|
||||
* - 店铺:账单用「线上真实店铺」优先,订单侧用销售全量店铺名,统一把下划线归一为横杠
|
||||
* - 店铺:业绩明细按账单「原始店铺」归集并匹配主体;「线上单号对应实际店铺」
|
||||
* 只用于关联订单侧店铺,统一把下划线归一为横杠
|
||||
* - 同一店铺同一订单号多笔收款 → 标注「同单多笔收款」,商品金额只挂一次
|
||||
*/
|
||||
class SyncStoreReceiptOrderMatches extends Command
|
||||
@ -225,6 +227,13 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
if ($result === self::SUCCESS && ! (bool) $this->option('planting-only')) {
|
||||
$this->refreshStoreReportPaidSales();
|
||||
}
|
||||
if (
|
||||
$result === self::SUCCESS
|
||||
&& ! (bool) $this->option('dry-run')
|
||||
&& (int) $this->option('limit') === 0
|
||||
) {
|
||||
$this->refreshProductCosts();
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
@ -822,7 +831,7 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
[$productStatus, $productAmount, $productRemark] = $this->matchOrderSide(
|
||||
(string) $group['online_order_no'],
|
||||
$core,
|
||||
(string) $group['shop_key'],
|
||||
(string) ($group['match_shop_key'] ?? $group['shop_key']),
|
||||
$orderAmount,
|
||||
$orderSeen,
|
||||
$coreSeen,
|
||||
@ -833,7 +842,7 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
[$paidStatus, $paidAmount, $paidRemark] = $this->matchOrderSide(
|
||||
(string) $group['online_order_no'],
|
||||
$core,
|
||||
(string) $group['shop_key'],
|
||||
(string) ($group['match_shop_key'] ?? $group['shop_key']),
|
||||
$orderPaidNet,
|
||||
$orderSeen,
|
||||
$coreSeen,
|
||||
@ -872,7 +881,7 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
[$altStatus, $altAmount] = $this->matchOrderSide(
|
||||
(string) $group['online_order_no'],
|
||||
$core,
|
||||
(string) $group['shop_key'],
|
||||
(string) ($group['match_shop_key'] ?? $group['shop_key']),
|
||||
$orderPaidAlt,
|
||||
$orderSeen,
|
||||
$coreSeen,
|
||||
@ -890,7 +899,7 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
[$payStatus, $payValue] = $this->matchOrderSide(
|
||||
(string) $group['online_order_no'],
|
||||
$core,
|
||||
(string) $group['shop_key'],
|
||||
(string) ($group['match_shop_key'] ?? $group['shop_key']),
|
||||
$orderPaidPay,
|
||||
$orderSeen,
|
||||
$coreSeen,
|
||||
@ -1075,6 +1084,37 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
: sprintf(' 店铺维度报表销量汇总:业绩明细无变化,沿用 %d 行。', $result['stored_rows']));
|
||||
}
|
||||
|
||||
/** 业绩明细写入后,按同一账期和平台自动重算商品成本。 */
|
||||
private function refreshProductCosts(): void
|
||||
{
|
||||
try {
|
||||
$result = app(ProductCostAutoRefresh::class)->refresh(
|
||||
trim((string) $this->argument('month')),
|
||||
(bool) $this->option('planting-only')
|
||||
? ''
|
||||
: trim((string) $this->option('platform')),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->warn('商品成本自动更新失败:' . $exception->getMessage());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($result['status'] === 'skipped') {
|
||||
return;
|
||||
}
|
||||
if ($result['status'] !== 'succeeded') {
|
||||
$this->warn('商品成本自动更新失败,请查看日志或稍后手动重跑。');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->line(sprintf(
|
||||
' 商品成本自动更新:已完成 %d 个平台。',
|
||||
count($result['platforms']),
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
/** 只回填「种菜金额 / 标签」:按种菜明细表与聚水潭种菜标签的并集判断。 */
|
||||
private function backfillPlantingAmounts(string $reportMonth): int
|
||||
@ -1365,7 +1405,7 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
$promoOnlyGroups = [];
|
||||
foreach ($bills as $bill) {
|
||||
$billCount++;
|
||||
$storeName = (string) ($bill->store_name ?? '');
|
||||
$storeName = trim((string) ($bill->store_name ?? ''));
|
||||
$billItem = (string) ($bill->bill_item ?? '');
|
||||
// 收入 / 优惠 / 冲减 / 退款统一按科目映射表的当前财务备注判桶;
|
||||
// 只有当前科目映射表没有规则时,remark() 才回落到旧总账备注表。
|
||||
@ -1399,16 +1439,22 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
$rawNo = trim((string) ($bill->{$orderColumn} ?? ''));
|
||||
$core = self::cleanOrderNo($rawNo);
|
||||
$identity = self::orderIdentity($rawNo);
|
||||
$realStore = $realStoreColumn !== '' ? (string) ($bill->{$realStoreColumn} ?? '') : '';
|
||||
$shopKey = self::normalizeShop($realStore !== '' ? $realStore : (string) $bill->store_name);
|
||||
$realStore = $realStoreColumn !== ''
|
||||
? trim((string) ($bill->{$realStoreColumn} ?? ''))
|
||||
: '';
|
||||
// 主体变更后,同一实际店铺可能对应不同原始店铺和主体。
|
||||
// 业绩行必须保留原始店铺作为统计与主体归属维度;实际店铺仅供订单匹配。
|
||||
$displayStore = $storeName !== '' ? $storeName : $realStore;
|
||||
$shopKey = self::normalizeShop($displayStore);
|
||||
$matchShopKey = self::normalizeShop($realStore !== '' ? $realStore : $displayStore);
|
||||
$key = $shopKey . '|' . $identity;
|
||||
|
||||
if (! isset($groups[$key])) {
|
||||
$groups[$key] = [
|
||||
'platform' => (string) $source['label'],
|
||||
// 展示名优先用「线上真实店铺」(与匹配键同源):账户名(如「支付宝-XX公司」)只是收款壳。
|
||||
'store_name' => $realStore !== '' ? $realStore : (string) ($bill->store_name ?? ''),
|
||||
'store_name' => $displayStore,
|
||||
'shop_key' => $shopKey,
|
||||
'match_shop_key' => $matchShopKey,
|
||||
'online_order_no' => $rawNo,
|
||||
'order_core_no' => $core,
|
||||
'order_identity' => $identity,
|
||||
@ -1438,7 +1484,8 @@ class SyncStoreReceiptOrderMatches extends Command
|
||||
if (! isset($promoOnlyGroups[$promoKey])) {
|
||||
$promoOnlyGroups[$promoKey] = [
|
||||
'shop_key' => $shopKey,
|
||||
'store_name' => $realStore !== '' ? $realStore : $storeName,
|
||||
'match_shop_key' => $matchShopKey,
|
||||
'store_name' => $displayStore,
|
||||
'online_order_no' => $rawNo,
|
||||
'order_core_no' => $core,
|
||||
'order_identity' => $identity,
|
||||
|
||||
@ -254,6 +254,7 @@ class SyncStoreReceiptProductCost extends Command
|
||||
. " i.name as item_name, i.qty as qty, i.amount as amount, o.status as status, "
|
||||
. " i.shop_i_id as shop_i_id, i.shop_sku_id as shop_sku_id, "
|
||||
. " i.outer_oi_id as outer_oi_id, "
|
||||
. " i.raw_so_id as raw_so_id, o.is_merge as is_merge, "
|
||||
. " i.properties_value as properties_value, i.src_combine_sku_id as src_combine_sku_id
|
||||
FROM tmp_cost_order_nos t
|
||||
STRAIGHT_JOIN {$source['orders']} o ON o.so_id = t.no
|
||||
@ -273,6 +274,9 @@ class SyncStoreReceiptProductCost extends Command
|
||||
if ($core === '' || ! isset($billByCore[$core])) {
|
||||
continue;
|
||||
}
|
||||
if (! $this->mergeOrderItemBelongsToCore($row, $core)) {
|
||||
continue;
|
||||
}
|
||||
$sku = trim((string) $row->sku_id);
|
||||
if ($sku === '') {
|
||||
continue;
|
||||
@ -3293,9 +3297,18 @@ class SyncStoreReceiptProductCost extends Command
|
||||
return [];
|
||||
}
|
||||
|
||||
// 9) 只保留叶子行:o_id 没有被同组其他行的 link_o_id 引用的,才是实际发货行。
|
||||
// 9) 只保留叶子行:o_id 没有被同组「未取消、非 Merged」行的 link_o_id 引用的,才是实际发货行。
|
||||
// 全部引用母单的子单都已取消时,不能把已发货的 Sent 母单当成汇总层删除;
|
||||
// 合单与原始单可能互相 link,Merged 原始单不能反向把 Sent 合单判成母单。
|
||||
$parentIds = [];
|
||||
foreach ($unique as $row) {
|
||||
if (in_array(
|
||||
strtoupper(trim((string) ($row['status'] ?? ''))),
|
||||
['CANCELLED', 'MERGED'],
|
||||
true,
|
||||
)) {
|
||||
continue;
|
||||
}
|
||||
$parent = trim((string) ($row['parent_o_id'] ?? ''));
|
||||
if ($parent !== '' && $parent !== '0') {
|
||||
$parentIds[$parent] = true;
|
||||
@ -3362,6 +3375,24 @@ class SyncStoreReceiptProductCost extends Command
|
||||
return array_values($aggregated);
|
||||
}
|
||||
|
||||
/**
|
||||
* 合单可能包含多个线上订单的商品。当前账单订单只能吸收 raw_so_id
|
||||
* 或 outer_oi_id 指向自己的商品,避免把合单中的其他订单重复计价。
|
||||
*/
|
||||
private function mergeOrderItemBelongsToCore(object $row, string $core): bool
|
||||
{
|
||||
if (trim((string) ($row->is_merge ?? '0')) !== '1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$sourceOrder = self::cleanOrderNo((string) ($row->raw_so_id ?? ''));
|
||||
if ($sourceOrder === '') {
|
||||
$sourceOrder = self::cleanOrderNo((string) ($row->outer_oi_id ?? ''));
|
||||
}
|
||||
|
||||
return $sourceOrder === '' || $sourceOrder === $core;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组合装条码拆组件:聚水潭的组合装 sku 形如
|
||||
* ZH-<条码>-<数量>[-<条码>-<数量>...]
|
||||
|
||||
29
app/Console/Commands/SyncUnshippedWaybills.php
Normal file
29
app/Console/Commands/SyncUnshippedWaybills.php
Normal file
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Support\UnshippedWaybills;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
final class SyncUnshippedWaybills extends Command
|
||||
{
|
||||
protected $signature = 'courier:sync-unshipped-waybills';
|
||||
protected $description = '从共享镜像和已导入订单日志重算未发出明细';
|
||||
|
||||
public function handle(UnshippedWaybills $waybills): int
|
||||
{
|
||||
$failed = false;
|
||||
foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) {
|
||||
if (!$waybills->sync($source)) {
|
||||
$warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning');
|
||||
$this->warn($label.':'.$warning);
|
||||
$failed = true;
|
||||
} else {
|
||||
$state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first();
|
||||
$this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。');
|
||||
}
|
||||
}
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -43,24 +43,21 @@ class Kernel extends ConsoleKernel
|
||||
->withoutOverlapping(60)
|
||||
->runInBackground();
|
||||
|
||||
$schedule->command('business-mirror:sync-product-purchase-prices')
|
||||
->dailyAt('05:00')
|
||||
->withoutOverlapping(60)
|
||||
->runInBackground();
|
||||
|
||||
$schedule->command('business-mirror:sync-tables operations_replica.rpt.jst_Orders')
|
||||
->dailyAt('05:00')
|
||||
->withoutOverlapping(60)
|
||||
->runInBackground();
|
||||
|
||||
// 退款待确认的当前状态按分钟增量刷新,确认完成后页面可及时移除。
|
||||
$schedule->command('business-mirror:sync-tables jiansun.dbo.jst_refund_view')
|
||||
->everyMinute()
|
||||
->withoutOverlapping(5)
|
||||
// 聚水潭推广费用按日期、平台、店铺自动汇总到共享镜像;最近 7 天覆盖迟到修订。
|
||||
$schedule->command('business-mirror:sync-promotion-expenses --days=7 --quiet')
|
||||
->dailyAt('03:10')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(90)
|
||||
->appendOutputTo(storage_path('logs/promotion-expense-sync.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 退款待确认四张镜像每天 06:00 专属刷新,确保 10:00 前完成;
|
||||
// 当前退款状态单独按分钟刷新,失败状态由财务驾驶舱展示。
|
||||
// 同步失败状态由财务驾驶舱展示。
|
||||
$schedule->command('business-mirror:sync-tables --daily-only --max-batches=0')
|
||||
->dailyAt('06:00')
|
||||
->timezone('Asia/Shanghai')
|
||||
@ -75,9 +72,6 @@ class Kernel extends ConsoleKernel
|
||||
->withoutOverlapping(120)
|
||||
->runInBackground();
|
||||
|
||||
// 供应商主档由 /etc/cron.d/caiwu-jiansun-snapshots 在 08:15 使用
|
||||
// 全局上游同步锁执行,不能在这里重复调度,避免两个完整同步互相覆盖。
|
||||
|
||||
// 店铺违规信息预警:每天同步副本库抓取结果到统一表(本地补充字段不覆盖)。
|
||||
$schedule->command('store-violations:sync')
|
||||
->dailyAt('05:30')
|
||||
@ -111,17 +105,34 @@ class Kernel extends ConsoleKernel
|
||||
->appendOutputTo(storage_path('logs/inventory-warehouse-mapping-alert.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 四平台账单:每日检查最近 7 天,周日扩展检查最近 62 天。
|
||||
// 命令只读,若输出 JSON 中的 missing/suspicious 非空,账单自动化应回头比较上游当前控制数。
|
||||
$schedule->command('bill-sync:audit-window --days=7 --json')
|
||||
->dailyAt('10:30')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(30)
|
||||
->appendOutputTo(storage_path('logs/bill-sync-window-audit.log'))
|
||||
->runInBackground();
|
||||
$schedule->command('bill-sync:audit-window --days=62 --json')
|
||||
->weeklyOn(0, '10:45')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(30)
|
||||
->appendOutputTo(storage_path('logs/bill-sync-window-audit.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 财务台账:从 AI 库 rpt 同步动账明细,按日重算账户流水。
|
||||
// 生产宿主机 cron 仍需配置对应的 finance-ledger:sync-rpt 入口。
|
||||
$schedule->command('finance-ledger:sync-rpt --days=7 --merge')
|
||||
$schedule->command('finance-ledger:sync-rpt --days=7 --merge --sources=store,withdrawal')
|
||||
->dailyAt('02:30')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(120)
|
||||
->runInBackground();
|
||||
|
||||
$schedule->command('business-mirror:sync-third-party-warehouse-storage --max-batches=0')
|
||||
->dailyAt('00:00')
|
||||
->withoutOverlapping(180)
|
||||
// 钉钉审批和供应商应付每小时增量;店铺相关来源每天同步一次。
|
||||
$schedule->command('finance-ledger:sync-rpt --days=2 --merge --sources=dingtalk,payable --quiet')
|
||||
->hourlyAt(5)
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(10)
|
||||
->runInBackground();
|
||||
|
||||
// 钉钉财务日报:高频增量同步,次日 12:00 截止的补交日志也能及时进入统计。
|
||||
@ -140,6 +151,18 @@ class Kernel extends ConsoleKernel
|
||||
->appendOutputTo(storage_path('logs/ding-attendance-sync.log'))
|
||||
->runInBackground();
|
||||
|
||||
// 票聚销方管理的可用发票额度按 15 分钟同步到共享镜像;失败时页面继续使用上一版。
|
||||
$piaojuCookieFile = trim((string) config('piaoju.cookie_file', ''));
|
||||
if (trim((string) config('piaoju.cookie', '')) !== ''
|
||||
|| ($piaojuCookieFile !== '' && is_file($piaojuCookieFile))) {
|
||||
$schedule->command('piaoju:sync-invoice-quotas --quiet')
|
||||
->cron('*/15 * * * *')
|
||||
->timezone('Asia/Shanghai')
|
||||
->withoutOverlapping(15)
|
||||
->appendOutputTo(storage_path('logs/piaoju-invoice-quota-sync.log'))
|
||||
->runInBackground();
|
||||
}
|
||||
|
||||
if ((bool) config('services.esign.polling_enabled', false)) {
|
||||
$schedule->command('esign:poll-signatures --quiet')
|
||||
->cron('*/2 * * * *')
|
||||
|
||||
@ -5,6 +5,7 @@ namespace App\Http\Controllers\Auth;
|
||||
use App\Abstracts\Http\Controller;
|
||||
use App\Http\Requests\Auth\Login as Request;
|
||||
use App\Models\Common\Contact;
|
||||
use App\Services\Auth\DingTalkOAuthClient;
|
||||
use Illuminate\Foundation\Auth\AuthenticatesUsers;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
@ -13,11 +14,6 @@ class Login extends Controller
|
||||
{
|
||||
use AuthenticatesUsers;
|
||||
|
||||
/**
|
||||
* Where to redirect users after login.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $redirectTo = '/';
|
||||
|
||||
/**
|
||||
@ -30,108 +26,79 @@ class Login extends Controller
|
||||
$this->middleware('guest', ['except' => 'destroy']);
|
||||
}
|
||||
|
||||
public function create()
|
||||
public function create(DingTalkOAuthClient $client)
|
||||
{
|
||||
return view('auth.login.create');
|
||||
return view('auth.login.create', [
|
||||
'dingtalkAvailable' => $client->isConfigured(),
|
||||
'passwordLoginEnabled' => (bool) config('auth.password_login_enabled', false),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
// Attempt to login
|
||||
if (! auth()->attempt($request->only('email', 'password'), $request->get('remember', false))) {
|
||||
if (! config('auth.password_login_enabled', false)) {
|
||||
return $this->credentialsDisabled();
|
||||
}
|
||||
|
||||
if (! auth()->attempt($request->only('email', 'password'), false)) {
|
||||
return $this->respondLoginFailed();
|
||||
}
|
||||
|
||||
// Get user object
|
||||
$request->session()->forget(['dingtalk_identity_id', 'dingtalk_roster_checked_at']);
|
||||
$user = user();
|
||||
|
||||
// Check if user is enabled
|
||||
if (! $user->enabled) {
|
||||
$this->logout();
|
||||
|
||||
// Security (CWE-204): avoid distinct error messages that would
|
||||
// allow valid email enumeration. Log the real reason server-side
|
||||
// for administrators/auditing without leaking it to the client.
|
||||
Log::info('Login denied: account disabled', [
|
||||
'email' => $request->email,
|
||||
]);
|
||||
Log::info('Local login denied: account disabled');
|
||||
|
||||
return $this->respondLoginFailed();
|
||||
}
|
||||
|
||||
$company = $user->withoutEvents(function () use ($user) {
|
||||
return $user->companies()->enabled()->first();
|
||||
});
|
||||
|
||||
// Logout if no company assigned
|
||||
$company = $user->withoutEvents(fn () => $user->companies()->enabled()->first());
|
||||
if (! $company) {
|
||||
$this->logout();
|
||||
|
||||
// Security (CWE-204): do not expose "no company" message to the
|
||||
// client; log it server-side instead.
|
||||
Log::info('Login denied: no company assigned', [
|
||||
'email' => $request->email,
|
||||
]);
|
||||
Log::info('Local login denied: no company assigned');
|
||||
|
||||
return $this->respondLoginFailed();
|
||||
}
|
||||
|
||||
// Redirect to portal if is customer
|
||||
if ($user->isCustomer()) {
|
||||
$path = session('url.intended', '');
|
||||
$portalHome = $user->contact instanceof Contact
|
||||
&& $user->contact->type === Contact::VENDOR_TYPE
|
||||
? route('portal.supplier-reconciliation.index', ['company_id' => $company->id])
|
||||
: route('portal.dashboard', ['company_id' => $company->id]);
|
||||
|
||||
// Path must start with company id and 'portal' prefix
|
||||
if (!Str::startsWith($path, $company->id . '/portal')) {
|
||||
$path = session('url.intended', '');
|
||||
if (! Str::startsWith($path, $company->id.'/portal')) {
|
||||
$path = $portalHome;
|
||||
}
|
||||
|
||||
if (! $request->expectsJson()) {
|
||||
return redirect()->to($path);
|
||||
}
|
||||
return $request->expectsJson()
|
||||
? response()->json([
|
||||
'status' => null,
|
||||
'success' => true,
|
||||
'error' => false,
|
||||
'message' => trans('auth.login_redirect'),
|
||||
'data' => null,
|
||||
'redirect' => url($path),
|
||||
])
|
||||
: redirect()->to($path);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
$url = route($user->landing_page, ['company_id' => $company->id]);
|
||||
$request->session()->forget('url.intended');
|
||||
|
||||
return $request->expectsJson()
|
||||
? response()->json([
|
||||
'status' => null,
|
||||
'success' => true,
|
||||
'error' => false,
|
||||
'message' => trans('auth.login_redirect'),
|
||||
'data' => null,
|
||||
'redirect' => url($path),
|
||||
]);
|
||||
}
|
||||
|
||||
// Redirect to landing page if is user
|
||||
$url = route($user->landing_page, ['company_id' => $company->id]);
|
||||
|
||||
// 登录后固定回到首页(财务驾驶舱),不再回跳上次打开/被拦截的业务页面。
|
||||
$request->session()->forget('url.intended');
|
||||
|
||||
if (! $request->expectsJson()) {
|
||||
return redirect()->to($url);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'status' => null,
|
||||
'success' => true,
|
||||
'error' => false,
|
||||
'message' => trans('auth.login_redirect'),
|
||||
'data' => null,
|
||||
'redirect' => url($url),
|
||||
]);
|
||||
'redirect' => url($url),
|
||||
])
|
||||
: redirect()->to($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the generic failed-login JSON response.
|
||||
*
|
||||
* Security (CWE-204): every rejected login returns the same message and
|
||||
* response shape so an unauthenticated attacker cannot distinguish
|
||||
* "email does not exist" from "disabled" or "no company" and enumerate
|
||||
* valid registered email addresses.
|
||||
*/
|
||||
protected function respondLoginFailed()
|
||||
{
|
||||
$request = app('Illuminate\Http\Request');
|
||||
@ -152,6 +119,16 @@ class Login extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Credential-based entry points are intentionally kept as redirects so
|
||||
* old bookmarks and invitation emails reach the DingTalk-only notice.
|
||||
*/
|
||||
public function credentialsDisabled()
|
||||
{
|
||||
return redirect()->route('login')
|
||||
->with('dingtalk_error', trans('auth.dingtalk.credentials_disabled'));
|
||||
}
|
||||
|
||||
public function destroy()
|
||||
{
|
||||
$this->logout();
|
||||
|
||||
@ -36,7 +36,9 @@ class AccessoryReshipDeductions extends Controller
|
||||
fputcsv($file, ['交易单号','补发快递单号','补发快递','补发时间','原始条形码','处理后条形码','补发运费','匹配状态','首发快递公司(候选)','首发快递单号(候选)','首发所属月份(候选)','扣款比例(%)','扣款金额','说明']);
|
||||
foreach ($data->rows($filters) as $row) {
|
||||
if (!AccessoryReshipPageData::inCategory($row, $filters['match_status'])) continue;
|
||||
$values = [$row['trade_no'], $row['express_no'], ($row['express_name1'] ?: ($row['express_name2'] ?? '')), $row['ship_time'], $row['barcode'], $row['normalized_barcode'], $row['freight'], $row['deduction_state'] === 'ready' ? '可扣款' : ($row['status'] === 'matched' ? '已匹配待核对' : '未匹配不扣款'), implode(' / ', array_column($row['matches'], 'courier')), implode(' / ', array_column($row['matches'], 'express_no')), implode(' / ', array_column($row['matches'], 'month')), $row['deduction_rate_basis_points'] === null ? '' : number_format($row['deduction_rate_basis_points'] / 100, 2, '.', '') . '%', $row['deduction_cents'] === null ? '' : number_format($row['deduction_cents'] / 100, 2, '.', ''), $row['deduction_note']];
|
||||
$status = $row['deduction_state'] === 'excluded_courier' ? '不扣款'
|
||||
: ($row['deduction_state'] === 'ready' ? '可扣款' : ($row['status'] === 'matched' ? '已匹配待核对' : '未匹配不扣款'));
|
||||
$values = [$row['trade_no'], $row['express_no'], ($row['express_name1'] ?: ($row['express_name2'] ?? '')), $row['ship_time'], $row['barcode'], $row['normalized_barcode'], $row['freight'], $status, implode(' / ', array_column($row['matches'], 'courier')), implode(' / ', array_column($row['matches'], 'express_no')), implode(' / ', array_column($row['matches'], 'month')), $row['deduction_rate_basis_points'] === null ? '' : number_format($row['deduction_rate_basis_points'] / 100, 2, '.', '') . '%', $row['deduction_cents'] === null ? '' : number_format($row['deduction_cents'] / 100, 2, '.', ''), $row['deduction_note']];
|
||||
fputcsv($file, array_map(static function ($value) {
|
||||
$value = (string) $value;
|
||||
return preg_match('/^[=+\-@\t\r\n]/u', $value) ? "'" . $value : $value;
|
||||
|
||||
84
app/Http/Controllers/Business/ContractExport.php
Normal file
84
app/Http/Controllers/Business/ContractExport.php
Normal file
@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Business\CourierContractPageData;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use ZipStream\CompressionMethod;
|
||||
use ZipStream\ZipStream;
|
||||
|
||||
final class ContractExport
|
||||
{
|
||||
public function supplier(CourierContractPageData $contracts): StreamedResponse
|
||||
{
|
||||
return $this->download($contracts, 'supplier', '供应商');
|
||||
}
|
||||
|
||||
public function courier(CourierContractPageData $contracts): StreamedResponse
|
||||
{
|
||||
return $this->download($contracts, 'courier', '快递');
|
||||
}
|
||||
|
||||
private function download(CourierContractPageData $contracts, string $partnerType, string $label): StreamedResponse
|
||||
{
|
||||
$manifest = tmpfile();
|
||||
abort_unless($manifest, 500, '无法创建合同清单。');
|
||||
|
||||
return response()->streamDownload(static function () use ($contracts, $manifest, $partnerType, $label): void {
|
||||
$zip = new ZipStream(defaultCompressionMethod: CompressionMethod::STORE, sendHttpHeaders: false);
|
||||
$disk = Storage::disk('uploads');
|
||||
try {
|
||||
fwrite($manifest, "\xEF\xBB\xBF");
|
||||
$columns = [$label, '期限状态', '合同编号', '开始日期', '结束日期', '距到期天数',
|
||||
'甲方签署主体', '乙方签署主体', '签署单号', '签署原件'];
|
||||
if ($partnerType === 'courier') {
|
||||
$columns = [...$columns, '乙方法定代表人', '创建人', '创建时间', '归档时间'];
|
||||
}
|
||||
fputcsv($manifest, $columns, ',', '"', '');
|
||||
foreach ($contracts->exportRows($partnerType) as $row) {
|
||||
$path = $row['signed_path'];
|
||||
$attachment = '归档附件缺失';
|
||||
if (filled($path) && $disk->exists($path)) {
|
||||
$pdf = $disk->readStream($path);
|
||||
if (is_resource($pdf)) {
|
||||
$attachment = '签署原件/合同-' . $row['id'] . '.pdf';
|
||||
try {
|
||||
$zip->addFileFromStream($attachment, $pdf);
|
||||
} finally {
|
||||
fclose($pdf);
|
||||
}
|
||||
} else {
|
||||
$attachment = '归档附件读取失败';
|
||||
}
|
||||
}
|
||||
|
||||
$values = [
|
||||
$row['courier_name'], CourierContractPageData::STATUSES[$row['status']], $row['number'],
|
||||
$row['start_date'], $row['end_date'], $row['days'], $row['party_a'], $row['party_b'], $row['business_no'], $attachment,
|
||||
];
|
||||
if ($partnerType === 'courier') {
|
||||
$values = [...$values, $row['legal_representative'], $row['creator'],
|
||||
$row['created_at']?->format('Y-m-d H:i'), $row['archived_at']?->format('Y-m-d H:i')];
|
||||
}
|
||||
$values = array_map(static function ($value): string|int {
|
||||
if (is_int($value)) {
|
||||
return $value;
|
||||
}
|
||||
$value = (string) $value;
|
||||
return preg_match('/^[\s\x00-\x1f]*[=+@-]|^[\t\r\n]/u', $value) ? "'" . $value : $value;
|
||||
}, $values);
|
||||
fputcsv($manifest, $values, ',', '"', '');
|
||||
}
|
||||
|
||||
rewind($manifest);
|
||||
$zip->addFileFromStream($label . '合同清单.csv', $manifest);
|
||||
$zip->finish();
|
||||
} finally {
|
||||
fclose($manifest);
|
||||
}
|
||||
}, $label . '合作合同-' . now()->format('Ymd-His') . '.zip', [
|
||||
'Content-Type' => 'application/zip', 'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -27,8 +27,6 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class CourierAgreementSignatures extends Controller
|
||||
{
|
||||
private const COOPERATION_SECONDARY_ESIGN_ACCOUNT = '18052733960';
|
||||
|
||||
public function __construct(
|
||||
private readonly CourierAgreementSignatureService $service,
|
||||
private readonly CourierQuoteSignatureService $quoteSignatureService,
|
||||
@ -66,22 +64,22 @@ class CourierAgreementSignatures extends Controller
|
||||
abort_unless(Schema::hasTable('business_courier_agreement_signatures'), 503, '协议签署数据表尚未完成迁移,请先执行数据库迁移。');
|
||||
}
|
||||
|
||||
if ($request->input('document_type') === 'cooperation-contract' && $request->input('partner_type') === 'courier') {
|
||||
// 合作合同统一由我方固定 E 签宝账号完成第二签署方签署。
|
||||
$request->merge([
|
||||
'secondary_esign_account' => self::COOPERATION_SECONDARY_ESIGN_ACCOUNT,
|
||||
]);
|
||||
}
|
||||
|
||||
if (in_array($requestedType, ['account-proof', 'account-change', 'entity-change', 'cooperation-contract', 'authorization', 'shared-contract'], true)
|
||||
if (in_array($requestedType, ['account-proof', 'account-change', 'entity-change', 'cooperation-contract', 'authorization', 'shared-contract', 'quote-confirmation'], true)
|
||||
&& ! $request->filled('counterparty_signer_type')) {
|
||||
// Existing integrations omit this field and historically meant an
|
||||
// enterprise signer, so keep that behavior as the compatibility default.
|
||||
$request->merge(['counterparty_signer_type' => 'organization']);
|
||||
}
|
||||
|
||||
if ($requestedType === 'cooperation-contract') {
|
||||
$request->merge([
|
||||
'cooperation_party_a_phone' => CourierAgreementSignature::COOPERATION_PARTY_A_PHONE,
|
||||
'cooperation_party_b_phone' => $request->input('esign_account'),
|
||||
]);
|
||||
}
|
||||
|
||||
$data = $request->validate($this->rules(), [
|
||||
'secondary_operator_name.required_if' => '请填写我方 E 签宝账号绑定的实名认证姓名。',
|
||||
'secondary_esign_account.required_if' => '请填写另一签署方的 E 签宝账号。',
|
||||
]);
|
||||
$type = $data['document_type'];
|
||||
if ($type === 'authorization' && count($data['authorization_items'] ?? []) === 0) {
|
||||
@ -89,11 +87,6 @@ class CourierAgreementSignatures extends Controller
|
||||
}
|
||||
if ($type === 'shared-contract') {
|
||||
$data['contract_partner_name'] = trim((string) $data['contract_partner_name']);
|
||||
if ($data['counterparty_signer_type'] === 'person') {
|
||||
$data['operator_name'] = $data['contract_partner_name'];
|
||||
} elseif (blank($data['operator_name'] ?? null)) {
|
||||
throw ValidationException::withMessages(['operator_name' => '请填写物流商归属企业经办人的 E 签宝实名认证姓名。']);
|
||||
}
|
||||
$sharedCouriers = collect($data['shared_courier_names'] ?? [])
|
||||
->map(static fn ($name): string => trim((string) $name))
|
||||
->filter()
|
||||
@ -111,15 +104,23 @@ class CourierAgreementSignatures extends Controller
|
||||
$data['shared_courier_name'] = $sharedCouriers[0];
|
||||
$data['shared_note'] = trim((string) ($data['shared_note'] ?? '')) ?: null;
|
||||
}
|
||||
if (in_array($type, ['account-proof', 'account-change'], true)) {
|
||||
if (in_array($type, ['account-proof', 'account-change', 'quote-confirmation'], true)) {
|
||||
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
|
||||
$data['operator_name'] = trim((string) ($data['operator_name'] ?? '')) ?: null;
|
||||
|
||||
if ($data['counterparty_signer_type'] === 'organization' && blank($data['operator_name'])) {
|
||||
$usesCourierAccountLookup = $type === 'account-proof' && $data['partner_type'] === 'courier';
|
||||
|
||||
if ($type !== 'quote-confirmation' && ! $usesCourierAccountLookup
|
||||
&& $data['counterparty_signer_type'] === 'organization' && blank($data['operator_name'])) {
|
||||
throw ValidationException::withMessages(['operator_name' => '企业签署主体必须填写 E 签宝实名认证姓名。']);
|
||||
}
|
||||
|
||||
if ($data['counterparty_signer_type'] === 'person') {
|
||||
if ($type === 'quote-confirmation' && $data['counterparty_signer_type'] === 'organization'
|
||||
&& in_array($data['operator_name'], [trim($data['courier_name']), trim($data['counterparty_organization_name'])], true)) {
|
||||
throw ValidationException::withMessages(['operator_name' => '请填写签署账号绑定的个人实名姓名,不能填写快递名称或企业名称。']);
|
||||
}
|
||||
|
||||
if ($data['counterparty_signer_type'] === 'person' && ! $usesCourierAccountLookup) {
|
||||
// A personal signer uses the same real name for the signer and
|
||||
// the E-sign identity; the UI should not require it twice.
|
||||
$data['operator_name'] = trim((string) $data['counterparty_organization_name']);
|
||||
@ -132,42 +133,9 @@ class CourierAgreementSignatures extends Controller
|
||||
);
|
||||
$data['entity_change_old_company_deregistered'] = $formerCompanyDeregistered;
|
||||
$data['counterparty_signer_type'] = $formerCompanyDeregistered ? 'person' : 'organization';
|
||||
|
||||
if (blank($data['operator_name'] ?? null)) {
|
||||
throw ValidationException::withMessages(['operator_name' => $formerCompanyDeregistered
|
||||
? '请填写原公司法人的 E 签宝实名认证姓名。'
|
||||
: '请填写变更前主体签署人的 E 签宝实名认证姓名。']);
|
||||
}
|
||||
if (blank($data['secondary_esign_account'] ?? null)) {
|
||||
throw ValidationException::withMessages(['secondary_esign_account' => '请填写变更后主体的 E 签宝账号。']);
|
||||
}
|
||||
if (blank($data['secondary_operator_name'] ?? null)) {
|
||||
throw ValidationException::withMessages(['secondary_operator_name' => '请填写变更后主体签署人的 E 签宝实名认证姓名。']);
|
||||
}
|
||||
}
|
||||
if ($type === 'cooperation-contract') {
|
||||
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
|
||||
if ($data['counterparty_signer_type'] === 'person') {
|
||||
$data['operator_name'] = trim((string) $data['cooperation_party_b_name']);
|
||||
} elseif (blank($data['operator_name'] ?? null)) {
|
||||
$party = $data['partner_type'] === 'supplier' ? '供应商' : '快递方';
|
||||
throw ValidationException::withMessages(['operator_name' => "请填写{$party}企业经办人的 E 签宝实名认证姓名。"]);
|
||||
}
|
||||
if (blank($data['secondary_operator_name'] ?? null)) {
|
||||
throw ValidationException::withMessages(['secondary_operator_name' => '请填写我方 E 签宝账号绑定的实名认证姓名。']);
|
||||
}
|
||||
$companyNames = [trim($data['cooperation_party_a_name'])];
|
||||
if ($data['counterparty_signer_type'] === 'organization') {
|
||||
$companyNames[] = trim($data['cooperation_party_b_name']);
|
||||
}
|
||||
foreach (['operator_name' => $data['partner_type'] === 'supplier' ? '供应商' : '快递方', 'secondary_operator_name' => '我方'] as $field => $party) {
|
||||
$data[$field] = trim($data[$field]);
|
||||
if (in_array($data[$field], $companyNames, true)) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => "{$party}实名认证姓名应填写账号绑定的个人姓名,不能填写甲乙方公司名称。",
|
||||
]);
|
||||
}
|
||||
}
|
||||
if ($type === 'cooperation-contract' && preg_match('/^1\d{10}$/', $data['esign_account']) !== 1) {
|
||||
throw ValidationException::withMessages(['esign_account' => '合作合同的乙方 E 签宝账号必须填写 11 位手机号。']);
|
||||
}
|
||||
if ($type === 'authorization') {
|
||||
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
|
||||
@ -337,6 +305,26 @@ class CourierAgreementSignatures extends Controller
|
||||
{
|
||||
$this->ensureCanManage();
|
||||
abort_unless($agreementSignature->status === CourierAgreementSignature::STATUS_COMPLETED && $agreementSignature->remote_status === '2', 422, '只有签署完成的协议可以人工归档。');
|
||||
$signature = $this->service->archive($agreementSignature, null, user_id(), $this->archiveReason($request));
|
||||
|
||||
return redirect()
|
||||
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
|
||||
->with('success', "{$signature->documentLabel()}已人工确认并归档。");
|
||||
}
|
||||
|
||||
public function archiveQuote(Request $request, CourierQuoteSignature $quoteSignature): RedirectResponse
|
||||
{
|
||||
$this->ensureCanManage();
|
||||
abort_unless($quoteSignature->company_id === (int) company_id(), 404);
|
||||
$signature = $this->quoteSignatureService->confirmArchive($quoteSignature, user_id(), $this->archiveReason($request));
|
||||
|
||||
return redirect()
|
||||
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
|
||||
->with('success', "报价确认单 {$signature->version?->version_code} 已人工确认并归档。");
|
||||
}
|
||||
|
||||
private function archiveReason(Request $request): string
|
||||
{
|
||||
$data = $request->validate([
|
||||
'archive_reason_code' => ['required', 'in:completed,confirmed,backfill,other'],
|
||||
'archive_note' => ['nullable', 'string', 'max:200'],
|
||||
@ -351,12 +339,7 @@ class CourierAgreementSignatures extends Controller
|
||||
if ($data['archive_reason_code'] === 'other' && $note === '') {
|
||||
throw ValidationException::withMessages(['archive_note' => '选择“其他”时请填写归档说明。']);
|
||||
}
|
||||
$reason = $note === '' ? $reasonLabel : $reasonLabel . ':' . $note;
|
||||
$signature = $this->service->archive($agreementSignature, null, user_id(), $reason);
|
||||
|
||||
return redirect()
|
||||
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
|
||||
->with('success', "{$signature->documentLabel()}已人工确认并归档。");
|
||||
return $note === '' ? $reasonLabel : $reasonLabel . ':' . $note;
|
||||
}
|
||||
|
||||
public function destroy(Request $request, CourierAgreementSignature $agreementSignature): JsonResponse|RedirectResponse
|
||||
@ -371,7 +354,7 @@ class CourierAgreementSignatures extends Controller
|
||||
|
||||
private function deleteTask(Request $request, CourierAgreementSignature|CourierQuoteSignature $task): JsonResponse|RedirectResponse
|
||||
{
|
||||
$this->ensureCanAdminister();
|
||||
abort_unless(AgreementSigningPermissions::canDelete(), 403, '当前账号没有协议签署删除权限。');
|
||||
abort_unless($task->company_id === (int) company_id(), 404);
|
||||
$request->validate(['delete_confirmed' => ['required', 'accepted']]);
|
||||
|
||||
@ -490,14 +473,20 @@ class CourierAgreementSignatures extends Controller
|
||||
'signature_date' => ['required', 'date'],
|
||||
'signing_deadline' => $date,
|
||||
'esign_account' => ['required', 'string', 'max:255'],
|
||||
'secondary_esign_account' => ['required_if:document_type,cooperation-contract,authorization', 'nullable', 'string', 'max:255'],
|
||||
'secondary_operator_name' => ['nullable', 'string', 'min:2', 'max:100'],
|
||||
'operator_name' => ['nullable', 'string', 'min:2', 'max:100'],
|
||||
'counterparty_organization_name' => ['required_if:document_type,account-proof,account-change', 'nullable', 'string', 'min:2', 'max:255'],
|
||||
'counterparty_signer_type' => ['required_if:document_type,account-proof,account-change,entity-change,cooperation-contract,authorization,shared-contract', 'nullable', 'in:organization,person'],
|
||||
'secondary_esign_account' => [Rule::excludeIf(request('document_type') === 'cooperation-contract'), 'required_if:document_type,authorization,entity-change', 'nullable', 'string', 'max:255'],
|
||||
'secondary_operator_name' => ['exclude_if:document_type,entity-change', 'nullable', 'string', 'min:2', 'max:100'],
|
||||
'operator_name' => [
|
||||
Rule::excludeIf(in_array(request('document_type'), ['cooperation-contract', 'entity-change'], true)
|
||||
|| (request('partner_type') === 'courier'
|
||||
&& in_array(request('document_type'), CourierAgreementSignature::COURIER_DOCUMENTS_WITH_ACCOUNT_LOOKUP, true))),
|
||||
'nullable', 'string', 'min:2', 'max:100',
|
||||
],
|
||||
'counterparty_organization_name' => ['required_if:document_type,account-proof,account-change,quote-confirmation', 'nullable', 'string', 'min:2', 'max:255'],
|
||||
'counterparty_signer_type' => ['required_if:document_type,account-proof,account-change,entity-change,cooperation-contract,authorization,shared-contract,quote-confirmation', 'nullable', 'in:organization,person'],
|
||||
'secondary_signer_type' => ['nullable', 'in:organization,person'],
|
||||
'entity_change_old_company_deregistered' => ['nullable', 'boolean'],
|
||||
'archive_mode' => ['required', 'in:auto,manual'],
|
||||
'quote_reissue_reason' => ['exclude_unless:document_type,quote-confirmation', 'nullable', 'string', 'min:2', 'max:200'],
|
||||
'account_proof_effective_date' => ['required_if:document_type,account-proof', 'date'],
|
||||
'account_proof_account_name' => ['required_if:document_type,account-proof', 'string', 'max:255'],
|
||||
'account_proof_bank_name' => ['required_if:document_type,account-proof', 'string', 'max:255'],
|
||||
@ -539,7 +528,11 @@ class CourierAgreementSignatures extends Controller
|
||||
'payment_counterparty' => ['required_if:document_type,authorization', 'string', 'max:255'],
|
||||
'authorization_start_date' => ['required_if:document_type,authorization', 'date'],
|
||||
'authorization_end_date' => ['required_if:document_type,authorization', 'date', 'after_or_equal:authorization_start_date'],
|
||||
] + $supplierFields + CourierAgreementCredentials::rules((string) request('document_type'), request()->boolean('credential_required'));
|
||||
] + $supplierFields + CourierAgreementCredentials::rules(
|
||||
(string) request('document_type'),
|
||||
request()->boolean('credential_required'),
|
||||
(string) request('partner_type', 'courier'),
|
||||
);
|
||||
}
|
||||
|
||||
private function payload(array $data): array
|
||||
@ -548,6 +541,9 @@ class CourierAgreementSignatures extends Controller
|
||||
$payload = array_intersect_key($data, array_flip($allowed));
|
||||
unset($payload['esign_account'], $payload['idempotency_key'], $payload['operator_name'], $payload['credential_images']);
|
||||
$payload['authorization_items'] = array_values(array_map('strval', $data['authorization_items'] ?? []));
|
||||
if (($data['document_type'] ?? '') === 'cooperation-contract') {
|
||||
$payload['cooperation_bilateral_signing'] = true;
|
||||
}
|
||||
if (($data['document_type'] ?? '') === 'cooperation-contract' && ($data['partner_type'] ?? 'courier') === 'courier') {
|
||||
$payload['cooperation_party_b_signing_place'] = trim((string) ($data['cooperation_party_b_signing_place'] ?? '')) ?: '常州市';
|
||||
$payload['cooperation_contract_number'] = trim((string) ($data['cooperation_contract_number'] ?? ''));
|
||||
@ -555,11 +551,10 @@ class CourierAgreementSignatures extends Controller
|
||||
? null : trim((string) ($data['cooperation_party_b_legal_representative'] ?? ''));
|
||||
}
|
||||
if (($data['document_type'] ?? null) === 'entity-change') {
|
||||
$payload['former_legal_representative'] = trim((string) ($data['operator_name'] ?? ''));
|
||||
$payload['entity_proof_date'] = $data['signature_date'] ?? null;
|
||||
}
|
||||
if (($data['partner_type'] ?? 'courier') === 'supplier' && ($data['document_type'] ?? '') === 'cooperation-contract') {
|
||||
$payload['supplier_contract_signer_name'] = $data['operator_name'];
|
||||
$payload['supplier_contract_signer_name'] = $data['counterparty_signer_type'] === 'person' ? $data['cooperation_party_b_name'] : null;
|
||||
}
|
||||
return $payload;
|
||||
}
|
||||
@ -571,20 +566,30 @@ class CourierAgreementSignatures extends Controller
|
||||
->findOrFail((int) $data['quote_version_id']);
|
||||
$this->ensureQuoteVersionMatchesCourier($version, $data['courier_name']);
|
||||
|
||||
$signature = $this->quoteSignatureService->prepareVersion($version, user_id(), $data['signature_date']);
|
||||
$counterpartyName = trim($data['counterparty_organization_name']);
|
||||
$reissueReason = trim((string) ($data['quote_reissue_reason'] ?? ''));
|
||||
abort_if($reissueReason !== '' && ! AgreementSigningPermissions::canDelete(), 403, '当前账号没有更正重签权限。');
|
||||
$signature = $this->quoteSignatureService->prepareVersion(
|
||||
$version, user_id(), $data['signature_date'], $data['signing_subject'], $counterpartyName,
|
||||
$reissueReason === '' ? null : $reissueReason,
|
||||
);
|
||||
$account = trim((string) $data['esign_account']);
|
||||
$signature = $this->quoteSignatureService->send($signature, [
|
||||
'signing_subject' => $data['signing_subject'],
|
||||
'organization_name' => $version->carrier_name,
|
||||
'operator_name' => trim((string) ($data['operator_name'] ?? '')) ?: $version->carrier_name,
|
||||
'signer_type' => $data['counterparty_signer_type'],
|
||||
'organization_name' => $counterpartyName,
|
||||
'operator_name' => $data['operator_name'],
|
||||
'operator_account' => $account,
|
||||
'notice_type' => filter_var($account, FILTER_VALIDATE_EMAIL) !== false ? '2' : '1',
|
||||
'archive_mode' => $data['archive_mode'],
|
||||
'expires_at' => \Illuminate\Support\Carbon::parse($data['signing_deadline'])->endOfDay(),
|
||||
], user_id());
|
||||
|
||||
$archiveMessage = $signature->requiresManualArchive() ? '回传后由财务确认归档' : '签署完成后自动归档';
|
||||
|
||||
return redirect()
|
||||
->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks'])
|
||||
->with('success', "报价确认单 {$version->version_code} 已推送到 E 签宝,等待快递方签署并自动回传归档。")
|
||||
->with('success', "报价确认单 {$version->version_code} 已推送到 E 签宝,等待快递方签署,{$archiveMessage}。")
|
||||
->with('quote_signature_id', $signature->id);
|
||||
}
|
||||
|
||||
|
||||
477
app/Http/Controllers/Business/CourierBillController.php
Normal file
477
app/Http/Controllers/Business/CourierBillController.php
Normal file
@ -0,0 +1,477 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Support\CourierBills\Category;
|
||||
use App\Support\CourierBills\CourierBillMatcher;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\StatementExporter;
|
||||
use App\Support\CourierBills\StreamingWorkbook;
|
||||
use App\Support\CourierBills\Waybill;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use RuntimeException;
|
||||
|
||||
/** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */
|
||||
final class CourierBillController extends Controller
|
||||
{
|
||||
public const VIEWS = ['overview' => '对账总览', 'statement' => '单家对账单', 'details' => '对账明细', 'upload' => '上传账单',
|
||||
'ledger' => '结算台账', 'groups' => '对账分组'];
|
||||
|
||||
public function __construct(
|
||||
private readonly CourierBillStore $store,
|
||||
private readonly CourierBillMatcher $matcher,
|
||||
) {}
|
||||
|
||||
public function page(Request $request): array
|
||||
{
|
||||
$view = array_key_exists((string) $request->query('cb_view'), self::VIEWS) ? (string) $request->query('cb_view') : 'overview';
|
||||
$data = ['view' => 'business.pages.courier-payables.courier-bills.page', 'cbView' => $view, 'cbViews' => self::VIEWS,
|
||||
'cbSection' => self::section($request), 'cbUnavailable' => false];
|
||||
try {
|
||||
$db = $this->store->db();
|
||||
$months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all();
|
||||
$month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m'));
|
||||
$data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $this->store->groups()];
|
||||
$data += match ($view) {
|
||||
'statement' => $this->statementData($request),
|
||||
'details' => $this->detailsData($request, $month),
|
||||
'upload' => $this->uploadData($month),
|
||||
'ledger' => $this->ledgerData($request),
|
||||
'groups' => $this->groupsData($request),
|
||||
default => $this->overviewData($month),
|
||||
};
|
||||
} catch (QueryException $error) {
|
||||
report($error);
|
||||
$data['cbUnavailable'] = true;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function overviewData(string $month): array
|
||||
{
|
||||
$db = $this->store->db();
|
||||
$statements = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||
->where('s.bill_month', $month)->orderBy('g.owner')->orderBy('g.name')
|
||||
->get(['s.*', 'g.name as group_name', 'g.owner', 'g.summary_carrier']);
|
||||
$sums = $db->table('courier_bill_summary_items')->whereIn('statement_id', $statements->pluck('id'))
|
||||
->groupBy('statement_id')->selectRaw('statement_id, SUM(bill_amount) as bill, SUM(self_amount) as self')
|
||||
->get()->keyBy('statement_id');
|
||||
$pending = $db->table('courier_bill_lines')->whereIn('statement_id', $statements->pluck('id'))
|
||||
->whereNull('resolution')->whereNotIn('category', [Category::MATCH])
|
||||
->groupBy('statement_id')->selectRaw('statement_id, COUNT(*) as n')->pluck('n', 'statement_id');
|
||||
$rows = $statements->map(function ($s) use ($sums, $pending): array {
|
||||
$bill = (float) ($sums[$s->id]->bill ?? 0);
|
||||
$self = (float) ($sums[$s->id]->self ?? 0);
|
||||
|
||||
return ['id' => $s->id, 'group' => $s->group_name, 'owner' => $s->owner, 'carrier' => $s->summary_carrier ?: $s->group_name,
|
||||
'status' => $s->status, 'lines' => (int) $s->line_count, 'bill' => $bill, 'diff' => round($bill - $self, 2),
|
||||
'confirmed' => $self, 'pending' => (int) ($pending[$s->id] ?? 0), 'matched_at' => $s->matched_at];
|
||||
})->all();
|
||||
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
|
||||
|
||||
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbTotals' => [
|
||||
'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')),
|
||||
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
|
||||
]];
|
||||
}
|
||||
|
||||
private function statementData(Request $request): array
|
||||
{
|
||||
$db = $this->store->db();
|
||||
$statement = $db->table('courier_bill_statements')->find((int) $request->query('statement'));
|
||||
if ($statement === null) {
|
||||
return ['cbStatement' => null];
|
||||
}
|
||||
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
||||
$counts = $db->table('courier_bill_lines')->where('statement_id', $statement->id)
|
||||
->groupBy('category', 'category_month')->selectRaw('category, category_month, COUNT(*) as n, SUM(bill_amount) as bill')
|
||||
->get();
|
||||
$tabs = [];
|
||||
foreach ($counts as $row) {
|
||||
$key = in_array($row->category, [Category::PRIOR, Category::LATER], true) ? $row->category . ':' . $row->category_month : (string) $row->category;
|
||||
$tabs[$key] = ['label' => Category::label((string) $row->category, $row->category_month), 'count' => (int) $row->n];
|
||||
}
|
||||
uksort($tabs, fn ($a, $b) => array_search(strtok($a, ':'), array_keys(Category::LABELS), true) <=> array_search(strtok($b, ':'), array_keys(Category::LABELS), true) ?: strcmp($a, $b));
|
||||
$unprovided = $db->table('courier_bill_unprovided')->where('statement_id', $statement->id)->count();
|
||||
if ($unprovided > 0) {
|
||||
$tabs[Category::UNPROVIDED] = ['label' => Category::LABELS[Category::UNPROVIDED], 'count' => $unprovided];
|
||||
}
|
||||
$tab = (string) $request->query('cat', array_key_first($tabs) ?? '');
|
||||
if ($tab === Category::UNPROVIDED) {
|
||||
$lines = $db->table('courier_bill_unprovided')->where('statement_id', $statement->id)->orderBy('id')->paginate(50, ['*'], 'page')->withQueryString();
|
||||
} else {
|
||||
[$category, $categoryMonth] = array_pad(explode(':', $tab, 2), 2, null);
|
||||
$query = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->where('category', $category);
|
||||
if ($categoryMonth !== null) {
|
||||
$query->where('category_month', $categoryMonth);
|
||||
}
|
||||
$lines = $query->orderBy('id')->paginate(50, ['id', 'waybill_no', 'bill_amount', 'bill_weight', 'ship_time', 'express_name',
|
||||
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
|
||||
}
|
||||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
|
||||
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->distinct()->pluck('file_id');
|
||||
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->where('statement_id', $statement->id)->orWhereIn('id', $fileIds))->orderBy('id')->get();
|
||||
$shippingSync = null;
|
||||
try {
|
||||
$shippingSync = app(\App\Support\CourierBills\ShippingLookup::class)->connection()->table('jst_oms_shipping')->max('ship_time');
|
||||
} catch (QueryException) {
|
||||
}
|
||||
|
||||
$related = app(StatementExporter::class)->related((int) $statement->id);
|
||||
$relatedNames = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||
->whereIn('s.id', $related)->pluck('g.name', 's.id');
|
||||
|
||||
return ['cbRelated' => collect($related)->map(fn ($id) => ['id' => $id, 'name' => $relatedNames[$id] ?? ''])->all(),
|
||||
'cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
|
||||
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync];
|
||||
}
|
||||
|
||||
private function detailsData(Request $request, string $month): array
|
||||
{
|
||||
$filters = $request->validate([
|
||||
'group_id' => ['nullable', 'integer'], 'category' => ['nullable', Rule::in(array_keys(Category::LABELS))],
|
||||
'resolution' => ['nullable', Rule::in(['pending', 'all', ...array_keys(Category::RESOLUTIONS)])],
|
||||
'owner' => ['nullable', 'string', 'max:64'], 'min_diff' => ['nullable', 'numeric'], 'waybills' => ['nullable', 'string', 'max:20000'],
|
||||
'all_months' => ['nullable', 'boolean'],
|
||||
]);
|
||||
$query = $this->detailsQuery($filters, $month);
|
||||
|
||||
return ['cbFilters' => $filters, 'cbLines' => $query->orderBy('l.id')->paginate(50, ['l.*', 's.bill_month', 's.status as statement_status', 'g.name as group_name', 'g.owner'])
|
||||
->withQueryString(), 'cbOwners' => collect($this->store->groups())->pluck('owner')->filter()->unique()->values()->all()];
|
||||
}
|
||||
|
||||
private function detailsQuery(array $filters, string $month)
|
||||
{
|
||||
$query = $this->store->db()->table('courier_bill_lines as l')->join('courier_bill_statements as s', 's.id', '=', 'l.statement_id')
|
||||
->join('courier_bill_groups as g', 'g.id', '=', 's.group_id');
|
||||
if (empty($filters['all_months'])) {
|
||||
$query->where('s.bill_month', $month);
|
||||
}
|
||||
if (! empty($filters['group_id'])) {
|
||||
$query->where('s.group_id', (int) $filters['group_id']);
|
||||
}
|
||||
if (! empty($filters['category'])) {
|
||||
$query->where('l.category', $filters['category']);
|
||||
}
|
||||
$resolution = $filters['resolution'] ?? 'pending';
|
||||
if ($resolution === 'pending') {
|
||||
$query->whereNull('l.resolution')->where('l.category', '<>', Category::MATCH);
|
||||
} elseif ($resolution !== 'all') {
|
||||
$query->where('l.resolution', $resolution);
|
||||
}
|
||||
if (! empty($filters['owner'])) {
|
||||
$query->where('g.owner', $filters['owner']);
|
||||
}
|
||||
if (isset($filters['min_diff']) && $filters['min_diff'] !== null && $filters['min_diff'] !== '') {
|
||||
$query->whereRaw('ABS(COALESCE(l.bill_amount,0) - COALESCE(l.self_amount,0)) >= ?', [(float) $filters['min_diff']]);
|
||||
}
|
||||
$numbers = array_values(array_unique(array_filter(array_map(fn ($n) => Waybill::normalize($n),
|
||||
preg_split('/[\r\n,,\s]+/u', (string) ($filters['waybills'] ?? '')) ?: []))));
|
||||
if (count($numbers) > 1000) {
|
||||
throw ValidationException::withMessages(['waybills' => '最多同时查询 1000 个快递单号。']);
|
||||
}
|
||||
if ($numbers !== []) {
|
||||
$query->whereIn('l.waybill_no', $numbers);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function uploadData(string $month): array
|
||||
{
|
||||
return ['cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
|
||||
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
|
||||
}
|
||||
|
||||
private function ledgerData(Request $request): array
|
||||
{
|
||||
$db = $this->store->db();
|
||||
$search = Waybill::normalize((string) $request->query('waybill'));
|
||||
|
||||
return [
|
||||
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->groupBy('g.name', 'l.settle_month')->selectRaw('g.name as group_name, l.settle_month, COUNT(*) as n, SUM(l.amount) as amount, SUM(CASE WHEN l.statement_id IS NULL THEN 1 ELSE 0 END) as imported')
|
||||
->orderByDesc('l.settle_month')->orderBy('g.name')->limit(500)->get(),
|
||||
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||||
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
|
||||
'cbSearch' => $search,
|
||||
];
|
||||
}
|
||||
|
||||
private function groupsData(Request $request): array
|
||||
{
|
||||
$summary = app(\App\Support\CourierBills\PayableSummary::class);
|
||||
$data = ['cbSummaryMonths' => $summary->months(), 'cbUnassigned' => null, 'cbScanMonth' => null];
|
||||
$scan = self::monthParam($request->query('scan'));
|
||||
if ($scan !== null) {
|
||||
$data['cbScanMonth'] = $scan;
|
||||
$data['cbUnassigned'] = $this->store->unassignedExpressNames(app(\App\Support\CourierBills\ShippingLookup::class)->monthExpressNames($scan));
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function groupsFromSummary(Request $request)
|
||||
{
|
||||
$month = $request->validate(['summary_month' => ['required', 'date_format:Y-m']], [], ['summary_month' => '汇总月份'])['summary_month'];
|
||||
$rows = app(\App\Support\CourierBills\PayableSummary::class)->rows($month);
|
||||
if ($rows === []) {
|
||||
throw ValidationException::withMessages(['courier_bills' => $month . ' 还没有快递应付汇总,请先在「快递应付汇总」导入手工快递汇总表。']);
|
||||
}
|
||||
$result = $this->store->groupsFromSummary($rows);
|
||||
|
||||
return $this->back($request, ['cb_view' => 'groups'], '已按 ' . $month . ' 快递应付汇总新建 ' . $result['created'] . ' 个分组(每个承运商一个,快递名称1 = 承运商);'
|
||||
. $result['skipped'] . ' 个跳过(停运且本月无金额,或已有分组)。请再点「检查未归组的快递名称1」,把发货数据里名字不一样的快递名称1 补进对应分组。');
|
||||
}
|
||||
|
||||
public function importGroups(Request $request)
|
||||
{
|
||||
$file = $request->validate(['groups' => ['required', 'file', 'max:10240']], [], ['groups' => '分组文件'])['groups'];
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
throw ValidationException::withMessages(['groups' => '只支持 xlsx、xls、csv。']);
|
||||
}
|
||||
$result = $this->guard(fn () => $this->store->importGroups($file->getRealPath(), $extension));
|
||||
|
||||
return $this->back($request, ['cb_view' => 'groups'], '已导入分组:新增 ' . $result['created'] . ' 个,覆盖 ' . $result['updated'] . ' 个。');
|
||||
}
|
||||
|
||||
public function exportGroups()
|
||||
{
|
||||
$groups = $this->store->groups();
|
||||
|
||||
return response()->streamDownload(function () use ($groups): void {
|
||||
$book = new StreamingWorkbook();
|
||||
$book->row('对账分组', CourierBillStore::GROUP_HEADERS, true);
|
||||
foreach ($groups as $group) {
|
||||
$book->row('对账分组', [$group->name, implode('、', $group->express_names), $group->summary_carrier, $group->bundle, $group->owner,
|
||||
$group->keywords, $group->waybill_header, $group->amount_header, $group->weight_header]);
|
||||
}
|
||||
if ($groups === []) {
|
||||
$book->row('对账分组', ['河北中通-江三', '河北中通-江三、河北中通小件-江三', '河北中通-江三', '河北中通-江三+霸州百世快运-雅柏', '负责人姓名', '河北中通', '', '', '']);
|
||||
}
|
||||
$book->writeTo(fopen('php://output', 'wb'));
|
||||
}, '对账分组.xlsx');
|
||||
}
|
||||
|
||||
public function deleteGroup(Request $request, int $group)
|
||||
{
|
||||
$this->guard(fn () => $this->store->deleteGroup($group));
|
||||
|
||||
return $this->back($request, ['cb_view' => 'groups'], '已删除分组。');
|
||||
}
|
||||
|
||||
public function addExpressName(Request $request, int $group)
|
||||
{
|
||||
$data = $request->validate(['express_name' => ['required', 'string', 'max:128']]);
|
||||
$this->guard(fn () => $this->store->addExpressName($group, $data['express_name']));
|
||||
|
||||
return $this->back($request, [], '已把「' . $data['express_name'] . '」加进分组。');
|
||||
}
|
||||
|
||||
public function upload(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'month' => ['required', 'date_format:Y-m'],
|
||||
'files' => ['required', 'array', 'max:60'], 'files.*' => ['file', 'max:51200'],
|
||||
], [], ['files' => '账单文件', 'files.*' => '账单文件']);
|
||||
foreach ($data['files'] as $file) {
|
||||
if (! in_array(strtolower($file->getClientOriginalExtension()), CourierBillStore::EXTENSIONS, true)) {
|
||||
throw ValidationException::withMessages(['files' => '只支持 xlsx、xls、csv、zip:' . $file->getClientOriginalName()]);
|
||||
}
|
||||
}
|
||||
$ids = $this->guard(fn () => $this->store->upload($data['files'], $data['month'], [], self::user()));
|
||||
$files = $this->store->db()->table('courier_bill_files')->whereIn('id', $ids)->get();
|
||||
$split = $files->filter(fn ($f) => str_contains((string) $f->message, '合并账单已拆分'))->count();
|
||||
|
||||
return $this->back($request, ['cb_view' => 'upload', 'month' => $data['month']],
|
||||
'已上传 ' . count($ids) . ' 个文件:已读入 ' . $files->where('status', 'parsed')->count() . ' 个,待选分组 '
|
||||
. $files->where('status', 'pending_group')->count() . ' 个,失败 ' . $files->where('status', 'failed')->count() . ' 个'
|
||||
. ($split > 0 ? ';其中 ' . $split . ' 个是合并账单,已按快递名称1 拆到各自分组' : '') . '。');
|
||||
}
|
||||
|
||||
public function assign(Request $request, int $file)
|
||||
{
|
||||
$data = $request->validate(['group_id' => ['required', 'integer']]);
|
||||
$this->guard(fn () => $this->store->assign($file, (int) $data['group_id']));
|
||||
|
||||
return $this->back($request, [], '已读入并对账。');
|
||||
}
|
||||
|
||||
public function deleteFile(Request $request, int $file)
|
||||
{
|
||||
$this->guard(fn () => $this->store->deleteFile($file));
|
||||
|
||||
return $this->back($request, [], '已删除文件。');
|
||||
}
|
||||
|
||||
public function rematch(Request $request, int $statement)
|
||||
{
|
||||
$done = $this->guard(fn () => $this->store->rematch($statement));
|
||||
|
||||
return $this->back($request, [], '已按当前规则重新读取账单文件、按当前对账分组重新拆分,并按最新发货数据、未发出明细和结算台账重新匹配'
|
||||
. (count($done) > 1 ? '(同一张账单涉及 ' . count($done) . ' 张对账单,一起更新了)' : '') . '。');
|
||||
}
|
||||
|
||||
public function resolve(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'lines' => ['required', 'array', 'max:2000'], 'lines.*' => ['integer'],
|
||||
'resolution' => ['required', Rule::in(['clear', ...array_keys(Category::RESOLUTIONS)])],
|
||||
], [], ['lines' => '明细']);
|
||||
$resolution = $data['resolution'] === 'clear' ? null : $data['resolution'];
|
||||
$count = 0;
|
||||
$byStatement = $this->store->db()->table('courier_bill_lines')->whereIn('id', $data['lines'])->get(['id', 'statement_id'])->groupBy('statement_id');
|
||||
foreach ($byStatement as $statementId => $lines) {
|
||||
$count += $this->guard(fn () => $this->matcher->resolve((int) $statementId, $lines->pluck('id')->all(), $resolution, self::user()));
|
||||
}
|
||||
|
||||
return $this->back($request, [], '已更新 ' . $count . ' 条明细的处理结果,小汇总已重算。');
|
||||
}
|
||||
|
||||
public function addItem(Request $request, int $statement)
|
||||
{
|
||||
$data = $request->validate(['label' => ['required', 'string', 'max:255'], 'bill' => ['nullable', 'numeric'], 'self' => ['nullable', 'numeric']],
|
||||
[], ['label' => '项目名称', 'bill' => '快递提供金额', 'self' => '自算金额']);
|
||||
$this->guard(fn () => $this->store->addSummaryItem($statement, $data['label'], isset($data['bill']) ? (float) $data['bill'] : null,
|
||||
isset($data['self']) ? (float) $data['self'] : null));
|
||||
|
||||
return $this->back($request, [], '已加入小汇总。');
|
||||
}
|
||||
|
||||
public function deleteItem(Request $request, int $statement, int $item)
|
||||
{
|
||||
$this->guard(fn () => $this->store->deleteSummaryItem($statement, $item));
|
||||
|
||||
return $this->back($request, [], '已删除。');
|
||||
}
|
||||
|
||||
public function confirm(Request $request, int $statement)
|
||||
{
|
||||
$this->guard(fn () => $this->store->confirm($statement, self::user()));
|
||||
|
||||
return $this->back($request, [], '已确认结算,单号已记入结算台账。');
|
||||
}
|
||||
|
||||
public function unconfirm(Request $request, int $statement)
|
||||
{
|
||||
$this->guard(fn () => $this->store->unconfirm($statement));
|
||||
|
||||
return $this->back($request, [], '已撤销确认,结算台账里这批单号已删除。');
|
||||
}
|
||||
|
||||
public function saveGroup(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
|
||||
'summary_carrier' => ['nullable', 'string', 'max:128'], 'bundle' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'],
|
||||
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
|
||||
], [], ['name' => '分组名称', 'express_names' => '快递名称1']);
|
||||
$exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name']))
|
||||
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
|
||||
if ($exists) {
|
||||
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
||||
}
|
||||
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
||||
$this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
||||
|
||||
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
|
||||
}
|
||||
|
||||
public function importLedger(Request $request)
|
||||
{
|
||||
$file = $request->validate(['ledger' => ['required', 'file', 'max:51200']], [], ['ledger' => '台账文件'])['ledger'];
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||||
throw ValidationException::withMessages(['ledger' => '只支持 xlsx、xls、csv。']);
|
||||
}
|
||||
$result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension));
|
||||
$message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号';
|
||||
if ($result['rejected'] > 0) {
|
||||
$message .= ',' . $result['rejected'] . ' 行未导入' . ($result['unknown_groups'] ? '(分组不存在:' . implode('、', array_slice($result['unknown_groups'], 0, 10)) . ')' : '');
|
||||
}
|
||||
|
||||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||||
}
|
||||
|
||||
public function exportStatement(Request $request, int $statement)
|
||||
{
|
||||
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||||
->where('s.id', $statement)->first(['s.bill_month', 'g.name']);
|
||||
abort_if($row === null, 404);
|
||||
$related = app(StatementExporter::class)->related($statement);
|
||||
$label = count($related) > 1 ? $row->name . '等' . count($related) . '家' : $row->name;
|
||||
$name = str_replace(['/', '\\'], '-', $label) . '_' . $row->bill_month . '_对账(内部版).xlsx';
|
||||
|
||||
return response()->streamDownload(function () use ($statement): void {
|
||||
$output = fopen('php://output', 'wb');
|
||||
app(StatementExporter::class)->export($statement, $output);
|
||||
}, $name);
|
||||
}
|
||||
|
||||
public function exportDetails(Request $request)
|
||||
{
|
||||
$month = self::monthParam($request->query('month')) ?? now()->subMonth()->format('Y-m');
|
||||
$filters = $request->validate(['group_id' => ['nullable', 'integer'], 'category' => ['nullable', 'string'],
|
||||
'resolution' => ['nullable', 'string'], 'owner' => ['nullable', 'string'], 'min_diff' => ['nullable', 'numeric'],
|
||||
'waybills' => ['nullable', 'string', 'max:20000'], 'all_months' => ['nullable', 'boolean']]);
|
||||
$query = $this->detailsQuery($filters, $month);
|
||||
|
||||
return response()->streamDownload(function () use ($query): void {
|
||||
$book = new StreamingWorkbook();
|
||||
$book->row('对账明细', ['账单月份', '对账分组', '负责人', '快递单号', '快递提供运费', '快递提供重量', '分类', '发货时间', '发货数据快递名称1',
|
||||
'核算运费', '计费重量', '自算金额', '差异', '未发出来源', '处理结果', '处理人'], true);
|
||||
foreach ($query->orderBy('l.id')->select(['l.*', 's.bill_month', 'g.name as group_name', 'g.owner'])->lazyById(1000, 'l.id', 'id') as $line) {
|
||||
$book->row('对账明细', [$line->bill_month, $line->group_name, $line->owner, (string) $line->waybill_no,
|
||||
$line->bill_amount === null ? null : (float) $line->bill_amount, $line->bill_weight === null ? null : (float) $line->bill_weight,
|
||||
Category::label((string) $line->category, $line->category_month), $line->ship_time, $line->express_name,
|
||||
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->charge_weight === null ? null : (float) $line->charge_weight,
|
||||
$line->self_amount === null ? null : (float) $line->self_amount, round((float) $line->bill_amount - (float) $line->self_amount, 2),
|
||||
$line->unshipped_sources, Category::RESOLUTIONS[$line->resolution] ?? null, $line->resolved_by]);
|
||||
}
|
||||
$book->writeTo(fopen('php://output', 'wb'));
|
||||
}, '对账明细.xlsx');
|
||||
}
|
||||
|
||||
/** @template T @param callable():T $action @return T */
|
||||
private function guard(callable $action): mixed
|
||||
{
|
||||
try {
|
||||
return $action();
|
||||
} catch (RuntimeException $error) {
|
||||
throw ValidationException::withMessages(['courier_bills' => $error->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
private function back(Request $request, array $query, string $message)
|
||||
{
|
||||
$target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => self::section($request),
|
||||
'page' => 'courier-bill-reconciliation', ...$query]);
|
||||
|
||||
return redirect()->to($target)->with('courier_bills_message', $message);
|
||||
}
|
||||
|
||||
public static function section(Request $request): string
|
||||
{
|
||||
$section = (string) ($request->route('section') ?? $request->input('section') ?? '');
|
||||
|
||||
return $section === 'courier-payables-final' ? 'courier-payables-final' : 'courier-payables';
|
||||
}
|
||||
|
||||
private static function monthParam(mixed $value): ?string
|
||||
{
|
||||
return is_string($value) && preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $value) ? $value : null;
|
||||
}
|
||||
|
||||
private static function user(): string
|
||||
{
|
||||
$user = user();
|
||||
|
||||
return (string) ($user?->name ?? $user?->email ?? 'system');
|
||||
}
|
||||
}
|
||||
@ -11,9 +11,19 @@ class CourierContracts extends Controller
|
||||
{
|
||||
/** A read-only archive entry point with courier-information page access, not signing-management access. */
|
||||
public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse
|
||||
{
|
||||
return $this->serveFile($agreementSignature, $kind, 'courier');
|
||||
}
|
||||
|
||||
public function downloadSupplier(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse
|
||||
{
|
||||
return $this->serveFile($agreementSignature, $kind, 'supplier');
|
||||
}
|
||||
|
||||
private function serveFile(CourierAgreementSignature $agreementSignature, string $kind, string $partnerType): StreamedResponse
|
||||
{
|
||||
abort_unless($agreementSignature->company_id === (int) company_id()
|
||||
&& $agreementSignature->archivedCourierContractPayload() !== null, 404);
|
||||
&& $agreementSignature->archivedContractPayload($partnerType) !== null, 404);
|
||||
$path = match ($kind) {
|
||||
'signed' => $agreementSignature->signed_pdf_path,
|
||||
'certificate' => $agreementSignature->certificate_path,
|
||||
|
||||
@ -93,6 +93,7 @@ class CourierOnboardings extends Controller
|
||||
/** 后台变价页:复用入驻报价填写区,以最新版本(或已退回的变价单)为底稿。 */
|
||||
public function requote(CourierOnboarding $onboarding): View|RedirectResponse
|
||||
{
|
||||
app(\App\Support\CourierQuoteWorkflowPermissions::class)->assertInitiator((int) user_id());
|
||||
$this->ensureReady();
|
||||
$quoteManagement = route('business.pages.show', ['section' => 'courier-payables', 'page' => 'quote-management']);
|
||||
if ($onboarding->status !== CourierOnboarding::STATUS_ACTIVATED) {
|
||||
@ -100,9 +101,9 @@ class CourierOnboardings extends Controller
|
||||
}
|
||||
$requotes = $this->requotes();
|
||||
$open = $requotes->openChange($onboarding);
|
||||
if ($open !== null && $open->status === \App\Models\Business\CourierQuoteChange::STATUS_PENDING_REVIEW) {
|
||||
if ($open !== null && (in_array($open->status, [\App\Models\Business\CourierQuoteChange::STATUS_PENDING_REVIEW, \App\Models\Business\CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW], true) || $open->created_by !== user_id())) {
|
||||
return redirect()->route('business.courier-quote-changes.show', $open)
|
||||
->with('success', "已有待审核的变价单 {$open->number},审核完成后再发起新的变价。");
|
||||
->with('success', "已有未完成的变价单 {$open->number},请先查看该单;待审核单可由发起人撤回修改。");
|
||||
}
|
||||
|
||||
$version = $requotes->latestVersion($onboarding);
|
||||
@ -139,6 +140,7 @@ class CourierOnboardings extends Controller
|
||||
...\App\Http\Controllers\Onboarding\CourierOnboardingForms::quoteRules(),
|
||||
'summary' => ['required', 'string', 'min:2', 'max:2000'],
|
||||
'quote_end_date' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:quote_effective_date'],
|
||||
...\App\Support\CourierQuotePeriods::rules(),
|
||||
], [
|
||||
'summary.required' => '请写一下这次变价的原因或依据,审核和对账时要看。',
|
||||
'quote_end_date.after_or_equal' => '结束日期不能早于执行日期。',
|
||||
|
||||
@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Support\CourierBills\PayableSummary;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use RuntimeException;
|
||||
|
||||
/** 快递应付汇总:所有承运商的月度应付,格式同手工快递汇总表。 */
|
||||
final class CourierPayableSummaryController extends Controller
|
||||
{
|
||||
public const STATUSES = ['已确认', '待处理', '本月无账单', '旧账挂账'];
|
||||
|
||||
public function __construct(private readonly PayableSummary $summary) {}
|
||||
|
||||
public function page(Request $request): array
|
||||
{
|
||||
$data = ['view' => 'business.pages.courier-payables.courier-payable-summary', 'psSection' => CourierBillController::section($request),
|
||||
'psUnavailable' => false, 'psRows' => [], 'psMonths' => [], 'psMonth' => null];
|
||||
try {
|
||||
$months = $this->summary->months();
|
||||
$month = is_string($request->query('month')) && in_array($request->query('month'), $months, true) ? $request->query('month') : ($months[0] ?? null);
|
||||
$rows = $month === null ? [] : $this->summary->rows($month);
|
||||
$status = in_array($request->query('status'), self::STATUSES, true) ? $request->query('status') : null;
|
||||
$keyword = trim((string) $request->query('q'));
|
||||
$filtered = array_values(array_filter($rows, static function (array $row) use ($status, $keyword, $request): bool {
|
||||
$c = $row['cells'];
|
||||
foreach (['company' => 'C', 'owner' => 'D', 'state' => 'E'] as $param => $letter) {
|
||||
if (filled($request->query($param)) && (string) ($c[$letter] ?? '') !== (string) $request->query($param)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return ($status === null || $row['status'] === $status)
|
||||
&& ($keyword === '' || str_contains((string) ($c['H'] ?? ''), $keyword) || str_contains((string) ($c['G'] ?? ''), $keyword));
|
||||
}));
|
||||
$counts = array_count_values(array_column($rows, 'status'));
|
||||
$options = static fn (string $letter): array => collect($rows)->pluck('cells.' . $letter)->filter()->unique()->sort()->values()->all();
|
||||
$data = array_merge($data, ['psMonths' => $months, 'psMonth' => $month, 'psRows' => $filtered, 'psAll' => count($rows),
|
||||
'psCounts' => $counts, 'psStatus' => $status, 'psCompanies' => $options('C'), 'psOwners' => $options('D'),
|
||||
'psTotals' => collect(PayableSummary::MONEY)->mapWithKeys(fn ($k) => [$k => array_sum(array_map(fn ($r) => (float) ($r['cells'][$k] ?? 0), $filtered))])->all()]);
|
||||
} catch (QueryException $error) {
|
||||
report($error);
|
||||
$data['psUnavailable'] = true;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function import(Request $request)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'summary' => ['required', 'file', 'max:51200']],
|
||||
[], ['summary' => '快递汇总表', 'month' => '月份']);
|
||||
if (strtolower($data['summary']->getClientOriginalExtension()) !== 'xlsx') {
|
||||
throw ValidationException::withMessages(['summary' => '请上传 xlsx 格式的快递汇总表。']);
|
||||
}
|
||||
$result = $this->guard(fn () => $this->summary->import($data['summary']->getRealPath(), $data['month']));
|
||||
|
||||
return $this->back($request, $data['month'], '已导入 ' . $data['month'] . ' 快递汇总 ' . $result['rows'] . ' 个承运商。');
|
||||
}
|
||||
|
||||
public function createMonth(Request $request)
|
||||
{
|
||||
$month = $request->validate(['month' => ['required', 'date_format:Y-m']])['month'];
|
||||
$count = $this->guard(fn () => $this->summary->createMonth($month));
|
||||
|
||||
return $this->back($request, $month, '已生成 ' . $month . ':' . $count . ' 个承运商,月初结余按上月「本月应付 − 本次实付」结转。');
|
||||
}
|
||||
|
||||
public function update(Request $request, int $row)
|
||||
{
|
||||
$data = $request->validate(['column' => ['required', Rule::in(array_keys(PayableSummary::EDITABLE))], 'value' => ['nullable', 'string', 'max:500']]);
|
||||
$this->guard(fn () => $this->summary->updateCell($row, $data['column'], $data['value'] ?? null));
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
return redirect()->to(url()->previous())->with('courier_summary_message', '已保存。');
|
||||
}
|
||||
|
||||
public function addCarrier(Request $request)
|
||||
{
|
||||
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'carrier' => ['required', 'string', 'max:128']], [], ['carrier' => '承运商']);
|
||||
$this->guard(fn () => $this->summary->addCarrier($data['month'], $data['carrier']));
|
||||
|
||||
return $this->back($request, $data['month'], '已新增承运商。');
|
||||
}
|
||||
|
||||
public function export(Request $request)
|
||||
{
|
||||
$month = $request->validate(['month' => ['required', 'date_format:Y-m']])['month'];
|
||||
|
||||
return response()->streamDownload(function () use ($month): void {
|
||||
$this->summary->export($month, fopen('php://output', 'wb'));
|
||||
}, '快递应付汇总_' . $month . '.xlsx');
|
||||
}
|
||||
|
||||
private function guard(callable $action): mixed
|
||||
{
|
||||
try {
|
||||
return $action();
|
||||
} catch (RuntimeException $error) {
|
||||
throw ValidationException::withMessages(['courier_summary' => $error->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
private function back(Request $request, string $month, string $message)
|
||||
{
|
||||
return redirect()->route('business.pages.show', ['section' => CourierBillController::section($request),
|
||||
'page' => 'courier-payable-summary', 'month' => $month])->with('courier_summary_message', $message);
|
||||
}
|
||||
}
|
||||
@ -6,6 +6,7 @@ use App\Abstracts\Http\Controller;
|
||||
use App\Business\CourierProfileData;
|
||||
use App\Models\Business\CourierPaymentAccount;
|
||||
use App\Models\Business\CourierProfile;
|
||||
use App\Utilities\CourierProfilePermissions;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@ -20,6 +21,7 @@ class CourierProfiles extends Controller
|
||||
|
||||
public function update(Request $request, string $expcode): RedirectResponse
|
||||
{
|
||||
abort_unless(CourierProfilePermissions::canEdit(), 403, '未获授权编辑快递资料。');
|
||||
$row = $this->profiles->currentRow($expcode);
|
||||
abort_if($row === null, 404);
|
||||
|
||||
@ -29,6 +31,8 @@ class CourierProfiles extends Controller
|
||||
in_array($field, CourierProfile::BOOLEAN_FIELDS, true) => ['nullable', 'in:0,1'],
|
||||
in_array($field, CourierProfile::DATE_FIELDS, true) => ['nullable', 'date'],
|
||||
$field === 'expname' => ['required', 'string', 'max:100'],
|
||||
CourierProfile::fieldOptions($field) !== null => ['nullable', \Illuminate\Validation\Rule::in(array_keys(CourierProfile::fieldOptions($field)))],
|
||||
$field === 'courier_email' => ['nullable', 'email', 'max:255'],
|
||||
default => ['nullable', 'string', 'max:255'],
|
||||
};
|
||||
}
|
||||
|
||||
@ -2,10 +2,14 @@
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Business\CourierProfileData;
|
||||
use App\Models\Business\CourierQuoteChange;
|
||||
use App\Models\Business\CourierQuoteVersion;
|
||||
use App\Models\Business\CourierStockQuoteEntry;
|
||||
use App\Services\Esign\EsignClient;
|
||||
use App\Support\CourierQuoteChangeService;
|
||||
use App\Support\CourierQuoteChangeExport;
|
||||
use App\Support\CourierQuoteWorkflowPermissions;
|
||||
use App\Support\CourierOnboardingService;
|
||||
use App\Support\CourierQuoteSignatureService;
|
||||
use App\Support\CourierRequoteService;
|
||||
@ -15,6 +19,10 @@ use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\View\View;
|
||||
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
|
||||
class CourierQuoteChanges extends Controller
|
||||
{
|
||||
@ -38,15 +46,30 @@ class CourierQuoteChanges extends Controller
|
||||
->paginate(20)
|
||||
->withQueryString();
|
||||
|
||||
$quoteReviewer = $this->canReview();
|
||||
$admin = $this->canAdminister();
|
||||
$permissions = app(CourierQuoteWorkflowPermissions::class);
|
||||
$workflow = $permissions->settings();
|
||||
$stageAccess = [];
|
||||
$reviewableIds = $changes->filter(function ($change) use ($permissions, &$stageAccess) {
|
||||
if (!in_array($change->status, [CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW], true)) return false;
|
||||
// 本页同环节和同自审条件仅核验一次;下个请求重新读取权限和花名册。
|
||||
$key = $change->status . ':' . (int) $change->isStockQuote() . ':' . (int) ($change->created_by === user_id());
|
||||
return $stageAccess[$key] ??= $permissions->canReviewChange($change, (int) user_id());
|
||||
})->pluck('id')->all();
|
||||
|
||||
return view('business.pages.courier-payables.quote-change-history', [
|
||||
'changes' => $changes,
|
||||
'canReview' => $this->canReview(),
|
||||
'canReview' => $quoteReviewer || $admin,
|
||||
'reviewableChangeIds' => $reviewableIds,
|
||||
'filters' => $filters,
|
||||
'quoteWorkflow' => $workflow,
|
||||
'carrierOptions' => CourierQuoteChange::query()->whereNotNull('carrier_name')->distinct()->orderBy('carrier_name')->pluck('carrier_name')->all(),
|
||||
'changeTypeOptions' => CourierQuoteChange::query()->whereNotNull('change_type')->distinct()->orderBy('change_type')->pluck('change_type')->all(),
|
||||
'statusOptions' => [
|
||||
CourierQuoteChange::STATUS_DRAFT => '草稿',
|
||||
CourierQuoteChange::STATUS_PENDING_REVIEW => '待审核',
|
||||
CourierQuoteChange::STATUS_PENDING_REVIEW => $workflow['staged'] ? '待初审' : '待审核',
|
||||
CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW => '待复审',
|
||||
CourierQuoteChange::STATUS_RETURNED => '已退回',
|
||||
CourierQuoteChange::STATUS_APPROVED => '已审核',
|
||||
],
|
||||
@ -57,7 +80,7 @@ class CourierQuoteChanges extends Controller
|
||||
private function historyFilters(Request $request): array
|
||||
{
|
||||
$status = (string) $request->input('status', '');
|
||||
$allowed = [CourierQuoteChange::STATUS_DRAFT, CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_RETURNED, CourierQuoteChange::STATUS_APPROVED];
|
||||
$allowed = [CourierQuoteChange::STATUS_DRAFT, CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW, CourierQuoteChange::STATUS_RETURNED, CourierQuoteChange::STATUS_APPROVED];
|
||||
|
||||
return [
|
||||
'carrier' => mb_substr(trim((string) $request->input('carrier', '')), 0, 100),
|
||||
@ -68,6 +91,7 @@ class CourierQuoteChanges extends Controller
|
||||
|
||||
public function create(Request $request): View|RedirectResponse
|
||||
{
|
||||
app(CourierQuoteWorkflowPermissions::class)->assertInitiator((int) user_id());
|
||||
$quotes = $this->snapshot->load()['quotes'] ?? [];
|
||||
abort_if($quotes === [], 422, '尚未导入可用于变更的报价版本。');
|
||||
|
||||
@ -99,6 +123,11 @@ class CourierQuoteChanges extends Controller
|
||||
$requoteDiff = $onboarding !== null
|
||||
? $this->requotes->diff($onboarding, $this->requotes->basePayload($onboarding, $quoteChange), $quoteChange->quote_payload)
|
||||
: null;
|
||||
$reviewAllowed = $this->canReview($quoteChange);
|
||||
$quoteWorkflow = app(CourierQuoteWorkflowPermissions::class)->settings();
|
||||
$canManageSignature = $this->canAdminister() || $reviewAllowed;
|
||||
$signingDetails = $canManageSignature && $onboarding === null && $quoteChange->version?->signature?->canSend()
|
||||
? $this->signingDetailsFor($quoteChange->version) : [];
|
||||
|
||||
return view('business.pages.courier-payables.quote-change-show', [
|
||||
'change' => $quoteChange,
|
||||
@ -109,15 +138,49 @@ class CourierQuoteChanges extends Controller
|
||||
? $this->requotes->reviewWarnings($quoteChange, $requoteDiff)
|
||||
: [],
|
||||
'voidedBy' => $quoteChange->version?->voided_by ? user_model_class()::query()->find($quoteChange->version->voided_by)?->name : null,
|
||||
'canReview' => $this->canReview() && ($quoteChange->created_by !== user_id() || config('courier_onboarding.allow_same_reviewer')),
|
||||
'canManageSignature' => $this->canReview(),
|
||||
'canReview' => app(CourierQuoteWorkflowPermissions::class)->canReviewChange($quoteChange, (int) user_id()),
|
||||
'canWithdraw' => ! $quoteChange->isStockQuote() && in_array($quoteChange->status, [CourierQuoteChange::STATUS_PENDING_REVIEW, CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW], true)
|
||||
&& $quoteChange->created_by === user_id() && app(CourierQuoteWorkflowPermissions::class)->can('initiators', (int) user_id()),
|
||||
'canManageSignature' => $canManageSignature,
|
||||
'canCorrectPeriods' => $reviewAllowed && !$quoteChange->isStockQuote()
|
||||
&& app(\App\Support\CourierQuotePeriodCorrection::class)->available($quoteChange),
|
||||
'quoteSigningAccount' => $signingDetails['account'] ?? '',
|
||||
'quoteSigningParty' => $signingDetails['party_b'] ?? '',
|
||||
'canVoidQuote' => $this->canAdminister(),
|
||||
'quoteWorkflow' => $quoteWorkflow,
|
||||
'esignConfigured' => EsignClient::configured(),
|
||||
'esignEnvironment' => (string) config('services.esign.environment', 'sandbox'),
|
||||
]);
|
||||
}
|
||||
|
||||
private function signingDetailsFor(CourierQuoteVersion $version): array
|
||||
{
|
||||
try {
|
||||
$row = app(CourierInformationMirrorRepository::class)->signingAccountSource(
|
||||
(string) $version->courier_expcode, (string) $version->carrier_name,
|
||||
);
|
||||
if ($row === null) {
|
||||
return [];
|
||||
}
|
||||
$profiles = app(CourierProfileData::class);
|
||||
$row = $profiles->apply($row, $profiles->overrides([(string) $row->expcode])[(string) $row->expcode] ?? []);
|
||||
|
||||
return [
|
||||
'account' => trim((string) ($row->dzqzjbr ?? '')),
|
||||
'party_b' => trim((string) ($row->tradebody ?? '')),
|
||||
];
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public function edit(CourierQuoteChange $quoteChange): View|RedirectResponse
|
||||
{
|
||||
if (! $quoteChange->isStockQuote()) {
|
||||
app(CourierQuoteWorkflowPermissions::class)->assertInitiator((int) user_id());
|
||||
}
|
||||
abort_unless($quoteChange->isEditable() && $quoteChange->created_by === user_id(), 403);
|
||||
if ($quoteChange->isStockQuote()) {
|
||||
return redirect()->route('business.courier-stock-quotes.edit', data_get($quoteChange->quote_payload, 'stock_quote_entry_id'));
|
||||
@ -149,14 +212,55 @@ class CourierQuoteChanges extends Controller
|
||||
->with('success', "{$change->number} 已提交审核。");
|
||||
}
|
||||
|
||||
public function withdraw(CourierQuoteChange $quoteChange): RedirectResponse
|
||||
{
|
||||
$change = $this->service->withdraw($quoteChange, (int) user_id());
|
||||
|
||||
return redirect()->route('business.courier-quote-changes.edit', $change)
|
||||
->with('success', "{$change->number} 已撤回为草稿,修改后请重新提交审核。");
|
||||
}
|
||||
|
||||
public function correctPeriods(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
...\App\Support\CourierQuotePeriods::rules(),
|
||||
'effective_date' => ['required', 'date_format:Y-m-d'],
|
||||
'execution_mode' => ['required', 'in:permanent,temporary'],
|
||||
]);
|
||||
app(\App\Support\CourierQuotePeriodCorrection::class)->correct($quoteChange, $data, (int) user_id());
|
||||
return redirect()->route('business.courier-quote-changes.show', $quoteChange)
|
||||
->with('success', '执行区间已更正,价格不变,待签文件已重新生成。请核对后再发起签署。');
|
||||
}
|
||||
|
||||
public function export(CourierQuoteChange $quoteChange): StreamedResponse
|
||||
{
|
||||
$book = app(CourierQuoteChangeExport::class)->build($quoteChange);
|
||||
|
||||
return response()->streamDownload(function () use ($book): void {
|
||||
try {
|
||||
(new Xlsx($book))->save('php://output');
|
||||
} finally {
|
||||
$book->disconnectWorksheets();
|
||||
}
|
||||
}, $quoteChange->number . '-变价后报价.xlsx', [
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
|
||||
public function approve(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
|
||||
{
|
||||
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
|
||||
abort_unless($this->canReview($quoteChange), 403, '当前账号没有报价审核权限。');
|
||||
if ($quoteChange->isStockQuote()) {
|
||||
$request->validate(['stock_rules_confirmed' => ['accepted']], ['stock_rules_confirmed.accepted' => '请先核对原报价、计费规则及实际执行日期。']);
|
||||
}
|
||||
$change = $this->service->approve($quoteChange, user_id(), $request->boolean('stock_signature_verified'));
|
||||
|
||||
if ($change->status === CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW) {
|
||||
return redirect()->route('business.courier-quote-changes.show', $change)
|
||||
->with('success', '初审通过,已转复审。任意一名指定复审人员通过后才生成生效报价版本。');
|
||||
}
|
||||
|
||||
$message = "审核完成,已生成新报价版本 {$change->version->version_code}。";
|
||||
|
||||
if ($change->isStockQuote()) {
|
||||
@ -194,7 +298,7 @@ class CourierQuoteChanges extends Controller
|
||||
|
||||
public function batchApprove(Request $request): RedirectResponse
|
||||
{
|
||||
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
|
||||
abort_unless($this->canReview() || $this->canAdminister(), 403, '当前账号没有报价审核权限。');
|
||||
$input = $request->validate([
|
||||
'ids' => ['required', 'array', 'min:1', 'max:100'],
|
||||
'ids.*' => ['required', 'integer', 'min:1', 'distinct'],
|
||||
@ -231,7 +335,7 @@ class CourierQuoteChanges extends Controller
|
||||
/** 已入驻快递的变价版本按入驻资料(重新)推送到快递 e签宝。 */
|
||||
public function pushToCourier(CourierQuoteChange $quoteChange): RedirectResponse
|
||||
{
|
||||
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
|
||||
abort_unless($this->canAdminister() || $this->canReview($quoteChange), 403, '当前账号没有报价审核权限。');
|
||||
abort_if($quoteChange->isStockQuote(), 422, '存量报价请先核对历史签署资料,补签通过详情页手动发起。');
|
||||
$onboarding = $this->requotes->onboardingForCourier($quoteChange->carrier_name);
|
||||
abort_if($onboarding === null || $quoteChange->version === null, 404);
|
||||
@ -244,7 +348,7 @@ class CourierQuoteChanges extends Controller
|
||||
/** 作废发错的报价版本(未签完的同时撤回 e签宝 签署任务)。 */
|
||||
public function void(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
|
||||
{
|
||||
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
|
||||
abort_unless($this->canAdminister(), 403, '当前账号没有报价审核权限。');
|
||||
abort_if($quoteChange->version === null, 404);
|
||||
$data = $request->validate(
|
||||
['void_reason' => ['required', 'string', 'min:2', 'max:500']],
|
||||
@ -257,7 +361,7 @@ class CourierQuoteChanges extends Controller
|
||||
|
||||
public function returnForChanges(Request $request, CourierQuoteChange $quoteChange): RedirectResponse
|
||||
{
|
||||
abort_unless($this->canReview(), 403, '当前账号没有报价审核权限。');
|
||||
abort_unless($this->canReview($quoteChange), 403, '当前账号没有报价审核权限。');
|
||||
$validated = $request->validate([
|
||||
'review_note' => ['required', 'string', 'min:2', 'max:1000'],
|
||||
]);
|
||||
@ -270,9 +374,19 @@ class CourierQuoteChanges extends Controller
|
||||
private function validatedChange(Request $request, bool $requiresSource): array
|
||||
{
|
||||
$rules = [
|
||||
...\App\Support\CourierQuotePeriods::rules(),
|
||||
'end_date' => ['nullable', 'date_format:Y-m-d'],
|
||||
'change_type' => ['required', 'in:费率调整,面单调整,规则备注,执行日期,其他'],
|
||||
'effective_date' => ['required', 'date_format:Y-m-d'],
|
||||
'summary' => ['required', 'string', 'min:2', 'max:2000'],
|
||||
'quote_notes' => ['sometimes', 'array', 'max:500'],
|
||||
'quote_notes.*' => ['nullable', 'string', 'max:10000'],
|
||||
'province_additions' => ['sometimes', 'array', 'max:34'],
|
||||
'province_additions.*' => ['array:region,prices,note'],
|
||||
'province_additions.*.region' => ['required', 'string', 'max:16', 'regex:/^[\p{Han}]+$/u'],
|
||||
'province_additions.*.prices' => ['required', 'array'],
|
||||
'province_additions.*.prices.*' => ['required', 'numeric', 'min:0', 'decimal:0,4'],
|
||||
'province_additions.*.note' => ['nullable', 'string', 'max:10000'],
|
||||
'items' => ['required', 'array', 'min:1', 'max:500'],
|
||||
'items.*.source_cell' => ['required', 'regex:/^[A-Z]+[1-9][0-9]*$/'],
|
||||
'items.*.source_row' => ['required', 'integer', 'min:0'],
|
||||
@ -302,6 +416,7 @@ class CourierQuoteChanges extends Controller
|
||||
'quotes' => $quotes,
|
||||
'source' => $source,
|
||||
'editableCells' => $this->editableCells($source, $existingItems),
|
||||
'editableNotes' => \App\Support\CourierQuoteNotes::cells($source, $change?->quote_payload['quote_notes'] ?? []),
|
||||
];
|
||||
}
|
||||
|
||||
@ -390,7 +505,17 @@ class CourierQuoteChanges extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
private function canReview(): bool
|
||||
private function canReview(?CourierQuoteChange $change = null): bool
|
||||
{
|
||||
if ($change && (app(CourierQuoteWorkflowPermissions::class)->settings()['staged']
|
||||
|| $change->status === CourierQuoteChange::STATUS_PENDING_FINAL_REVIEW)) {
|
||||
return app(CourierQuoteWorkflowPermissions::class)->canReviewChange($change, (int) user_id());
|
||||
}
|
||||
return $change?->isStockQuote() ? $this->canAdminister()
|
||||
: app(CourierQuoteWorkflowPermissions::class)->can('reviewers', (int) user_id());
|
||||
}
|
||||
|
||||
private function canAdminister(): bool
|
||||
{
|
||||
return in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true);
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ use App\Models\Business\CourierQuoteSignature;
|
||||
use App\Models\Business\CourierQuoteVersion;
|
||||
use App\Services\Esign\EsignClient;
|
||||
use App\Support\CourierQuoteSignatureService;
|
||||
use App\Support\CourierQuoteWorkflowPermissions;
|
||||
use App\Utilities\SystemAccess;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@ -22,26 +23,30 @@ class CourierQuoteSignatures extends Controller
|
||||
|
||||
public function prepare(Request $request, CourierQuoteVersion $quoteVersion): RedirectResponse
|
||||
{
|
||||
$this->ensureCanManage();
|
||||
$this->ensureCanManage($quoteVersion);
|
||||
abort_unless($quoteVersion->status === 'approved', 422, '只有已审核报价版本可以生成签署文件。');
|
||||
$data = $request->validate([
|
||||
'signature_date' => ['required', 'date'],
|
||||
'organization_name' => ['nullable', 'string', 'min:2', 'max:255'],
|
||||
]);
|
||||
$signature = $this->service->prepareVersion($quoteVersion, user_id(), $data['signature_date']);
|
||||
$signature = $this->service->prepareVersion($quoteVersion, user_id(), $data['signature_date'], null, $data['organization_name'] ?? null);
|
||||
|
||||
return redirect()->route('business.courier-quote-changes.show', $quoteVersion->source_change_id)
|
||||
->with('success', "{$quoteVersion->version_code} 的签署 PDF 已生成,文件校验值已固定。")
|
||||
->withInput($request->only(['signer_type', 'organization_name', 'operator_account', 'notice_type', 'signature_date', 'expires_at']))
|
||||
->with('signature_id', $signature->id);
|
||||
}
|
||||
|
||||
public function send(Request $request, CourierQuoteSignature $quoteSignature): RedirectResponse
|
||||
{
|
||||
$this->ensureCanManage();
|
||||
$this->ensureCanManage($quoteSignature->version);
|
||||
abort_unless($quoteSignature->version?->status === 'approved', 422, '只有已审核报价版本可以发起签署。');
|
||||
abort_unless(EsignClient::configured(), 422, 'E 签宝沙箱尚未配置 App ID 或 AppSecret。');
|
||||
$data = $request->validate([
|
||||
'signer_type' => ['nullable', 'in:organization,person'],
|
||||
'organization_name' => ['required', 'string', 'min:2', 'max:255'],
|
||||
'operator_name' => ['required', 'string', 'min:2', 'max:100'],
|
||||
'signing_subject' => ['nullable', 'string', 'min:2', 'max:255'],
|
||||
'operator_name' => ['nullable', 'string', 'min:2', 'max:100'],
|
||||
'operator_account' => ['required', 'string', 'max:255'],
|
||||
'notice_type' => ['required', 'in:1,2'],
|
||||
'signature_date' => ['required', 'date'],
|
||||
@ -52,6 +57,8 @@ class CourierQuoteSignatures extends Controller
|
||||
$quoteSignature->version,
|
||||
user_id(),
|
||||
$data['signature_date'],
|
||||
$data['signing_subject'] ?? null,
|
||||
$data['organization_name'],
|
||||
);
|
||||
$signature = $this->service->send($quoteSignature, $data, user_id());
|
||||
$environment = $signature->environment === 'sandbox' ? '沙箱' : '正式环境';
|
||||
@ -62,7 +69,7 @@ class CourierQuoteSignatures extends Controller
|
||||
|
||||
public function synchronize(CourierQuoteSignature $quoteSignature): RedirectResponse
|
||||
{
|
||||
$this->ensureCanManage();
|
||||
$this->ensureCanManage($quoteSignature->version);
|
||||
$signature = $this->service->synchronize($quoteSignature, user_id());
|
||||
$message = $signature->status === CourierQuoteSignature::STATUS_ARCHIVED
|
||||
? '签署完成,签署 PDF 和完成证书已私有归档。'
|
||||
@ -137,8 +144,12 @@ class CourierQuoteSignatures extends Controller
|
||||
*/
|
||||
public function sheet(CourierQuoteVersion $quoteVersion): StreamedResponse
|
||||
{
|
||||
$values = json_decode((string) $quoteVersion->values_json, true);
|
||||
$table = self::quoteTableWithNotes(self::quoteLayout(is_array($values) ? $values : []))['rows'];
|
||||
$confirmation = app(\App\Support\CourierQuoteConfirmation::class)->data($quoteVersion);
|
||||
$layout = self::quoteLayout($confirmation['values']);
|
||||
if ($quoteVersion->isTemporary()) {
|
||||
array_unshift($layout['notes'], $confirmation['temporary_note']);
|
||||
}
|
||||
$table = self::quoteTableWithNotes($layout)['rows'];
|
||||
abort_if($table === [], 404, '这份报价没有可导出的价格表。');
|
||||
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
@ -147,8 +158,9 @@ class CourierQuoteSignatures extends Controller
|
||||
foreach ($table as $rowIndex => $row) {
|
||||
foreach ($row as $columnIndex => $value) {
|
||||
$cell = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnIndex + 1) . ($rowIndex + 1);
|
||||
if (is_int($value) || is_float($value)) {
|
||||
$sheet->setCellValue($cell, $value);
|
||||
if ($rowIndex > 0 && $columnIndex > 0 && $columnIndex < count($table[0]) - 1 && is_numeric($value)) {
|
||||
$sheet->setCellValue($cell, (float) $value);
|
||||
$sheet->getStyle($cell)->getNumberFormat()->setFormatCode('0.00');
|
||||
} elseif ($value !== null && $value !== '') {
|
||||
$sheet->setCellValueExplicit($cell, (string) $value, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
|
||||
}
|
||||
@ -181,7 +193,7 @@ class CourierQuoteSignatures extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* 从报价矩阵里截出价格表:从「省份」表头行开始,到第一行只有一格文字(说明、备注)为止。
|
||||
* 从报价矩阵里截出价格表;未报价的省份占位行不输出,也不中断后续报价。
|
||||
*
|
||||
* @param array<int,mixed> $values
|
||||
* @return list<list<string|int|float|null>>
|
||||
@ -193,7 +205,7 @@ class CourierQuoteSignatures extends Controller
|
||||
|
||||
/**
|
||||
* 报价矩阵拆成「价格表」和「价格表以外的文字」:
|
||||
* - table:从「省份」表头行开始,到第一行只有一格文字为止;
|
||||
* - table:从「省份」表头行开始,跳过未报价的省份占位行,到说明文字为止;
|
||||
* - notes:其余所有文字行(执行时间、计费方式、计泡、起算重量、报价备注等),第一行标题除外;
|
||||
* - row_keys:价格表每一行在原矩阵里的下标(用于对应公式)。
|
||||
*
|
||||
@ -214,6 +226,16 @@ class CourierQuoteSignatures extends Controller
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($start === null) {
|
||||
foreach ($rows as $index => $row) {
|
||||
if (filled($row[0] ?? null) || $filled($row) < 2) continue;
|
||||
$next = $rows[$index + 1] ?? [];
|
||||
if (filled($next[0] ?? null) && collect(array_slice($next, 1))->contains(fn ($cell) => is_numeric($cell))) {
|
||||
$start = $index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($start === null) {
|
||||
foreach ($rows as $index => $row) {
|
||||
if ($filled($row) >= 2) {
|
||||
@ -229,7 +251,22 @@ class CourierQuoteSignatures extends Controller
|
||||
$table = [];
|
||||
$rowKeys = [];
|
||||
$end = $start;
|
||||
for ($i = $start; $i < count($rows) && $filled($rows[$i]) >= 2; $i++) {
|
||||
for ($i = $start; $i < count($rows); $i++) {
|
||||
if ($filled($rows[$i]) < 2) {
|
||||
// Imported sheets retain destinations with no quote. They are neither
|
||||
// prices nor billing notes, and prices may resume below them.
|
||||
$region = \App\Support\CourierQuoteFreightCalculator::regionKey((string) ($rows[$i][0] ?? ''));
|
||||
if ($filled($rows[$i]) === 1 && in_array($region, [
|
||||
'北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙江',
|
||||
'江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南',
|
||||
'广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海',
|
||||
'内蒙古', '广西', '西藏', '宁夏', '新疆', '香港', '澳门', '台湾', '拉萨',
|
||||
], true)) {
|
||||
$end = $i + 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
$table[] = array_values($rows[$i]);
|
||||
$rowKeys[] = $keys[$i];
|
||||
$end = $i + 1;
|
||||
@ -266,7 +303,7 @@ class CourierQuoteSignatures extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* 价格表右侧加一列「备注」,每条计费条件占一行;条件比省份多时在表尾补行。
|
||||
* 复用价格表已有的「备注」列,缺少时再添加;条件比省份多时在表尾补行。
|
||||
*
|
||||
* @param array{table:list<list<mixed>>,notes:list<string>,row_keys:list<int|string>} $layout
|
||||
* @return array{rows:list<list<mixed>>,row_keys:list<int|string|null>}
|
||||
@ -279,12 +316,19 @@ class CourierQuoteSignatures extends Controller
|
||||
}
|
||||
$notes = $layout['notes'];
|
||||
$width = count($table[0]);
|
||||
$hasNoteColumn = preg_match('/^(备注|说明)[::]?$/u', trim((string) $table[0][$width - 1])) === 1;
|
||||
$rows = [];
|
||||
$keys = [];
|
||||
$total = max(count($table), count($notes) + 1);
|
||||
for ($i = 0; $i < $total; $i++) {
|
||||
$row = $table[$i] ?? array_fill(0, $width, null);
|
||||
$row[] = $i === 0 ? '备注' : ($notes[$i - 1] ?? null);
|
||||
if ($hasNoteColumn) {
|
||||
if ($i > 0 && filled($notes[$i - 1] ?? null)) {
|
||||
$row[$width - 1] = implode("\n", array_filter([$row[$width - 1], $notes[$i - 1]], static fn ($value) => $value !== null && $value !== ''));
|
||||
}
|
||||
} else {
|
||||
$row[] = $i === 0 ? '备注' : ($notes[$i - 1] ?? null);
|
||||
}
|
||||
$rows[] = $row;
|
||||
$keys[] = $layout['row_keys'][$i] ?? null;
|
||||
}
|
||||
@ -309,10 +353,12 @@ class CourierQuoteSignatures extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
private function ensureCanManage(): void
|
||||
private function ensureCanManage(?CourierQuoteVersion $version = null): void
|
||||
{
|
||||
abort_unless(
|
||||
in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true),
|
||||
in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true)
|
||||
|| ($version?->change && ! $version->change->isStockQuote()
|
||||
&& app(CourierQuoteWorkflowPermissions::class)->can('reviewers', (int) user_id())),
|
||||
403,
|
||||
'当前账号没有报价签署管理权限。',
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
214
app/Http/Controllers/Business/PayablesUnpricedCycleExport.php
Normal file
214
app/Http/Controllers/Business/PayablesUnpricedCycleExport.php
Normal file
@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Modules\EcommerceFinance\Services\PayablesFinalRegistry;
|
||||
use Modules\EcommerceFinance\Services\PayablesUnpricedCycleProcessor;
|
||||
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Border;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class PayablesUnpricedCycleExport extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SupplierPayableOverrideStore $store,
|
||||
private readonly PayablesFinalRegistry $registry,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
}
|
||||
|
||||
public function export(Request $request): StreamedResponse
|
||||
{
|
||||
$requestedPeriod = trim((string) $request->query('month', ''));
|
||||
$period = preg_match('/^\d{4}-\d{2}$/', $requestedPeriod) === 1
|
||||
? $requestedPeriod
|
||||
: now()->subMonthNoOverflow()->format('Y-m');
|
||||
$companyId = (int) (company_id() ?: 1);
|
||||
|
||||
$deliveryRows = $this->periodRows(
|
||||
PayablesUnpricedCycleProcessor::DELIVERY_PRICED_DATASET,
|
||||
$period,
|
||||
$companyId,
|
||||
);
|
||||
$returnRows = $this->periodRows(
|
||||
PayablesUnpricedCycleProcessor::RETURN_PRICED_DATASET,
|
||||
$period,
|
||||
$companyId,
|
||||
);
|
||||
$deliverySummary = $this->summary($deliveryRows, 'guessAmount', 'amount');
|
||||
$returnSummary = $this->summary($returnRows, 'guess_amount', 'amount');
|
||||
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$summarySheet = $spreadsheet->getActiveSheet();
|
||||
$summarySheet->setTitle('账期汇总');
|
||||
$summarySheet->fromArray([
|
||||
['类型', '记录数', '件数', '金额', '预估金额'],
|
||||
['送货未定价', $deliverySummary['count'], $deliverySummary['quantity'], $deliverySummary['amount'], $deliverySummary['estimated_amount']],
|
||||
['退货未定价', $returnSummary['count'], $returnSummary['quantity'], $returnSummary['amount'], $returnSummary['estimated_amount']],
|
||||
], null, 'A1');
|
||||
$this->styleSheet($summarySheet, 5, 3, [2 => 'number', 3 => 'number', 4 => 'number', 5 => 'number']);
|
||||
$summarySheet->getColumnDimension('A')->setWidth(18);
|
||||
foreach (['B', 'C', 'D', 'E'] as $column) {
|
||||
$summarySheet->getColumnDimension($column)->setWidth(18);
|
||||
}
|
||||
|
||||
$deliverySheet = $spreadsheet->createSheet();
|
||||
$this->writeDetailSheet(
|
||||
$deliverySheet,
|
||||
'送货未定价',
|
||||
$this->registry->fields(PayablesFinalRegistry::SECTION_SUPPLIER, 'delivery-unpriced'),
|
||||
$deliveryRows,
|
||||
);
|
||||
|
||||
$returnSheet = $spreadsheet->createSheet();
|
||||
$this->writeDetailSheet(
|
||||
$returnSheet,
|
||||
'退货未定价',
|
||||
$this->registry->fields(PayablesFinalRegistry::SECTION_SUPPLIER, 'return-unpriced'),
|
||||
$returnRows,
|
||||
);
|
||||
$spreadsheet->setActiveSheetIndex(0);
|
||||
|
||||
$fileName = '之前月未定价-本月定价_' . $period . '_' . now()->format('Ymd_His') . '.xlsx';
|
||||
|
||||
return response()->streamDownload(function () use ($spreadsheet): void {
|
||||
(new Xlsx($spreadsheet))->save('php://output');
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
}, $fileName, [
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function periodRows(string $dataset, string $period, int $companyId): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$this->store->listRows($dataset, $companyId),
|
||||
static fn (array $row): bool => (string) ($row['_accounting_period'] ?? '') === $period,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return array{count:int,quantity:float,amount:float,estimated_amount:float}
|
||||
*/
|
||||
private function summary(array $rows, string $estimatedAmountField, string $amountField): array
|
||||
{
|
||||
$quantity = 0.0;
|
||||
$amount = 0.0;
|
||||
$estimatedAmount = 0.0;
|
||||
foreach ($rows as $row) {
|
||||
if (is_numeric($row['qty'] ?? null)) {
|
||||
$quantity += (float) $row['qty'];
|
||||
}
|
||||
if (is_numeric($row[$amountField] ?? null)) {
|
||||
$amount += (float) $row[$amountField];
|
||||
}
|
||||
if (is_numeric($row[$estimatedAmountField] ?? null)) {
|
||||
$estimatedAmount += (float) $row[$estimatedAmountField];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'count' => count($rows),
|
||||
'quantity' => $quantity,
|
||||
'amount' => $amount,
|
||||
'estimated_amount' => $estimatedAmount,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,array{label:string,type:string}> $fields
|
||||
* @param list<array<string,mixed>> $rows
|
||||
*/
|
||||
private function writeDetailSheet(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet,
|
||||
string $title,
|
||||
array $fields,
|
||||
array $rows,
|
||||
): void {
|
||||
$sheet->setTitle($title);
|
||||
$headers = array_merge(['序号'], array_column($fields, 'label'));
|
||||
$sheet->fromArray($headers, null, 'A1');
|
||||
|
||||
$data = [];
|
||||
foreach ($rows as $index => $row) {
|
||||
$line = [$index + 1];
|
||||
foreach ($fields as $field => $definition) {
|
||||
$value = $row[$field] ?? '';
|
||||
$line[] = $definition['type'] === 'number' && is_numeric($value)
|
||||
? (float) $value
|
||||
: (string) $value;
|
||||
}
|
||||
$data[] = $line;
|
||||
}
|
||||
if ($data !== []) {
|
||||
$sheet->fromArray($data, null, 'A2');
|
||||
}
|
||||
|
||||
$lastColumn = Coordinate::stringFromColumnIndex(count($headers));
|
||||
$lastRow = max(1, count($data) + 1);
|
||||
$types = [];
|
||||
$columnIndex = 2;
|
||||
foreach ($fields as $definition) {
|
||||
if ($definition['type'] === 'number') {
|
||||
$types[$columnIndex] = 'number';
|
||||
}
|
||||
$column = Coordinate::stringFromColumnIndex($columnIndex);
|
||||
$sheet->getColumnDimension($column)->setWidth(min(32, max(12, mb_strlen($definition['label']) * 2 + 5)));
|
||||
$columnIndex++;
|
||||
}
|
||||
$sheet->getColumnDimension('A')->setWidth(9);
|
||||
$this->styleSheet($sheet, count($headers), $lastRow, $types);
|
||||
$sheet->freezePane('A2');
|
||||
$sheet->setAutoFilter('A1:' . $lastColumn . $lastRow);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,string> $types
|
||||
*/
|
||||
private function styleSheet(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet,
|
||||
int $columnCount,
|
||||
int $rowCount,
|
||||
array $types,
|
||||
): void {
|
||||
$lastColumn = Coordinate::stringFromColumnIndex($columnCount);
|
||||
$headerRange = 'A1:' . $lastColumn . '1';
|
||||
$sheet->getStyle($headerRange)->applyFromArray([
|
||||
'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
|
||||
'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']],
|
||||
'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER, 'vertical' => Alignment::VERTICAL_CENTER],
|
||||
'borders' => ['allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'D8D2C7']]],
|
||||
]);
|
||||
$sheet->getRowDimension(1)->setRowHeight(24);
|
||||
if ($rowCount > 1) {
|
||||
$sheet->getStyle('A2:' . $lastColumn . $rowCount)
|
||||
->getBorders()
|
||||
->getAllBorders()
|
||||
->setBorderStyle(Border::BORDER_THIN)
|
||||
->getColor()
|
||||
->setRGB('E7E2D8');
|
||||
}
|
||||
foreach ($types as $index => $type) {
|
||||
if ($type !== 'number') {
|
||||
continue;
|
||||
}
|
||||
$column = Coordinate::stringFromColumnIndex($index);
|
||||
$sheet->getStyle($column . '2:' . $column . max(2, $rowCount))
|
||||
->getNumberFormat()
|
||||
->setFormatCode('#,##0.00');
|
||||
}
|
||||
}
|
||||
}
|
||||
126
app/Http/Controllers/Business/PlantingReimbursementWorkbench.php
Normal file
126
app/Http/Controllers/Business/PlantingReimbursementWorkbench.php
Normal file
@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use InvalidArgumentException;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementReferences as References;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
|
||||
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbookExporter as Exporter;
|
||||
use Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData as PageData;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
|
||||
/** 种菜报销工作台:上传参考名单、导出对账 / 打款明细 / 种菜任务工单导入模板。 */
|
||||
class PlantingReimbursementWorkbench extends Controller
|
||||
{
|
||||
public function upload(Request $request, string $kind, References $references)
|
||||
{
|
||||
abort_unless(isset(References::KINDS[$kind]), 404);
|
||||
$request->validate(['file' => ['required', 'file', 'max:51200']]);
|
||||
$file = $request->file('file');
|
||||
$name = (string) $file->getClientOriginalName();
|
||||
$redirect = redirect()->route('business.pages.show', [
|
||||
'company_id' => company_id(),
|
||||
'section' => 'planting-data',
|
||||
'page' => 'planting-reimbursement-workbench',
|
||||
'date' => (string) $request->input('date', ''),
|
||||
'paid_from' => (string) $request->input('paid_from', ''),
|
||||
'scope' => (string) $request->input('scope', ''),
|
||||
]);
|
||||
|
||||
try {
|
||||
$rows = $references->parse($kind, (string) $file->getRealPath(), $name);
|
||||
$references->replace((int) company_id(), $kind, $rows, $name, optional(user())->id);
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
return $redirect->with('error', References::KINDS[$kind] . '上传失败:' . $exception->getMessage());
|
||||
} catch (\Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return $redirect->with('error', References::KINDS[$kind] . '上传失败,请检查文件格式后重新上传。');
|
||||
}
|
||||
|
||||
return $redirect->with('success', sprintf('%s已更新:%s 条。', References::KINDS[$kind], number_format(count($rows))));
|
||||
}
|
||||
|
||||
public function export(string $type, PageData $page, Exporter $exporter)
|
||||
{
|
||||
abort_unless(isset(Exporter::TYPES[$type]), 404);
|
||||
$filters = $page->filters();
|
||||
// 导出前必须先在聚工单核对条数、金额一致。
|
||||
if (request('verified') !== '1') {
|
||||
return redirect()->route('business.pages.show', [
|
||||
'company_id' => company_id(), 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench',
|
||||
] + array_diff_key($filters, ['decision' => true]))->with('error', '请先在聚工单按同样条件查询,核对条数和最终报销金额一致后,勾选「已核对」再导出。');
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $page->build($filters);
|
||||
$spreadsheet = $exporter->build($type, $result);
|
||||
} catch (\Throwable $exception) {
|
||||
report($exception);
|
||||
abort(503, '聚工单镜像未就绪,未生成不完整的导出文件,请稍后重试。');
|
||||
}
|
||||
|
||||
return response()->streamDownload(static function () use ($spreadsheet): void {
|
||||
(new Xlsx($spreadsheet))->save('php://output');
|
||||
}, $exporter->fileName($type, $result['summary']), [
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
]);
|
||||
}
|
||||
|
||||
public function saveRobot(Request $request, Robot $robot)
|
||||
{
|
||||
$robot->save([
|
||||
'webhook' => (string) $request->input('webhook', ''),
|
||||
'secret' => (string) $request->input('secret', ''),
|
||||
'keyword' => (string) $request->input('keyword', ''),
|
||||
'reporters' => (string) $request->input('reporters', ''),
|
||||
'digest_webhook' => (string) $request->input('digest_webhook', ''),
|
||||
'digest_secret' => (string) $request->input('digest_secret', ''),
|
||||
'clear_digest' => $request->boolean('clear_digest'),
|
||||
]);
|
||||
|
||||
return $this->back($request)->with('success', '钉钉机器人设置已保存。');
|
||||
}
|
||||
|
||||
/** 按发起人把取消 / 待复查通知发到钉钉群(须先勾选已与聚工单核对)。 */
|
||||
public function notify(Request $request, PageData $page, Robot $robot)
|
||||
{
|
||||
$filters = $page->filters();
|
||||
if ($request->input('verified') !== '1') {
|
||||
return $this->back($request)->with('error', '请先在聚工单核对条数和金额一致,勾选「已核对」后再发通知。');
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $page->build($filters);
|
||||
$sent = $robot->sendNotices((int) company_id(), $filters['date'], $result['summary']['notices'], $request->boolean('force'));
|
||||
} catch (\Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return $this->back($request)->with('error', '群通知发送失败:' . mb_substr($exception->getMessage(), 0, 120));
|
||||
}
|
||||
|
||||
$message = sprintf('群通知:发送 %d 人,跳过已发 %d 人', $sent['sent'], $sent['skipped']);
|
||||
if ($sent['failed'] > 0) {
|
||||
$message .= ',失败 ' . $sent['failed'] . ' 人';
|
||||
}
|
||||
if ($sent['unmatched'] !== []) {
|
||||
$message .= ';钉钉里没匹配到、未能 @ 的:' . implode('、', $sent['unmatched']);
|
||||
}
|
||||
|
||||
return $this->back($request)->with($sent['failed'] > 0 ? 'error' : 'success', $message . '。');
|
||||
}
|
||||
|
||||
private function back(Request $request)
|
||||
{
|
||||
return redirect()->route('business.pages.show', array_filter([
|
||||
'company_id' => company_id(),
|
||||
'section' => 'planting-data',
|
||||
'page' => 'planting-reimbursement-workbench',
|
||||
'date' => (string) $request->input('date', ''),
|
||||
'paid_from' => (string) $request->input('paid_from', ''),
|
||||
'scope' => (string) $request->input('scope', ''),
|
||||
], static fn ($v) => $v !== ''));
|
||||
}
|
||||
}
|
||||
518
app/Http/Controllers/Business/ServiceCompanyReconciliation.php
Normal file
518
app/Http/Controllers/Business/ServiceCompanyReconciliation.php
Normal file
@ -0,0 +1,518 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Business\CompanyPlan\CompanyPlanRepository;
|
||||
use App\Business\ServiceCompanyReconciliation\ServiceCompanyReconciliationRepository;
|
||||
use App\Utilities\FinanceLedgerAccess;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\View\View;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
|
||||
class ServiceCompanyReconciliation extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ServiceCompanyReconciliationRepository $repository,
|
||||
private readonly CompanyPlanRepository $companyPlanRepository,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
}
|
||||
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$tenantId = (int) (company_id() ?: 1);
|
||||
$period = $this->period($request);
|
||||
$companyPlanSyncError = $this->syncCompanyPlan($tenantId);
|
||||
$serviceCompanies = $this->repository->serviceCompanies($tenantId, $period);
|
||||
|
||||
return view('business.pages.financial-operations.service-company-reconciliation', [
|
||||
'isDetail' => false,
|
||||
'period' => $period,
|
||||
'periodOptions' => $this->periodOptions(),
|
||||
'serviceCompanies' => $serviceCompanies,
|
||||
'serviceCompany' => null,
|
||||
'relations' => [],
|
||||
'settlements' => [],
|
||||
'assignedPeople' => [],
|
||||
'availablePeople' => [],
|
||||
'storeCompanies' => [],
|
||||
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
|
||||
'fixedFeeRatePercent' => null,
|
||||
'companyDirectory' => $this->repository->companyDirectory(),
|
||||
'companyPlanSyncError' => $companyPlanSyncError,
|
||||
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
|
||||
'summary' => [
|
||||
'companies' => count($serviceCompanies),
|
||||
'people' => array_sum(array_column($serviceCompanies, 'people_count')),
|
||||
'labor_cost' => array_sum(array_column($serviceCompanies, 'labor_cost')),
|
||||
'settlement_amount' => array_sum(array_column($serviceCompanies, 'settlement_amount')),
|
||||
'pending' => count(array_filter(
|
||||
$serviceCompanies,
|
||||
static fn (array $row): bool => in_array(
|
||||
$row['reconciliation_status'],
|
||||
['待生成', '待确认', '未配置'],
|
||||
true,
|
||||
),
|
||||
)),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(Request $request, int $serviceCompany): View
|
||||
{
|
||||
$tenantId = (int) (company_id() ?: 1);
|
||||
$companyPlanSyncError = $this->syncCompanyPlan($tenantId);
|
||||
$company = $this->repository->serviceCompany($tenantId, $serviceCompany);
|
||||
abort_if($company === null, 404);
|
||||
|
||||
$period = $this->period($request);
|
||||
$allRelations = $this->repository->relations($tenantId, $serviceCompany);
|
||||
$settlements = $this->repository->settlements($tenantId, $serviceCompany, $period);
|
||||
$storeCompanyIncome = $this->repository->storeCompanyIncome($tenantId, $period);
|
||||
$invoiceCompletion = $this->completionFilter($request, 'invoice_completion');
|
||||
$paymentCompletion = $this->completionFilter($request, 'payment_completion');
|
||||
$contractAttachments = $this->repository->contractAttachmentsForRelations(
|
||||
$tenantId,
|
||||
$serviceCompany,
|
||||
array_map(static fn (array $relation): int => (int) $relation['id'], $allRelations),
|
||||
);
|
||||
$relations = array_values(array_filter(
|
||||
$this->relationsWithSettlementState(
|
||||
$allRelations,
|
||||
$settlements,
|
||||
$contractAttachments,
|
||||
$storeCompanyIncome,
|
||||
),
|
||||
static function (array $relation) use ($invoiceCompletion, $paymentCompletion): bool {
|
||||
if ($invoiceCompletion === 'unfinished' && $paymentCompletion === 'unfinished') {
|
||||
return $relation['invoice_completion'] === 'unfinished'
|
||||
|| $relation['payment_completion'] === 'unfinished';
|
||||
}
|
||||
|
||||
return $relation['invoice_completion'] === $invoiceCompletion
|
||||
&& $relation['payment_completion'] === $paymentCompletion;
|
||||
},
|
||||
));
|
||||
$assignedPeople = $this->repository->assignedPeople($tenantId, $serviceCompany);
|
||||
$availablePeople = array_values($this->repository->availablePeople($tenantId));
|
||||
$periodStart = CarbonImmutable::createFromFormat('!Y-m', $period)->startOfMonth();
|
||||
$periodEnd = $periodStart->endOfMonth();
|
||||
$currentPersonKeys = array_column(
|
||||
array_filter($assignedPeople, static fn (array $row): bool => $row['is_current']),
|
||||
'person_key',
|
||||
);
|
||||
|
||||
return view('business.pages.financial-operations.service-company-reconciliation', [
|
||||
'isDetail' => true,
|
||||
'period' => $period,
|
||||
'periodOptions' => $this->periodOptions(),
|
||||
'serviceCompanies' => [],
|
||||
'serviceCompany' => $company,
|
||||
'relations' => $relations,
|
||||
'relationTotal' => count($allRelations),
|
||||
'invoiceCompletion' => $invoiceCompletion,
|
||||
'paymentCompletion' => $paymentCompletion,
|
||||
'settlements' => $settlements,
|
||||
'assignedPeople' => $assignedPeople,
|
||||
'availablePeople' => $availablePeople,
|
||||
'currentPersonKeys' => array_flip($currentPersonKeys),
|
||||
'storeCompanies' => $this->repository->storeCompanies($tenantId),
|
||||
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
|
||||
'fixedFeeRatePercent' => ServiceCompanyReconciliationRepository::fixedFeeRatePercent(
|
||||
(string) $company['service_type_code'],
|
||||
),
|
||||
'companyDirectory' => $this->repository->companyDirectory(),
|
||||
'companyPlanSyncError' => $companyPlanSyncError,
|
||||
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
|
||||
'summary' => [
|
||||
'people' => count($currentPersonKeys),
|
||||
'labor_cost' => array_sum(array_column(
|
||||
array_filter($assignedPeople, static fn (array $row): bool => $row['is_current']),
|
||||
'salary',
|
||||
)),
|
||||
'stores' => count(array_filter(
|
||||
$allRelations,
|
||||
static fn (array $row): bool => $row['status'] === 'active'
|
||||
&& $row['effective_from'] <= $periodEnd->toDateString()
|
||||
&& ($row['effective_to'] === null
|
||||
|| $row['effective_to'] >= $periodStart->toDateString()),
|
||||
)),
|
||||
'settlement_amount' => array_sum(array_column($settlements, 'service_fee')),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $relations
|
||||
* @param list<array<string,mixed>> $settlements
|
||||
* @param array<int,list<array<string,mixed>>> $contractAttachments
|
||||
* @param array<string,float> $storeCompanyIncome
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
private function relationsWithSettlementState(
|
||||
array $relations,
|
||||
array $settlements,
|
||||
array $contractAttachments,
|
||||
array $storeCompanyIncome,
|
||||
): array {
|
||||
$settlementsByRelation = [];
|
||||
foreach ($settlements as $settlement) {
|
||||
$key = (string) $settlement['store_company_key'] . '|' . (string) $settlement['service_type_code'];
|
||||
$settlementsByRelation[$key] = $settlement;
|
||||
}
|
||||
|
||||
return array_map(static function (array $relation) use (
|
||||
$settlementsByRelation,
|
||||
$contractAttachments,
|
||||
$storeCompanyIncome,
|
||||
): array {
|
||||
$key = (string) $relation['store_company_key'] . '|' . (string) $relation['service_type_code'];
|
||||
$settlement = $settlementsByRelation[$key] ?? null;
|
||||
$incomeAmount = (float) ($storeCompanyIncome[(string) $relation['store_company_key']] ?? 0);
|
||||
$calculatedSettlementAmount = round($incomeAmount * (float) $relation['fee_rate'], 2);
|
||||
$invoiceCompleted = $settlement !== null
|
||||
&& in_array((string) $settlement['invoice_status'], ['invoiced', 'waived'], true);
|
||||
$paymentCompleted = $settlement !== null
|
||||
&& (string) $settlement['payment_status'] === 'paid';
|
||||
|
||||
return [
|
||||
...$relation,
|
||||
'period_settlement_id' => $settlement['id'] ?? null,
|
||||
'income_amount' => $incomeAmount,
|
||||
'settlement_amount' => $settlement !== null
|
||||
? (float) $settlement['service_fee']
|
||||
: $calculatedSettlementAmount,
|
||||
'invoice_status' => $settlement['invoice_status'] ?? null,
|
||||
'payment_status' => $settlement['payment_status'] ?? null,
|
||||
'invoice_completion' => $invoiceCompleted ? 'completed' : 'unfinished',
|
||||
'payment_completion' => $paymentCompleted ? 'completed' : 'unfinished',
|
||||
'contract_attachments' => $contractAttachments[(int) $relation['id']] ?? [],
|
||||
];
|
||||
}, $relations);
|
||||
}
|
||||
|
||||
private function completionFilter(Request $request, string $key): string
|
||||
{
|
||||
$value = (string) $request->query($key, 'unfinished');
|
||||
|
||||
return in_array($value, ['completed', 'unfinished'], true) ? $value : 'unfinished';
|
||||
}
|
||||
|
||||
public function storeCompany(Request $request): RedirectResponse
|
||||
{
|
||||
$this->authorizeEdit();
|
||||
$validated = $this->validateCompany($request);
|
||||
$company = $this->repository->saveServiceCompany(
|
||||
(int) (company_id() ?: 1),
|
||||
$validated,
|
||||
(string) user()->name,
|
||||
);
|
||||
|
||||
return redirect()
|
||||
->route('business.service-company-reconciliation.show', [
|
||||
'serviceCompany' => $company['id'],
|
||||
])
|
||||
->with('success', '服务公司已登记。');
|
||||
}
|
||||
|
||||
public function updateCompany(Request $request, int $serviceCompany): RedirectResponse
|
||||
{
|
||||
$this->authorizeEdit();
|
||||
$validated = $this->validateCompany($request);
|
||||
$this->repository->saveServiceCompany(
|
||||
(int) (company_id() ?: 1),
|
||||
$validated,
|
||||
(string) user()->name,
|
||||
$serviceCompany,
|
||||
);
|
||||
|
||||
return back()->with('success', '服务公司信息已更新。');
|
||||
}
|
||||
|
||||
public function storeRelation(Request $request, int $serviceCompany): RedirectResponse
|
||||
{
|
||||
$this->authorizeEdit();
|
||||
$validated = $this->validateRelation($request);
|
||||
$this->repository->saveRelation(
|
||||
(int) (company_id() ?: 1),
|
||||
$serviceCompany,
|
||||
$validated,
|
||||
(string) user()->name,
|
||||
);
|
||||
|
||||
return back()->with('success', '店铺公司结算关系已保存。');
|
||||
}
|
||||
|
||||
public function updateRelation(
|
||||
Request $request,
|
||||
int $serviceCompany,
|
||||
int $relation,
|
||||
): RedirectResponse {
|
||||
$this->authorizeEdit();
|
||||
$validated = $this->validateRelation($request);
|
||||
$this->repository->saveRelation(
|
||||
(int) (company_id() ?: 1),
|
||||
$serviceCompany,
|
||||
$validated,
|
||||
(string) user()->name,
|
||||
$relation,
|
||||
);
|
||||
|
||||
return back()->with('success', '店铺公司结算关系已更新并生成新版本。');
|
||||
}
|
||||
|
||||
public function storeRelationAttachment(
|
||||
Request $request,
|
||||
int $serviceCompany,
|
||||
int $relation,
|
||||
): RedirectResponse {
|
||||
$this->authorizeEdit();
|
||||
$validated = $request->validate([
|
||||
'attachment' => ['required', 'file', 'mimes:pdf,jpg,jpeg,png,webp,doc,docx', 'max:20480'],
|
||||
'period' => ['required', 'date_format:Y-m'],
|
||||
'invoice_completion' => ['nullable', 'in:completed,unfinished'],
|
||||
'payment_completion' => ['nullable', 'in:completed,unfinished'],
|
||||
]);
|
||||
$tenantId = (int) (company_id() ?: 1);
|
||||
$file = $validated['attachment'];
|
||||
$originalName = mb_substr(basename((string) $file->getClientOriginalName()), 0, 255);
|
||||
$extension = strtolower((string) $file->getClientOriginalExtension());
|
||||
$disk = Storage::disk('uploads');
|
||||
$directory = sprintf(
|
||||
'service-company-contracts/%d/%d/%d',
|
||||
$tenantId,
|
||||
$serviceCompany,
|
||||
$relation,
|
||||
);
|
||||
$filename = Str::uuid()->toString() . ($extension !== '' ? '.' . $extension : '');
|
||||
$path = $disk->putFileAs($directory, $file, $filename);
|
||||
if (! is_string($path) || $path === '') {
|
||||
throw new \RuntimeException('合同附件保存失败,请稍后重试。');
|
||||
}
|
||||
|
||||
try {
|
||||
$this->repository->saveContractAttachment(
|
||||
$tenantId,
|
||||
$serviceCompany,
|
||||
$relation,
|
||||
[
|
||||
'original_name' => $originalName,
|
||||
'path' => $path,
|
||||
'mime_type' => $file->getMimeType() ?: 'application/octet-stream',
|
||||
'size' => (int) $file->getSize(),
|
||||
],
|
||||
(string) user()->name,
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$disk->delete($path);
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('business.service-company-reconciliation.show', [
|
||||
'serviceCompany' => $serviceCompany,
|
||||
'period' => $validated['period'],
|
||||
'tab' => 'relations',
|
||||
'invoice_completion' => $validated['invoice_completion'] ?? 'unfinished',
|
||||
'payment_completion' => $validated['payment_completion'] ?? 'unfinished',
|
||||
])
|
||||
->with('success', '合同附件已上传。');
|
||||
}
|
||||
|
||||
public function relationAttachment(
|
||||
int $serviceCompany,
|
||||
int $relation,
|
||||
int $attachment,
|
||||
): StreamedResponse {
|
||||
$tenantId = (int) (company_id() ?: 1);
|
||||
$file = $this->repository->contractAttachment(
|
||||
$tenantId,
|
||||
$serviceCompany,
|
||||
$relation,
|
||||
$attachment,
|
||||
);
|
||||
abort_if($file === null, 404);
|
||||
|
||||
$disk = Storage::disk('uploads');
|
||||
abort_unless($disk->exists((string) $file['path']), 404, '合同附件不存在。');
|
||||
|
||||
return $disk->response((string) $file['path'], (string) $file['original_name'], [
|
||||
'Cache-Control' => 'private, no-store',
|
||||
'Content-Type' => (string) ($file['mime_type'] ?: 'application/octet-stream'),
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
]);
|
||||
}
|
||||
|
||||
public function assignPerson(Request $request, int $serviceCompany): RedirectResponse
|
||||
{
|
||||
$this->authorizeEdit();
|
||||
$validated = $request->validate([
|
||||
'person_key' => ['required', 'string', 'max:191'],
|
||||
'effective_from' => ['required', 'date_format:Y-m-d'],
|
||||
]);
|
||||
$this->repository->assignPerson(
|
||||
(int) (company_id() ?: 1),
|
||||
$serviceCompany,
|
||||
$validated['person_key'],
|
||||
$validated['effective_from'],
|
||||
(string) user()->name,
|
||||
);
|
||||
|
||||
return back()->with('success', '人员归属已保存。');
|
||||
}
|
||||
|
||||
public function endPerson(Request $request, int $serviceCompany, int $assignment): RedirectResponse
|
||||
{
|
||||
$this->authorizeEdit();
|
||||
$validated = $request->validate([
|
||||
'effective_to' => ['required', 'date_format:Y-m-d'],
|
||||
]);
|
||||
$this->repository->endPersonAssignment(
|
||||
(int) (company_id() ?: 1),
|
||||
$serviceCompany,
|
||||
$assignment,
|
||||
$validated['effective_to'],
|
||||
);
|
||||
|
||||
return back()->with('success', '人员归属已结束。');
|
||||
}
|
||||
|
||||
public function generateSettlements(Request $request, int $serviceCompany): RedirectResponse
|
||||
{
|
||||
$this->authorizeEdit();
|
||||
$validated = $request->validate([
|
||||
'period' => ['required', 'date_format:Y-m'],
|
||||
]);
|
||||
$result = $this->repository->generateSettlements(
|
||||
(int) (company_id() ?: 1),
|
||||
$serviceCompany,
|
||||
$validated['period'],
|
||||
(string) user()->name,
|
||||
);
|
||||
|
||||
$message = "已生成 {$result['generated']} 条结算预览。";
|
||||
if ($result['errors'] !== []) {
|
||||
$message .= ' 未生成:' . implode(';', array_slice($result['errors'], 0, 5));
|
||||
}
|
||||
|
||||
return redirect()
|
||||
->route('business.service-company-reconciliation.show', [
|
||||
'serviceCompany' => $serviceCompany,
|
||||
'period' => $validated['period'],
|
||||
'tab' => 'relations',
|
||||
])
|
||||
->with($result['generated'] > 0 ? 'success' : 'error', $message);
|
||||
}
|
||||
|
||||
public function updateSettlement(
|
||||
Request $request,
|
||||
int $serviceCompany,
|
||||
int $settlement,
|
||||
): RedirectResponse {
|
||||
$this->authorizeEdit();
|
||||
$validated = $request->validate([
|
||||
'action' => ['nullable', 'in:confirm,save'],
|
||||
'invoice_status' => ['nullable', 'in:pending,partial,invoiced,waived'],
|
||||
'invoice_amount' => ['nullable', 'numeric', 'min:0'],
|
||||
'payment_status' => ['nullable', 'in:pending,partial,paid'],
|
||||
'paid_amount' => ['nullable', 'numeric', 'min:0'],
|
||||
'notes' => ['nullable', 'string', 'max:1000'],
|
||||
]);
|
||||
$this->repository->updateSettlement(
|
||||
(int) (company_id() ?: 1),
|
||||
$serviceCompany,
|
||||
$settlement,
|
||||
$validated,
|
||||
(string) user()->name,
|
||||
);
|
||||
|
||||
return back()->with('success', '开票与到账状态已更新。');
|
||||
}
|
||||
|
||||
private function period(Request $request): string
|
||||
{
|
||||
$period = trim((string) $request->query('period', ''));
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1) {
|
||||
return $period;
|
||||
}
|
||||
|
||||
return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
|
||||
}
|
||||
|
||||
/** @return list<array{value:string,label:string}> */
|
||||
private function periodOptions(): array
|
||||
{
|
||||
$current = CarbonImmutable::now()->startOfMonth();
|
||||
|
||||
return collect(range(0, 11))->map(static function (int $monthsAgo) use ($current): array {
|
||||
$month = $current->subMonthsNoOverflow($monthsAgo);
|
||||
|
||||
return [
|
||||
'value' => $month->format('Y-m'),
|
||||
'label' => $month->format('Y年n月'),
|
||||
];
|
||||
})->all();
|
||||
}
|
||||
|
||||
private function authorizeEdit(): void
|
||||
{
|
||||
abort_unless(FinanceLedgerAccess::canEditMapping(user()), 403, '当前账号没有维护服务公司对账的权限。');
|
||||
}
|
||||
|
||||
private function syncCompanyPlan(int $tenantId): ?string
|
||||
{
|
||||
try {
|
||||
$rows = $this->companyPlanRepository->serviceCompanyRows($tenantId);
|
||||
$this->repository->syncCompanyPlanServiceCompanies($tenantId, $rows);
|
||||
|
||||
return null;
|
||||
} catch (\Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return '公司盘点服务公司同步暂时失败,当前先显示已登记的服务公司。';
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function validateCompany(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'company_name' => ['required', 'string', 'max:200'],
|
||||
'unified_social_credit_code' => ['nullable', 'string', 'max:64'],
|
||||
'service_type_code' => ['required', 'in:' . implode(',', array_keys(
|
||||
ServiceCompanyReconciliationRepository::SERVICE_TYPES,
|
||||
))],
|
||||
'taxpayer_type' => ['nullable', 'string', 'max:64'],
|
||||
'business_registration_type' => ['nullable', 'string', 'max:64'],
|
||||
'company_status' => ['nullable', 'in:正常,注销中,已注销'],
|
||||
'planning_target_amount' => ['nullable', 'numeric', 'min:0'],
|
||||
'status' => ['required', 'in:active,inactive'],
|
||||
'notes' => ['nullable', 'string', 'max:500'],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function validateRelation(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'store_company_key' => ['required', 'string', 'max:191'],
|
||||
'base_metric' => ['required', 'in:' . implode(',', array_keys(
|
||||
ServiceCompanyReconciliationRepository::BASE_METRICS,
|
||||
))],
|
||||
'fee_rate_percent' => ['required', 'numeric', 'min:0', 'max:100'],
|
||||
'effective_from' => ['required', 'date_format:Y-m-d'],
|
||||
'effective_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:effective_from'],
|
||||
'contract_no' => ['nullable', 'string', 'max:64'],
|
||||
'contract_status' => ['required', 'in:pending,stamped,waived'],
|
||||
'status' => ['required', 'in:active,inactive'],
|
||||
'notes' => ['nullable', 'string', 'max:500'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
26
app/Http/Controllers/Business/ShippingMeasuredWeights.php
Normal file
26
app/Http/Controllers/Business/ShippingMeasuredWeights.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Modules\EcommerceFinance\Services\ShippingMeasuredWeightImporter;
|
||||
|
||||
class ShippingMeasuredWeights extends Controller
|
||||
{
|
||||
public function import(Request $request, ShippingMeasuredWeightImporter $importer): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'measured_weight_file' => ['required', 'file', 'mimes:xlsx', 'max:10240'],
|
||||
], [], ['measured_weight_file' => '称重重量表']);
|
||||
|
||||
$result = $importer->import(
|
||||
$request->file('measured_weight_file')->getRealPath(),
|
||||
(int) company_id(),
|
||||
(int) $request->user()->id,
|
||||
);
|
||||
|
||||
return back()->with('shipping_measured_weight_message', "已读取 {$result['source_rows']} 行,保存 {$result['keys']} 条快递和条码的称重重量记录。");
|
||||
}
|
||||
}
|
||||
@ -7,6 +7,8 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Modules\EcommerceFinance\Services\SupplierNegativeAlertDingTalkWorkflow;
|
||||
use Modules\EcommerceFinance\View\SupplierNegativeAlertPageData;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
|
||||
class SupplierNegativeAlertDingTalkActions extends Controller
|
||||
@ -44,6 +46,7 @@ class SupplierNegativeAlertDingTalkActions extends Controller
|
||||
'supplier' => ['nullable', 'string', 'max:191'],
|
||||
'checker' => ['nullable', 'string', 'max:191'],
|
||||
'settlement_method' => ['nullable', 'string', 'max:191'],
|
||||
'handling' => ['nullable', 'in:,pending'],
|
||||
]);
|
||||
$purchaser = trim((string) ($data['purchaser'] ?? ''));
|
||||
$filters = [
|
||||
@ -52,6 +55,7 @@ class SupplierNegativeAlertDingTalkActions extends Controller
|
||||
'checker' => (string) ($data['checker'] ?? ''),
|
||||
'settlement_method' => (string) ($data['settlement_method'] ?? ''),
|
||||
'purchaser' => $purchaser,
|
||||
'handling' => (string) ($data['handling'] ?? ''),
|
||||
];
|
||||
$filteredRows = $this->pageData->rowsForFilters([
|
||||
...$filters,
|
||||
@ -113,4 +117,64 @@ class SupplierNegativeAlertDingTalkActions extends Controller
|
||||
return back()->with('success', "已发送至{$result['group_name']}:采购 {$purchaser},"
|
||||
. "{$result['supplier_count']} 家供应商、{$result['row_count']} 条预警。");
|
||||
}
|
||||
|
||||
public function export(Request $request): StreamedResponse
|
||||
{
|
||||
$data = $this->pageData->exportData($request->query());
|
||||
$fields = array_values(array_filter(
|
||||
(array) ($data['fields'] ?? []),
|
||||
static fn (array $field): bool => ($field['name'] ?? '') !== 'company',
|
||||
));
|
||||
$fields[] = ['name' => 'handling_result_meta', 'label' => '回传信息', 'type' => 'text'];
|
||||
$rows = (array) ($data['rows'] ?? []);
|
||||
$filters = (array) ($data['filters'] ?? []);
|
||||
$period = trim((string) ($filters['month'] ?? '')) ?: '全部月份';
|
||||
$filename = '供应商负数预警_' . $period . '_' . now()->format('Ymd_His') . '.csv';
|
||||
|
||||
return response()->streamDownload(function () use ($fields, $rows): void {
|
||||
$stream = fopen('php://output', 'w');
|
||||
if ($stream === false) {
|
||||
throw new RuntimeException('无法创建供应商负数预警导出文件。');
|
||||
}
|
||||
|
||||
fwrite($stream, "\xEF\xBB\xBF");
|
||||
fputcsv($stream, array_map(
|
||||
static fn (array $field): string => (string) ($field['label'] ?? ''),
|
||||
$fields,
|
||||
));
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$values = [];
|
||||
foreach ($fields as $field) {
|
||||
$name = (string) ($field['name'] ?? '');
|
||||
$value = $row[$name] ?? '';
|
||||
if ($name === 'handling_result' && trim((string) $value) === '') {
|
||||
$value = '采购未回传';
|
||||
} elseif (is_array($value)) {
|
||||
$value = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
$values[] = $this->csvCell($value);
|
||||
}
|
||||
fputcsv($stream, $values);
|
||||
}
|
||||
|
||||
fclose($stream);
|
||||
}, $filename, [
|
||||
'Content-Type' => 'text/csv; charset=UTF-8',
|
||||
'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
|
||||
private function csvCell(mixed $value): string
|
||||
{
|
||||
$text = trim((string) $value);
|
||||
if ($text === '' || is_numeric($text)) {
|
||||
return $text;
|
||||
}
|
||||
if (preg_match('/^\d{12,}$/', $text) === 1) {
|
||||
return "'" . $text;
|
||||
}
|
||||
|
||||
return preg_match('/^[=+@\t\r]/u', $text) === 1 ? "'" . $text : $text;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user