Compare commits

..

9 Commits

Author SHA1 Message Date
j.jiang
f8c594c3de merge: 同步线上最新 main (#640) 2026-10-26 19:58:14 +08:00
j.jiang
49489a59d0 merge: 同步线上最新 main (#633) 后发布 2026-10-26 19:39:18 +08:00
j.jiang
49c692b4d6 chore: 移除调试临时文件(会话 cookie 不应入库) 2026-10-26 17:57:35 +08:00
j.jiang
b53b077deb merge: 带上筛选栏网格修复 2026-10-26 17:57:28 +08:00
j.jiang
56391d4e81 merge: 同步 main 到性能分支(部署前对齐) 2026-10-26 17:57:21 +08:00
j.jiang
c898308f18 fix: 恢复报表筛选栏网格布局(#602 精简样式导致字段整行堆叠)
#602 把 .installation-filter-bar 的 display/grid-template-columns 移到了
安装明细页专用的 .installation-filter-primary / .installation-filter-time /
.installation-filter-actions 内部容器,但店铺维度报表、业绩明细、进销存报表、
入库明细四个页面仍直接以 .installation-filter-field 作为栅格项,失去网格后
每个筛选项各占一整行,查询/清除按钮被挤到最右下角。

新增 .installation-filter-bar--grid 修饰类,恢复四列栅格(1100px 两列、
650px 单列)与左对齐操作区,并只应用到上述四个直接使用字段栅格的表单;
安装明细页使用内部容器排版,不受影响。
2026-10-26 17:52:33 +08:00
j.jiang
6cbfe27afc fix: 物化状态同时校验空值,兼容尚未部署新代码的同步任务
状态表标记已物化、但旧版本同步代码重刷账期时不写物化列,会留下 NULL
导致页面把未物化行当成 0 差额。现在读取状态时同时检查该账期是否还有
has_difference 为 NULL 的行,有则回退实时规则表达式(缓存 10 分钟)。
2026-10-26 17:36:20 +08:00
j.jiang
089c2dd603 perf: 补业绩明细排序索引,回填后页面热缓存 24ms
- 新增 (report_month, occurred_date, store_name, online_order_no) 索引,
  默认列表不再对整月 32 万行做 filesort;
- 文档补充共享库回填实测数据(91.7 万行回填 5.9 分钟,三项一致性差异 0;
  联动统计 84.9 秒 → 冷 1.7 秒 / 热 2 毫秒,页面 7.7 秒 → 冷 1.7 秒 / 热 24 毫秒)。
2026-10-26 17:31:51 +08:00
j.jiang
4ea833d0d8 perf: 业绩明细差额规则落库,切月份统计从数十秒降到亚秒级
业绩明细页的「差额合计」「差额异常备注」「差额(有/无)」原先都在查询时
逐行现算同一套规则链(生成 SQL 24KB/50KB,含 36 处 ops_jst_orders 关联
子查询)。整月 32.4 万行实测:联动统计 14.5~41.6 秒,页面主体 2.7~4.6 秒。

- 新增物化列 difference_reason_index / base_difference / has_difference,
  以及 (report_month, difference_reason_index)、(report_month, has_difference)、
  (report_month, store_name, platform) 三个索引和物化状态表;
- 新增 store-receipt:materialize-differences 命令(分批写入、支持 --dry-run
  三项一致性校验,默认连带重算相邻月份以覆盖跨月备注);
- store-receipt:order-match:sync 成功后自动物化(--skip-materialize 可关闭);
- 页面聚合、联动统计、备注/差额筛选改读物化列,规则指纹不匹配或未物化时
  自动回退实时表达式,功能不受影响;
- 月份下拉缓存 6 小时、指标卡聚合 5 分钟、联动统计 1 小时,缓存键带规则
  指纹、物化状态与数据版本,物化后自动失效;
- 前端联动统计改为展开下拉时按需请求,页面加载不再同步统计整月。

规则表达式仍以 Pages 的静态方法为唯一口径,物化命令直接复用,不在 PHP 中
重写规则。本地用 7,907 行副本验证:三项一致性差异为 0,数字与实时口径完全
一致;联动统计 76ms→21ms、页面 56ms→41ms(同一数据)。详见
docs/业绩明细差额物化.md。
2026-10-26 16:36:13 +08:00
1333 changed files with 8139 additions and 264973 deletions

View File

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

View File

@ -1,6 +1,6 @@
# ============================================================
# 聚水潭开放平台接入 —— caiwu 直连发货数据和店铺级推广费
# 凭据写入 runtime/.env(勿提交 Git)。
# 聚水潭(聚石塔 / 奇门)开放平台接入 —— caiwu 直连发货数据
# 复用工作平台现有授权。把下列键补进 runtime/.env(勿提交 Git)。
# 值留空时同步器会安全拒绝请求,不会误拉。
# ============================================================
@ -12,24 +12,6 @@ JST_APP_KEY=
JST_APP_SECRET=
JST_CUSTOMER_ID=
# 聚水潭新开放平台(胜算收费接口:获取胜算店铺级推广费)
# 与上面的奇门 JST_* 以及经典接口 JUSHUITAN_PARTNER_* 不是同一套凭据。
JUSHUITAN_OPEN_API_BASE_URL=https://openapi.jushuitan.com
JUSHUITAN_APP_KEY=
JUSHUITAN_APP_SECRET=
JUSHUITAN_ACCESS_TOKEN=
JUSHUITAN_SHOP_PROMOTION_FEE_HISTORY_START=2026-01-01
JUSHUITAN_SHOP_PROMOTION_FEE_OVERLAP_DAYS=7
JUSHUITAN_SHOP_PROMOTION_FEE_PAGE_SIZE=100
JUSHUITAN_SHOP_PROMOTION_FEE_MAX_PAGES=500
# 胜算“平台资金账户余额”固定账号(仅生产服务器私有 runtime/.env)
# 自动补齐拼多多新店首次账单月份的期初余额。
JUSHUITAN_ERP_ACCOUNT=
JUSHUITAN_ERP_PASSWORD=
# 可选,逗号分隔的财务系统用户 ID;为空时通知 super_admin。
JUSHUITAN_PDD_OPENING_ALERT_USER_IDS=
# 奇门固定参数(一般无需改)
JST_API_VERSION=2
JST_FORMAT=json

1
.gitignore vendored
View File

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

View File

@ -173,7 +173,7 @@
"refersTo": "button-primary",
"description": "浅色内容区的主要操作,使用可读深金而不是亮金。",
"html": "<button type=\"button\" class=\"ds-btn-primary\">查询</button>",
"css": ".ds-btn-primary { height: 34px; padding: 0 14px; border: 1px solid #856632; border-radius: 8px; background: #856632; color: #fff; font: 500 13px/1.5 'JetBrains Mono', 'CaiWu CJK', monospace; cursor: pointer; transition: background 150ms cubic-bezier(.22,1,.36,1), border-color 150ms cubic-bezier(.22,1,.36,1); } .ds-btn-primary:hover { background: #6A5129; border-color: #6A5129; } .ds-btn-primary:focus-visible { outline: none; box-shadow: 0 0 0 3px rgba(133,102,50,.20); } .ds-btn-primary:active { transform: translateY(1px); } .ds-btn-primary:disabled { opacity: .55; cursor: not-allowed; transform: none; }"
"css": ".ds-btn-primary { height: 34px; padding: 0 14px; border: 1px solid #856632; border-radius: 8px; background: #856632; color: #fff; font: 500 13px/1.5 'JetBrains Mono', 'Microsoft YaHei', monospace; cursor: pointer; transition: background 150ms cubic-bezier(.22,1,.36,1), border-color 150ms cubic-bezier(.22,1,.36,1); } .ds-btn-primary:hover { background: #6A5129; border-color: #6A5129; } .ds-btn-primary:focus-visible { outline: none; box-shadow: 0 0 0 3px rgba(133,102,50,.20); } .ds-btn-primary:active { transform: translateY(1px); } .ds-btn-primary:disabled { opacity: .55; cursor: not-allowed; transform: none; }"
},
{
"name": "Secondary Button",
@ -181,7 +181,7 @@
"refersTo": "button-secondary",
"description": "次要操作保持白底、暖灰边界和正文墨色。",
"html": "<button type=\"button\" class=\"ds-btn-secondary\">重置</button>",
"css": ".ds-btn-secondary { height: 34px; padding: 0 14px; border: 1px solid #D8D2C7; border-radius: 8px; background: #fff; color: #171717; font: 500 13px/1.5 'JetBrains Mono', 'CaiWu CJK', monospace; cursor: pointer; transition: background 150ms cubic-bezier(.22,1,.36,1), border-color 150ms cubic-bezier(.22,1,.36,1); } .ds-btn-secondary:hover { border-color: #A17D3E; background: #FBF8F1; } .ds-btn-secondary:focus-visible { outline: none; box-shadow: 0 0 0 3px rgba(133,102,50,.20); } .ds-btn-secondary:active { background: #F7F0DE; } .ds-btn-secondary:disabled { opacity: .55; cursor: not-allowed; }"
"css": ".ds-btn-secondary { height: 34px; padding: 0 14px; border: 1px solid #D8D2C7; border-radius: 8px; background: #fff; color: #171717; font: 500 13px/1.5 'JetBrains Mono', 'Microsoft YaHei', monospace; cursor: pointer; transition: background 150ms cubic-bezier(.22,1,.36,1), border-color 150ms cubic-bezier(.22,1,.36,1); } .ds-btn-secondary:hover { border-color: #A17D3E; background: #FBF8F1; } .ds-btn-secondary:focus-visible { outline: none; box-shadow: 0 0 0 3px rgba(133,102,50,.20); } .ds-btn-secondary:active { background: #F7F0DE; } .ds-btn-secondary:disabled { opacity: .55; cursor: not-allowed; }"
},
{
"name": "Text Field",
@ -189,7 +189,7 @@
"refersTo": "input-default",
"description": "紧凑、清晰、具有可见标签和深金焦点状态的业务输入框。",
"html": "<label class=\"ds-field\"><span class=\"ds-field-label\">订单号</span><input class=\"ds-field-input\" type=\"text\" placeholder=\"请输入订单号\"></label>",
"css": ".ds-field { display: inline-flex; min-width: 220px; flex-direction: column; gap: 5px; color: #171717; font-family: 'JetBrains Mono', 'CaiWu CJK', monospace; } .ds-field-label { color: #595959; font-size: 12px; font-weight: 500; line-height: 16px; } .ds-field-input { height: 34px; padding: 0 10px; border: 1px solid #D8D2C7; border-radius: 8px; background: #fff; color: #171717; font: 400 13px/1.5 inherit; outline: none; transition: border-color 150ms cubic-bezier(.22,1,.36,1), box-shadow 150ms cubic-bezier(.22,1,.36,1); } .ds-field-input::placeholder { color: #595959; } .ds-field-input:hover { border-color: #AFA99E; } .ds-field-input:focus { border-color: #856632; box-shadow: 0 0 0 3px rgba(133,102,50,.20); } .ds-field-input:disabled { background: #EEE9DF; color: #595959; cursor: not-allowed; }"
"css": ".ds-field { display: inline-flex; min-width: 220px; flex-direction: column; gap: 5px; color: #171717; font-family: 'JetBrains Mono', 'Microsoft YaHei', monospace; } .ds-field-label { color: #595959; font-size: 12px; font-weight: 500; line-height: 16px; } .ds-field-input { height: 34px; padding: 0 10px; border: 1px solid #D8D2C7; border-radius: 8px; background: #fff; color: #171717; font: 400 13px/1.5 inherit; outline: none; transition: border-color 150ms cubic-bezier(.22,1,.36,1), box-shadow 150ms cubic-bezier(.22,1,.36,1); } .ds-field-input::placeholder { color: #595959; } .ds-field-input:hover { border-color: #AFA99E; } .ds-field-input:focus { border-color: #856632; box-shadow: 0 0 0 3px rgba(133,102,50,.20); } .ds-field-input:disabled { background: #EEE9DF; color: #595959; cursor: not-allowed; }"
},
{
"name": "Sidebar Active Item",
@ -197,7 +197,7 @@
"refersTo": "sidebar-item-active",
"description": "浅黑功能栏上的单一圆形 chevron 活动状态。",
"html": "<div class=\"ds-sidebar\"><a class=\"ds-sidebar-item is-active\" href=\"#\"><svg class=\"ds-sidebar-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 4h16v16H4zM8 9h8M8 13h8M8 17h5\"/></svg><span>店铺收款账户账单</span><span class=\"ds-active-indicator\" aria-hidden=\"true\">›</span></a></div>",
"css": ".ds-sidebar { width: 224px; padding: 8px; background: #1D1D1F; } .ds-sidebar-item { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border-radius: 4px; color: #F0E4BF; font: 500 12px/16px 'JetBrains Mono', 'CaiWu CJK', monospace; text-decoration: none; transition: background 150ms cubic-bezier(.22,1,.36,1); } .ds-sidebar-item:hover { background: rgba(240,228,191,.10); } .ds-sidebar-item.is-active { background: #2A2927; color: #F2E7C5; } .ds-sidebar-icon { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; } .ds-active-indicator { display: inline-flex; width: 16px; height: 16px; margin-left: auto; align-items: center; justify-content: center; border: 1px solid rgba(246,233,194,.72); border-radius: 999px; background: rgba(246,233,194,.14); color: #F6E9C2; font-size: 14px; } .ds-sidebar-item:focus-visible { outline: 2px solid #F2E7C5; outline-offset: 2px; }"
"css": ".ds-sidebar { width: 224px; padding: 8px; background: #1D1D1F; } .ds-sidebar-item { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border-radius: 4px; color: #F0E4BF; font: 500 12px/16px 'JetBrains Mono', 'Microsoft YaHei', monospace; text-decoration: none; transition: background 150ms cubic-bezier(.22,1,.36,1); } .ds-sidebar-item:hover { background: rgba(240,228,191,.10); } .ds-sidebar-item.is-active { background: #2A2927; color: #F2E7C5; } .ds-sidebar-icon { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; } .ds-active-indicator { display: inline-flex; width: 16px; height: 16px; margin-left: auto; align-items: center; justify-content: center; border: 1px solid rgba(246,233,194,.72); border-radius: 999px; background: rgba(246,233,194,.14); color: #F6E9C2; font-size: 14px; } .ds-sidebar-item:focus-visible { outline: 2px solid #F2E7C5; outline-offset: 2px; }"
},
{
"name": "Workspace Tabs",
@ -205,7 +205,7 @@
"refersTo": "tab-active",
"description": "白色工作区内使用深金活动文字和单一金色下划线的局部标签切换。",
"html": "<nav class=\"ds-tabs\" aria-label=\"账户类型\"><a class=\"ds-tab is-active\" aria-current=\"page\" href=\"#\">淘系支付宝账户</a><a class=\"ds-tab\" href=\"#\">淘系微信账户</a></nav>",
"css": ".ds-tabs { display: flex; align-items: center; gap: 36px; min-height: 34px; padding: 0 32px; overflow-x: auto; border: 1px solid #D8D2C7; border-radius: 16px; background: #fff; } .ds-tab { position: relative; display: inline-flex; min-height: 34px; align-items: center; color: #595959; font: 600 14px/1.25 'JetBrains Mono', 'CaiWu CJK', monospace; text-decoration: none; white-space: nowrap; transition: color 150ms cubic-bezier(.22,1,.36,1); } .ds-tab:hover, .ds-tab.is-active { color: #856632; } .ds-tab.is-active::after { position: absolute; right: 0; bottom: 0; left: 0; height: 3px; border-radius: 999px 999px 0 0; background: #B9954F; content: ''; } .ds-tab:focus-visible { outline: 2px solid #856632; outline-offset: 3px; }"
"css": ".ds-tabs { display: flex; align-items: center; gap: 36px; min-height: 34px; padding: 0 32px; overflow-x: auto; border: 1px solid #D8D2C7; border-radius: 16px; background: #fff; } .ds-tab { position: relative; display: inline-flex; min-height: 34px; align-items: center; color: #595959; font: 600 14px/1.25 'JetBrains Mono', 'Microsoft YaHei', monospace; text-decoration: none; white-space: nowrap; transition: color 150ms cubic-bezier(.22,1,.36,1); } .ds-tab:hover, .ds-tab.is-active { color: #856632; } .ds-tab.is-active::after { position: absolute; right: 0; bottom: 0; left: 0; height: 3px; border-radius: 999px 999px 0 0; background: #B9954F; content: ''; } .ds-tab:focus-visible { outline: 2px solid #856632; outline-offset: 3px; }"
},
{
"name": "Business Panel",
@ -213,21 +213,21 @@
"refersTo": "panel",
"description": "使用白色表面、暖灰边界和有限圆角的单层业务容器。",
"html": "<section class=\"ds-panel\"><h2 class=\"ds-panel-title\">账单明细</h2><p class=\"ds-panel-copy\">按账户和日期范围核对交易数据。</p></section>",
"css": ".ds-panel { padding: 16px; border: 1px solid #D8D2C7; border-radius: 12px; background: #fff; color: #171717; font-family: 'JetBrains Mono', 'CaiWu CJK', monospace; } .ds-panel-title { margin: 0; color: #171717; font-size: 14px; font-weight: 600; line-height: 1.25; } .ds-panel-copy { max-width: 70ch; margin: 8px 0 0; color: #595959; font-size: 13px; line-height: 1.5; } .ds-panel:focus-within { border-color: #856632; }"
"css": ".ds-panel { padding: 16px; border: 1px solid #D8D2C7; border-radius: 12px; background: #fff; color: #171717; font-family: 'JetBrains Mono', 'Microsoft YaHei', monospace; } .ds-panel-title { margin: 0; color: #171717; font-size: 14px; font-weight: 600; line-height: 1.25; } .ds-panel-copy { max-width: 70ch; margin: 8px 0 0; color: #595959; font-size: 13px; line-height: 1.5; } .ds-panel:focus-within { border-color: #856632; }"
},
{
"name": "Status Tags",
"kind": "chip",
"description": "语义颜色只表达真实业务状态,并始终带文字。",
"html": "<div class=\"ds-tags\"><span class=\"ds-tag ds-tag-success\">已核对</span><span class=\"ds-tag ds-tag-warning\">待处理</span><span class=\"ds-tag ds-tag-danger\">异常</span></div>",
"css": ".ds-tags { display: flex; gap: 8px; font-family: 'JetBrains Mono', 'CaiWu CJK', monospace; } .ds-tag { display: inline-flex; min-height: 24px; align-items: center; padding: 2px 8px; border-radius: 999px; font-size: 12px; font-weight: 500; } .ds-tag-success { background: #F1F6EE; color: #53793E; } .ds-tag-warning { background: #FEF5E7; color: #935F07; } .ds-tag-danger { background: #FAE6E6; color: #B80000; }"
"css": ".ds-tags { display: flex; gap: 8px; font-family: 'JetBrains Mono', 'Microsoft YaHei', monospace; } .ds-tag { display: inline-flex; min-height: 24px; align-items: center; padding: 2px 8px; border-radius: 999px; font-size: 12px; font-weight: 500; } .ds-tag-success { background: #F1F6EE; color: #53793E; } .ds-tag-warning { background: #FEF5E7; color: #935F07; } .ds-tag-danger { background: #FAE6E6; color: #B80000; }"
},
{
"name": "Finance Data Table",
"kind": "custom",
"description": "紧凑、可扫描、数字右对齐的财务数据表。支持列显示/隐藏、拖动排序、恢复默认及按用户和具体表格保存;冻结多层表头,横向滚动条始终可达。导出明确筛选范围和可见列顺序,保留精度并排除密码;允许导入的业务提供模板、预览、校验及失败反馈,只读镜像不写回。",
"html": "<table class=\"ds-table\"><thead><tr><th>订单号</th><th class=\"ds-num\">收入</th><th class=\"ds-num\">余额</th></tr></thead><tbody><tr><td>20260722001</td><td class=\"ds-num ds-income\">¥1,280.00</td><td class=\"ds-num\">¥8,460.00</td></tr></tbody></table>",
"css": ".ds-table { width: 100%; border-collapse: collapse; overflow: hidden; border: 1px solid #D8D2C7; border-radius: 12px; background: #fff; color: #171717; font: 400 12.5px/1.5 'JetBrains Mono', 'CaiWu CJK', monospace; } .ds-table th { padding: 9px 10px; border-bottom: 1px solid #D8D2C7; background: #FBF8F1; color: #595959; font-size: 12px; font-weight: 600; text-align: left; } .ds-table td { padding: 9px 10px; border-bottom: 1px solid #EEE9DF; } .ds-table tbody tr:hover { background: #F7F0DE; } .ds-table .ds-num { text-align: right; font-variant-numeric: tabular-nums; } .ds-table .ds-income { color: #B80000; font-weight: 600; }"
"css": ".ds-table { width: 100%; border-collapse: collapse; overflow: hidden; border: 1px solid #D8D2C7; border-radius: 12px; background: #fff; color: #171717; font: 400 12.5px/1.5 'JetBrains Mono', 'Microsoft YaHei', monospace; } .ds-table th { padding: 9px 10px; border-bottom: 1px solid #D8D2C7; background: #FBF8F1; color: #595959; font-size: 12px; font-weight: 600; text-align: left; } .ds-table td { padding: 9px 10px; border-bottom: 1px solid #EEE9DF; } .ds-table tbody tr:hover { background: #F7F0DE; } .ds-table .ds-num { text-align: right; font-variant-numeric: tabular-nums; } .ds-table .ds-income { color: #B80000; font-weight: 600; }"
}
],
"narrative": {
@ -236,7 +236,7 @@
"keyCharacteristics": [
"深黑工具轨道、浅黑功能栏、浅色内容区,三层边界清楚。",
"浅金用于深色导航,深金用于浅色内容区的文字与主要操作。",
"全站使用 JetBrains Mono 与仓库内置 CaiWu CJK 字体,标题和数据采用固定字号,不使用流体放大。",
"全站使用 JetBrains Mono,标题和数据采用固定字号,不使用流体放大。",
"页面标题位于内容区右侧,保持 14px;导航使用统一的紧凑字号。",
"一、二级导航统一 12px;同一层级的图标、字号和交互状态必须一致。",
"表格、筛选器和状态反馈优先,装饰性卡片、阴影和动画受到严格限制。",
@ -250,7 +250,6 @@
{ "name": "The Fixed-Scale Rule", "body": "产品界面使用固定 rem 字号,不使用 clamp() 放大标题;桌面与移动端通过布局重排适配,不通过夸张缩放字体适配。", "section": "typography" },
{ "name": "The Stable-First-Paint Rule", "body": "关键字号、行高和容器尺寸必须由首屏 CSS 直接提供,不能等待 JavaScript 或异步样式后再缩小,禁止首次进入时出现巨大字体闪烁。", "section": "typography" },
{ "name": "The One-Family Rule", "body": "按钮、标签、导航、表格和正文都使用同一字体家族;禁止在数据界面引入装饰性展示字体。", "section": "typography" },
{ "name": "The Cross-Platform Control Rule", "body": "业务控件不得依赖 macOS、Windows 或不同浏览器的原生外观。字体使用仓库内置 Web 字体;下拉框、复选框、日期选择、联想输入使用项目自绘控件;桌面筛选区使用明确 CSS 网格。新页面必须在 Safari 与 Chromium 下验证布局、换行和控件尺寸一致。", "section": "typography" },
{ "name": "The Flat-by-Default Rule", "body": "静态业务面板默认无阴影;若已经有 1px 边框,不得再叠加 16px 以上模糊半径的宽阴影。", "section": "elevation" },
{ "name": "The No-Nested-Cards Rule", "body": "卡片只用于真实分组;卡片内部不能再套同样外观的卡片。优先使用标题、间距、分隔线和表格分组表达层级。", "section": "elevation" }
],

View File

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

View File

@ -22,22 +22,22 @@ colors:
info: "#006395"
typography:
title:
fontFamily: "JetBrains Mono, CaiWu CJK, monospace"
fontFamily: "JetBrains Mono, Microsoft YaHei, PingFang SC, monospace"
fontSize: "0.875rem"
fontWeight: 600
lineHeight: 1.25
body:
fontFamily: "JetBrains Mono, CaiWu CJK, monospace"
fontFamily: "JetBrains Mono, Microsoft YaHei, PingFang SC, monospace"
fontSize: "0.8125rem"
fontWeight: 400
lineHeight: 1.5
label:
fontFamily: "JetBrains Mono, CaiWu CJK, monospace"
fontFamily: "JetBrains Mono, Microsoft YaHei, PingFang SC, monospace"
fontSize: "0.75rem"
fontWeight: 500
lineHeight: 1.333
data:
fontFamily: "JetBrains Mono, CaiWu CJK, monospace"
fontFamily: "JetBrains Mono, Microsoft YaHei, PingFang SC, monospace"
fontSize: "0.78125rem"
fontWeight: 400
lineHeight: 1.5
@ -180,9 +180,9 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视
## 3. Typography
**Display Font:** JetBrains Mono (with bundled CaiWu CJK, monospace)
**Display Font:** JetBrains Mono (with Microsoft YaHei, PingFang SC, monospace)
**Body Font:** JetBrains Mono (with bundled CaiWu CJK, monospace)
**Body Font:** JetBrains Mono (with Microsoft YaHei, PingFang SC, monospace)
**Label/Mono Font:** JetBrains Mono
@ -206,8 +206,6 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视
**The One-Family Rule.** 按钮、标签、导航、表格和正文都使用同一字体家族;禁止在数据界面引入装饰性展示字体。
**The Cross-Platform Control Rule.** 业务控件不得依赖 macOS、Windows 或不同浏览器的原生外观。字体使用仓库内置 Web 字体;下拉框、复选框、日期选择、联想输入使用项目自绘控件;桌面筛选区使用明确 CSS 网格。新页面必须在 Safari 与 Chromium 下验证布局、换行和控件尺寸一致。
## 4. Elevation
界面默认采用“色调分层 + 细边界”,不是依赖大阴影堆叠。工具轨道、功能栏和内容区通过背景明度形成第一层深度;内容面板通过白色表面与细边界形成第二层。阴影只用于浮层或短暂交互反馈。
@ -265,7 +263,6 @@ CaiWuXiTong 是一个需要长时间、高频率使用的财务工作台。视
- 标准高度 34px,8px 圆角,白底、1px 边界;标签位于字段上方,12px/500。
- 聚焦使用深金边框和半透明焦点环;占位文字至少使用辅助墨色,不允许低对比浅灰。
- 错误状态使用语义危险色、明确文字和错误图标;不能只把边框染红。
- 不使用原生 `datalist`、系统日期框或未归一的系统下拉外观承载业务交互;关联选项使用项目自绘菜单或勾选面板,避免 macOS 与 Windows 显示不同。
### Cards / Containers

View File

@ -1,10 +1,6 @@
# CaiWuXiTong 本地测试环境
本说明用于开发者在自己的电脑上启动项目。项目使用 Docker。
本地环境只用于开发、测试、构建和发布。生产取数和后台任务不得依赖本机常驻服务;上游网络问题应在生产服务器或公司固定网络设施解决,不安装开发机中继。
默认访问地址为:
本说明用于开发者在自己的电脑上启动项目。项目使用 Docker,默认访问地址为:
```text
http://127.0.0.1:18088
@ -58,8 +54,6 @@ 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`,也不得对团队共享系统数据库自行迁移。
@ -141,10 +135,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 --profile dev stop
docker compose -f docker-compose.local.yml stop
# 再次启动
docker compose -f docker-compose.local.yml up -d app mysql
docker compose -f docker-compose.local.yml start
```
不要执行 `docker compose down -v`、删除数据库卷或强制迁移。确需重置本地临时库时,先确认不会影响当前系统数据库配置并找负责人或 Codex处理。
@ -153,7 +147,7 @@ docker compose -f docker-compose.local.yml up -d app mysql
- PHP、配置、模块、页面模板和路由目录已经挂载到容器;开发环境关闭 PHP OPcache 和 Blade 编译缓存,刷新浏览器即可加载最新源码,无需重启 PHP 服务;
- 开发环境启动时只执行 `optimize:clear`,不会生成 Laravel 的配置、路由或视图缓存;生产环境仍保留原有缓存构建机制;
- 普通初始化只启动 PHP 和 MySQL,前端自动编译通过 `dev` profile 按需启动,见下一节。
- 本地 Compose 会同时启动 `frontend` watcher。修改 `resources/assets` 下的 Vue、JavaScript 或 SCSS 后,Laravel Mix 会通过轮询自动重新编译,Apache 使用共享静态资源卷提供最新文件;浏览器刷新即可看到结果。
- 如果 watcher 构建失败,查看 `docker compose -f docker-compose.local.yml logs -f frontend`;修复源码后它会继续监听并重新编译。
- Composer 依赖、前端依赖、Dockerfile 或构建资源发生变化时,重新执行 `bash deploy/local-init.sh`,脚本会自动重建;
- 修改 `runtime/.env` 后,执行:
@ -163,31 +157,7 @@ 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
```
停止本地环境时保留数据卷;再次运行初始化脚本会恢复 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 或正式构建流程。
停止本地环境时,`app`、`frontend` 和 `mysql` 会一起停止;再次运行初始化脚本会恢复 PHP 服务和前端 watcher。
## 相关文档

View File

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

View File

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

View File

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

View File

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

View File

@ -1,321 +0,0 @@
<?php
namespace App\Business\CompanyPlan;
use PDO;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use RuntimeException;
use Throwable;
/**
* 公司盘点中的公司持股关系。
*
* 数据来自资产盘点工作簿“主体明细”的“股东”列,只保留股东本身也是盘点主体的公司关系,
* 供公司盘点备注跳转到公司基础信息并按股东过滤。
*/
class CompanyPlanCompanyRepository
{
public const SUBSIDIARY_NOTE = '名下有子公司,暂不注销';
private ?PDO $pdo = null;
public function pdo(): PDO
{
if ($this->pdo instanceof PDO) {
return $this->pdo;
}
$path = (string) config('company_plan.database_path');
$directory = dirname($path);
if (! is_dir($directory) && ! mkdir($directory, 0775, true) && ! is_dir($directory)) {
throw new RuntimeException('无法创建公司盘点原型数据目录。');
}
$pdo = new PDO('sqlite:' . $path, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('PRAGMA busy_timeout = 5000');
$pdo->exec('PRAGMA journal_mode = WAL');
$this->ensureSchema($pdo);
return $this->pdo = $pdo;
}
private function ensureSchema(PDO $pdo): void
{
$pdo->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS company_plan_company_relations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
company_id INTEGER NOT NULL,
plan_row_id INTEGER,
shareholder_company_name TEXT NOT NULL,
related_company_name TEXT NOT NULL,
related_unified_social_credit_code TEXT,
share_ratio TEXT,
shareholders_text TEXT NOT NULL,
source_sheet TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE (company_id, shareholder_company_name, related_company_name)
)
SQL);
$pdo->exec(
'CREATE INDEX IF NOT EXISTS company_plan_company_relations_shareholder_index '
. 'ON company_plan_company_relations (company_id, shareholder_company_name)'
);
}
/**
* @return array{source_sheet:string,scanned:int,relationships:int,shareholders:int}
*/
public function importFromWorkbook(string $path, int $companyId): array
{
if (! is_file($path)) {
throw new RuntimeException('源工作簿不存在:' . $path);
}
$reader = IOFactory::createReaderForFile($path);
$reader->setReadDataOnly(true);
$book = $reader->load($path);
try {
$sheet = $book->getSheetByName('主体明细');
if (! $sheet instanceof Worksheet) {
throw new RuntimeException('源工作簿缺少“主体明细”工作表。');
}
$rows = $sheet->toArray(null, true, false, false);
[$headerRow, $headers] = $this->findHeaders($rows);
if (! isset($headers['company_name'], $headers['shareholders'])) {
throw new RuntimeException('“主体明细”缺少“公司名称”或“股东”表头。');
}
$planRows = [];
$statement = $this->pdo()->prepare(
'SELECT id, company_name FROM company_plan_rows WHERE company_id = ?'
);
$statement->execute([$companyId]);
foreach ($statement->fetchAll() as $planRow) {
$name = trim((string) $planRow['company_name']);
$planRows[self::normalizeCompanyName($name)] = [
'id' => (int) $planRow['id'],
'name' => $name,
];
}
$relations = [];
$shareholders = [];
$scanned = 0;
foreach (array_slice($rows, $headerRow + 1) as $row) {
$relatedCompany = $this->cell($row, $headers['company_name']);
$shareholderText = $this->cell($row, $headers['shareholders']);
if ($relatedCompany === '' || $shareholderText === '') {
continue;
}
$scanned++;
foreach ($this->shareholderEntries($shareholderText) as [$shareholderName, $ratio]) {
$match = $planRows[self::normalizeCompanyName($shareholderName)] ?? null;
if ($match === null) {
continue;
}
$key = $match['name'] . '|' . $relatedCompany;
$relations[$key] = [
'plan_row_id' => $match['id'],
'shareholder_company_name' => $match['name'],
'related_company_name' => $relatedCompany,
'related_unified_social_credit_code' => isset($headers['credit_code'])
? $this->nullableCell($row, $headers['credit_code'], 64)
: null,
'share_ratio' => $ratio !== '' ? $ratio : null,
'shareholders_text' => $ratio !== ''
? $match['name'] . ':' . $ratio
: $match['name'],
'source_sheet' => '主体明细',
];
$shareholders[$match['name']] = true;
}
}
$pdo = $this->pdo();
$pdo->beginTransaction();
try {
$pdo->prepare('DELETE FROM company_plan_company_relations WHERE company_id = ?')
->execute([$companyId]);
$insert = $pdo->prepare(<<<'SQL'
INSERT INTO company_plan_company_relations (
company_id, plan_row_id, shareholder_company_name, related_company_name,
related_unified_social_credit_code, share_ratio, shareholders_text,
source_sheet, created_at, updated_at
) VALUES (
:company_id, :plan_row_id, :shareholder_company_name, :related_company_name,
:related_unified_social_credit_code, :share_ratio, :shareholders_text,
:source_sheet, :created_at, :updated_at
)
SQL);
$now = now()->toDateTimeString();
foreach ($relations as $relation) {
$insert->execute([
':company_id' => $companyId,
':plan_row_id' => $relation['plan_row_id'],
':shareholder_company_name' => mb_substr($relation['shareholder_company_name'], 0, 255),
':related_company_name' => mb_substr($relation['related_company_name'], 0, 255),
':related_unified_social_credit_code' => $relation['related_unified_social_credit_code'],
':share_ratio' => $relation['share_ratio'],
':shareholders_text' => mb_substr($relation['shareholders_text'], 0, 500),
':source_sheet' => $relation['source_sheet'],
':created_at' => $now,
':updated_at' => $now,
]);
}
$pdo->commit();
} catch (Throwable $exception) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $exception;
}
return [
'source_sheet' => '主体明细',
'scanned' => $scanned,
'relationships' => count($relations),
'shareholders' => count($shareholders),
];
} finally {
$book->disconnectWorksheets();
}
}
/** @return array<string,int> 键包含原名称和归一化名称。 */
public function countsByShareholder(int $companyId): array
{
$statement = $this->pdo()->prepare(
'SELECT shareholder_company_name, COUNT(*) AS total '
. 'FROM company_plan_company_relations WHERE company_id = ? '
. 'GROUP BY shareholder_company_name'
);
$statement->execute([$companyId]);
$counts = [];
foreach ($statement->fetchAll() as $row) {
$name = (string) $row['shareholder_company_name'];
$counts[$name] = (int) $row['total'];
$counts[self::normalizeCompanyName($name)] = (int) $row['total'];
}
return $counts;
}
/**
* @return array<string,array{company_name:string,shareholders_text:string,share_ratio:?string}>
*/
public function relationsForShareholder(int $companyId, string $shareholderCompany): array
{
$statement = $this->pdo()->prepare(
'SELECT related_company_name, shareholders_text, share_ratio '
. 'FROM company_plan_company_relations '
. 'WHERE company_id = :company_id AND shareholder_company_name = :shareholder_company '
. 'ORDER BY related_company_name ASC'
);
$statement->execute([
':company_id' => $companyId,
':shareholder_company' => trim($shareholderCompany),
]);
$relations = [];
foreach ($statement->fetchAll() as $row) {
$name = trim((string) $row['related_company_name']);
$relations[self::normalizeCompanyName($name)] = [
'company_name' => $name,
'shareholders_text' => (string) $row['shareholders_text'],
'share_ratio' => $row['share_ratio'] !== null ? (string) $row['share_ratio'] : null,
];
}
return $relations;
}
public static function normalizeCompanyName(string $name): string
{
$normalized = preg_replace('/[\s\x{00A0}\x{3000}]+/u', '', trim($name)) ?? trim($name);
return mb_strtolower(str_replace(['(', ')'], ['(', ')'], $normalized));
}
/**
* @param list<array<int,mixed>> $rows
* @return array{0:int,1:array<string,int>}
*/
private function findHeaders(array $rows): array
{
$aliases = [
'公司名称' => 'company_name',
'统一社会信用代码' => 'credit_code',
'股东' => 'shareholders',
];
foreach (array_slice($rows, 0, 20, true) as $index => $row) {
$headers = [];
foreach ($row as $column => $value) {
$header = preg_replace('/\s+/u', '', trim((string) $value)) ?? '';
if (isset($aliases[$header])) {
$headers[$aliases[$header]] = $column;
}
}
if (isset($headers['company_name'], $headers['shareholders'])) {
return [$index, $headers];
}
}
throw new RuntimeException('未识别到“主体明细”的公司名称和股东表头。');
}
/**
* @param array<int,mixed> $row
* @return list<array{0:string,1:string}>
*/
private function shareholderEntries(string $text): array
{
$entries = [];
foreach (preg_split('/[|;;]/u', $text) ?: [] as $part) {
$part = trim(str_replace("\u{00A0}", ' ', $part));
if ($part === '') {
continue;
}
if (! preg_match('/^(.+?)[::]\s*(.*)$/u', $part, $matches)) {
$entries[] = [$part, ''];
continue;
}
$name = trim($matches[1]);
$ratio = trim($matches[2]);
if ($name !== '') {
$entries[] = [$name, $ratio];
}
}
return $entries;
}
/** @param array<int,mixed> $row */
private function cell(array $row, int $column): string
{
$value = $row[$column] ?? null;
return $value === null ? '' : trim(str_replace("\u{00A0}", ' ', (string) $value));
}
/** @param array<int,mixed> $row */
private function nullableCell(array $row, int $column, int $length): ?string
{
$value = $this->cell($row, $column);
return $value !== '' ? mb_substr($value, 0, $length) : null;
}
}

View File

@ -1,271 +0,0 @@
<?php
namespace App\Business\CompanyPlan;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Throwable;
class CompanyPlanPageData
{
public function __construct(
private readonly CompanyPlanRepository $repository,
private readonly CompanyPlanWorkbookImporter $importer,
private readonly CompanyPlanShopRepository $shops,
private readonly CompanyPlanCompanyRepository $companies,
) {}
/**
* @return array<string,mixed>
*/
public function page(Request $request): array
{
$companyId = (int) (company_id() ?: 1);
$userId = (int) (auth()->id() ?: 0);
$filters = self::filters($request);
$error = null;
$payload = [
'rows' => [],
'total' => 0,
'page' => 1,
'per_page' => $filters['per_page'],
'last_page' => 1,
];
$summary = [
'total' => 0,
'retained' => 0,
'cancelled_done' => 0,
'cancelling' => 0,
'plan_cancelled_pending' => 0,
];
$options = [
'plan' => ['保留', '注销', '待定'],
'company_status' => ['正常', '注销中', '已注销'],
'company_type' => [],
'taxpayer_type' => [],
'business_registration_type' => [],
];
$importPreview = null;
$shopFilters = self::shopFilters($request);
$shopPayload = [
'rows' => [],
'total' => 0,
'page' => 1,
'per_page' => $shopFilters['shop_per_page'],
'last_page' => 1,
];
$shopSummary = ['total' => 0, 'companies' => 0, 'statuses' => []];
$shopStatusOptions = [];
$shopCounts = [];
$shareholdingCounts = [];
try {
$payload = $this->repository->paginate(
$companyId,
$filters,
max((int) ($filters['page'] ?? 1), 1),
(int) $filters['per_page'],
);
$summary = $this->repository->summary($companyId);
$storedOptions = $this->repository->filterOptions($companyId);
foreach (['plan', 'company_status', 'company_type', 'taxpayer_type', 'business_registration_type'] as $field) {
$options[$field] = array_values(array_unique(array_merge(
$options[$field],
$storedOptions[$field] ?? [],
)));
}
$token = (string) $request->session()->get('company_plan_preview_token', '');
if ($token !== '') {
$importPreview = $this->importer->previewByToken($token, $companyId, $userId);
if ($importPreview === null) {
$request->session()->forget('company_plan_preview_token');
}
}
$shopPayload = $this->shops->paginate(
$companyId,
$shopFilters,
(int) $shopFilters['shop_page'],
(int) $shopFilters['shop_per_page'],
);
$shopSummary = $this->shops->summary($companyId, $shopFilters);
$shopStatusOptions = $this->shops->statusOptions($companyId);
$shopCounts = $this->shops->countsByCompany($companyId);
$shareholdingCounts = $this->companies->countsByShareholder($companyId);
} catch (Throwable $exception) {
report($exception);
$error = '公司盘点本地原型数据暂时无法读取。请确认 storage/app 可写后重新加载。';
}
$rows = new LengthAwarePaginator(
array_map(static fn (array $row): object => (object) $row, $payload['rows']),
(int) $payload['total'],
(int) $payload['per_page'],
(int) $payload['page'],
[
'path' => $request->url(),
'query' => $request->except(['page', 'shop_page']),
],
);
return [
'view' => 'business.pages.company-management.company-plan',
'companyPlanRows' => $rows,
'companyPlanFields' => CompanyPlanRepository::FIELDS,
'companyPlanFilters' => $filters,
'companyPlanSummary' => $summary,
'companyPlanSummaryCards' => $this->summaryCards($summary, $request),
'companyPlanOptions' => $options,
'companyPlanImportPreview' => $importPreview,
'companyPlanError' => $error,
'companyPlanShopRows' => array_map(static fn (array $row): object => (object) $row, $shopPayload['rows']),
'companyPlanShopFields' => CompanyPlanShopRepository::FIELDS,
'companyPlanShopFilters' => $shopFilters,
'companyPlanShopTotal' => (int) $shopPayload['total'],
'companyPlanShopPage' => (int) $shopPayload['page'],
'companyPlanShopLastPage' => (int) $shopPayload['last_page'],
'companyPlanShopSummary' => $shopSummary,
'companyPlanShopStatuses' => $shopStatusOptions,
'companyPlanShopCounts' => $shopCounts,
'companyPlanShareholdingCounts' => $shareholdingCounts,
];
}
/**
* @return array{
* keyword:string,
* plan:string,
* company_status:string,
* company_type:string,
* taxpayer_type:string,
* business_registration_type:string,
* remark_keyword:string,
* remark_state:string,
* sort:string,
* direction:string,
* page:int,
* per_page:int
* }
*/
public static function filters(Request $request): array
{
$sortable = array_column(CompanyPlanRepository::FIELDS, 'name');
$perPage = (int) $request->query('per_page', 25);
if (! in_array($perPage, [25, 50, 100], true)) {
$perPage = 25;
}
return [
'keyword' => mb_substr(trim((string) $request->query('keyword', '')), 0, 191),
'plan' => mb_substr(trim((string) $request->query('plan', '')), 0, 64),
'company_status' => mb_substr(trim((string) $request->query('company_status', '')), 0, 64),
'company_type' => mb_substr(trim((string) $request->query('company_type', '')), 0, 64),
'taxpayer_type' => mb_substr(trim((string) $request->query('taxpayer_type', '')), 0, 64),
'business_registration_type' => mb_substr(trim((string) $request->query('business_registration_type', '')), 0, 64),
'remark_keyword' => mb_substr(trim((string) $request->query('remark_keyword', '')), 0, 191),
'remark_state' => in_array($request->query('remark_state'), ['filled', 'empty'], true)
? (string) $request->query('remark_state')
: '',
'sort' => in_array($request->query('sort'), $sortable, true)
? (string) $request->query('sort')
: 'sequence_no',
'direction' => $request->query('direction') === 'desc' ? 'desc' : 'asc',
'page' => max((int) $request->query('page', 1), 1),
'per_page' => $perPage,
];
}
/**
* 未完结店铺表的筛选条件。
*
* @return array{shop_keyword:string,shop_status:string,shop_company:string,shop_page:int,shop_per_page:int}
*/
public static function shopFilters(Request $request): array
{
$perPage = (int) $request->query('shop_per_page', 25);
if (! in_array($perPage, [25, 50, 100], true)) {
$perPage = 25;
}
return [
'shop_keyword' => mb_substr(trim((string) $request->query('shop_keyword', '')), 0, 191),
'shop_status' => mb_substr(trim((string) $request->query('shop_status', '')), 0, 64),
'shop_company' => mb_substr(trim((string) $request->query('shop_company', '')), 0, 255),
'shop_page' => max((int) $request->query('shop_page', 1), 1),
'shop_per_page' => $perPage,
];
}
/**
* @param array{total:int,retained:int,cancelled_done:int,cancelling:int,plan_cancelled_pending:int} $summary
* @return list<array{label:string,value:int,hint:string,tone:string,filter:string,url:string,active:bool}>
*/
private function summaryCards(array $summary, Request $request): array
{
$baseQuery = $request->query();
unset(
$baseQuery['page'],
$baseQuery['per_page'],
$baseQuery['plan'],
$baseQuery['company_status'],
$baseQuery['remark_state'],
);
$buildUrl = static function (array $extra) use ($request, $baseQuery): string {
return $request->url() . '?' . http_build_query(array_merge($baseQuery, $extra, ['page' => 1]))
. '#company-plan-table';
};
$currentPlan = (string) $request->query('plan', '');
$currentStatus = (string) $request->query('company_status', '');
$currentRemarkState = (string) $request->query('remark_state', '');
return [
[
'label' => '公司总数',
'value' => $summary['total'],
'hint' => '当前导入的全部主体',
'tone' => 'accent',
'filter' => 'all',
'url' => $buildUrl([]),
'active' => $currentPlan === '' && $currentStatus === '' && $currentRemarkState === '',
],
[
'label' => '规划保留',
'value' => $summary['retained'],
'hint' => '点击筛选规划为“保留”',
'tone' => 'success',
'filter' => 'plan:retained',
'url' => $buildUrl(['plan' => '保留']),
'active' => $currentPlan === '保留',
],
[
'label' => '已注销',
'value' => $summary['cancelled_done'],
'hint' => '点击筛选公司状态为“已注销”',
'tone' => 'danger',
'filter' => 'status:cancelled_done',
'url' => $buildUrl(['company_status' => '已注销']),
'active' => $currentStatus === '已注销',
],
[
'label' => '注销中',
'value' => $summary['cancelling'],
'hint' => '点击筛选注销办理中的主体',
'tone' => 'warning',
'filter' => 'status:cancelling',
'url' => $buildUrl(['company_status' => '注销中']),
'active' => $currentStatus === '注销中',
],
[
'label' => '规划注销未发起',
'value' => $summary['plan_cancelled_pending'],
'hint' => '规划为注销、公司状态仍是正常',
'tone' => 'info',
'filter' => 'plan:cancelled_pending',
'url' => $buildUrl(['plan' => '注销', 'company_status' => '正常']),
'active' => $currentPlan === '注销' && $currentStatus === '正常',
],
];
}
}

View File

@ -1,664 +0,0 @@
<?php
namespace App\Business\CompanyPlan;
use PDO;
class CompanyPlanRepository
{
/**
* 页面与 Excel 共用的字段契约,顺序与附件「主体盘点」完全一致。
*
* @var list<array{name:string,label:string,type:string}>
*/
public const FIELDS = [
['name' => 'sequence_no', 'label' => '序号', 'type' => 'integer'],
['name' => 'company_name', 'label' => '公司名称', 'type' => 'text'],
['name' => 'company_type', 'label' => '类型', 'type' => 'text'],
['name' => 'taxpayer_type', 'label' => '税务类型', 'type' => 'text'],
['name' => 'registered_at', 'label' => '注册时间', 'type' => 'date'],
['name' => 'business_registration_type', 'label' => '工商类型', 'type' => 'text'],
['name' => 'unified_social_credit_code', 'label' => '统一社会信用代码', 'type' => 'text'],
['name' => 'plan', 'label' => '规划', 'type' => 'text'],
['name' => 'company_status', 'label' => '公司状态', 'type' => 'text'],
['name' => 'tax_cancellation', 'label' => '注销-税务', 'type' => 'text'],
['name' => 'business_cancellation', 'label' => '注销-工商', 'type' => 'text'],
['name' => 'bank_cancellation', 'label' => '注销-银行', 'type' => 'text'],
['name' => 'notes', 'label' => '备注', 'type' => 'text'],
];
/** @var list<string> */
public const MUTABLE_FIELDS = [
'sequence_no',
'company_name',
'company_type',
'taxpayer_type',
'registered_at',
'business_registration_type',
'unified_social_credit_code',
'plan',
'company_status',
'tax_cancellation',
'business_cancellation',
'bank_cancellation',
'notes',
];
/**
* 类型口径归一:历史数据中的“个体户”统一视为“个体工商户”。
*
* @var array<string,string>
*/
private const COMPANY_TYPE_ALIASES = [
'个体户' => '个体工商户',
];
/**
* 公司状态口径归一:历史数据中的“注销”统一视为“已注销”。
*
* @var array<string,string>
*/
private const COMPANY_STATUS_ALIASES = [
'注销' => '已注销',
];
/**
* 写入与查询选项共用的口径归一映射,键为字段名。
*
* @var array<string,array<string,string>>
*/
private const FIELD_ALIASES = [
'company_type' => self::COMPANY_TYPE_ALIASES,
'company_status' => self::COMPANY_STATUS_ALIASES,
];
private ?PDO $pdo = null;
public function pdo(): PDO
{
if ($this->pdo instanceof PDO) {
return $this->pdo;
}
$path = (string) config('company_plan.database_path');
$directory = dirname($path);
if (! is_dir($directory) && ! mkdir($directory, 0775, true) && ! is_dir($directory)) {
throw new \RuntimeException('无法创建公司盘点原型数据目录。');
}
$pdo = new PDO('sqlite:' . $path, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('PRAGMA busy_timeout = 5000');
$pdo->exec('PRAGMA journal_mode = WAL');
$this->ensureSchema($pdo);
return $this->pdo = $pdo;
}
/**
* @param array<string,mixed> $filters
* @return array{rows:list<array<string,mixed>>,total:int,page:int,per_page:int,last_page:int}
*/
public function paginate(int $companyId, array $filters, int $page, int $perPage): array
{
[$whereSql, $params] = $this->where($companyId, $filters);
$sort = $this->safeSort((string) ($filters['sort'] ?? 'sequence_no'));
$direction = (($filters['direction'] ?? 'asc') === 'desc') ? 'DESC' : 'ASC';
$pdo = $this->pdo();
$countStatement = $pdo->prepare("SELECT COUNT(*) FROM company_plan_rows {$whereSql}");
$countStatement->execute($params);
$total = (int) $countStatement->fetchColumn();
$lastPage = max(1, (int) ceil($total / max($perPage, 1)));
$page = min(max($page, 1), $lastPage);
$offset = ($page - 1) * $perPage;
$orderSql = "CASE WHEN {$sort} IS NULL OR TRIM(CAST({$sort} AS TEXT)) = '' THEN 1 ELSE 0 END ASC, "
. "{$sort} {$direction}, id ASC";
$statement = $pdo->prepare(
"SELECT * FROM company_plan_rows {$whereSql} ORDER BY {$orderSql} LIMIT :limit OFFSET :offset"
);
foreach ($params as $key => $value) {
$statement->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$statement->bindValue(':limit', $perPage, PDO::PARAM_INT);
$statement->bindValue(':offset', $offset, PDO::PARAM_INT);
$statement->execute();
return [
'rows' => $statement->fetchAll(),
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'last_page' => $lastPage,
];
}
/**
* @param array<string,mixed> $filters
* @return list<array<string,mixed>>
*/
public function exportRows(int $companyId, array $filters): array
{
[$whereSql, $params] = $this->where($companyId, $filters);
$sort = $this->safeSort((string) ($filters['sort'] ?? 'sequence_no'));
$direction = (($filters['direction'] ?? 'asc') === 'desc') ? 'DESC' : 'ASC';
$statement = $this->pdo()->prepare(
"SELECT * FROM company_plan_rows {$whereSql} "
. "ORDER BY CASE WHEN {$sort} IS NULL OR TRIM(CAST({$sort} AS TEXT)) = '' THEN 1 ELSE 0 END ASC, "
. "{$sort} {$direction}, id ASC"
);
$statement->execute($params);
return $statement->fetchAll();
}
/** @return array{total:int,retained:int,cancelled_done:int,cancelling:int,plan_cancelled_pending:int} */
public function summary(int $companyId): array
{
$statement = $this->pdo()->prepare(<<<'SQL'
SELECT
COUNT(*) AS total,
COALESCE(SUM(CASE WHEN TRIM(COALESCE(plan, '')) = '保留' THEN 1 ELSE 0 END), 0) AS retained,
COALESCE(SUM(CASE WHEN TRIM(COALESCE(company_status, '')) = '已注销' THEN 1 ELSE 0 END), 0) AS cancelled_done,
COALESCE(SUM(CASE WHEN TRIM(COALESCE(company_status, '')) = '注销中' THEN 1 ELSE 0 END), 0) AS cancelling,
COALESCE(SUM(CASE WHEN TRIM(COALESCE(plan, '')) = '注销' AND TRIM(COALESCE(company_status, '')) = '正常' THEN 1 ELSE 0 END), 0) AS plan_cancelled_pending
FROM company_plan_rows
WHERE company_id = :company_id
SQL);
$statement->execute([':company_id' => $companyId]);
$row = $statement->fetch() ?: [];
return [
'total' => (int) ($row['total'] ?? 0),
'retained' => (int) ($row['retained'] ?? 0),
'cancelled_done' => (int) ($row['cancelled_done'] ?? 0),
'cancelling' => (int) ($row['cancelling'] ?? 0),
'plan_cancelled_pending' => (int) ($row['plan_cancelled_pending'] ?? 0),
];
}
/** @return array<string,list<string>> */
public function filterOptions(int $companyId): array
{
return [
'plan' => $this->distinctValues($companyId, 'plan'),
'company_status' => $this->distinctValues($companyId, 'company_status'),
'company_type' => $this->distinctValues($companyId, 'company_type'),
'taxpayer_type' => $this->distinctValues($companyId, 'taxpayer_type'),
'business_registration_type' => $this->distinctValues($companyId, 'business_registration_type'),
];
}
/** @return array{taxpayer_type:list<string>,business_registration_type:list<string>} */
public function classificationFilterOptions(int $companyId): array
{
return [
'taxpayer_type' => $this->distinctValues($companyId, 'taxpayer_type'),
'business_registration_type' => $this->distinctValues($companyId, 'business_registration_type'),
];
}
/** @return array<string,true> */
public function companyNames(int $companyId): array
{
$statement = $this->pdo()->prepare(
'SELECT company_name FROM company_plan_rows WHERE company_id = :company_id'
);
$statement->execute([':company_id' => $companyId]);
$names = [];
foreach ($statement->fetchAll(PDO::FETCH_COLUMN) as $name) {
$normalized = $this->normalizeCompanyName((string) $name);
if ($normalized !== '') {
$names[$normalized] = true;
}
}
return $names;
}
/**
* 公司基础信息页按当前页公司读取盘点中的税务、工商类型。
*
* @param list<string> $companyNames
* @param list<string> $creditCodes
* @return list<array<string,mixed>>
*/
public function classificationReferencesForCompanies(
int $companyId,
array $companyNames,
array $creditCodes = [],
): array {
$conditions = [];
$params = [':company_id' => $companyId];
foreach (array_values(array_unique(array_filter(array_map('trim', $companyNames)))) as $index => $name) {
$key = ':company_name_' . $index;
$conditions[] = "REPLACE(LOWER(TRIM(COALESCE(company_name, ''))), ' ', '') = {$key}";
$params[$key] = mb_strtolower(preg_replace('/\s+/u', '', $name) ?? $name);
}
foreach (array_values(array_unique(array_filter(array_map('trim', $creditCodes)))) as $index => $code) {
$key = ':credit_code_' . $index;
$conditions[] = "REPLACE(UPPER(TRIM(COALESCE(unified_social_credit_code, ''))), ' ', '') = {$key}";
$params[$key] = mb_strtoupper(preg_replace('/\s+/u', '', $code) ?? $code);
}
if ($conditions === []) {
return [];
}
$statement = $this->pdo()->prepare(
'SELECT company_name, unified_social_credit_code, taxpayer_type, business_registration_type '
. 'FROM company_plan_rows WHERE company_id = :company_id AND (' . implode(' OR ', $conditions) . ') '
. 'ORDER BY CASE WHEN sequence_no IS NULL OR TRIM(CAST(sequence_no AS TEXT)) = \'\' THEN 1 ELSE 0 END, '
. 'sequence_no, id'
);
$statement->execute($params);
return $statement->fetchAll();
}
/**
* 按盘点口径筛选或排序时读取当前公司的全部类型资料。
*
* @return list<array<string,mixed>>
*/
public function allClassificationReferences(int $companyId): array
{
$statement = $this->pdo()->prepare(
'SELECT company_name, unified_social_credit_code, taxpayer_type, business_registration_type '
. 'FROM company_plan_rows WHERE company_id = :company_id '
. 'ORDER BY CASE WHEN sequence_no IS NULL OR TRIM(CAST(sequence_no AS TEXT)) = \'\' THEN 1 ELSE 0 END, '
. 'sequence_no, id'
);
$statement->execute([':company_id' => $companyId]);
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, plan, registered_at '
. '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(
'SELECT * FROM company_plan_rows WHERE company_id = :company_id AND id = :id LIMIT 1'
);
$statement->execute([':company_id' => $companyId, ':id' => $id]);
$row = $statement->fetch();
return $row === false ? null : $row;
}
public function companyNameExists(int $companyId, string $companyName, ?int $exceptId = null): bool
{
$sql = 'SELECT COUNT(*) FROM company_plan_rows WHERE company_id = :company_id AND company_name = :company_name';
$params = [':company_id' => $companyId, ':company_name' => trim($companyName)];
if ($exceptId !== null) {
$sql .= ' AND id <> :id';
$params[':id'] = $exceptId;
}
$statement = $this->pdo()->prepare($sql);
$statement->execute($params);
return (int) $statement->fetchColumn() > 0;
}
/**
* @param array<string,mixed> $data
*/
public function update(int $companyId, int $id, array $data, ?int $userId): void
{
$values = $this->normalizeMutableData($data);
$assignments = [];
$params = [
':company_id' => $companyId,
':id' => $id,
':updated_by' => $userId,
':updated_at' => now()->format('Y-m-d H:i:s'),
];
foreach ($values as $field => $value) {
$assignments[] = "{$field} = :{$field}";
$params[':' . $field] = $value;
}
$assignments[] = 'updated_by = :updated_by';
$assignments[] = 'updated_at = :updated_at';
$statement = $this->pdo()->prepare(
'UPDATE company_plan_rows SET ' . implode(', ', $assignments)
. ' WHERE company_id = :company_id AND id = :id'
);
$statement->execute($params);
}
/**
* @param list<array<string,mixed>> $rows
* @return array{created:int,updated:int,skipped:int}
*/
public function importRows(int $companyId, array $rows, string $duplicateMode, ?int $userId): array
{
$pdo = $this->pdo();
$pdo->beginTransaction();
$created = 0;
$updated = 0;
$skipped = 0;
try {
$lookup = $pdo->prepare(
'SELECT id FROM company_plan_rows WHERE company_id = :company_id AND company_name = :company_name LIMIT 1'
);
$insert = $pdo->prepare(<<<'SQL'
INSERT INTO company_plan_rows (
company_id, sequence_no, company_name, company_type, taxpayer_type, registered_at,
business_registration_type, unified_social_credit_code, plan, company_status,
tax_cancellation, business_cancellation, bank_cancellation, notes,
created_by, updated_by, created_at, updated_at
) VALUES (
:company_id, :sequence_no, :company_name, :company_type, :taxpayer_type, :registered_at,
:business_registration_type, :unified_social_credit_code, :plan, :company_status,
:tax_cancellation, :business_cancellation, :bank_cancellation, :notes,
:created_by, :updated_by, :created_at, :updated_at
)
SQL);
$update = $pdo->prepare(<<<'SQL'
UPDATE company_plan_rows SET
sequence_no = :sequence_no,
company_name = :company_name,
company_type = :company_type,
taxpayer_type = :taxpayer_type,
registered_at = :registered_at,
business_registration_type = :business_registration_type,
unified_social_credit_code = :unified_social_credit_code,
plan = :plan,
company_status = :company_status,
tax_cancellation = :tax_cancellation,
business_cancellation = :business_cancellation,
bank_cancellation = :bank_cancellation,
notes = :notes,
updated_by = :updated_by,
updated_at = :updated_at
WHERE company_id = :company_id AND id = :id
SQL);
$now = now()->format('Y-m-d H:i:s');
foreach ($rows as $row) {
$companyName = trim((string) ($row['company_name'] ?? ''));
if ($companyName === '') {
$skipped++;
continue;
}
$values = $this->normalizeMutableData($row);
$lookup->execute([':company_id' => $companyId, ':company_name' => $companyName]);
$existingId = $lookup->fetchColumn();
if ($existingId !== false) {
if ($duplicateMode === 'skip') {
$skipped++;
continue;
}
$update->execute([
':company_id' => $companyId,
':id' => (int) $existingId,
...$this->importBindingParams($values),
':updated_by' => $userId,
':updated_at' => $now,
]);
$updated++;
continue;
}
$insert->execute([
':company_id' => $companyId,
...$this->importBindingParams($values),
':created_by' => $userId,
':updated_by' => $userId,
':created_at' => $now,
':updated_at' => $now,
]);
$created++;
}
$pdo->commit();
} catch (\Throwable $exception) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $exception;
}
return compact('created', 'updated', 'skipped');
}
public function normalizeCompanyName(string $name): string
{
return mb_strtolower(preg_replace('/\s+/u', '', trim($name)) ?? trim($name));
}
private function ensureSchema(PDO $pdo): void
{
$pdo->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS company_plan_rows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
company_id INTEGER NOT NULL,
sequence_no INTEGER,
company_name TEXT NOT NULL,
company_type TEXT,
taxpayer_type TEXT,
registered_at TEXT,
business_registration_type TEXT,
unified_social_credit_code TEXT,
plan TEXT,
company_status TEXT,
tax_cancellation TEXT,
business_cancellation TEXT,
bank_cancellation TEXT,
notes TEXT,
created_by INTEGER,
updated_by INTEGER,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE (company_id, company_name)
)
SQL);
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_plan_index ON company_plan_rows (company_id, plan)');
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_status_index ON company_plan_rows (company_id, company_status)');
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_type_index ON company_plan_rows (company_id, company_type)');
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_tax_index ON company_plan_rows (company_id, taxpayer_type)');
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_sequence_index ON company_plan_rows (company_id, sequence_no)');
// 类型口径归一:把存量“个体户”改写为“个体工商户”,幂等执行。
$pdo->exec(
"UPDATE company_plan_rows SET company_type = '个体工商户' "
. "WHERE company_type IS NOT NULL AND TRIM(COALESCE(company_type, '')) = '个体户'"
);
// 公司状态口径归一:把存量“注销”改写为“已注销”,幂等执行。
$pdo->exec(
"UPDATE company_plan_rows SET company_status = '已注销' "
. "WHERE company_status IS NOT NULL AND TRIM(COALESCE(company_status, '')) = '注销'"
);
}
/**
* @param array<string,mixed> $filters
* @return array{0:string,1:array<string,mixed>}
*/
private function where(int $companyId, array $filters): array
{
$where = ['company_id = :company_id'];
$params = [':company_id' => $companyId];
$keyword = trim((string) ($filters['keyword'] ?? ''));
if ($keyword !== '') {
$where[] = "(company_name LIKE :keyword ESCAPE '!' OR unified_social_credit_code LIKE :keyword ESCAPE '!')";
$params[':keyword'] = '%' . $this->escapeLike($keyword) . '%';
}
foreach (['plan', 'company_status', 'company_type', 'taxpayer_type', 'business_registration_type'] as $field) {
$value = trim((string) ($filters[$field] ?? ''));
if ($value !== '') {
$where[] = "{$field} = :{$field}";
$params[':' . $field] = $value;
}
}
$remarkKeyword = trim((string) ($filters['remark_keyword'] ?? ''));
if ($remarkKeyword !== '') {
$where[] = "COALESCE(notes, '') LIKE :remark_keyword ESCAPE '!'";
$params[':remark_keyword'] = '%' . $this->escapeLike($remarkKeyword) . '%';
}
$remarkState = (string) ($filters['remark_state'] ?? '');
if ($remarkState === 'filled') {
$where[] = "TRIM(COALESCE(notes, '')) <> ''";
} elseif ($remarkState === 'empty') {
$where[] = "TRIM(COALESCE(notes, '')) = ''";
}
return ['WHERE ' . implode(' AND ', $where), $params];
}
private function escapeLike(string $value): string
{
return str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value);
}
private function safeSort(string $sort): string
{
return in_array($sort, self::MUTABLE_FIELDS, true) ? $sort : 'sequence_no';
}
/** @return list<string> */
private function distinctValues(int $companyId, string $field): array
{
if (! in_array($field, self::MUTABLE_FIELDS, true)) {
return [];
}
$statement = $this->pdo()->prepare(
"SELECT DISTINCT TRIM({$field}) AS value FROM company_plan_rows "
. "WHERE company_id = :company_id AND {$field} IS NOT NULL AND TRIM({$field}) <> '' "
. "ORDER BY value COLLATE NOCASE"
);
$statement->execute([':company_id' => $companyId]);
$values = array_values(array_filter(array_map(
static fn (mixed $value): string => trim((string) $value),
$statement->fetchAll(PDO::FETCH_COLUMN)
), static fn (string $value): bool => $value !== ''));
if ($field === 'company_type') {
$values = array_values(array_unique(array_map(
static fn (string $value): string => self::COMPANY_TYPE_ALIASES[$value] ?? $value,
$values
)));
}
if (isset(self::FIELD_ALIASES[$field])) {
$aliases = self::FIELD_ALIASES[$field];
$values = array_values(array_unique(array_map(
static fn (string $value): string => $aliases[$value] ?? $value,
$values
)));
}
return $values;
}
/**
* @param array<string,mixed> $data
* @return array<string,mixed>
*/
private function normalizeMutableData(array $data): array
{
$values = [];
foreach (self::MUTABLE_FIELDS as $field) {
$value = $data[$field] ?? null;
if (is_string($value)) {
$value = trim($value);
}
$values[$field] = $value === '' ? null : $value;
}
if (isset($values['sequence_no']) && is_numeric($values['sequence_no'])) {
$values['sequence_no'] = (int) $values['sequence_no'];
}
if (isset($values['company_type']) && is_string($values['company_type'])) {
$values['company_type'] = self::COMPANY_TYPE_ALIASES[$values['company_type']] ?? $values['company_type'];
}
if (isset($values['company_status']) && is_string($values['company_status'])) {
$values['company_status'] = self::COMPANY_STATUS_ALIASES[$values['company_status']] ?? $values['company_status'];
}
return $values;
}
/**
* @param array<string,mixed> $values
* @return array<string,mixed>
*/
private function importBindingParams(array $values): array
{
$params = [];
foreach (self::MUTABLE_FIELDS as $field) {
$params[':' . $field] = $values[$field] ?? null;
}
return $params;
}
}

View File

@ -1,443 +0,0 @@
<?php
namespace App\Business\CompanyPlan;
use PDO;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use RuntimeException;
use Throwable;
/**
* 主体关联的「未完结店铺」数据层。
*
* 数据来自资产盘点工作簿里两张未完结店铺明细表(Sheet3 / Sheet6),
* 按公司名称与 company_plan_rows 关联,供公司盘点页面展示与跳转。
*/
class CompanyPlanShopRepository
{
/** 页面展示的字段顺序。 */
public const FIELDS = [
['name' => 'shop_name', 'label' => '店铺名称'],
['name' => 'company_name', 'label' => '所属主体'],
['name' => 'shop_status', 'label' => '店铺状态'],
['name' => 'profit_center', 'label' => '利润中心'],
['name' => 'owner', 'label' => '店铺负责人'],
['name' => 'opened_on', 'label' => '开店时间'],
['name' => 'successor', 'label' => '接替主体'],
['name' => 'source_sheet', 'label' => '来源'],
];
private ?PDO $pdo = null;
public function pdo(): PDO
{
if ($this->pdo instanceof PDO) {
return $this->pdo;
}
$path = (string) config('company_plan.database_path');
$directory = dirname($path);
if (! is_dir($directory) && ! mkdir($directory, 0775, true) && ! is_dir($directory)) {
throw new RuntimeException('无法创建公司盘点原型数据目录。');
}
$pdo = new PDO('sqlite:' . $path, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('PRAGMA busy_timeout = 5000');
$pdo->exec('PRAGMA journal_mode = WAL');
$this->ensureSchema($pdo);
return $this->pdo = $pdo;
}
private function ensureSchema(PDO $pdo): void
{
$pdo->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS company_plan_shops (
id INTEGER PRIMARY KEY AUTOINCREMENT,
company_id INTEGER NOT NULL,
plan_row_id INTEGER,
company_name TEXT NOT NULL,
shop_name TEXT NOT NULL,
shop_status TEXT,
profit_center TEXT,
owner TEXT,
opened_on TEXT,
successor TEXT,
source_sheet TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE (company_id, shop_name)
)
SQL);
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_shops_company_index ON company_plan_shops (company_id, company_name)');
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_shops_status_index ON company_plan_shops (company_id, shop_status)');
// 备注口径归一:有未完结店铺的规划注销主体统一显示“关联店铺未办结”,幂等执行。
$pdo->exec(
"UPDATE company_plan_rows SET notes = '关联店铺未办结' "
. "WHERE TRIM(COALESCE(plan, '')) = '注销' "
. "AND TRIM(COALESCE(company_status, '')) = '正常' "
. "AND notes LIKE '存在未完结店铺%' "
. "AND EXISTS ("
. "SELECT 1 FROM company_plan_shops AS shops "
. "WHERE shops.company_id = company_plan_rows.company_id "
. "AND shops.company_name = company_plan_rows.company_name"
. ")"
);
}
/**
* 从资产盘点工作簿导入未完结店铺。
*
* @return array{sheets:array<string,int>,imported:int,linked:int,skipped:int}
*/
public function importFromWorkbook(string $path, int $companyId): array
{
if (! is_file($path)) {
throw new RuntimeException('源工作簿不存在:' . $path);
}
$reader = IOFactory::createReaderForFile($path);
$reader->setReadDataOnly(true);
$book = $reader->load($path);
$shops = [];
$sheetStats = [];
// 未完结店铺明细固定在工作簿的 Sheet3 与 Sheet6;
// 「店铺基础资料」等表结构相近但口径不同,不能混入。
$sheets = array_values(array_filter(
$book->getAllSheets(),
static fn ($sheet): bool => preg_match('/^sheet\s*[36]$/i', trim((string) $sheet->getTitle())) === 1,
));
if ($sheets === []) {
$sheets = $book->getAllSheets();
}
foreach ($sheets as $sheet) {
$rows = $sheet->toArray(null, true, false, false);
$layout = $this->detectLayout($rows);
if ($layout === null) {
continue;
}
$count = 0;
foreach (array_slice($rows, $layout['header_row'] + 1) as $row) {
$shop = $this->cell($row, $layout['columns']['shop']);
if ($shop === '') {
continue;
}
$company = $this->cell($row, $layout['columns']['company']);
$key = $this->normalizeName($company) . '|' . $shop;
$shops[$key] = [
'shop_name' => $shop,
'company_name' => $company,
'shop_status' => $this->cell($row, $layout['columns']['status']),
'profit_center' => $this->cell($row, $layout['columns']['center']),
'owner' => $this->cell($row, $layout['columns']['owner']),
'opened_on' => $this->dateCell($row, $layout['columns']['opened']),
'successor' => $this->cell($row, $layout['columns']['successor']),
'source_sheet' => $sheet->getTitle(),
];
$count++;
}
if ($count > 0) {
$sheetStats[$sheet->getTitle()] = $count;
}
}
$planRows = [];
$statement = $this->pdo()->prepare('SELECT id, company_name FROM company_plan_rows WHERE company_id = ?');
$statement->execute([$companyId]);
foreach ($statement->fetchAll() as $row) {
$planRows[$this->normalizeName((string) $row['company_name'])] = [
'id' => (int) $row['id'],
'name' => (string) $row['company_name'],
];
}
$pdo = $this->pdo();
$pdo->beginTransaction();
try {
$delete = $pdo->prepare('DELETE FROM company_plan_shops WHERE company_id = ?');
$delete->execute([$companyId]);
$insert = $pdo->prepare(<<<'SQL'
INSERT INTO company_plan_shops
(company_id, plan_row_id, company_name, shop_name, shop_status, profit_center, owner, opened_on, successor, source_sheet, created_at, updated_at)
VALUES
(:company_id, :plan_row_id, :company_name, :shop_name, :shop_status, :profit_center, :owner, :opened_on, :successor, :source_sheet, :created_at, :updated_at)
SQL);
$imported = 0;
$linked = 0;
$now = now()->toDateTimeString();
foreach ($shops as $shop) {
$match = $planRows[$this->normalizeName($shop['company_name'])] ?? null;
if ($match !== null) {
$linked++;
}
$insert->execute([
':company_id' => $companyId,
':plan_row_id' => $match['id'] ?? null,
':company_name' => $match['name'] ?? $shop['company_name'],
':shop_name' => mb_substr($shop['shop_name'], 0, 255),
':shop_status' => $shop['shop_status'] !== '' ? mb_substr($shop['shop_status'], 0, 64) : null,
':profit_center' => $shop['profit_center'] !== '' ? mb_substr($shop['profit_center'], 0, 128) : null,
':owner' => $shop['owner'] !== '' ? mb_substr($shop['owner'], 0, 128) : null,
':opened_on' => $shop['opened_on'],
':successor' => $shop['successor'] !== '' ? mb_substr($shop['successor'], 0, 255) : null,
':source_sheet' => $shop['source_sheet'],
':created_at' => $now,
':updated_at' => $now,
]);
$imported++;
}
$pdo->commit();
return [
'sheets' => $sheetStats,
'imported' => $imported,
'linked' => $linked,
'skipped' => count($shops) - $imported,
];
} catch (Throwable $exception) {
$pdo->rollBack();
throw $exception;
}
}
/**
* 通过表头识别未完结店铺明细表,返回表头行号与列映射。
*
* @param list<array<int,mixed>> $rows
* @return array{header_row:int,columns:array<string,int>}|null
*/
private function detectLayout(array $rows): ?array
{
foreach (array_slice($rows, 0, 6, true) as $index => $row) {
$labels = [];
foreach ($row as $column => $value) {
$label = preg_replace('/\s+/u', '', (string) $value);
if ($label !== '') {
// 同名表头取后出现的列(Sheet3 的“状态”第二次出现才是店铺状态)。
$labels[$label] = $column;
}
}
$shop = $labels['ERP系统店铺名称'] ?? $labels['店铺名称'] ?? null;
$company = $labels['主体'] ?? $labels['公司名称'] ?? null;
if ($shop === null || $company === null) {
continue;
}
return [
'header_row' => $index,
'columns' => [
'shop' => $shop,
'company' => $company,
'status' => $labels['店铺状态'] ?? $labels['状态'] ?? $shop,
'center' => $labels['利润中心'] ?? $labels['店铺所属利润中心'] ?? $shop,
'owner' => $labels['店铺负责人'] ?? $labels['负责人'] ?? $shop,
'opened' => $labels['开店时间'] ?? $shop,
'successor' => $labels['新主体'] ?? $labels['接替主体'] ?? $shop,
],
];
}
return null;
}
/** @param array<int,mixed> $row */
private function cell(array $row, int $column): string
{
$value = $row[$column] ?? null;
if ($value === null) {
return '';
}
return trim(str_replace("\u{00A0}", ' ', (string) $value));
}
/** @param array<int,mixed> $row */
private function dateCell(array $row, int $column): ?string
{
$value = $row[$column] ?? null;
if ($value === null || $value === '') {
return null;
}
if (is_numeric($value)) {
try {
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d');
} catch (Throwable $exception) {
return null;
}
}
$text = trim((string) $value);
return $text === '' ? null : mb_substr($text, 0, 32);
}
private function normalizeName(string $name): string
{
$normalized = preg_replace('/[\s\x{00A0}\x{3000}]+/u', '', $name) ?? $name;
return str_replace(['(', ')'], ['(', ')'], $normalized);
}
/**
* @param array{shop_keyword?:string,shop_status?:string,shop_company?:string} $filters
* @return array{rows:list<array<string,mixed>>,total:int,page:int,per_page:int,last_page:int}
*/
public function paginate(int $companyId, array $filters, int $page, int $perPage): array
{
[$whereSql, $params] = $this->where($companyId, $filters);
$pdo = $this->pdo();
$countStatement = $pdo->prepare("SELECT COUNT(*) FROM company_plan_shops {$whereSql}");
$countStatement->execute($params);
$total = (int) $countStatement->fetchColumn();
$lastPage = max(1, (int) ceil($total / max($perPage, 1)));
$page = min(max($page, 1), $lastPage);
$offset = ($page - 1) * $perPage;
$statement = $pdo->prepare(
"SELECT * FROM company_plan_shops {$whereSql} "
. 'ORDER BY company_name ASC, shop_name ASC LIMIT :limit OFFSET :offset'
);
foreach ($params as $key => $value) {
$statement->bindValue($key, $value);
}
$statement->bindValue(':limit', $perPage, PDO::PARAM_INT);
$statement->bindValue(':offset', $offset, PDO::PARAM_INT);
$statement->execute();
return [
'rows' => $statement->fetchAll(),
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'last_page' => $lastPage,
];
}
/**
* @param array{shop_keyword?:string,shop_status?:string,shop_company?:string} $filters
* @return array{0:string,1:array<string,mixed>}
*/
private function where(int $companyId, array $filters): array
{
$clauses = ['company_id = :company_id'];
$params = [':company_id' => $companyId];
$status = trim((string) ($filters['shop_status'] ?? ''));
if ($status !== '') {
$clauses[] = 'shop_status = :shop_status';
$params[':shop_status'] = $status;
}
$company = trim((string) ($filters['shop_company'] ?? ''));
if ($company !== '') {
$clauses[] = "REPLACE(REPLACE(company_name, '(', '('), ')', ')') = :shop_company";
$params[':shop_company'] = str_replace(['(', ')'], ['(', ')'], $company);
}
$keyword = trim((string) ($filters['shop_keyword'] ?? ''));
if ($keyword !== '') {
$clauses[] = '(shop_name LIKE :shop_keyword_shop OR company_name LIKE :shop_keyword_company)';
$params[':shop_keyword_shop'] = '%' . $keyword . '%';
$params[':shop_keyword_company'] = '%' . $keyword . '%';
}
return ['WHERE ' . implode(' AND ', $clauses), $params];
}
/**
* @param array{shop_keyword?:string,shop_status?:string,shop_company?:string} $filters
* @return array{total:int,companies:int,statuses:array<string,int>}
*/
public function summary(int $companyId, array $filters = []): array
{
[$whereSql, $params] = $this->where($companyId, $filters);
$pdo = $this->pdo();
$statement = $pdo->prepare("SELECT COUNT(*) AS total, COUNT(DISTINCT company_name) AS companies FROM company_plan_shops {$whereSql}");
$statement->execute($params);
$row = $statement->fetch() ?: [];
$statuses = [];
$statusStatement = $pdo->prepare(
"SELECT COALESCE(NULLIF(TRIM(shop_status), ''), '未标注') AS status, COUNT(*) AS n "
. "FROM company_plan_shops {$whereSql} GROUP BY status ORDER BY n DESC"
);
$statusStatement->execute($params);
foreach ($statusStatement->fetchAll() as $statusRow) {
$statuses[(string) $statusRow['status']] = (int) $statusRow['n'];
}
return [
'total' => (int) ($row['total'] ?? 0),
'companies' => (int) ($row['companies'] ?? 0),
'statuses' => $statuses,
];
}
/** @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();
}
/**
* 每个主体下的未完结店铺数量,用于主表徽章与跳转。
*
* @return array<string,int> 键为归一化后的公司名称
*/
public function countsByCompany(int $companyId): array
{
$statement = $this->pdo()->prepare(
'SELECT company_name, COUNT(*) AS n FROM company_plan_shops WHERE company_id = ? GROUP BY company_name'
);
$statement->execute([$companyId]);
$counts = [];
foreach ($statement->fetchAll() as $row) {
$name = (string) $row['company_name'];
$counts[$name] = (int) $row['n'];
$counts[$this->normalizeName($name)] = (int) $row['n'];
}
return $counts;
}
/** @return list<string> */
public function statusOptions(int $companyId): array
{
$statement = $this->pdo()->prepare(
"SELECT DISTINCT TRIM(shop_status) AS status FROM company_plan_shops "
. "WHERE company_id = ? AND TRIM(COALESCE(shop_status, '')) <> '' ORDER BY status"
);
$statement->execute([$companyId]);
return array_values(array_map(static fn (array $row): string => (string) $row['status'], $statement->fetchAll()));
}
}

View File

@ -1,101 +0,0 @@
<?php
namespace App\Business\CompanyPlan;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
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 CompanyPlanWorkbookExporter
{
/**
* @param list<array<string,mixed>> $rows
* @param list<string> $selectedFields
*/
public function download(array $rows, array $selectedFields, string $filename): StreamedResponse
{
$fields = collect(CompanyPlanRepository::FIELDS)->keyBy('name');
$selectedFields = array_values(array_filter(
$selectedFields,
static fn (string $field): bool => $fields->has($field)
));
if ($selectedFields === []) {
$selectedFields = array_column(CompanyPlanRepository::FIELDS, 'name');
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('公司盘点');
$lastColumn = Coordinate::stringFromColumnIndex(count($selectedFields));
$headers = array_map(
static fn (string $field): string => (string) $fields[$field]['label'],
$selectedFields
);
$sheet->fromArray($headers, null, 'A1');
$rowNumber = 2;
foreach ($rows as $row) {
foreach ($selectedFields as $columnIndex => $field) {
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1) . $rowNumber;
$value = $row[$field] ?? null;
if ($field === 'sequence_no' && is_numeric($value)) {
$sheet->setCellValue($coordinate, (int) $value);
} else {
$sheet->setCellValueExplicit(
$coordinate,
$value === null ? '' : (string) $value,
DataType::TYPE_STRING
);
}
}
$rowNumber++;
}
$sheet->freezePane('A2');
$sheet->setAutoFilter("A1:{$lastColumn}" . max($rowNumber - 1, 2));
$sheet->getStyle("A1:{$lastColumn}1")->applyFromArray([
'font' => ['bold' => true, 'color' => ['rgb' => '171717']],
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['rgb' => 'F7F0DE'],
],
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
],
'borders' => [
'allBorders' => ['borderStyle' => Border::BORDER_THIN, 'color' => ['rgb' => 'D8D2C7']],
],
]);
$sheet->getRowDimension(1)->setRowHeight(28);
foreach ($selectedFields as $columnIndex => $field) {
$letter = Coordinate::stringFromColumnIndex($columnIndex + 1);
$width = match ($field) {
'sequence_no' => 8,
'company_name' => 34,
'company_type', 'taxpayer_type', 'business_registration_type' => 18,
'registered_at' => 14,
'unified_social_credit_code' => 23,
'plan', 'company_status' => 13,
'tax_cancellation', 'business_cancellation', 'bank_cancellation' => 14,
'notes' => 48,
default => 16,
};
$sheet->getColumnDimension($letter)->setWidth($width);
}
return response()->streamDownload(function () use ($spreadsheet): void {
(new Xlsx($spreadsheet))->save('php://output');
$spreadsheet->disconnectWorksheets();
}, $filename, [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Cache-Control' => 'private, no-store',
]);
}
}

View File

@ -1,444 +0,0 @@
<?php
namespace App\Business\CompanyPlan;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Throwable;
class CompanyPlanWorkbookImporter
{
/**
* 类型口径归一:与 CompanyPlanRepository::COMPANY_TYPE_ALIASES 保持一致。
*
* @var array<string,string>
*/
private const COMPANY_TYPE_ALIASES = [
'个体户' => '个体工商户',
];
/**
* 公司状态口径归一:与 CompanyPlanRepository::COMPANY_STATUS_ALIASES 保持一致。
*
* @var array<string,string>
*/
private const COMPANY_STATUS_ALIASES = [
'注销' => '已注销',
];
private const KNOWN_HEADERS = [
'序号' => 'sequence_no',
'公司名称' => 'company_name',
'类型' => 'company_type',
'税务类型' => 'taxpayer_type',
'注册时间' => 'registered_at',
'工商类型' => 'business_registration_type',
'统一社会信用代码' => 'unified_social_credit_code',
'规划' => 'plan',
'公司状态' => 'company_status',
'注销-税务' => 'tax_cancellation',
'注销-工商' => 'business_cancellation',
'注销-银行' => 'bank_cancellation',
'备注' => 'notes',
];
public function __construct(private readonly CompanyPlanRepository $repository) {}
/**
* @return array<string,mixed>
*/
public function preview(UploadedFile $file, int $companyId, int $userId, string $duplicateMode): array
{
$duplicateMode = $duplicateMode === 'skip' ? 'skip' : 'update';
$parsed = $this->parse($file);
$existing = $this->repository->companyNames($companyId);
$newCount = 0;
$updateCount = 0;
$skipCount = 0;
foreach ($parsed['rows'] as $row) {
$exists = isset($existing[$this->repository->normalizeCompanyName($row['company_name'])]);
if (! $exists) {
$newCount++;
} elseif ($duplicateMode === 'skip') {
$skipCount++;
} else {
$updateCount++;
}
}
return [
'company_id' => $companyId,
'user_id' => $userId,
'generated_at' => now()->format('Y-m-d H:i:s'),
'duplicate_mode' => $duplicateMode,
'source_sheet' => $parsed['source_sheet'],
'mapped_headers' => $parsed['mapped_headers'],
'missing_headers' => $parsed['missing_headers'],
'scanned_rows' => $parsed['scanned_rows'],
'valid_rows' => count($parsed['rows']),
'blank_rows' => $parsed['blank_rows'],
'invalid_rows' => $parsed['invalid_rows'],
'invalid_count' => $parsed['invalid_count'],
'new_count' => $newCount,
'update_count' => $updateCount,
'skip_count' => $skipCount,
'rows' => $parsed['rows'],
'sample_rows' => array_slice($parsed['rows'], 0, 10),
];
}
public function storePreview(array $preview): string
{
$token = Str::random(40);
$json = json_encode(
$preview,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR
);
if (! Storage::disk((string) config('company_plan.preview_disk', 'local'))->put(
$this->previewPath($token),
$json
)) {
throw new \RuntimeException('无法保存公司盘点导入预览。');
}
return $token;
}
/**
* @return array<string,mixed>|null
*/
public function previewByToken(string $token, int $companyId, int $userId): ?array
{
if (! preg_match('/^[A-Za-z0-9]{40}$/', $token)) {
return null;
}
$disk = Storage::disk((string) config('company_plan.preview_disk', 'local'));
if (! $disk->exists($this->previewPath($token))) {
return null;
}
try {
$preview = json_decode($disk->get($this->previewPath($token)), true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable) {
$disk->delete($this->previewPath($token));
return null;
}
if (! is_array($preview)
|| (int) ($preview['company_id'] ?? 0) !== $companyId
|| (int) ($preview['user_id'] ?? 0) !== $userId) {
return null;
}
return $preview;
}
/**
* @return array{created:int,updated:int,skipped:int}
*/
public function confirm(string $token, int $companyId, int $userId, string $duplicateMode): array
{
$preview = $this->previewByToken($token, $companyId, $userId);
if ($preview === null) {
throw ValidationException::withMessages([
'import' => '导入预览已失效,请重新选择文件。',
]);
}
$result = $this->repository->importRows(
$companyId,
(array) ($preview['rows'] ?? []),
$duplicateMode === 'skip' ? 'skip' : 'update',
$userId,
);
$this->deletePreview($token);
return $result;
}
public function deletePreview(string $token): void
{
if (preg_match('/^[A-Za-z0-9]{40}$/', $token)) {
Storage::disk((string) config('company_plan.preview_disk', 'local'))
->delete($this->previewPath($token));
}
}
/**
* @return array{
* source_sheet:string,
* mapped_headers:list<string>,
* missing_headers:list<string>,
* scanned_rows:int,
* blank_rows:int,
* invalid_count:int,
* invalid_rows:list<array{row:int,company_name:string,reason:string}>,
* rows:list<array<string,mixed>>
* }
*/
private function parse(UploadedFile $file): array
{
try {
$reader = IOFactory::createReaderForFile($file->getRealPath());
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file->getRealPath());
} catch (Throwable $exception) {
report($exception);
throw ValidationException::withMessages([
'import' => '无法读取 Excel,请确认文件未损坏且格式为 xlsx/xls。',
]);
}
try {
[$worksheet, $headerRowIndex, $headerMap] = $this->resolveWorksheet($spreadsheet->getAllSheets());
} catch (Throwable $exception) {
$spreadsheet->disconnectWorksheets();
throw $exception;
}
$allRows = $worksheet->toArray(null, true, true, false);
$dataRows = array_slice($allRows, $headerRowIndex + 1);
$maxImportRows = max((int) config('company_plan.max_import_rows', 20000), 1);
if (count($dataRows) > $maxImportRows) {
$spreadsheet->disconnectWorksheets();
throw ValidationException::withMessages([
'import' => "单次最多导入 {$maxImportRows} 行,请拆分工作簿后重试。",
]);
}
$fieldsByName = collect(CompanyPlanRepository::FIELDS)->keyBy('name');
$mappedFields = array_values($headerMap);
$missingHeaders = $fieldsByName
->except($mappedFields)
->pluck('label')
->values()
->all();
$rows = [];
$invalidRows = [];
$invalidCount = 0;
$blankRows = 0;
$seenCompanies = [];
foreach ($dataRows as $offset => $rawRow) {
$sourceRow = $headerRowIndex + $offset + 2;
$hasAnyValue = false;
$rowInvalid = false;
$data = [];
foreach ($headerMap as $columnIndex => $fieldName) {
$rawValue = $rawRow[$columnIndex] ?? null;
if ($rawValue !== null && trim((string) $rawValue) !== '') {
$hasAnyValue = true;
}
try {
$data[$fieldName] = $this->normalizeValue($rawValue, $fieldName);
} catch (Throwable $exception) {
$data[$fieldName] = null;
$rowInvalid = true;
$this->appendInvalidRow(
$invalidRows,
$invalidCount,
$sourceRow,
(string) ($rawRow[array_search('company_name', $headerMap, true)] ?? ''),
'第 ' . ($columnIndex + 1) . ' 列“' . ($fieldsByName[$fieldName]['label'] ?? $fieldName) . '”格式不正确。',
);
}
}
if (! $hasAnyValue) {
$blankRows++;
continue;
}
$companyName = trim((string) ($data['company_name'] ?? ''));
if ($rowInvalid) {
continue;
}
if ($companyName === '') {
$this->appendInvalidRow($invalidRows, $invalidCount, $sourceRow, '', '公司名称为空。');
continue;
}
$normalizedCompany = $this->repository->normalizeCompanyName($companyName);
if (isset($seenCompanies[$normalizedCompany])) {
$this->appendInvalidRow(
$invalidRows,
$invalidCount,
$sourceRow,
$companyName,
'文件内公司名称重复,首次出现的第 ' . $seenCompanies[$normalizedCompany] . ' 行优先。',
);
continue;
}
$seenCompanies[$normalizedCompany] = $sourceRow;
$data['company_name'] = $companyName;
$data['_source_row'] = $sourceRow;
$rows[] = $data;
}
usort($invalidRows, static fn (array $left, array $right): int => $left['row'] <=> $right['row']);
$sourceSheet = $worksheet->getTitle();
$spreadsheet->disconnectWorksheets();
return [
'source_sheet' => $sourceSheet,
'mapped_headers' => array_values(array_map(
static fn (string $field): string => (string) ($fieldsByName[$field]['label'] ?? $field),
$mappedFields
)),
'missing_headers' => $missingHeaders,
'scanned_rows' => count($dataRows),
'blank_rows' => $blankRows,
'invalid_count' => $invalidCount,
'invalid_rows' => $invalidRows,
'rows' => $rows,
];
}
/**
* @param list<Worksheet> $worksheets
* @return array{0:Worksheet,1:int,2:array<int,string>}
*/
private function resolveWorksheet(array $worksheets): array
{
foreach ($worksheets as $worksheet) {
if ($worksheet->getTitle() === '主体盘点') {
$rows = $worksheet->toArray(null, true, true, false);
[$headerRowIndex, $headerMap] = $this->findHeader($rows);
if ($headerMap !== []) {
return [$worksheet, $headerRowIndex, $headerMap];
}
}
}
$best = null;
foreach ($worksheets as $worksheet) {
$rows = $worksheet->toArray(null, true, true, false);
[$headerRowIndex, $headerMap] = $this->findHeader($rows);
if ($best === null || count($headerMap) > count($best[2])) {
$best = [$worksheet, $headerRowIndex, $headerMap];
}
}
if ($best === null || ! in_array('company_name', $best[2], true)) {
throw ValidationException::withMessages([
'import' => '未找到“公司名称”等主体盘点表头,请使用下载的导入模板或附件中的“主体盘点”工作表。',
]);
}
return $best;
}
/**
* @param list<array<int,mixed>> $rows
* @return array{0:int,1:array<int,string>}
*/
private function findHeader(array $rows): array
{
$bestIndex = 0;
$bestMap = [];
foreach (array_slice($rows, 0, 20, true) as $rowIndex => $row) {
$map = [];
foreach ($row as $columnIndex => $value) {
$normalized = $this->normalizeHeader($value);
if (isset(self::KNOWN_HEADERS[$normalized])) {
$map[$columnIndex] = self::KNOWN_HEADERS[$normalized];
}
}
if (count($map) > count($bestMap)) {
$bestIndex = $rowIndex;
$bestMap = $map;
}
}
return [$bestIndex, $bestMap];
}
private function normalizeHeader(mixed $value): string
{
$header = str_replace(["\u{FEFF}", "\u{00A0}", '-', '—', '–'], ['', ' ', '-', '-', '-'], trim((string) $value));
return preg_replace('/\s+/u', '', $header) ?? $header;
}
private function normalizeValue(mixed $value, string $field): mixed
{
if ($value === null || trim((string) $value) === '') {
return null;
}
if ($field === 'sequence_no') {
if (! is_numeric($value)) {
throw new \InvalidArgumentException('序号不是数字');
}
return (int) $value;
}
if ($field === 'registered_at') {
return $this->normalizeDate($value);
}
$normalized = trim(str_replace("\u{00A0}", ' ', (string) $value));
if ($field === 'company_type') {
$normalized = self::COMPANY_TYPE_ALIASES[$normalized] ?? $normalized;
}
if ($field === 'company_status') {
$normalized = self::COMPANY_STATUS_ALIASES[$normalized] ?? $normalized;
}
return $normalized;
}
private function normalizeDate(mixed $value): string
{
if ($value instanceof \DateTimeInterface) {
return $value->format('Y-m-d');
}
if (is_numeric($value)) {
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d');
}
return \Illuminate\Support\Carbon::parse((string) $value)->format('Y-m-d');
}
/**
* @param list<array{row:int,company_name:string,reason:string}> $rows
*/
private function appendInvalidRow(array &$rows, int &$count, int $row, string $companyName, string $reason): void
{
$count++;
if (count($rows) < 200) {
$rows[] = [
'row' => $row,
'company_name' => trim($companyName),
'reason' => $reason,
];
}
}
private function previewPath(string $token): string
{
return trim((string) config('company_plan.preview_directory', 'company-plan/previews'), '/')
. '/' . $token . '.json';
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -9,7 +9,6 @@ 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;
/**
@ -34,7 +33,7 @@ final class CourierProfileData
/** 把覆盖值盖到快递资料行上,`_overridden` 记下改过的字段。 */
public function apply(object $row, array $overrides): object
{
$row = $this->fillFromOnboarding(clone $row);
$row = clone $row;
$changed = [];
foreach ($overrides as $field => $value) {
if (array_key_exists($field, CourierProfile::EDITABLE)) {
@ -156,16 +155,11 @@ 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;
}
@ -193,38 +187,36 @@ final class CourierProfileData
/** 保存编辑:只记和当前显示值不同的字段,并写一条操作日志。 */
public function update(string $expcode, ?string $courierName, object $current, array $values, int $userId): int
{
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];
$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;
}
if ($changes === []) {
return 0;
$new = $this->normalize($field, $values[$field]);
$old = $this->normalize($field, $current->{$field} ?? null);
if ($new === $old) {
continue;
}
$overrides[$field] = $new;
$changes[$field] = ['label' => $label, 'old' => $old, 'new' => $new];
}
if ($changes === []) {
return 0;
}
$profile->fill([
'courier_name' => $courierName ?: $profile->courier_name,
'overrides' => $overrides,
'updated_by' => $userId,
]);
$profile->created_by ??= $userId;
$profile->save();
$profile->fill([
'courier_name' => $courierName ?: $profile->courier_name,
'overrides' => $overrides,
'updated_by' => $userId,
]);
$profile->created_by ??= $userId;
$profile->save();
$this->log($expcode, 'edit', '修改 ' . implode('、', array_column($changes, 'label')), $changes, $userId);
$this->log($expcode, 'edit', '修改 ' . implode('、', array_column($changes, 'label')), $changes, $userId);
return count($changes);
});
return count($changes);
}
public function log(string $expcode, string $action, string $summary, ?array $changes, int $userId): void

View File

@ -1,294 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\SystemizationTodo;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\InventoryReportAuthoritativeImporter;
use RuntimeException;
class InventoryWarehouseMappingAlerts
{
public const CATEGORY = '商品价格管理';
public const SECTION = '进销存报表';
private const SOURCE_KEY_PREFIX = 'inventory-warehouse-unmapped:';
private readonly string $mirrorConnection;
public function __construct(
private readonly DatabaseManager $databases,
private readonly InventoryWarehouseShortNames $shortNames,
) {
$this->mirrorConnection = (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function latestMonth(): ?string
{
$connection = $this->databases->connection($this->mirrorConnection);
$schema = Schema::connection($this->mirrorConnection);
if (! $schema->hasTable('inventory_report_authoritative_months')) {
return null;
}
$month = $connection->table('inventory_report_authoritative_months')
->where('dataset_key', InventoryReportAuthoritativeImporter::DATASET_KEY)
->where('status', 'succeeded')
->whereNotNull('active_generation')
->orderByDesc('source_month')
->value('source_month');
return $month === null
? null
: Carbon::parse($month)->startOfMonth()->toDateString();
}
/**
* @return array{
* status:string,
* month:string,
* missing_pair_count:int,
* missing_row_count:int,
* task_id:?int,
* action:string
* }
*/
public function syncMonth(string $month, int $companyId = 1): array
{
$month = Carbon::parse($month)->startOfMonth()->toDateString();
$lockKey = sprintf('inventory-warehouse-mapping-alert:%d:%s', $companyId, $month);
return Cache::lock($lockKey, 120)->block(20, function () use ($month, $companyId): array {
return $this->syncMonthWithoutLock($month, $companyId);
});
}
/**
* @return array{
* status:string,
* month:string,
* source_rows:int,
* missing_pair_count:int,
* missing_row_count:int,
* missing:list<array{warehouse_provider:string,warehouse:string,source_rows:int}>
* }
*/
public function missingForMonth(string $month, int $companyId = 1): array
{
$month = Carbon::parse($month)->startOfMonth()->toDateString();
$connection = $this->databases->connection($this->mirrorConnection);
$schema = Schema::connection($this->mirrorConnection);
foreach (['inventory_report_authoritative_months', 'inventory_report_authoritative_rows'] as $table) {
if (! $schema->hasTable($table)) {
throw new RuntimeException('进销存权威月报表尚未完成迁移:' . $table);
}
}
$state = $connection->table('inventory_report_authoritative_months')
->where('dataset_key', InventoryReportAuthoritativeImporter::DATASET_KEY)
->whereDate('source_month', $month)
->where('status', 'succeeded')
->whereNotNull('active_generation')
->first();
if ($state === null) {
return [
'status' => 'unavailable',
'month' => $month,
'source_rows' => 0,
'missing_pair_count' => 0,
'missing_row_count' => 0,
'missing' => [],
];
}
$mapping = $this->shortNames->forCompany($companyId);
ksort($mapping, SORT_STRING);
$cacheKey = sprintf(
'inventory-warehouse-unmapped:%d:%s:%s:%s',
$companyId,
$month,
(string) $state->active_generation,
hash('sha256', (string) json_encode($mapping, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)),
);
return Cache::remember($cacheKey, now()->addMinutes(10), function () use (
$connection,
$state,
$month,
$mapping,
): array {
$sourcePairs = $connection->table('inventory_report_authoritative_rows')
->where('generation', (string) $state->active_generation)
->whereDate('report_month', $month)
->select(['warehouse_provider', 'warehouse'])
->selectRaw('COUNT(*) AS source_rows')
->groupBy('warehouse_provider', 'warehouse')
->orderByDesc('source_rows')
->orderBy('warehouse_provider')
->orderBy('warehouse')
->get();
$missing = [];
foreach ($sourcePairs as $pair) {
$provider = trim((string) $pair->warehouse_provider);
$warehouse = trim((string) $pair->warehouse);
$shortName = trim((string) ($mapping[$provider . "\0" . $warehouse] ?? ''));
if ($shortName !== '') {
continue;
}
$missing[] = [
'warehouse_provider' => $provider,
'warehouse' => $warehouse,
'source_rows' => (int) $pair->source_rows,
];
}
return [
'status' => 'ready',
'month' => $month,
'source_rows' => (int) $state->source_row_count,
'missing_pair_count' => count($missing),
'missing_row_count' => array_sum(array_column($missing, 'source_rows')),
'missing' => $missing,
];
});
}
/**
* @return array{
* status:string,
* month:string,
* missing_pair_count:int,
* missing_row_count:int,
* task_id:?int,
* action:string
* }
*/
private function syncMonthWithoutLock(string $month, int $companyId): array
{
$summary = $this->missingForMonth($month, $companyId);
if ($summary['status'] !== 'ready') {
throw new RuntimeException('该月份尚无已激活的进销存权威月报:' . $month);
}
$missing = $summary['missing'];
$sourceKey = self::SOURCE_KEY_PREFIX . substr($month, 0, 7);
$todo = SystemizationTodo::withTrashed()
->allCompanies()
->where('company_id', $companyId)
->where('source_key', $sourceKey)
->first();
if ($todo?->trashed()) {
return [
'status' => 'skipped',
'month' => $month,
'missing_pair_count' => count($missing),
'missing_row_count' => array_sum(array_column($missing, 'source_rows')),
'task_id' => (int) $todo->id,
'action' => 'deleted',
];
}
$monthLabel = Carbon::parse($month)->format('Y年n月');
if ($missing === []) {
if ($todo === null) {
return [
'status' => 'complete',
'month' => $month,
'missing_pair_count' => 0,
'missing_row_count' => 0,
'task_id' => null,
'action' => 'none',
];
}
if ($todo->status !== SystemizationTodo::STATUS_COMPLETED) {
$todo->update([
'status' => SystemizationTodo::STATUS_COMPLETED,
'completed_at' => today()->toDateString(),
'progress' => $monthLabel . ' 进销存报表的仓储方和仓库均已配置仓库简称,自动完成提醒。',
'notes' => null,
]);
return [
'status' => 'complete',
'month' => $month,
'missing_pair_count' => 0,
'missing_row_count' => 0,
'task_id' => (int) $todo->id,
'action' => 'completed',
];
}
return [
'status' => 'complete',
'month' => $month,
'missing_pair_count' => 0,
'missing_row_count' => 0,
'task_id' => (int) $todo->id,
'action' => 'unchanged',
];
}
$missingRowCount = array_sum(array_column($missing, 'source_rows'));
$progress = [
sprintf(
'%s 聚水潭进销存报表发现 %d 个“仓储方 / 仓库”组合未配置仓库简称,共涉及 %d 行。',
$monthLabel,
count($missing),
$missingRowCount,
),
'请前往“商品价格管理 → 进销存报表 → 仓库名称映射表”补充映射。',
'',
];
foreach ($missing as $index => $item) {
$progress[] = sprintf(
'%d. %s / %s(%d 行)',
$index + 1,
$item['warehouse_provider'],
$item['warehouse'],
$item['source_rows'],
);
}
$payload = [
'category' => self::CATEGORY,
'section' => self::SECTION,
'title' => $monthLabel . ' 进销存仓库简称待映射',
'status' => SystemizationTodo::STATUS_INCOMPLETE,
'completed_at' => null,
'progress' => implode("\n", $progress),
'notes' => null,
];
if ($todo === null) {
$todo = SystemizationTodo::allCompanies()->create([
...$payload,
'company_id' => $companyId,
'start_date' => today()->toDateString(),
'sort_order' => (int) SystemizationTodo::allCompanies()
->where('company_id', $companyId)
->max('sort_order') + 1,
'source_key' => $sourceKey,
'imported_at' => null,
]);
$action = 'created';
} else {
$action = $todo->status === SystemizationTodo::STATUS_COMPLETED
? 'reopened'
: 'updated';
$todo->update($payload);
}
return [
'status' => 'missing',
'month' => $month,
'missing_pair_count' => count($missing),
'missing_row_count' => $missingRowCount,
'task_id' => (int) $todo->id,
'action' => $action,
];
}
}

View File

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

View File

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

View File

@ -1,381 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
/**
* 聚水潭订单标签明细的每日同步。
*
* 先核对历史日期是否逐日覆盖、源订单是否在标签导入后再次变化,再补刷异常日期,
* 最后替换刷新最近数日以吸收上游迟到修改。
*/
class JstOrderLabelDailySynchronizer
{
public const SOURCE_DATASET = 'operations_replica.rpt.jst_Orders';
public function __construct(
private readonly DatabaseManager $databases,
private readonly JstOrderLabelImporter $importer,
) {}
/**
* @return array<string,mixed>
*/
public function sync(
string $from,
string $to,
int $companyId,
int $refreshDays = 7,
bool $dryRun = false,
): array {
[$fromDate, $toDate] = $this->dateRange($from, $to);
if ($companyId <= 0) {
throw new InvalidArgumentException('公司 ID 无效。');
}
if ($refreshDays < 1 || $refreshDays > 31) {
throw new InvalidArgumentException('刷新天数必须在 1 至 31 之间。');
}
$this->assertSourceReady();
$refreshStart = $fromDate->copy();
$candidateRefreshStart = $toDate->copy()->subDays($refreshDays - 1);
if ($candidateRefreshStart->gt($refreshStart)) {
$refreshStart = $candidateRefreshStart;
}
$historyEnd = $refreshStart->copy()->subDay();
$historyCoverage = $historyEnd->lt($fromDate)
? []
: $this->coverage($fromDate, $historyEnd, $companyId);
$historyIssues = array_values(array_filter(
$historyCoverage,
static fn (array $row): bool => $row['status'] !== 'ok',
));
foreach ($historyIssues as $issue) {
if ($issue['status'] === 'source_empty') {
throw new RuntimeException(sprintf(
'历史数据检查未通过:源订单镜像在 %s 没有订单,已停止拉取新数据。',
$issue['date'],
));
}
}
$backfills = $this->contiguousRanges($historyIssues);
if ($dryRun) {
return [
'status' => $historyIssues === [] ? 'would_refresh' : 'would_backfill',
'from' => $fromDate->toDateString(),
'to' => $toDate->toDateString(),
'checked_days' => (int) $fromDate->diffInDays($toDate) + 1,
'history_issues' => $historyIssues,
'backfills' => array_map(static fn (array $range): array => [
'from' => $range['from'],
'to' => $range['to'],
], $backfills),
'refresh' => [
'from' => $refreshStart->toDateString(),
'to' => $toDate->toDateString(),
],
];
}
$backfillResults = [];
foreach ($backfills as $range) {
$backfillResults[] = $this->importer->import(
$range['from'],
$range['to'],
$companyId,
true,
'jst-order-label-daily-sync',
);
}
if ($historyIssues !== []) {
$remainingHistory = $this->coverage($fromDate, $historyEnd, $companyId);
$remainingIssues = array_values(array_filter(
$remainingHistory,
static fn (array $row): bool => $row['status'] !== 'ok',
));
if ($remainingIssues !== []) {
throw new RuntimeException('历史缺口补导后仍未通过覆盖检查:' . $this->issueSummary($remainingIssues));
}
}
$refreshResult = $this->importer->import(
$refreshStart->toDateString(),
$toDate->toDateString(),
$companyId,
true,
'jst-order-label-daily-sync',
);
$finalCoverage = $this->coverage($fromDate, $toDate, $companyId);
$finalIssues = array_values(array_filter(
$finalCoverage,
static fn (array $row): bool => $row['status'] !== 'ok',
));
if ($finalIssues !== []) {
throw new RuntimeException('同步后覆盖检查未通过:' . $this->issueSummary($finalIssues));
}
return [
'status' => 'ok',
'from' => $fromDate->toDateString(),
'to' => $toDate->toDateString(),
'checked_days' => count($finalCoverage),
'backfilled_ranges' => array_map(static fn (array $range): array => [
'from' => $range['from'],
'to' => $range['to'],
], $backfills),
'backfill_results' => $backfillResults,
'refresh' => $refreshResult,
];
}
/**
* 只读确认指定日期都已覆盖且没有导入后的源订单变化;异常会阻止下游重算。
*
* @return list<array{
* date:string,
* source_orders:int,
* target_orders:int,
* target_rows:int,
* source_max_update_time:?string,
* target_imported_at:?string,
* status:string
* }>
*/
public function assertCovered(string $from, string $to, int $companyId): array
{
[$fromDate, $toDate] = $this->dateRange($from, $to);
if ($companyId <= 0) {
throw new InvalidArgumentException('公司 ID 无效。');
}
$this->assertSourceReady();
$coverage = $this->coverage($fromDate, $toDate, $companyId);
$issues = array_values(array_filter(
$coverage,
static fn (array $row): bool => $row['status'] !== 'ok',
));
if ($issues !== []) {
throw new RuntimeException('历史数据检查未通过:' . $this->issueSummary($issues));
}
return $coverage;
}
/**
* 逐日比较源订单覆盖,并比较源订单更新时间与标签日期的完整导入时间。
*
* 标签拆行后同一订单会出现多行,因此不能用总行数直接比较订单完整性。
* updateTime 晚于目标日最后导入时间,说明源订单可能只改了标签、未增删订单;
* 这类日期也必须整日重刷,否则订单数相同但标签内容会一直停留在旧版本。
*
* @return list<array{
* date:string,
* source_orders:int,
* target_orders:int,
* target_rows:int,
* source_max_update_time:?string,
* target_imported_at:?string,
* status:string
* }>
*/
public function coverage(Carbon $from, Carbon $to, int $companyId): array
{
$start = $from->copy()->startOfDay()->toDateTimeString();
$end = $to->copy()->addDay()->startOfDay()->toDateTimeString();
$mirror = $this->mirror();
$target = $this->databases->connection();
$sourceRows = $mirror->table('ops_jst_orders')
->where('order_date', '>=', $start)
->where('order_date', '<', $end)
->selectRaw(
'DATE(order_date) AS day, COUNT(DISTINCT so_id) AS order_count, '
. 'MAX(updateTime) AS source_max_update_time',
)
->groupByRaw('DATE(order_date)')
->get()
->keyBy('day');
$targetRows = $target->table('jst_order_labels')
->where('company_id', $companyId)
->whereNull('deleted_at')
->where('ordered_at', '>=', $start)
->where('ordered_at', '<', $end)
->selectRaw(
'DATE(ordered_at) AS day, COUNT(*) AS row_count, '
. 'COUNT(DISTINCT order_no) AS order_count, '
. 'MIN(created_at) AS target_imported_at',
)
->groupByRaw('DATE(ordered_at)')
->get()
->keyBy('day');
$coverage = [];
for ($day = $from->copy()->startOfDay(); $day->lte($to); $day->addDay()) {
$date = $day->toDateString();
$sourceOrders = (int) ($sourceRows[$date]->order_count ?? 0);
$targetOrderCount = (int) ($targetRows[$date]->order_count ?? 0);
$targetRowsCount = (int) ($targetRows[$date]->row_count ?? 0);
$sourceMaxUpdateTime = $sourceRows[$date]->source_max_update_time ?? null;
$targetImportedAt = $targetRows[$date]->target_imported_at ?? null;
$sourceUpdatedAt = $this->timestamp($sourceMaxUpdateTime);
$targetImportedAtCarbon = $this->timestamp($targetImportedAt);
$sourceIsNewer = $sourceUpdatedAt !== null
&& $targetImportedAtCarbon !== null
&& $sourceUpdatedAt->gt($targetImportedAtCarbon);
$status = match (true) {
$sourceOrders === 0 => 'source_empty',
$targetOrderCount === 0 => 'missing',
$targetOrderCount < $sourceOrders => 'incomplete',
$targetOrderCount > $sourceOrders => 'extra_orders',
$sourceIsNewer => 'stale',
default => 'ok',
};
$coverage[] = [
'date' => $date,
'source_orders' => $sourceOrders,
'target_orders' => $targetOrderCount,
'target_rows' => $targetRowsCount,
'source_max_update_time' => $sourceMaxUpdateTime,
'target_imported_at' => $targetImportedAt,
'status' => $status,
];
}
return $coverage;
}
private function assertSourceReady(): void
{
$mirror = $this->mirror();
$schema = $mirror->getSchemaBuilder();
if (! $schema->hasTable('ops_jst_orders')) {
throw new RuntimeException('聚水潭订单镜像尚未建立(ops_jst_orders)。');
}
if (! $schema->hasTable('business_mirror_table_states')) {
throw new RuntimeException('聚水潭订单镜像同步状态表尚未建立。');
}
$state = $mirror->table('business_mirror_table_states')
->where('dataset_key', self::SOURCE_DATASET)
->first(['status', 'initial_completed_at']);
if ($state === null || $state->initial_completed_at === null) {
throw new RuntimeException('聚水潭订单镜像尚未完成首次同步。');
}
if ((string) $state->status !== 'succeeded') {
throw new RuntimeException('聚水潭订单镜像最近同步未成功,已停止标签明细同步。');
}
}
private function mirror(): \Illuminate\Database\ConnectionInterface
{
return $this->databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* @param list<array{date:string}> $issues
* @return list<array{from:string,to:string}>
*/
private function contiguousRanges(array $issues): array
{
usort($issues, static fn (array $left, array $right): int => $left['date'] <=> $right['date']);
$ranges = [];
$start = null;
$previous = null;
foreach ($issues as $issue) {
$day = Carbon::createFromFormat('!Y-m-d', $issue['date'], 'Asia/Shanghai');
if ($start === null) {
$start = $day;
$previous = $day;
continue;
}
if (! $day->isSameDay($previous->copy()->addDay())) {
$ranges[] = ['from' => $start->toDateString(), 'to' => $previous->toDateString()];
$start = $day;
}
$previous = $day;
}
if ($start !== null && $previous !== null) {
$ranges[] = ['from' => $start->toDateString(), 'to' => $previous->toDateString()];
}
return $ranges;
}
/** @param list<array{date:string,status:string}> $issues */
private function issueSummary(array $issues): string
{
return implode(',', array_map(
static function (array $issue): string {
$detail = $issue['date'] . '=' . $issue['status'];
if (($issue['status'] ?? null) === 'stale') {
$detail .= sprintf(
'(源更新时间 %s,标签导入时间 %s)',
$issue['source_max_update_time'] ?? '空',
$issue['target_imported_at'] ?? '空',
);
}
return $detail;
},
$issues,
));
}
/** @return array{0:Carbon,1:Carbon} */
private function dateRange(string $from, string $to): array
{
$fromDate = $this->date($from);
$toDate = $this->date($to);
if ($fromDate === null || $toDate === null || $fromDate->gt($toDate)) {
throw new InvalidArgumentException('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。');
}
return [$fromDate, $toDate];
}
private function date(string $value): ?Carbon
{
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
return null;
}
try {
$date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
} catch (Throwable) {
return null;
}
return $date->format('Y-m-d') === $value ? $date : null;
}
private function timestamp(mixed $value): ?Carbon
{
if ($value === null || trim((string) $value) === '') {
return null;
}
try {
return Carbon::parse((string) $value, 'Asia/Shanghai');
} catch (Throwable) {
return null;
}
}
}

View File

@ -15,16 +15,11 @@ use RuntimeException;
* 两个数据源:
* - 共享镜像 ops_jst_orders(常规,覆盖镜像有数据的区间);
* - 聚水潭「导出订单」Excel(镜像没有的历史区间,例如 2026-03,只能靠财务导出补)。
*
* 卖家备注包含「SSDD」时同时生成 SSDD 标签。卖家备注不是聚水潭系统标签,
* 但种菜判断需要把这类订单纳入标签明细。
*/
class JstOrderLabelImporter
{
public const NO_LABEL = '(无标签)';
public const SELLER_REMARK_LABEL = 'SSDD';
private const READ_CHUNK = 2000;
private const INSERT_CHUNK = 2000;
@ -32,8 +27,6 @@ class JstOrderLabelImporter
/** 聚水潭导出文件里用到的表头。 */
private const EXPORT_COLUMNS = ['线上订单号', '店铺名称', '下单时间', '标签'];
private const EXPORT_OPTIONAL_COLUMNS = ['卖家备注'];
public function __construct(
private readonly DatabaseManager $databases,
private readonly ?XlsxSheetReader $exportReader = null,
@ -105,10 +98,7 @@ class JstOrderLabelImporter
continue;
}
$labels = $this->labelsForRecord(
(string) ($record->labels ?? ''),
(string) ($record->remark ?? ''),
);
$labels = $this->splitLabels((string) ($record->labels ?? ''));
if ($labels === []) {
$labels = [self::NO_LABEL];
$noLabelOrders++;
@ -231,12 +221,9 @@ class JstOrderLabelImporter
// 明细行带标签;不按订单判断就会给本来有标签的订单多写一行「(无标签)」。
$labeledOrders = [];
$anyRow = false;
foreach ($reader->rows($path, self::EXPORT_COLUMNS, self::EXPORT_OPTIONAL_COLUMNS) as $line) {
foreach ($reader->rows($path, self::EXPORT_COLUMNS) as $line) {
$anyRow = true;
if ($this->labelsForRecord(
(string) ($line['标签'] ?? ''),
(string) ($line['卖家备注'] ?? ''),
) === []) {
if ($this->splitLabels((string) ($line['标签'] ?? '')) === []) {
continue;
}
$orderNo = trim((string) ($line['线上订单号'] ?? ''));
@ -254,7 +241,7 @@ class JstOrderLabelImporter
}
// 第二遍:按「线上订单号 + 标签」去重后写入。
foreach ($reader->rows($path, self::EXPORT_COLUMNS, self::EXPORT_OPTIONAL_COLUMNS) as $line) {
foreach ($reader->rows($path, self::EXPORT_COLUMNS) as $line) {
$orderNo = trim((string) ($line['线上订单号'] ?? ''));
$orderedAt = $this->normalizeOrderedAt((string) ($line['下单时间'] ?? ''));
if ($orderNo === '' || $orderedAt === null) {
@ -268,10 +255,7 @@ class JstOrderLabelImporter
continue;
}
$labels = $this->labelsForRecord(
(string) ($line['标签'] ?? ''),
(string) ($line['卖家备注'] ?? ''),
);
$labels = $this->splitLabels((string) ($line['标签'] ?? ''));
$withoutLabel = $labels === [];
if ($withoutLabel) {
if (isset($labeledOrders[$orderNo])) {
@ -366,18 +350,6 @@ class JstOrderLabelImporter
return array_values(array_unique($out));
}
/** @return list<string> */
public function labelsForRecord(string $labels, string $sellerRemark): array
{
$labels = $this->splitLabels($labels);
if (stripos($sellerRemark, self::SELLER_REMARK_LABEL) !== false
&& ! in_array(self::SELLER_REMARK_LABEL, $labels, true)) {
$labels[] = self::SELLER_REMARK_LABEL;
}
return $labels;
}
private function normalizeDate(string $value, string $label): string
{
$value = trim($value);

View File

@ -1,297 +0,0 @@
<?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;
use Throwable;
class KukaPostingBaseImporter
{
private const INSERT_CHUNK = 500;
public function __construct(
private readonly DatabaseManager $databases,
private readonly XlsxSheetReader $reader,
) {
}
/**
* @return array{
* period: string,
* dry_run: bool,
* rows: int,
* stores: array<string, int>,
* store_count: int,
* order_count: int,
* skipped_store_rows: int,
* skipped_cancelled_rows: int,
* file_sha256: string
* }
*/
public function import(
string $path,
string $period,
?string $sheetName = 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_imports')
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) {
throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。');
}
$fields = (array) config('kuka_posting.fields', []);
$allowedStores = array_values((array) config('kuka_posting.stores', []));
if ($fields === [] || $allowedStores === []) {
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', '发货明细表')));
$fileHash = hash_file('sha256', $path);
if (! is_string($fileHash)) {
throw new RuntimeException('无法计算聚水潭导出文件摘要。');
}
$storeCounts = array_fill_keys($allowedStores, 0);
$orders = [];
$rowCount = 0;
$skippedStoreRows = 0;
$skippedCancelledRows = 0;
$sourceRowNumber = 1;
$now = now();
$write = function () use (
$connection,
$path,
$period,
$sheetName,
$companyId,
$fields,
$requiredSourceColumns,
$optionalSourceColumns,
$allowedStores,
&$storeCounts,
&$orders,
&$rowCount,
&$skippedStoreRows,
&$skippedCancelledRows,
&$sourceRowNumber,
$fileHash,
$now,
$dryRun,
): void {
if (! $dryRun) {
$connection->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->delete();
}
$batch = [];
$flush = static function () use (&$batch, $connection): void {
if ($batch === []) {
return;
}
$connection->table('kuka_posting_base_rows')->insert($batch);
$batch = [];
};
foreach ($this->reader->rows(
$path,
$requiredSourceColumns,
$optionalSourceColumns,
$sheetName,
) as $sourceValues) {
$sourceRowNumber++;
$storeName = trim((string) ($sourceValues['店铺'] ?? ''));
if ($storeName === '' || ! in_array($storeName, $allowedStores, true)) {
$skippedStoreRows++;
continue;
}
if (trim((string) ($sourceValues['订单状态'] ?? '')) === '已取消') {
$skippedCancelledRows++;
continue;
}
$payload = [];
foreach ($fields as $field) {
$source = (string) $field['source'];
$value = trim((string) ($sourceValues[$source] ?? ''));
if (($field['kind'] ?? null) === 'date') {
$value = $this->normalizeDate($value);
}
$payload[$source] = $value;
}
$rowCount++;
$storeCounts[$storeName]++;
$internalOrderNo = trim((string) ($payload['内部订单号'] ?? ''));
if ($internalOrderNo !== '') {
$orders[$internalOrderNo] = true;
}
if ($dryRun) {
continue;
}
$batch[] = [
'company_id' => $companyId,
'period' => $period,
'store_name' => $storeName,
'internal_order_no' => $this->limit($internalOrderNo, 191),
'online_order_no' => $this->limit((string) ($payload['线上订单号'] ?? ''), 191),
'product_code' => $this->limit((string) ($payload['商品编码'] ?? ''), 191),
'order_status' => $this->limit((string) ($payload['订单状态'] ?? ''), 64),
'order_date' => $this->nullableValue($payload['订单日期'] ?? ''),
'send_date' => $this->nullableValue($payload['发货日期'] ?? ''),
'pay_date' => $this->nullableValue($payload['付款日期'] ?? ''),
'confirm_date' => $this->nullableValue($payload['确认收货日期'] ?? ''),
'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 (count($batch) >= self::INSERT_CHUNK) {
$flush();
}
}
$flush();
if ($rowCount === 0) {
throw new RuntimeException('导出文件中没有指定店铺的数据,已保留原有基础数据。');
}
$missingStores = array_keys(array_filter(
$storeCounts,
static fn (int $count): bool => $count === 0,
));
if ($missingStores !== []) {
throw new RuntimeException('导出文件缺少指定店铺:' . implode('、', $missingStores));
}
if ($dryRun) {
return;
}
$import = [
'company_id' => $companyId,
'period' => $period,
'row_count' => $rowCount,
'store_count' => count(array_filter($storeCounts)),
'order_count' => count($orders),
'store_counts' => json_encode($storeCounts, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'file_name' => basename($path),
'file_sha256' => $fileHash,
'source_sheet' => $sheetName,
'completed_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
$connection->table('kuka_posting_base_imports')->upsert(
[$import],
['company_id', 'period'],
[
'row_count',
'store_count',
'order_count',
'store_counts',
'file_name',
'file_sha256',
'source_sheet',
'completed_at',
'updated_at',
],
);
};
if ($dryRun) {
$write();
} else {
$connection->transaction($write);
}
return [
'period' => $period,
'dry_run' => $dryRun,
'rows' => $rowCount,
'stores' => $storeCounts,
'store_count' => count(array_filter($storeCounts)),
'order_count' => count($orders),
'skipped_store_rows' => $skippedStoreRows,
'skipped_cancelled_rows' => $skippedCancelledRows,
'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 ($value === '') {
return '';
}
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 nullableValue(string $value): ?string
{
return $value === '' ? null : $value;
}
private function limit(string $value, int $length): ?string
{
$value = trim($value);
return $value === '' ? null : mb_substr($value, 0, $length);
}
}

View File

@ -1,240 +0,0 @@
<?php
namespace App\Business\KukaPostingBase;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Throwable;
class KukaPostingBasePageData
{
public function __construct(private readonly KukaPostingBaseRepository $repository)
{
}
/**
* @return array{
* directory: array<string, mixed>,
* rows: mixed,
* filters: array<string, mixed>,
* periods: list<string>,
* statuses: list<string>,
* stores: list<string>,
* import: ?array<string, mixed>,
* summary: array<string, mixed>,
* error: ?string
* }
*/
public function build(Request $request, int $companyId): array
{
$stores = array_values((array) config('kuka_posting.stores', []));
$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;
$period = trim((string) $request->query('period', ''));
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
$period = (string) ($latest->period ?? ($periods[0] ?? now()->format('Y-m')));
}
$storeName = trim((string) $request->query('store_name', ''));
if ($storeName !== '' && ! in_array($storeName, $stores, true)) {
$storeName = '';
}
$status = mb_substr(trim((string) $request->query('status', '')), 0, 64);
$keyword = mb_substr(trim((string) $request->query('keyword', '')), 0, 120);
$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));
$filters = [
'period' => $period,
'store_name' => $storeName,
'status' => $status,
'keyword' => $keyword,
'per_page' => $perPage,
];
$error = $available ? null : '顾家过账基础数据镜像尚未建立,请先执行数据库迁移。';
try {
$rows = $available
? $this->repository->paginate($companyId, $period, $filters, $page, $perPage)
: new LengthAwarePaginator([], 0, $perPage, $page, [
'path' => $request->url(),
'query' => $request->query(),
]);
$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) : [];
} catch (Throwable $exception) {
report($exception);
$statuses = [];
$error = '顾家过账基础数据暂时无法读取,请稍后重试;这不代表业务数据为 0。';
$rows = new LengthAwarePaginator([], 0, $perPage, $page, [
'path' => $request->url(),
'query' => $request->query(),
]);
}
$import = $available ? $this->repository->importFor($companyId, $period) : null;
$importData = null;
if ($import !== null) {
$storeCounts = json_decode((string) ($import->store_counts ?? ''), true);
$importData = [
'period' => (string) $import->period,
'row_count' => (int) $import->row_count,
'store_count' => (int) $import->store_count,
'order_count' => (int) $import->order_count,
'store_counts' => is_array($storeCounts) ? $storeCounts : [],
'file_name' => (string) $import->file_name,
'file_sha256' => (string) $import->file_sha256,
'source_sheet' => (string) $import->source_sheet,
'completed_at' => (string) $import->completed_at,
];
}
return [
'directory' => [
'icon' => 'dataset',
'status' => $importData === null ? '尚未导入' : '聚水潭原始明细',
'description' => '聚水潭“销售主题分析(新版)· 商品利润 · 明细(订单商品)”原始导出。仅保留指定 12 家店铺的 ' . $period . ' 数据。',
'empty' => '该账期还没有导入顾家过账基础数据。',
'fields' => $fields,
],
'rows' => $rows,
'filters' => $filters,
'periods' => $periods,
'statuses' => $statuses,
'stores' => $stores,
'import' => $importData,
'summary' => [
'filtered_rows' => $rows->total(),
'rows' => (int) ($importData['row_count'] ?? 0),
'stores' => (int) ($importData['store_count'] ?? 0),
'orders' => (int) ($importData['order_count'] ?? 0),
'completed_at' => $importData['completed_at'] ?? null,
],
'error' => $error,
];
}
private function decimal(mixed $value): ?string
{
$normalized = str_replace(',', '', trim((string) $value));
return $normalized !== '' && is_numeric($normalized) ? $normalized : null;
}
private function multiplyDecimal(string $cost, string $quantity): string
{
if (function_exists('bcmul')) {
return bcmul($cost, $quantity, 4);
}
return number_format((float) $cost * (float) $quantity, 4, '.', '');
}
}

View File

@ -1,238 +0,0 @@
<?php
namespace App\Business\KukaPostingBase;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
class KukaPostingBaseRepository
{
public function __construct(private readonly DatabaseManager $databases)
{
}
public function available(): bool
{
$schema = Schema::connection($this->connectionName());
return $schema->hasTable('kuka_posting_base_imports')
&& $schema->hasTable('kuka_posting_base_rows');
}
public function latestImport(int $companyId): ?object
{
if (! $this->available()) {
return null;
}
return $this->connection()
->table('kuka_posting_base_imports')
->where('company_id', $companyId)
->orderByDesc('period')
->first();
}
public function importFor(int $companyId, string $period): ?object
{
if (! $this->available()) {
return null;
}
return $this->connection()
->table('kuka_posting_base_imports')
->where('company_id', $companyId)
->where('period', $period)
->first();
}
/**
* @return list<string>
*/
public function periods(int $companyId): array
{
if (! $this->available()) {
return [];
}
return $this->connection()
->table('kuka_posting_base_imports')
->where('company_id', $companyId)
->orderByDesc('period')
->pluck('period')
->map(static fn (mixed $period): string => (string) $period)
->all();
}
/**
* @return list<string>
*/
public function statuses(int $companyId, string $period): array
{
if (! $this->available()) {
return [];
}
return $this->connection()
->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->whereNotNull('order_status')
->where('order_status', '!=', '')
->distinct()
->orderBy('order_status')
->pluck('order_status')
->map(static fn (mixed $status): string => (string) $status)
->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,
array $filters,
int $page,
int $perPage,
): LengthAwarePaginator {
$query = $this->connection()
->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period);
$storeName = trim((string) ($filters['store_name'] ?? ''));
if ($storeName !== '') {
$query->where('store_name', $storeName);
}
$status = trim((string) ($filters['status'] ?? ''));
if ($status !== '') {
$query->where('order_status', $status);
}
$keyword = trim((string) ($filters['keyword'] ?? ''));
if ($keyword !== '') {
$like = '%' . addcslashes($keyword, '\\%_') . '%';
$query->where(static function ($nested) use ($like): void {
$nested->where('internal_order_no', 'like', $like)
->orWhere('online_order_no', 'like', $like)
->orWhere('product_code', 'like', $like);
});
}
return $query
->orderBy('source_row_number')
->paginate($perPage, ['*'], 'page', $page)
->withQueryString();
}
private function connection(): ConnectionInterface
{
return $this->databases->connection($this->connectionName());
}
private function connectionName(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
}

View File

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

View File

@ -1,505 +0,0 @@
<?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');
}
}

View File

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

View File

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

View File

@ -1,178 +0,0 @@
<?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,
];
}
}

View File

@ -1,141 +0,0 @@
<?php
namespace App\Business;
use App\Models\Business\LaborExpenseSnapshot;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class LaborExpenseDataStore
{
public const MAX_ROWS = 2000;
/**
* @return array{rows: array<int, array<string, mixed>>, row_count: int, source_name: ?string, saved_by: ?int, saved_at: ?string}
*/
public function load(): array
{
$snapshot = LaborExpenseSnapshot::query()
->where('company_id', company_id())
->first();
return [
'rows' => is_array($snapshot?->rows) ? array_values($snapshot->rows) : [],
'row_count' => (int) ($snapshot?->row_count ?? 0),
'source_name' => $snapshot?->source_name,
'saved_by' => $snapshot?->saved_by,
'saved_at' => $snapshot?->saved_at?->toIso8601String(),
];
}
/**
* @param array<int, mixed> $rows
* @return array{rows: array<int, array<string, mixed>>, row_count: int, source_name: ?string, saved_by: ?int, saved_at: string}
*/
public function save(array $rows, ?string $sourceName, ?int $savedBy): array
{
if (count($rows) > self::MAX_ROWS) {
throw ValidationException::withMessages([
'rows' => '单次最多保存 ' . number_format(self::MAX_ROWS) . ' 行,请拆分后再保存。',
]);
}
$fields = collect(config('labor_expense_table.fields', []))
->filter(static fn (array $field): bool => ($field['kind'] ?? null) !== 'sequence'
&& blank($field['formula'] ?? null))
->values();
if ($fields->isEmpty()) {
throw ValidationException::withMessages([
'rows' => '人工费用表没有可保存的录入列。',
]);
}
$companyId = (int) company_id();
if ($companyId < 1) {
throw ValidationException::withMessages([
'rows' => '当前没有可保存的公司。',
]);
}
$normalizedRows = [];
foreach (array_values($rows) as $index => $row) {
if (! is_array($row)) {
throw ValidationException::withMessages([
'rows' => '第 ' . ($index + 1) . ' 行数据格式无效。',
]);
}
$record = [];
$hasValue = false;
foreach ($fields as $field) {
$value = $this->normalizeCell($row[$field['key']] ?? null, $field, $index + 1);
$record[$field['key']] = $value;
$hasValue = $hasValue || $value !== '';
}
if ($hasValue) {
$normalizedRows[] = $record;
}
}
$sourceName = trim((string) $sourceName);
$sourceName = $sourceName === '' ? null : mb_substr($sourceName, 0, 191);
$savedAt = now();
DB::transaction(function () use ($companyId, $sourceName, $savedBy, $savedAt, $normalizedRows): void {
LaborExpenseSnapshot::query()->updateOrCreate(
['company_id' => $companyId],
[
'source_name' => $sourceName,
'rows' => $normalizedRows,
'row_count' => count($normalizedRows),
'saved_by' => $savedBy,
'saved_at' => $savedAt,
],
);
});
return [
'rows' => $normalizedRows,
'row_count' => count($normalizedRows),
'source_name' => $sourceName,
'saved_by' => $savedBy,
'saved_at' => $savedAt->toIso8601String(),
];
}
private function normalizeCell(mixed $value, array $field, int $line): mixed
{
if ($value === null) {
return '';
}
$text = trim((string) $value);
if ($text === '') {
return '';
}
if (! in_array($field['kind'] ?? 'text', ['number', 'percent'], true)) {
if (mb_strlen($text) > 120) {
throw ValidationException::withMessages([
'rows' => "第 {$line} 行“{$field['label']}”不能超过 120 个字符。",
]);
}
return $text;
}
$isPercentText = ($field['kind'] ?? null) === 'percent' && str_ends_with($text, '%');
$number = str_replace([',', ',', '¥', '¥', '%'], '', $text);
if (! is_numeric($number)) {
throw ValidationException::withMessages([
'rows' => "第 {$line} 行“{$field['label']}”不是有效数字。",
]);
}
$normalized = (float) $number;
return $isPercentText ? $normalized / 100 : $normalized;
}
}

View File

@ -1,177 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Http\UploadedFile;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Throwable;
class LaborExpenseWorkbookImporter
{
private const MAX_DATA_ROWS = 2000;
/**
* @return array{rows: array<int, array<string, mixed>>, row_count: int, blank_count: int}
*/
public function import(UploadedFile $file): array
{
$fields = collect(config('labor_expense_table.fields', []))
->filter(static fn (array $field): bool => ($field['kind'] ?? null) !== 'sequence'
&& blank($field['formula'] ?? null));
if ($fields->isEmpty()) {
throw ValidationException::withMessages([
'import' => '人工费用表没有可导入的录入列。',
]);
}
$lookup = [];
foreach ($fields as $field) {
$lookup[$this->normalizeHeader($field['key'])] = $field['key'];
$lookup[$this->normalizeHeader($field['label'])] = $field['key'];
}
$spreadsheet = null;
try {
$readerType = match (mb_strtolower($file->getClientOriginalExtension())) {
'xlsx' => 'Xlsx',
'xls' => 'Xls',
'csv' => 'Csv',
default => throw new \RuntimeException('Unsupported workbook format.'),
};
$reader = IOFactory::createReader($readerType);
if (method_exists($reader, 'setReadDataOnly')) {
$reader->setReadDataOnly(true);
}
$spreadsheet = $reader->load($file->getRealPath());
[$sheetRows, $headerRow, $columns] = $this->bestSheet($spreadsheet, $lookup);
} catch (Throwable) {
throw ValidationException::withMessages([
'import' => '无法读取导入文件,请确认文件未损坏且格式为 xlsx、xls 或 csv。',
]);
} finally {
if ($spreadsheet) {
$spreadsheet->disconnectWorksheets();
}
}
if ($sheetRows === null || $columns === []) {
throw ValidationException::withMessages([
'import' => '未找到当前人工费用表的可录入列,请使用页面“导出全部字段”生成的文件作为模板。',
]);
}
$fieldMap = $fields->keyBy('key');
$rows = [];
$blankCount = 0;
foreach (array_slice($sheetRows, $headerRow + 1, null, true) as $rowIndex => $row) {
$record = [];
$hasValue = false;
foreach ($columns as $columnIndex => $fieldKey) {
$field = $fieldMap[$fieldKey];
$value = $this->normalizeCell(
$row[$columnIndex] ?? null,
$field['kind'] ?? 'text',
(int) $rowIndex + 1,
$field['label'] ?? $fieldKey,
);
$record[$fieldKey] = $value;
$hasValue = $hasValue || $value !== '';
}
if (! $hasValue) {
$blankCount++;
continue;
}
$rows[] = $record;
if (count($rows) > self::MAX_DATA_ROWS) {
throw ValidationException::withMessages([
'import' => '单次最多导入 ' . number_format(self::MAX_DATA_ROWS) . ' 行,请拆分文件后重试。',
]);
}
}
if ($rows === []) {
throw ValidationException::withMessages([
'import' => '表格中没有可导入的数据行。',
]);
}
return [
'rows' => $rows,
'row_count' => count($rows),
'blank_count' => $blankCount,
];
}
/**
* @return array{0: array<int, array<int, mixed>>|null, 1: int|null, 2: array<int, string>}
*/
private function bestSheet(mixed $spreadsheet, array $lookup): array
{
$best = [null, null, []];
$bestScore = 0;
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$rows = $worksheet->toArray(null, false, false, false);
foreach (array_slice($rows, 0, 30, true) as $rowIndex => $row) {
$columns = [];
foreach ($row as $columnIndex => $heading) {
$key = $this->normalizeHeader($heading);
if ($key !== '' && isset($lookup[$key])) {
$columns[$columnIndex] = $lookup[$key];
}
}
$score = count(array_unique(array_values($columns)));
if ($score > $bestScore) {
$best = [$rows, (int) $rowIndex, $columns];
$bestScore = $score;
}
}
}
return $best;
}
private function normalizeCell(mixed $value, string $kind, int $line, string $label): mixed
{
if ($value === null) {
return '';
}
$text = trim((string) $value);
if ($text === '') {
return '';
}
if (! in_array($kind, ['number', 'percent'], true)) {
return $text;
}
$isPercentText = $kind === 'percent' && str_ends_with($text, '%');
$number = str_replace([',', ',', '¥', '¥', '%'], '', $text);
if (! is_numeric($number)) {
throw ValidationException::withMessages([
'import' => "第 {$line} 行“{$label}”不是有效数字。",
]);
}
$normalized = (float) $number;
return $isPercentText ? $normalized / 100 : $normalized;
}
private function normalizeHeader(mixed $value): string
{
return mb_strtolower(preg_replace('/[\s\x{FEFF}_\-()()*::]+/u', '', trim((string) $value)));
}
}

View File

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

View File

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

View File

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

View File

@ -95,10 +95,9 @@ class PlantingWorkOrderSynchronizer
throw new InvalidArgumentException('起始日期不能晚于结束日期。');
}
// 「日期」= 工单完成日 − 1。结束日 30 日对应的完成时间可到次月 1 日 23:59:59,
// 因此边界整体后移时,排除上界要再加一天。
// 「日期」= 工单完成日 − 1,所以完成时间窗口整体后移一天。
$completeFrom = date('Y-m-d', strtotime($from . ' +1 day')) . ' 00:00:00';
$completeTo = date('Y-m-d', strtotime($to . ' +2 days')) . ' 00:00:00';
$completeTo = date('Y-m-d', strtotime($to . ' +1 day')) . ' 00:00:00';
$target = $this->databases->connection();
$mirror = $this->databases->connection((string) config('upstream_mirrors.connection', 'business_mirror'));

View File

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

View File

@ -1,184 +0,0 @@
<?php
namespace App\Business;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
/**
* 每日编排:先同步种菜报销工单,再核对标签覆盖,最后重算业绩明细种菜金额。
*/
class StoreReceiptPlantingDailySynchronizer
{
public const WORK_ORDER_DATASET = 'jiansun.dbo.jst_workOrderInfo';
public function __construct(
private readonly DatabaseManager $databases,
private readonly JstOrderLabelDailySynchronizer $labelCoverage,
private readonly PlantingWorkOrderSynchronizer $plantingWorkOrders,
) {}
/**
* @param list<string> $months
* @return array<string,mixed>
*/
public function sync(
string $from,
string $to,
int $companyId,
array $months = [],
bool $dryRun = false,
): array {
[$fromDate, $toDate] = $this->dateRange($from, $to);
if ($companyId <= 0) {
throw new InvalidArgumentException('公司 ID 无效。');
}
$months = $this->months($months, $toDate);
$this->assertWorkOrderSourceReady();
if ($dryRun) {
$coverage = $this->labelCoverage->assertCovered(
$fromDate->toDateString(),
$toDate->toDateString(),
$companyId,
);
return [
'status' => 'ready',
'from' => $fromDate->toDateString(),
'to' => $toDate->toDateString(),
'checked_days' => count($coverage),
'months' => $months,
'dry_run' => true,
];
}
$plantingSync = [];
foreach ($months as $month) {
$plantingSync[$month] = $this->plantingWorkOrders->sync(
$month . '-01',
$this->monthEnd($month),
$companyId,
);
}
try {
$coverage = $this->labelCoverage->assertCovered(
$fromDate->toDateString(),
$toDate->toDateString(),
$companyId,
);
} catch (Throwable $exception) {
return [
'status' => 'failed',
'error' => '种菜明细已同步,但标签覆盖检查失败:' . $exception->getMessage(),
'from' => $fromDate->toDateString(),
'to' => $toDate->toDateString(),
'months' => $months,
'planting_sync' => $plantingSync,
'dry_run' => false,
];
}
return [
'status' => 'ready_to_refresh',
'from' => $fromDate->toDateString(),
'to' => $toDate->toDateString(),
'checked_days' => count($coverage),
'months' => $months,
'planting_sync' => $plantingSync,
'dry_run' => false,
];
}
/** @return list<string> */
private function months(array $requested, Carbon $through): array
{
if ($requested === []) {
return [
$through->copy()->subMonthNoOverflow()->format('Y-m'),
$through->format('Y-m'),
];
}
$months = [];
foreach ($requested as $month) {
$month = trim((string) $month);
$normalized = null;
if (preg_match('/^\d{4}-\d{2}$/', $month) === 1) {
try {
$normalized = Carbon::createFromFormat('!Y-m', $month, 'Asia/Shanghai')->format('Y-m');
} catch (Throwable) {
$normalized = null;
}
}
if ($normalized !== $month) {
throw new InvalidArgumentException('月份格式无效,应为 YYYY-MM:' . $month);
}
$months[$month] = true;
}
$months = array_keys($months);
sort($months);
return $months;
}
private function assertWorkOrderSourceReady(): void
{
$mirror = $this->databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
$schema = $mirror->getSchemaBuilder();
if (! $schema->hasTable('business_mirror_table_states')) {
throw new RuntimeException('聚水潭协同工单镜像同步状态表尚未建立。');
}
$state = $mirror->table('business_mirror_table_states')
->where('dataset_key', self::WORK_ORDER_DATASET)
->first(['status', 'initial_completed_at']);
if ($state === null || $state->initial_completed_at === null) {
throw new RuntimeException('聚水潭协同工单镜像尚未完成首次同步。');
}
if ((string) $state->status !== 'succeeded') {
throw new RuntimeException('聚水潭协同工单镜像最近同步未成功。');
}
}
/** @return array{0:Carbon,1:Carbon} */
private function dateRange(string $from, string $to): array
{
$fromDate = $this->date($from);
$toDate = $this->date($to);
if ($fromDate === null || $toDate === null || $fromDate->gt($toDate)) {
throw new InvalidArgumentException('日期范围无效,应为 from <= to,格式 YYYY-MM-DD。');
}
return [$fromDate, $toDate];
}
private function date(string $value): ?Carbon
{
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
return null;
}
try {
$date = Carbon::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
} catch (Throwable) {
return null;
}
return $date->format('Y-m-d') === $value ? $date : null;
}
private function monthEnd(string $month): string
{
return Carbon::createFromFormat('!Y-m', $month, 'Asia/Shanghai')
->endOfMonth()
->toDateString();
}
}

View File

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

View File

@ -1,296 +0,0 @@
<?php
namespace App\Business;
use App\Models\Auth\User;
use App\Models\Business\SystemizationTodo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
class SystemizationTodoAuditLogger
{
public const TABLE = 'business_systemization_todo_audit_logs';
public const HISTORY_LIMIT = 500;
public const ACTION_LABELS = [
'create' => '新增',
'update' => '改动',
'delete' => '删除',
'import' => '导入',
];
public const FIELD_LABELS = [
'category' => '类型',
'section' => '内容',
'title' => '待办事项',
'owner' => '总负责人',
'assignee' => '责任人',
'start_date' => '开始时间',
'start_note' => '开始时间备注',
'due_date' => '完成时间',
'due_note' => '完成时间备注',
'status' => '状态',
'completed_at' => '完成日期',
'progress' => '完成情况',
'notes' => '备注',
'attachment_count' => '完成截图',
'sort_order' => '排序位置',
];
/**
* @return array<string, mixed>
*/
public function snapshot(SystemizationTodo $todo, bool $withAttachments = false): array
{
$snapshot = [
'id' => (int) $todo->id,
'category' => (string) ($todo->category ?? ''),
'section' => (string) ($todo->section ?? ''),
'title' => (string) ($todo->title ?? ''),
'owner' => (string) ($todo->owner ?? ''),
'assignee' => (string) ($todo->assignee ?? ''),
'start_date' => $todo->start_date?->format('Y-m-d') ?? '',
'start_note' => (string) ($todo->start_note ?? ''),
'due_date' => $todo->due_date?->format('Y-m-d') ?? '',
'due_note' => (string) ($todo->due_note ?? ''),
'status' => $todo->statusLabel(),
'completed_at' => $todo->completed_at?->format('Y-m-d') ?? '',
'progress' => (string) ($todo->progress ?? ''),
'notes' => (string) ($todo->notes ?? ''),
'sort_order' => (int) $todo->sort_order,
'source_key' => (string) ($todo->source_key ?? ''),
];
if ($withAttachments) {
$snapshot['attachment_count'] = (int) $todo->attachments()->count();
}
return $snapshot;
}
public function record(
string $action,
int $companyId,
?int $todoId,
?array $before,
?array $after,
?int $userId = null,
?string $actorName = null,
array $meta = [],
): void {
$this->recordMany([[
'company_id' => $companyId,
'todo_id' => $todoId,
'action' => $action,
'before' => $before,
'after' => $after,
'user_id' => $userId,
'actor_name' => $actorName,
'meta' => $meta,
]]);
}
/**
* @param array<int, array{
* company_id:int,
* todo_id:?int,
* action:string,
* before:?array,
* after:?array,
* user_id:?int,
* actor_name?:?string,
* meta?:array
* }> $events
*/
public function recordMany(array $events): void
{
if ($events === []) {
return;
}
if (! $this->tableReady()) {
throw new RuntimeException('系统化待办操作记录表尚未就绪,请先完成数据库迁移。');
}
$now = $this->platformNow();
$actorNames = [];
$rows = [];
foreach ($events as $event) {
$action = (string) ($event['action'] ?? '');
if (! array_key_exists($action, self::ACTION_LABELS)) {
throw new RuntimeException('不支持的待办操作记录类型。');
}
$userId = isset($event['user_id']) ? (int) $event['user_id'] : null;
$actorName = trim((string) ($event['actor_name'] ?? ''));
if ($actorName === '' && $userId !== null) {
if (! array_key_exists($userId, $actorNames)) {
$actorNames[$userId] = (string) (User::query()->whereKey($userId)->value('name') ?? '');
}
$actorName = $actorNames[$userId];
}
$meta = is_array($event['meta'] ?? null) ? $event['meta'] : [];
$rows[] = [
'company_id' => max(1, (int) ($event['company_id'] ?? 1)),
'todo_id' => isset($event['todo_id']) ? (int) $event['todo_id'] : null,
'action' => $action,
'before_json' => $this->json($event['before'] ?? null),
'after_json' => $this->json($event['after'] ?? null),
'actor_user_id' => $userId,
'actor_name' => mb_substr($actorName, 0, 191),
'extra_json' => $meta === [] ? null : $this->json($meta),
'at' => $now->toDateTimeString(),
'created_at' => $now->toDateTimeString(),
'updated_at' => $now->toDateTimeString(),
];
}
DB::table(self::TABLE)->insert($rows);
}
/**
* @return array<int, array<string, mixed>>
*/
public function history(
int $companyId,
int $limit = self::HISTORY_LIMIT,
?string $from = null,
?string $date = null,
): array
{
if (! $this->tableReady()) {
return [];
}
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()
->map(fn (object $row): array => $this->serializeEvent($row))
->all();
}
public function platformNow(): Carbon
{
$timezone = trim((string) config('app.platform_timezone', ''));
if ($timezone === '') {
$timezone = (string) config('app.timezone', 'UTC');
}
try {
return Carbon::now($timezone);
} catch (Throwable) {
return Carbon::now((string) config('app.timezone', 'UTC'));
}
}
/**
* @return array<string, mixed>
*/
private function serializeEvent(object $row): array
{
$before = $row->before_json ? json_decode((string) $row->before_json, true) : null;
$after = $row->after_json ? json_decode((string) $row->after_json, true) : null;
$before = is_array($before) ? $before : null;
$after = is_array($after) ? $after : null;
$meta = $row->extra_json ? json_decode((string) $row->extra_json, true) : [];
$meta = is_array($meta) ? $meta : [];
$source = $after ?? $before ?? [];
return [
'id' => (int) $row->id,
'at' => (string) $row->at,
'action' => (string) $row->action,
'action_label' => self::ACTION_LABELS[(string) $row->action] ?? (string) $row->action,
'todo_id' => $row->todo_id === null ? null : (int) $row->todo_id,
'category' => (string) ($source['category'] ?? ''),
'section' => (string) ($source['section'] ?? ''),
'title' => (string) ($source['title'] ?? ''),
'actor' => (string) ($row->actor_name ?? ''),
'before' => $before,
'after' => $after,
'meta' => $meta,
'changes' => $this->changes($before, $after),
];
}
/**
* @return array<int, string>
*/
private function changes(?array $before, ?array $after): array
{
if ($after === null && $before !== null) {
return ['删除前:' . $this->itemLabel($before)];
}
if ($before === null && $after !== null) {
return ['新增:' . $this->itemLabel($after)];
}
if ($before === null && $after === null) {
return ['—'];
}
$changes = [];
foreach (self::FIELD_LABELS as $field => $label) {
$old = $this->displayValue($field, $before[$field] ?? '');
$new = $this->displayValue($field, $after[$field] ?? '');
if ($old !== $new) {
$changes[] = $label . ':' . ($old !== '' ? $old : '空')
. ' → ' . ($new !== '' ? $new : '空');
}
}
return $changes === [] ? ['内容无变化'] : $changes;
}
private function itemLabel(array $row): string
{
$parts = array_values(array_filter([
trim((string) ($row['category'] ?? '')),
trim((string) ($row['section'] ?? '')),
trim((string) ($row['title'] ?? '')),
], static fn (string $value): bool => $value !== ''));
return $parts === [] ? '未命名待办' : implode(' · ', $parts);
}
private function displayValue(string $field, mixed $value): string
{
if ($field === 'attachment_count') {
return max(0, (int) $value) . ' 张';
}
return trim(str_replace(["\r\n", "\r"], "\n", (string) ($value ?? '')));
}
private function json(mixed $value): ?string
{
if ($value === null) {
return null;
}
$json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($json === false) {
throw new RuntimeException('待办操作记录序列化失败。');
}
return $json;
}
private function tableReady(): bool
{
try {
return DB::getSchemaBuilder()->hasTable(self::TABLE);
} catch (Throwable) {
return false;
}
}
}

View File

@ -23,28 +23,18 @@ class SystemizationTodoWorkbookImporter
'notes' => '备注',
];
public function __construct(
private readonly SystemizationTodoAuditLogger $audit,
) {
}
/**
* 导入财务系统化待办。只新增系统中不存在的来源行,不覆盖日常维护后的状态与截图。
*
* @return array{created:int,skipped:int,sheet:string}
*/
public function import(
string $path,
int $companyId,
?int $userId = null,
?string $originalName = null,
): array
public function import(string $path, int $companyId, ?int $userId = null): array
{
if (! is_file($path)) {
throw new RuntimeException('找不到待办 Excel 文件。');
}
$extension = $this->extension($path, $originalName);
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ($extension !== 'xlsx') {
throw new RuntimeException('系统化待办仅支持 .xlsx 文件。');
}
@ -68,15 +58,7 @@ class SystemizationTodoWorkbookImporter
);
$created = 0;
$skipped = 0;
DB::transaction(function () use (
$rows,
$sheetName,
$companyId,
$userId,
&$created,
&$skipped,
): void {
$auditEvents = [];
DB::transaction(function () use ($rows, $companyId, $userId, &$created, &$skipped): void {
foreach ($rows as $row) {
$exists = SystemizationTodo::withoutGlobalScopes()
->where('company_id', $companyId)
@ -87,29 +69,15 @@ class SystemizationTodoWorkbookImporter
continue;
}
$todo = SystemizationTodo::withoutGlobalScopes()->create([
SystemizationTodo::withoutGlobalScopes()->create([
...$row['data'],
'company_id' => $companyId,
'imported_at' => now(),
'created_by' => $userId,
'updated_by' => $userId,
]);
$auditEvents[] = [
'company_id' => $companyId,
'todo_id' => (int) $todo->id,
'action' => 'import',
'before' => null,
'after' => $this->audit->snapshot($todo),
'user_id' => $userId,
'meta' => [
'source' => 'excel',
'mode' => 'import',
'sheet' => $sheetName,
],
];
$created++;
}
$this->audit->recordMany($auditEvents);
});
return ['created' => $created, 'skipped' => $skipped, 'sheet' => $sheetName];
@ -125,19 +93,13 @@ class SystemizationTodoWorkbookImporter
*
* @return array{created:int,updated:int,retained:int,sheet:string}
*/
public function sync(
string $path,
int $companyId,
?int $userId = null,
bool $dryRun = false,
?string $originalName = null,
): array
public function sync(string $path, int $companyId, ?int $userId = null, bool $dryRun = false): array
{
if (! is_file($path)) {
throw new RuntimeException('找不到待办 Excel 文件。');
}
$extension = $this->extension($path, $originalName);
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ($extension !== 'xlsx') {
throw new RuntimeException('系统化待办仅支持 .xlsx 文件。');
}
@ -157,16 +119,13 @@ class SystemizationTodoWorkbookImporter
$headerInfo['row'],
$companyId,
);
$activeTodos = SystemizationTodo::withoutGlobalScopes()
$existing = SystemizationTodo::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
->whereNotNull('imported_at')
->orderBy('sort_order')
->orderBy('id')
->get();
$rows = $this->alignIncomingCategories($rows, $activeTodos);
$existing = $activeTodos
->filter(static fn (SystemizationTodo $todo): bool => $todo->imported_at !== null)
->values();
[$matches, $newIndexes] = $this->matchRows($rows, $existing);
$matchedIds = array_values($matches);
$retained = $existing
@ -212,11 +171,9 @@ class SystemizationTodoWorkbookImporter
$retainedSortOrder,
$companyId,
$userId,
$sheetName,
&$created,
&$updated,
): void {
$auditEvents = [];
SystemizationTodo::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
@ -228,7 +185,6 @@ class SystemizationTodoWorkbookImporter
if (! $todo) {
continue;
}
$before = $this->audit->snapshot($todo);
$todo->source_key = null;
$todo->syncOriginalAttribute('source_key');
$todo->fill($rows[$rowIndex]['data']);
@ -250,44 +206,18 @@ class SystemizationTodoWorkbookImporter
$todo->updated_by = $userId;
$todo->save();
if ($contentChanged) {
$auditEvents[] = [
'company_id' => $companyId,
'todo_id' => (int) $todo->id,
'action' => 'import',
'before' => $before,
'after' => $this->audit->snapshot($todo),
'user_id' => $userId,
'meta' => [
'source' => 'excel',
'mode' => 'sync',
'sheet' => $sheetName,
],
];
$updated++;
}
}
foreach ($newIndexes as $rowIndex) {
$todo = SystemizationTodo::withoutGlobalScopes()->create([
SystemizationTodo::withoutGlobalScopes()->create([
...$rows[$rowIndex]['data'],
'company_id' => $companyId,
'imported_at' => now(),
'created_by' => $userId,
'updated_by' => $userId,
]);
$auditEvents[] = [
'company_id' => $companyId,
'todo_id' => (int) $todo->id,
'action' => 'import',
'before' => null,
'after' => $this->audit->snapshot($todo),
'user_id' => $userId,
'meta' => [
'source' => 'excel',
'mode' => 'sync',
'sheet' => $sheetName,
],
];
$created++;
}
@ -299,8 +229,6 @@ class SystemizationTodoWorkbookImporter
'source_key' => $oldSourceKeys[$todo->id] ?? null,
]);
}
$this->audit->recordMany($auditEvents);
});
return [
@ -344,15 +272,11 @@ class SystemizationTodoWorkbookImporter
if ($rowNumber <= $headerRow) {
continue;
}
$categoryValue = $this->cleanImportedLabel(
$this->cell($cells, $columns['category'] ?? null)
);
$categoryValue = $this->cell($cells, $columns['category'] ?? null);
if ($categoryValue !== '') {
$category = $categoryValue;
}
$sectionValue = $this->cleanImportedLabel(
$this->cell($cells, $columns['section'] ?? null)
);
$sectionValue = $this->cell($cells, $columns['section'] ?? null);
if ($sectionValue !== '') {
$section = $sectionValue;
}
@ -371,10 +295,7 @@ class SystemizationTodoWorkbookImporter
[$finishDate, $finishNote] = $this->dateParts($finishText);
$progress = $this->cell($cells, $columns['progress'] ?? null);
$notes = $this->cell($cells, $columns['notes'] ?? null);
$progress = (string) (
SystemizationTodo::mergeNotesIntoProgress($progress, $notes) ?? ''
);
$status = $this->status($progress);
$status = $this->status($progress, $startText, $finishText);
foreach ($titles as $offset => $title) {
$titleIndex = $offset + 1;
@ -402,7 +323,7 @@ class SystemizationTodoWorkbookImporter
? ($finishDate ?? now()->toDateString())
: null,
'progress' => $progress !== '' ? $progress : null,
'notes' => null,
'notes' => $notes !== '' ? $notes : null,
'sort_order' => $sortOrder,
'source_key' => hash(
'sha256',
@ -441,7 +362,7 @@ class SystemizationTodoWorkbookImporter
static fn (string $line): bool => preg_match($marker, trim($line)) === 1,
);
if (count($numberedLines) < 2) {
return [$this->cleanImportedLabel($value)];
return [$value];
}
$segments = [];
@ -464,9 +385,7 @@ class SystemizationTodoWorkbookImporter
$segments[] = trim($current);
}
return $segments !== []
? $segments
: [$this->cleanImportedLabel($value)];
return $segments !== [] ? $segments : [$value];
}
/**
@ -500,32 +419,8 @@ class SystemizationTodoWorkbookImporter
$candidates[$sourceKey] ?? [],
fn (SystemizationTodo $todo): bool =>
! in_array($todo->id, $usedIds, true)
&& $this->matchGroupKey($todo->category) === $this->matchGroupKey($row['category'])
&& $this->matchGroupKey($todo->section) === $this->matchGroupKey($row['section']),
));
if ($available === []) {
continue;
}
usort($available, static fn (SystemizationTodo $a, SystemizationTodo $b): int =>
abs($a->sort_order - $row['data']['sort_order'])
<=> abs($b->sort_order - $row['data']['sort_order'])
);
$matches[$rowIndex] = $available[0]->id;
$usedIds[] = $available[0]->id;
}
// 同名待办可能分布在多个内容组,优先匹配同一「类型 + 内容」。
foreach ($rows as $rowIndex => $row) {
if (isset($matches[$rowIndex])) {
continue;
}
$key = $this->matchTitleKey($row['title']);
$available = array_values(array_filter(
$candidates[$key] ?? [],
fn (SystemizationTodo $todo): bool =>
! in_array($todo->id, $usedIds, true)
&& $this->matchGroupKey($todo->category) === $this->matchGroupKey($row['category'])
&& $this->matchGroupKey($todo->section) === $this->matchGroupKey($row['section']),
&& $this->matchText($todo->category) === $this->matchText($row['category'])
&& $this->matchText($todo->section) === $this->matchText($row['section']),
));
if ($available === []) {
continue;
@ -572,8 +467,8 @@ class SystemizationTodoWorkbookImporter
foreach ($remainingIds as $todoId) {
$todo = $todoById->get($todoId);
if (! $todo
|| $this->matchGroupKey($todo->category) !== $this->matchGroupKey($row['category'])
|| $this->matchGroupKey($todo->section) !== $this->matchGroupKey($row['section'])) {
|| $this->matchText($todo->category) !== $this->matchText($row['category'])
|| $this->matchText($todo->section) !== $this->matchText($row['section'])) {
continue;
}
$similarity = $this->titleSimilarity((string) $todo->title, $row['title']);
@ -604,39 +499,6 @@ class SystemizationTodoWorkbookImporter
];
}
/**
* 内容组已唯一归属某个类型时,忽略 Excel 中误填的类型占位值。
*
* @param array<int,array<string,mixed>> $rows
* @param \Illuminate\Support\Collection<int,SystemizationTodo> $activeTodos
* @return array<int,array<string,mixed>>
*/
private function alignIncomingCategories(
array $rows,
\Illuminate\Support\Collection $activeTodos,
): array {
$categoriesBySection = [];
foreach ($activeTodos as $todo) {
$sectionKey = $this->matchGroupKey($todo->section);
$category = trim((string) $todo->category);
if ($sectionKey === '' || $category === '') {
continue;
}
$categoriesBySection[$sectionKey][$this->matchText($category)] = $category;
}
foreach ($rows as &$row) {
$categories = $categoriesBySection[$this->matchGroupKey($row['section'])] ?? [];
if (count($categories) === 1) {
$category = reset($categories);
$row['data']['category'] = $category;
$row['category'] = $category;
}
}
return $rows;
}
private function matchTitleKey(?string $value): string
{
$value = preg_replace(
@ -648,20 +510,6 @@ class SystemizationTodoWorkbookImporter
return $this->matchText($value);
}
private function matchGroupKey(?string $value): string
{
return $this->matchTitleKey($this->cleanImportedLabel($value));
}
private function cleanImportedLabel(?string $value): string
{
return trim((string) preg_replace(
'/(^|\R)\s*(?:\d+|[一二三四五六七八九十百]+)\s*[、,,..::;;))]\s*/u',
'$1',
(string) $value,
));
}
private function matchText(?string $value): string
{
return mb_strtolower(
@ -795,16 +643,6 @@ class SystemizationTodoWorkbookImporter
return trim(str_replace("\u{00A0}", ' ', (string) $value));
}
private function extension(string $path, ?string $originalName): string
{
$name = trim((string) $originalName);
$extension = $name !== ''
? pathinfo($name, PATHINFO_EXTENSION)
: pathinfo($path, PATHINFO_EXTENSION);
return strtolower((string) $extension);
}
/**
* @return array{0:string|null,1:string}
*/
@ -836,12 +674,20 @@ class SystemizationTodoWorkbookImporter
return [null, mb_substr($value, 0, 100)];
}
private function status(string $progress): string
private function status(string $progress, string $startNote, string $finishNote): string
{
if (str_contains($progress, '已完成')) {
return SystemizationTodo::STATUS_COMPLETED;
}
if ($progress !== '') {
return str_contains($progress, '延期')
? SystemizationTodo::STATUS_DELAYED
: SystemizationTodo::STATUS_IN_PROGRESS;
}
if (str_contains($startNote, '延期') || str_contains($finishNote, '延期')) {
return SystemizationTodo::STATUS_DELAYED;
}
return SystemizationTodo::STATUS_INCOMPLETE;
return SystemizationTodo::STATUS_PENDING;
}
}

View File

@ -2,8 +2,6 @@
namespace App\Business;
use App\Business\CompanyPlan\CompanyPlanCompanyRepository;
use App\Business\CompanyPlan\CompanyPlanRepository;
use Illuminate\Pagination\LengthAwarePaginator;
use InvalidArgumentException;
use Modules\EcommerceFinance\Repositories\BusinessInformationMirrorRepository;
@ -18,7 +16,6 @@ use Throwable;
class UpstreamBusinessInformation
{
private const SOURCE = 'operations_replica';
private const COMPANY_ESTABLISHMENT_YEAR_FLOOR = 2000;
public function __construct(
private readonly UpstreamQueryCacheFactory $caches,
@ -27,7 +24,6 @@ class UpstreamBusinessInformation
private readonly ?StoreReportRepository $storeReports = null,
private readonly ?StoreAccountMirrorRepository $storeAccounts = null,
private readonly ?InstallationDetailMirrorRepository $installationMirror = null,
private readonly ?CompanyPlanRepository $companyPlans = null,
) {}
public function paginate(string $section, string $page, int $perPage = 50): LengthAwarePaginator
@ -72,19 +68,11 @@ class UpstreamBusinessInformation
private function shopInfoFlowPage(int $page, int $perPage): array
{
try {
$repository = app(\Modules\EcommerceFinance\Repositories\ShopInfoFlowMirrorRepository::class);
$filters = $this->pageFilters('financial-risk-control', 'process-statistics');
$payload = $repository->paginate(
return app(\Modules\EcommerceFinance\Repositories\ShopInfoFlowMirrorRepository::class)->paginate(
$page,
$perPage,
$filters,
$this->pageFilters('financial-risk-control', 'process-statistics'),
);
request()->attributes->set(
'process-statistics.current-approvers',
$repository->currentApproverOptions($filters),
);
return $payload;
} catch (\RuntimeException $exception) {
report($exception);
@ -127,334 +115,16 @@ class UpstreamBusinessInformation
private function companyPage(int $page, int $perPage): array
{
$filters = $this->pageFilters('company-management', 'basic-information');
$this->setCompanyPlanClassificationOptions();
$shareholderCompany = mb_substr(trim((string) request('shareholder_company', '')), 0, 255);
$relations = [];
if ($shareholderCompany !== '') {
$relations = app(CompanyPlanCompanyRepository::class)->relationsForShareholder(
(int) (company_id() ?: 1),
$shareholderCompany,
);
$relatedNames = array_values(array_map(
static fn (array $relation): string => $relation['company_name'],
$relations,
));
if ($relatedNames === []) {
return [
'data' => [],
'total' => 0,
'summary' => [
'total' => 0,
'normal' => 0,
'deregistered' => 0,
'general_taxpayer' => 0,
'small_taxpayer' => 0,
],
];
}
$filters['_company_names'] = $relatedNames;
}
$payload = $this->companyPlans !== null && $this->companyPageUsesPlanClassifications($filters)
? $this->companyPageWithPlanClassifications($page, $perPage, $filters)
: $this->page(
'company-information.read',
$page,
$perPage,
$filters,
fn () => $this->snapshot('company-information.read', [
'page' => $page,
'perPage' => $perPage,
]),
);
$payload['data'] = $this->companiesWithPlanClassifications($payload['data']);
if ($relations !== []) {
foreach ($payload['data'] as &$row) {
$relation = $relations[CompanyPlanCompanyRepository::normalizeCompanyName(
(string) ($row['company_name'] ?? '')
)] ?? null;
if ($relation !== null) {
$row['shareholders'] = $relation['shareholders_text'];
}
}
unset($row);
}
return $payload;
}
private function setCompanyPlanClassificationOptions(): void
{
if ($this->companyPlans === null) {
return;
}
try {
$options = $this->companyPlans->classificationFilterOptions((int) (company_id() ?: 1));
request()->attributes->set(
'company-information.taxpayer-type-options',
array_values(array_unique(array_map(
fn (string $value): string => $this->normalizeTaxType($value) ?? $value,
$options['taxpayer_type'],
))),
);
request()->attributes->set(
'company-information.business-registration-type-options',
$options['business_registration_type'],
);
} catch (Throwable $exception) {
report($exception);
}
}
/**
* @param array<string,string|list<string>> $filters
*/
private function companyPageUsesPlanClassifications(array $filters): bool
{
return ($filters['taxpayer_type'] ?? '') !== ''
|| ($filters['business_registration_type'] ?? '') !== ''
|| in_array($filters['_sort'] ?? '', ['taxpayer_type', 'business_registration_type'], true);
}
/**
* @param array<string,string|list<string>> $filters
* @return array{data:list<array<string,mixed>>,total:int,summary:array<string,mixed>}
*/
private function companyPageWithPlanClassifications(int $page, int $perPage, array $filters): array
{
$sourceFilters = array_diff_key($filters, array_flip([
'taxpayer_type',
'business_registration_type',
'_sort',
'_direction',
]));
try {
$rows = array_map(
fn (array $row): array => $this->mapCompany($row),
$this->mirror->allCompaniesForClassification($sourceFilters),
);
} catch (\RuntimeException $exception) {
if ($exception->getMessage() !== 'business_mirror_dataset_not_ready') {
throw $exception;
}
throw new ServiceUnavailableHttpException(null, '当前数据源暂不支持所选条件查询,请检查共享业务镜像状态。');
}
$rows = $this->companiesWithPlanClassifications(
$rows,
$this->companyPlanClassificationReferences(all: true),
return $this->page(
'company-information.read',
$page,
$perPage,
$filters,
fn () => $this->snapshot('company-information.read', [
'page' => $page,
'perPage' => $perPage,
]),
);
$rows = array_values(array_filter(
$rows,
fn (array $row): bool => $this->companyClassificationsMatchFilters($row, $filters),
));
$this->sortCompanyClassifications($rows, $filters);
$total = count($rows);
$offset = ($page - 1) * $perPage;
return [
'data' => array_slice($rows, $offset, $perPage),
'total' => $total,
'summary' => [],
];
}
/**
* 税务、工商类型以当前公司的公司盘点为准;盘点字段为空时保留基础资料。
*
* @param list<array<string,mixed>> $rows
* @param list<array<string,mixed>>|null $references
* @return list<array<string,mixed>>
*/
private function companiesWithPlanClassifications(array $rows, ?array $references = null): array
{
if ($this->companyPlans === null || $rows === []) {
return $rows;
}
$references ??= $this->companyPlanClassificationReferences($rows);
$index = $this->companyPlanClassificationIndex($references);
foreach ($rows as &$row) {
$reference = $this->matchedCompanyPlanClassification(
$index,
$row['company_name'] ?? null,
[$row],
);
$planTaxType = trim((string) ($reference['taxpayer_type'] ?? ''));
$row['taxpayer_category'] = $this->normalizeTaxType(
$planTaxType !== '' ? $planTaxType : ($row['taxpayer_category'] ?? null),
);
$planBusinessType = trim((string) ($reference['business_registration_type'] ?? ''));
if ($planBusinessType !== '') {
$row['business_registration_type'] = $planBusinessType;
} else {
$businessType = trim((string) ($row['business_registration_type'] ?? ''));
$row['business_registration_type'] = $businessType !== '' ? $businessType : '/';
}
}
unset($row);
return $rows;
}
/**
* @param list<array<string,mixed>> $rows
* @return list<array<string,mixed>>
*/
private function companyPlanClassificationReferences(array $rows = [], bool $all = false): array
{
if ($this->companyPlans === null) {
return [];
}
try {
$companyId = (int) (company_id() ?: 1);
if ($all) {
return $this->companyPlans->allClassificationReferences($companyId);
}
return $this->companyPlans->classificationReferencesForCompanies(
$companyId,
array_values(array_column($rows, 'company_name')),
array_values(array_column($rows, 'unified_social_credit_code')),
);
} catch (Throwable $exception) {
report($exception);
return [];
}
}
/**
* @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
*/
private function companyClassificationsMatchFilters(array $row, array $filters): bool
{
foreach ([
'taxpayer_type' => 'taxpayer_category',
'business_registration_type' => 'business_registration_type',
] as $filterKey => $rowKey) {
$expected = $filters[$filterKey] ?? '';
$expectedValues = is_array($expected)
? array_values(array_filter(array_map('trim', $expected), static fn (string $value): bool => $value !== ''))
: array_values(array_filter([trim((string) $expected)], static fn (string $value): bool => $value !== ''));
if ($expectedValues === []) {
continue;
}
if ($filterKey === 'taxpayer_type') {
$expectedValues = array_map(fn (string $value): ?string => $this->normalizeTaxType($value), $expectedValues);
}
$actual = trim((string) ($row[$rowKey] ?? ''));
if (! in_array($actual, $expectedValues, true)) {
return false;
}
}
return true;
}
/**
* @param list<array<string,mixed>> $rows
* @param array<string,string|list<string>> $filters
*/
private function sortCompanyClassifications(array &$rows, array $filters): void
{
$sort = (string) ($filters['_sort'] ?? '');
if ($sort === '') {
return;
}
$sortKey = match ($sort) {
'taxpayer_type' => 'taxpayer_category',
'registered_at' => 'establishment_date',
'billing_officer' => 'financial_officer',
'basic_deposit_account' => 'basic_deposit_account_number',
default => $sort,
};
$direction = ($filters['_direction'] ?? 'asc') === 'desc' ? -1 : 1;
usort($rows, static function (array $left, array $right) use ($sortKey, $direction): int {
$leftValue = trim((string) ($left[$sortKey] ?? ''));
$rightValue = trim((string) ($right[$sortKey] ?? ''));
$comparison = is_numeric($leftValue) && is_numeric($rightValue)
? (float) $leftValue <=> (float) $rightValue
: strnatcasecmp($leftValue, $rightValue);
return $comparison !== 0
? $comparison * $direction
: ((int) ($right['id'] ?? 0) <=> (int) ($left['id'] ?? 0));
});
}
private function normalizeCompanyName(mixed $value): string
{
return mb_strtolower(preg_replace('/\s+/u', '', trim((string) $value)) ?? trim((string) $value));
}
private function normalizeCreditCode(mixed $value): string
{
return mb_strtoupper(preg_replace('/\s+/u', '', trim((string) $value)) ?? trim((string) $value));
}
private function companySnapshot(UpstreamReadOnlyQuery $query, int $page, int $perPage): array
@ -529,7 +199,7 @@ SQL);
}
/**
* 店铺基础信息页从店铺账号镜像关联负责人;部门负责人不使用旧档案兜底。
* 店铺基础信息页每次读取时把负责人字段覆盖为店铺账号镜像中的值。
* 账号店铺名与 ERP 店铺名只差下划线/空格,因此统一归一后关联。
*
* @param list<array<string,mixed>> $rows
@ -542,16 +212,16 @@ SQL);
$key = StoreAccountMirrorRepository::storeNameKey($row['erp_store_name'] ?? '');
$match = $ownership[$key] ?? null;
if ($match === null) {
// 部门负责人只认店铺账号密码镜像,不能沿用可能属于其他口径的旧档案值。
$row['department_manager'] = null;
continue;
}
if ($match['operation_owner'] !== '') {
$row['store_manager'] = $match['operation_owner'];
foreach ([
'store_manager' => $match['operation_owner'],
'department_manager' => $match['operation_department_head'],
] as $field => $value) {
if ($value !== '') {
$row[$field] = $value;
}
}
$departmentManager = trim((string) $match['operation_department_head']);
$row['department_manager'] = $departmentManager !== '' ? $departmentManager : null;
}
unset($row);
@ -837,7 +507,6 @@ 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,
@ -848,11 +517,6 @@ 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;
@ -867,29 +531,15 @@ 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']] ?? [];
$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']
$taxType = $classification['tax_type']
?? $row['company_details'][0]['taxpayer_category']
?? null;
$businessType = $planBusinessType !== ''
? $planBusinessType
: $classification['business_registration_type']
$businessType = $classification['business_registration_type']
?? $row['company_details'][0]['business_registration_type']
?? null;
$classificationStatus = trim((string) ($classification['status'] ?? ''));
@ -901,26 +551,19 @@ SQL);
$row['tax_type'] = $this->normalizeTaxType($taxType) ?? '/';
$businessType = trim((string) $businessType);
$row['business_registration_type'] = $retained
&& ($planBusinessType !== '' || in_array($businessType, ['核定', '个人独资企业'], true))
&& in_array($businessType, ['核定', '个人独资企业'], true)
? $businessType
: '/';
}
unset($row);
// 服务公司结算收入列按业务要求默认隐藏;整列为空的月份也默认隐藏,金额 0 仍视为有账单。
// 整列为空的月份默认隐藏;金额 0 仍视为有账单,不隐藏。
request()->attributes->set(
'subject-operating-report.default_hidden_columns',
array_values(array_unique([
'previous_month_settlement_income',
...$this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true),
])),
$this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true),
);
$rows = array_values(array_filter($rows, fn (array $row): bool => $this->subjectMatchesFilters($row, $filters)));
request()->attributes->set(
'directory.status-counts',
$this->subjectStatusCounts($rows),
);
$summary = $this->subjectSummary($rows, $companyStatusReady);
$this->sortSubjectRows($rows, $filters);
$offset = ($page - 1) * $perPage;
@ -929,66 +572,6 @@ SQL);
return ['data' => $pageRows, 'total' => count($rows), 'summary' => $summary];
}
/**
* 状态查数使用筛选后的全量主体行,不受当前分页影响。
*
* @param list<array<string,mixed>> $rows
* @return array{
* total:int,
* fields:list<array{
* name:string,
* label:string,
* values:list<array{value:string,label:string,count:int}>
* }>
* }
*/
private function subjectStatusCounts(array $rows): array
{
$definitions = [
'company_status' => '公司状态',
'company_type' => '公司类型',
'tax_type' => '税务类型',
'business_registration_type' => '工商类型',
'can_change_entity' => '能否变更主体',
'plan' => '规划',
'new_entity' => '新主体',
];
$fields = [];
foreach ($definitions as $name => $label) {
$counts = [];
foreach ($rows as $row) {
$value = trim((string) ($row[$name] ?? ''));
$counts[$value] = ($counts[$value] ?? 0) + 1;
}
$values = [];
foreach ($counts as $value => $count) {
$display = $value !== '' ? $value : '未填写';
$values[] = [
'value' => (string) $value,
'label' => $display,
'count' => $count,
];
}
usort($values, static function (array $left, array $right): int {
return ($right['count'] <=> $left['count'])
?: strnatcasecmp($left['label'], $right['label']);
});
$fields[] = [
'name' => $name,
'label' => $label,
'values' => $values,
];
}
return [
'total' => count($rows),
'fields' => $fields,
];
}
/** @param list<array<string,mixed>> $rows */
private function subjectSummary(array $rows, bool $companyStatusReady): array
{
@ -1120,7 +703,7 @@ SQL);
}
}
foreach (['rolling_12m_income', 'previous_month_settlement_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
foreach (['rolling_12m_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
$needle = str_replace(',', '', trim((string) ($filters[$key] ?? '')));
if ($needle !== '' && (! is_numeric($needle) || ! is_numeric($row[$key] ?? null)
|| abs((float) $row[$key] - (float) $needle) > 0.000001)) {
@ -1138,7 +721,6 @@ 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',
];
@ -1476,18 +1058,14 @@ SQL);
private function mapCompany(array $row): array
{
$row = $this->toUtf8($row);
$companyStatus = trim((string) ($row['company_status'] ?? ''));
$row['company_status'] = match ($companyStatus) {
'0', '正常' => '正常',
'1', '注销', '已注销' => '已注销',
default => $companyStatus !== '' ? $companyStatus : null,
};
$row['establishment_date'] = $this->companyEstablishmentDate(
$row['establishment_date'] ?? null,
$row['company_status'] === '已注销',
);
$row['establishment_date'] = $this->date($row['establishment_date'] ?? null);
$row['subscribed_at'] = $this->date($row['subscribed_at'] ?? null);
$row['city'] = RegisteredAddressCity::parse($row['registered_address'] ?? null);
$row['company_status'] = match ((string) ($row['company_status'] ?? '')) {
'0' => '正常',
'1' => '已注销',
default => $row['company_status'] ?? null,
};
$businessType = trim((string) ($row['business_registration_type'] ?? ''));
$row['business_registration_type'] = in_array($businessType, ['核定', '个人独资企业'], true)
? $businessType
@ -1496,30 +1074,6 @@ SQL);
return $row;
}
private function companyEstablishmentDate(mixed $value, bool $deregistered): ?string
{
if ($deregistered) {
return '/';
}
if ($value === null || trim((string) $value) === '') {
return null;
}
// 上游用 1900-01-01 表示未知成立日期;公司资料不展示 2000 年前或非法日期。
$date = substr(trim((string) $value), 0, 10);
if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $parts)) {
return '/';
}
[, $year, $month, $day] = array_map('intval', $parts);
if ($year < self::COMPANY_ESTABLISHMENT_YEAR_FLOOR || ! checkdate($month, $day, $year)) {
return '/';
}
return $date;
}
private function mapStore(array $row): array
{
$row = $this->toUtf8($row);
@ -1540,7 +1094,6 @@ SQL);
$row = $this->toUtf8($row);
$row['registration_date'] = $this->date($row['registration_date'] ?? null);
$row['expiry_date'] = $this->date($row['expiry_date'] ?? null);
$row['trademark_type'] = $this->trademarkClassification($row['trademark_type'] ?? null);
$row['trademark_status'] = match ((string) ($row['trademark_status'] ?? '')) {
'0' => '未启用',
'1' => '有效',
@ -1550,14 +1103,6 @@ SQL);
return $row;
}
private function trademarkClassification(mixed $value): ?string
{
preg_match_all('/\d+/u', (string) ($value ?? ''), $matches);
$classes = array_values(array_unique($matches[0]));
return $classes === [] ? null : implode(',', $classes);
}
private function toUtf8(array $row): array
{
foreach ($row as &$value) {

View File

@ -45,7 +45,7 @@ class WithdrawalBalanceAlertSynchronizer
/**
* @return array{balance_date:string,dates:list<string>,alerts:array<int,array<string,mixed>>,created:int,updated:int}
*/
public function syncForDate(int $companyId, string $balanceDate, ?string $sourceScope = null): array
public function syncForDate(int $companyId, string $balanceDate): array
{
$dates = self::datesEndingAt($balanceDate);
$stores = StoreReceivingAccount::withoutGlobalScopes()
@ -64,12 +64,7 @@ class WithdrawalBalanceAlertSynchronizer
];
}
$balancesByDate = $this->shopBalances->matchesForStoresOnDates(
$stores,
$dates,
null,
$sourceScope,
);
$balancesByDate = $this->shopBalances->matchesForStoresOnDates($stores, $dates);
$reserveStandards = $stores->mapWithKeys(
static fn (StoreReceivingAccount $store): array => [
(int) $store->id => WithdrawalReserveStandard::amountFor(

View File

@ -30,12 +30,7 @@ class XlsxSheetReader
* @param list<string|list<string>> $optionalColumns 可选列:文件里有就取,没有就跳过(不报错)。
* @return Generator<int, array<string, string>>
*/
public function rows(
string $path,
array $columns,
array $optionalColumns = [],
?string $sheetName = null,
): Generator
public function rows(string $path, array $columns, array $optionalColumns = []): Generator
{
if (! is_file($path)) {
throw new RuntimeException('订单导出文件不存在:' . $path);
@ -46,7 +41,7 @@ class XlsxSheetReader
throw new RuntimeException('无法打开订单导出文件(不是有效的 xlsx):' . $path);
}
$stream = $zip->getStream($this->worksheetPath($zip, $sheetName));
$stream = $zip->getStream($this->worksheetPath($zip));
if ($stream === false) {
$zip->close();
@ -257,43 +252,16 @@ class XlsxSheetReader
return $index - 1;
}
private function worksheetPath(ZipArchive $zip, ?string $sheetName = null): string
private function worksheetPath(ZipArchive $zip): string
{
$workbook = $zip->getFromName('xl/workbook.xml');
$relationships = $zip->getFromName('xl/_rels/workbook.xml.rels');
if (is_string($workbook) && is_string($relationships)) {
$relationshipId = null;
preg_match_all('/<(?:[A-Za-z0-9_]+:)?sheet\b([^>]*)\/?>/', $workbook, $sheets);
if (is_string($workbook) && is_string($relationships)
&& preg_match('/<sheet[^>]*r:id="([^"]+)"/', $workbook, $sheet) === 1
&& preg_match('/Id="' . preg_quote($sheet[1], '/') . '"[^>]*Target="([^"]+)"/', $relationships, $target) === 1) {
$path = ltrim($target[1], '/');
foreach ($sheets[1] ?? [] as $attributes) {
if (preg_match('/\bname=(["\'])(.*?)\1/s', $attributes, $name) !== 1
|| preg_match('/\br:id=(["\'])(.*?)\1/s', $attributes, $id) !== 1) {
continue;
}
$candidateName = html_entity_decode($name[2], ENT_QUOTES | ENT_XML1, 'UTF-8');
if ($sheetName !== null && $candidateName !== $sheetName) {
continue;
}
$relationshipId = $id[2];
break;
}
if ($relationshipId !== null
&& preg_match(
'/<(?:[A-Za-z0-9_]+:)?Relationship\b[^>]*\bId=(["\'])' . preg_quote($relationshipId, '/') . '\1[^>]*\bTarget=(["\'])(.*?)\2[^>]*\/?>/s',
$relationships,
$target,
) === 1) {
$path = ltrim($target[3], '/');
return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path;
}
if ($sheetName !== null) {
throw new RuntimeException('导出文件缺少工作表:' . $sheetName);
}
return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path;
}
for ($i = 0; $i < $zip->numFiles; $i++) {

View File

@ -1,185 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Utilities\FinanceLedgerAccountShouldKeep;
use App\Utilities\FinanceLedgerAccountType;
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 = [];
$personalCardIds = [];
$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 (FinanceLedgerAccountType::isAlwaysRetained($account->account_type ?? null)) {
$personalCardIds[] = $accountId;
} elseif (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($personalCardIds),
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,
$personalCardIds,
$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,
]);
}
foreach (array_chunk($personalCardIds, 500) as $ids) {
$connection->table('fin_accounts')
->whereIn('id', $ids)
->update([
'company_plan' => '保留',
'account_should_keep' => '是',
'updated_at' => $now,
]);
}
});
$this->info(sprintf(
'已更新 %d 个账户:保留 %d 个,暂时保留 %d 个,个人卡固定保留 %d 个;另有 %d 个支付宝或网商银行账户保持原状。',
count($retainedIds) + count($temporaryIds) + count($personalCardIds),
count($retainedIds),
count($temporaryIds),
count($personalCardIds),
count($preservedIds),
));
return self::SUCCESS;
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
/**
* @return array<string,string>
*/
private function companyNames(string $path): array
{
if (! is_file($path)) {
throw new \RuntimeException('公司保留名单文件不存在:' . $path);
}
$worksheet = IOFactory::load($path)->getActiveSheet();
$rows = $worksheet->toArray(null, true, true, false);
if ($rows === []) {
return [];
}
$header = array_map(
fn (mixed $value): string => $this->normalizeCompanyName((string) $value),
$rows[0],
);
$column = array_search('公司名称', $header, true);
if ($column === false) {
$column = 0;
} else {
array_shift($rows);
}
$companies = [];
foreach ($rows as $row) {
$name = trim((string) ($row[$column] ?? ''));
$key = $this->normalizeCompanyName($name);
if ($key !== '') {
$companies[$key] = $name;
}
}
return $companies;
}
private function normalizeCompanyName(string $name): string
{
$name = str_replace(
['(', ')', '【', '】', ' '],
['(', ')', '[', ']', ' '],
trim($name),
);
$name = (string) preg_replace('/\s+/u', '', $name);
return mb_strtolower($name, 'UTF-8');
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,58 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\CompanyAlipayBillImporter;
use Throwable;
class ImportCompanyAlipayBills extends Command
{
protected $signature = 'finance-ledger:import-company-alipay
{path : 支付宝交易记录 CSV/XLSX/XLS 文件}
{--date= : 账单日期 YYYY-MM-DD,默认前一天}
{--account= : 支付宝登录账号,用于匹配账户总表}
{--account-short= : 账户总表简称;账号重复时必填}
{--dry-run : 只校验,不写入财务台账}';
protected $description = '导入公司非店铺支付宝前一天交易到财务台账动账明细';
public function handle(CompanyAlipayBillImporter $importer): int
{
$date = trim((string) ($this->option('date') ?: now()->subDay()->toDateString()));
$account = trim((string) $this->option('account'));
if ($account === '') {
$this->error('必须使用 --account 指定支付宝登录账号。');
return self::FAILURE;
}
try {
$result = $importer->import(
(string) $this->argument('path'),
$account,
$date,
$this->option('account-short') ?: null,
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('支付宝账单未导入,保留原有动账明细。' . $exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '值'], [
['校验模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['账单日期', $result['balance_date']],
['账户简称', $result['account_short']],
['有效笔数', $result['rows']],
['收入合计', number_format((float) $result['income'], 2)],
['支出合计', number_format((float) $result['expense'], 2)],
['替换原记录', $result['replaced']],
['每日流水行数', $result['recalculated']['flows'] ?? '-'],
]);
$this->info($result['dry_run'] ? '支付宝账单校验完成。' : '支付宝账单已接入财务台账动账明细。');
return self::SUCCESS;
}
}

View File

@ -1,74 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\CompanyAlipayStatementImporter;
use Throwable;
class ImportCompanyAlipayStatement extends Command
{
protected $signature = 'finance-ledger:import-alipay-statement
{path : 支付宝账务组合查询 XLS/XLSX 文件}
{--account= : 支付宝登录账号}
{--account-short= : 账户总表简称}
{--from= : 起始日期 YYYY-MM-DD}
{--to= : 结束日期 YYYY-MM-DD}
{--opening-balance= : 起始日期零时余额}
{--replace-sources= : 需要替换的重复来源,多个用逗号分隔}
{--dry-run : 只校验,不写入财务台账}';
protected $description = '导入支付宝账务组合查询流水,保留对方信息、余额和付款备注';
public function handle(CompanyAlipayStatementImporter $importer): int
{
$account = trim((string) $this->option('account'));
$from = trim((string) $this->option('from'));
$to = trim((string) $this->option('to'));
if ($account === '' || $from === '' || $to === '') {
$this->error('必须指定 --account、--from 和 --to。');
return self::FAILURE;
}
$openingOption = trim((string) $this->option('opening-balance'));
$openingBalance = $openingOption === '' ? null : (float) $openingOption;
$replaceSources = array_values(array_filter(array_map(
'trim',
explode(',', (string) $this->option('replace-sources')),
)));
try {
$result = $importer->import(
(string) $this->argument('path'),
$account,
$from,
$to,
$this->option('account-short') ?: null,
$openingBalance,
$replaceSources,
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('支付宝流水未导入,保留原有数据。' . $exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '值'], [
['校验模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['日期范围', $result['from'] . ' 至 ' . $result['to']],
['账户简称', $result['account_short']],
['期初余额', number_format((float) $result['opening_balance'], 2)],
['有效笔数', $result['rows']],
['收入合计', number_format((float) $result['income'], 2)],
['支出合计', number_format((float) $result['expense'], 2)],
['期末余额', number_format((float) $result['closing_balance'], 2)],
['替换原记录', $result['replaced']],
['每日流水行数', $result['recalculated']['flows'] ?? '-'],
]);
$this->info($result['dry_run'] ? '支付宝流水校验完成。' : '支付宝流水已导入财务台账。');
return self::SUCCESS;
}
}

View File

@ -1,44 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\CourierBillStore;
use Illuminate\Console\Command;
/**
* 导入手工小汇总类目(JSON:[{"group":"分组名","title":"块标题","labels":["运费10月",…]}]),当作某月的小汇总类目模板。
* 页面上「导入手工小汇总」读的是发送版账单本身;这个命令给已经整理好的类目清单用(如 10 月首批)。
*/
final class ImportCourierSummaryTemplates extends Command
{
protected $signature = 'courier-bills:import-summary-templates {file : JSON 文件} {--month= : 这些小汇总是哪个月的账单,如 2026-10}';
protected $description = '导入手工小汇总类目,作为快递账单对账小汇总的类目模板';
public function handle(CourierBillStore $store): int
{
$month = (string) $this->option('month');
if (! preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $month)) {
$this->error('--month 要写成 2026-10 这样');
return self::FAILURE;
}
$blocks = json_decode((string) @file_get_contents((string) $this->argument('file')), true);
if (! is_array($blocks)) {
$this->error('读不了 JSON 文件');
return self::FAILURE;
}
$blocks = array_values(array_filter(array_map(static fn ($b): ?array => is_array($b) && isset($b['title'], $b['labels']) && is_array($b['labels'])
? ['title' => (string) $b['title'], 'labels' => array_map('strval', $b['labels']), 'group' => isset($b['group']) ? (string) $b['group'] : null,
'source' => isset($b['source']) ? (string) $b['source'] : null]
: null, $blocks)));
$result = $store->saveSummaryTemplates($blocks, $month);
$this->info('读到 ' . $result['blocks'] . ' 块,记下 ' . count($result['saved']) . ' 家 ' . $month . ' 的类目:' . implode('、', $result['saved']));
if ($result['unknown'] !== []) {
$this->warn('没找到分组:' . implode('、', $result['unknown']));
}
return self::SUCCESS;
}
}

View File

@ -2,17 +2,13 @@
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}
@ -24,10 +20,7 @@ class ImportDewuSettlementBills extends Command
protected $description = '导入并核验聚胜算得物完整账单(保留全部渠道)';
public function handle(
DewuSettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
public function handle(DewuSettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -74,10 +67,6 @@ class ImportDewuSettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->queueBillPerformanceResync($performanceResync, 'dewu', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -1,177 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\Auth\FinanceRoster;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Repositories\DingAttendanceMirrorRepository;
use Throwable;
class ImportDingAttendanceSchedules extends Command
{
protected $signature = 'business-mirror:import-ding-attendance-schedules
{--file= : DWS attendance schedule get 返回的 JSON 文件}
{--stdin : 从标准输入读取 JSON}
{--from= : 查询开始日期 YYYY-MM-DD}
{--to= : 查询结束日期 YYYY-MM-DD}';
protected $description = '导入钉钉人员排班,供日志漏写扣分识别公司工作日和休息日';
public function handle(
DingAttendanceMirrorRepository $repository,
FinanceRoster $roster,
): int {
if (! $repository->scheduleAvailable()) {
$this->error('钉钉排班镜像表尚未建立,请先执行数据库迁移。');
return self::FAILURE;
}
$raw = $this->option('stdin')
? stream_get_contents(STDIN)
: (($path = trim((string) $this->option('file'))) !== '' && is_file($path)
? file_get_contents($path)
: '');
if (! is_string($raw) || trim($raw) === '') {
$repository->recordScheduleFailure('dingtalk_schedule_payload_missing');
$this->error('未读取到钉钉排班 JSON。');
return self::FAILURE;
}
try {
$decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$records = is_array($decoded) && is_array($decoded['result'] ?? null)
? $decoded['result']
: (is_array($decoded) && array_is_list($decoded) ? $decoded : []);
$names = [];
foreach ($roster->cachedFinanceMembers() as $member) {
$userId = trim((string) ($member['userid'] ?? ''));
if ($userId !== '') {
$names[$userId] = trim((string) ($member['name'] ?? ''));
}
}
$now = now();
$rows = [];
$userIds = [];
$dates = [];
foreach ($records as $record) {
if (! is_array($record)) {
continue;
}
$scheduleId = trim((string) ($record['id'] ?? ''));
$userId = trim((string) ($record['userId'] ?? ''));
$workDate = $this->dateValue($record['workDate'] ?? null);
if ($scheduleId === '' || $userId === '' || $workDate === null) {
continue;
}
$userIds[$userId] = $userId;
$dates[$workDate] = $workDate;
$rawRest = strtoupper(trim((string) ($record['isRest'] ?? 'N')));
$rows[$scheduleId] = [
'schedule_id' => mb_substr($scheduleId, 0, 64),
'user_id' => mb_substr($userId, 0, 128),
'user_name' => mb_substr($names[$userId] ?? '', 0, 191),
'work_date' => $workDate,
'group_id' => $this->unsignedInteger($record['groupId'] ?? null),
'class_id' => $this->unsignedInteger($record['classId'] ?? null),
'is_rest' => $rawRest === 'Y' ? 'Y' : 'N',
'check_status' => $this->nullableString($record['checkStatus'] ?? null, 32),
'time_changed' => (bool) ($record['timeChanged'] ?? false),
'source_payload' => json_encode($record, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
'synced_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
}
if ($rows === []) {
$repository->recordScheduleFailure('dingtalk_schedule_empty');
$this->error('钉钉排班 JSON 中没有可导入的排班记录。');
return self::FAILURE;
}
$from = $this->dateOption('from') ?? min($dates);
$to = $this->dateOption('to') ?? max($dates);
if ($from > $to) {
throw new \InvalidArgumentException('排班导入开始日期不能晚于结束日期。');
}
$count = $repository->replaceScheduleWindow(
array_values($rows),
array_values($userIds),
$from,
$to,
);
$repository->recordScheduleSuccess($count, $from, $to);
$this->info(sprintf(
'钉钉排班导入完成:%d 人、%d 天、%d 条排班。',
count($userIds),
count($dates),
$count,
));
return self::SUCCESS;
} catch (Throwable $exception) {
$repository->recordScheduleFailure('dingtalk_schedule_import_failed');
report($exception);
$this->error('钉钉排班导入失败。');
return self::FAILURE;
}
}
private function dateOption(string $name): ?string
{
$value = trim((string) $this->option($name));
if ($value === '') {
return null;
}
if (preg_match('/^\d{4}-\d{2}-\d{2}$/D', $value) !== 1) {
throw new \InvalidArgumentException('排班导入日期格式应为 YYYY-MM-DD。');
}
return Carbon::createFromFormat('!Y-m-d', $value, config('app.timezone', 'Asia/Shanghai'))->toDateString();
}
private function dateValue(mixed $value): ?string
{
if ($value === null || $value === '') {
return null;
}
try {
$timezone = (string) config('app.timezone', 'Asia/Shanghai');
if (is_numeric($value)) {
$timestamp = (int) $value;
return ($timestamp > 99999999999
? Carbon::createFromTimestampMs($timestamp, $timezone)
: Carbon::createFromTimestamp($timestamp, $timezone))->toDateString();
}
return Carbon::parse((string) $value, $timezone)->toDateString();
} catch (Throwable) {
return null;
}
}
private function unsignedInteger(mixed $value): ?int
{
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
}
private function nullableString(mixed $value, int $length): ?string
{
if (! is_scalar($value)) {
return null;
}
$value = trim((string) $value);
return $value === '' ? null : mb_substr($value, 0, $length);
}
}

View File

@ -13,7 +13,7 @@ class ImportDingProcessDetails extends Command
{--scope=personal_permission : 数据权限范围标识}
{--replace : 导入前清空同一范围的数据}';
protected $description = '兼容导入旧版铺平 CSV;生产请使用 business-mirror:sync-ding-process-details';
protected $description = '导入钉钉流程明细到共享业务镜像';
public function handle(DingProcessDetailMirrorImporter $importer): int
{

View File

@ -2,16 +2,12 @@
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= : 核对支出合计}
@ -19,10 +15,7 @@ class ImportDouyinAuthoritativeBills extends Command
protected $description = '校验并原子启用指定月份或月初至截止日的胜算抖音明细,保留旧版本用于回滚';
public function handle(
DouyinAuthoritativeBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
public function handle(DouyinAuthoritativeBillImporter $importer): int
{
try {
$result = $importer->import((string) $this->argument('path'), (string) $this->argument('month'),
@ -32,10 +25,6 @@ class ImportDouyinAuthoritativeBills extends Command
return self::FAILURE;
}
$this->info('胜算抖音明细已启用,范围:[' . $result['period_start'] . ', ' . $result['period_end'] . '),笔数:' . $result['row_count']);
if (! $this->queueBillPerformanceResync($performanceResync, 'douyin', $result, true)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -1,51 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\DouyinOpeningBalanceImporter;
use RuntimeException;
use Throwable;
class ImportDouyinOpeningBalances extends Command
{
protected $signature = 'business-mirror:import-douyin-opening-balances
{path : 抖音月度余额表 XLSX/XLS/CSV}
{--period-end= : 期末余额截止日期,必须是月末 YYYY-MM-DD}';
protected $description = '导入抖音月度期末余额,作为后续月份期初余额的滚动基准';
public function handle(DouyinOpeningBalanceImporter $importer): int
{
$periodEnd = trim((string) $this->option('period-end'));
if ($periodEnd === '') {
$this->error('缺少 --period-end。');
return self::FAILURE;
}
try {
$result = $importer->import((string) $this->argument('path'), $periodEnd);
} catch (InvalidArgumentException|RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('抖音期初余额导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['截止日期', '店铺数', '期末余额合计', '替换旧行数', '来源文件'], [[
$result['period_end'],
$result['total'],
$result['balance_total'],
$result['replaced'],
$result['source_filename'],
]]);
return self::SUCCESS;
}
}

View File

@ -1,46 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Console\Command;
/**
* 导入代发厂家手工汇总的样子(JSON:[{"factory":"厂家名","title":"10月临沂恒思","headers":["原始","简尚核对","差异"],"labels":["运费",…],"total":"合计"}]),
* 导出代发对账时「汇总」表照它套。页面上「导入手工汇总」读的是手工做好的账单本身;这个命令给整理好的清单用(如 10 月首批)。
*/
final class ImportDropshipSummaryTemplates extends Command
{
protected $signature = 'dropship-freight:import-summary-templates {file : JSON 文件} {--month= : 这些汇总是哪个月的账单,如 2026-10}';
protected $description = '导入代发厂家手工汇总的样子,作为代发对账导出「汇总」表的模板';
public function handle(DropshipFreightStore $store): int
{
$month = (string) $this->option('month');
if (! preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $month)) {
$this->error('--month 要写成 2026-10 这样');
return self::FAILURE;
}
$blocks = json_decode((string) @file_get_contents((string) $this->argument('file')), true);
if (! is_array($blocks)) {
$this->error('读不了 JSON 文件');
return self::FAILURE;
}
$blocks = array_values(array_filter(array_map(static fn ($b): ?array => is_array($b) && isset($b['title'], $b['headers'], $b['labels'])
&& is_array($b['headers']) && is_array($b['labels'])
? ['title' => (string) $b['title'], 'headers' => array_map('strval', $b['headers']), 'labels' => array_map('strval', $b['labels']),
'total' => isset($b['total']) ? (string) $b['total'] : '合计', 'factory' => isset($b['factory']) ? (string) $b['factory'] : null,
'source' => isset($b['source']) ? (string) $b['source'] : null]
: null, $blocks)));
$result = $store->saveSummaryTemplates($blocks, $month);
$this->info('读到 ' . $result['blocks'] . ' 家,记下 ' . count($result['saved']) . ' 家 ' . $month . ' 的汇总样子:' . implode('、', $result['saved']));
if ($result['unknown'] !== []) {
$this->warn('系统里没找到这些厂家(没有代发运费的厂家可以不管):' . implode('、', $result['unknown']));
}
return self::SUCCESS;
}
}

View File

@ -2,7 +2,6 @@
namespace App\Console\Commands;
use App\Business\InventoryWarehouseMappingAlerts;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\InventoryReportAuthoritativeImporter;
use Throwable;
@ -10,15 +9,11 @@ use Throwable;
class ImportInventoryReportAuthoritativeMonth extends Command
{
protected $signature = 'business-mirror:import-inventory-report-month
{path : 聚水潭按商品、按仓库、按月多维分析完整 XLSX 导出文件}
{--company-id=1 : 提醒任务归属公司}';
{path : 聚水潭按商品、按仓库、按月多维分析完整 XLSX 导出文件}';
protected $description = '导入进销存报表权威月明细,保留仓储方和子仓维度';
public function handle(
InventoryReportAuthoritativeImporter $importer,
InventoryWarehouseMappingAlerts $alerts,
): int
public function handle(InventoryReportAuthoritativeImporter $importer): int
{
try {
$result = $importer->import((string) $this->argument('path'));
@ -36,33 +31,6 @@ class ImportInventoryReportAuthoritativeMonth extends Command
$result['source_rows'],
));
try {
$alert = $alerts->syncMonth(
$result['source_month'],
max(1, (int) $this->option('company-id')),
);
if ($alert['missing_pair_count'] > 0) {
$this->warn(sprintf(
'仓库简称提醒:%d 个仓储方/仓库组合未映射,涉及 %d 行;提醒任务 #%d 已%s。',
$alert['missing_pair_count'],
$alert['missing_row_count'],
$alert['task_id'],
match ($alert['action']) {
'created' => '创建',
'reopened' => '重新打开',
default => '更新',
},
));
} else {
$this->info('仓库简称映射完整。');
}
} catch (Throwable $exception) {
report($exception);
$this->error('进销存月报已导入,但仓库简称提醒任务创建失败:' . $exception->getMessage());
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -2,27 +2,20 @@
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,
BillPerformanceResyncDispatcher $performanceResync,
): int
public function handle(JdDailyBillImporter $importer): int
{
$lock = Cache::lock('jd-daily-bill-import', 21600);
if (! $lock->get()) {
@ -33,20 +26,7 @@ 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']);
$queuedJd = $this->queueBillPerformanceResync(
$performanceResync,
'jd-transactions',
$result,
true,
);
$queuedJingxi = $this->queueBillPerformanceResync(
$performanceResync,
'jingxi',
$result,
true,
);
return $queuedJd && $queuedJingxi ? self::SUCCESS : self::FAILURE;
return self::SUCCESS;
} catch (Throwable $e) {
$this->error('京东日账单未启用,保留上一版本。' . ($e instanceof \InvalidArgumentException ? $e->getMessage() : '请检查文件、重复记录及镜像连接。'));
return self::FAILURE;

View File

@ -4,7 +4,6 @@ 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;
@ -15,7 +14,6 @@ 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 : 只校验和统计,不写入共享业务库}';
@ -27,31 +25,13 @@ 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 {
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'),
);
}
$result = $importer->import(
(string) $this->argument('path'),
$this->option('balance-date') === null ? null : (string) $this->option('balance-date'),
(string) $this->option('scope'),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
@ -59,54 +39,38 @@ class ImportJushuitanShopBalances extends Command
return self::FAILURE;
}
if ($allDates) {
foreach ($result['dates'] as $daily) {
$this->info(sprintf(
'%s:%s 共 %d 条,替换原有 %d 条。',
$daily['dry_run'] ? '校验完成' : '导入完成',
$daily['balance_date'],
$daily['total'],
$daily['replaced'],
));
}
} else {
$this->info(sprintf(
'%s:%s 共 %d 条,替换原有 %d 条。',
$result['dry_run'] ? '校验完成' : '导入完成',
$result['balance_date'],
$result['total'],
$result['replaced'],
));
}
$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;
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']) {
@ -139,33 +103,4 @@ class ImportJushuitanShopBalances extends Command
return $financeFallbackFailed ? self::FAILURE : self::SUCCESS;
}
/** @return list<string> */
private function rangeDates(string $range): array
{
$parts = explode(':', $range);
if (count($parts) !== 2) {
throw new \InvalidArgumentException('日期范围格式应为 YYYY-MM-DD:YYYY-MM-DD。');
}
$start = CarbonImmutable::createFromFormat('!Y-m-d', trim($parts[0]), 'Asia/Shanghai');
$end = CarbonImmutable::createFromFormat('!Y-m-d', trim($parts[1]), 'Asia/Shanghai');
if (! $start instanceof CarbonImmutable
|| $start->format('Y-m-d') !== trim($parts[0])
|| ! $end instanceof CarbonImmutable
|| $end->format('Y-m-d') !== trim($parts[1])
|| $end->lt($start)) {
throw new \InvalidArgumentException('日期范围格式应为 YYYY-MM-DD:YYYY-MM-DD,且结束日期不能早于开始日期。');
}
if ($start->diffInDays($end) > 366) {
throw new \InvalidArgumentException('单次多日期导入不能超过 366 天。');
}
$dates = [];
for ($date = $start; $date->lte($end); $date = $date->addDay()) {
$dates[] = $date->format('Y-m-d');
}
return $dates;
}
}

View File

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

View File

@ -1,63 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Business\KukaPostingBase\KukaPostingBaseImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportKukaPostingBase extends Command
{
protected $signature = 'business-mirror:import-kuka-posting-base
{path : 聚水潭销售主题分析(新版)明细导出 XLSX 文件}
{--month= : 账期 YYYY-MM}
{--sheet= : 工作表名称,默认按配置读取“发货明细表”}
{--company=1 : 公司 ID}
{--dry-run : 只校验文件、店铺和行数,不写入共享镜像}';
protected $description = '导入顾家过账基础数据(仅指定 12 家店铺)';
public function handle(KukaPostingBaseImporter $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,
$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;
}
$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['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);
$this->info($result['dry_run'] ? '顾家过账基础数据校验完成。' : '顾家过账基础数据已导入共享镜像。');
return self::SUCCESS;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,115 +0,0 @@
<?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 = $registry->storeDataset($section, $dataset);
$totalCreated = 0;
$totalUpdated = 0;
$totalRows = 0;
try {
foreach ($files as $index => $path) {
$file = new UploadedFile(
$path,
basename($path),
'text/csv',
null,
true,
);
$prepared = $runner->prepare(
$file,
$fields,
$storeDataset,
$companyId,
$userId,
);
$token = $prepared['token'];
$offset = 0;
$created = 0;
$updated = 0;
do {
$progress = $runner->process($token, $offset, null, $companyId);
$offset = $progress['offset'];
$created = $progress['created'];
$updated = $progress['updated'];
} while (! $progress['done']);
$totalCreated += $created;
$totalUpdated += $updated;
$totalRows += (int) $prepared['total'];
$this->line(sprintf(
'[%d/%d] %s:%s 行,新增 %s,更新 %s',
$index + 1,
count($files),
basename($path),
number_format((int) $prepared['total']),
number_format($created),
number_format($updated),
));
}
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'导入完成:文件 %s 个,读取 %s 行,新增 %s,更新 %s。',
number_format(count($files)),
number_format($totalRows),
number_format($totalCreated),
number_format($totalUpdated),
));
return self::SUCCESS;
}
}

View File

@ -1,75 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\PinduoduoPlatformBalanceImporter;
use RuntimeException;
use Throwable;
class ImportPinduoduoPlatformBalances extends Command
{
protected $signature = 'business-mirror:import-pdd-platform-balances
{path : 聚水潭平台资金账户余额 XLSX/XLS/CSV}
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD;文件名含 YYYY-MM 时可省略}';
protected $description = '导入拼多多“期初余额”和“平台实际期末余额”,并自动维护待补期初队列';
public function handle(PinduoduoPlatformBalanceImporter $importer): int
{
$periodEnd = trim((string) $this->option('period-end'));
if ($periodEnd === '') {
$periodEnd = $this->periodEndFromFilename((string) $this->argument('path'));
}
if ($periodEnd === '') {
$this->error('无法从文件名识别账期,请使用 --period-end=YYYY-MM-DD 指定月末。');
return self::FAILURE;
}
try {
$result = $importer->import((string) $this->argument('path'), $periodEnd);
} catch (InvalidArgumentException|RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('拼多多平台期末余额导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['截止日期', '店铺数', '期初行数', '期初合计', '期末余额合计', '替换旧行数', '来源文件'], [[
$result['period_end'],
$result['total'],
$result['opening_total'],
$result['opening_balance_total'],
$result['balance_total'],
$result['replaced'],
$result['source_filename'],
]]);
return self::SUCCESS;
}
private function periodEndFromFilename(string $path): string
{
$filename = basename($path);
if (preg_match('/(20\d{2})[-_年](\d{1,2})/u', $filename, $matches) !== 1) {
return '';
}
$month = (int) $matches[2];
if ($month < 1 || $month > 12) {
return '';
}
$date = \DateTimeImmutable::createFromFormat(
'!Y-n-j',
sprintf('%d-%d-1', (int) $matches[1], $month),
);
return $date === false ? '' : $date->format('Y-m-t');
}
}

View File

@ -2,18 +2,13 @@
namespace App\Console\Commands;
use App\Console\Commands\Concerns\QueuesBillPerformanceResync;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BillPerformanceResyncDispatcher;
use Modules\EcommerceFinance\Services\PinduoduoOpeningBalanceAutoResolver;
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}
@ -21,16 +16,11 @@ class ImportPinduoduoSettlementBills extends Command
{--expected-count= : 完整账单权威笔数}
{--expected-income= : 完整账单权威收入}
{--expected-expense= : 完整账单权威支出}
{--batch=1000 : 分批写入行数}
{--skip-opening-sync : 本次不自动补齐期初余额}';
{--batch=1000 : 分批写入行数}';
protected $description = '导入并核验聚胜算拼多多完整账单(保留全部账户类型)';
public function handle(
PinduoduoSettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
PinduoduoOpeningBalanceAutoResolver $openingResolver,
): int
public function handle(PinduoduoSettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -77,27 +67,6 @@ class ImportPinduoduoSettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->option('skip-opening-sync')) {
try {
$opening = $openingResolver->resolve();
if ($opening['checked'] > 0) {
$this->line(sprintf(
'期初自动补录:检查 %d 家,补齐 %d 家,仍待处理 %d 家。',
$opening['checked'],
$opening['resolved'],
$opening['pending'],
));
}
} catch (Throwable $exception) {
report($exception);
$this->warn('账单已导入,但期初自动补录暂未完成;每日兜底任务会继续重试。');
}
}
if (! $this->queueBillPerformanceResync($performanceResync, 'pinduoduo', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\PortalFreightBillImports;
use Illuminate\Console\Command;
final class ImportPortalFreightBills extends Command
{
protected $signature = 'portal-freight:import-pending';
protected $description = '受限批容器处理一份厂家或快递门户运费账单';
public function handle(PortalFreightBillImports $imports): int
{
$imports->processNext();
return self::SUCCESS;
}
}

View File

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

View File

@ -1,20 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\SupplierBookkeepingShippingImporter;
class ImportSupplierBookkeepingShipments extends Command
{
protected $signature = 'supplier-bookkeeping:import-shipments {file} {manifest} {--dry-run}';
protected $description = '流式导入工作平台月度发货精简文件;保留来源摘要,支持断点,整月完成后生效';
public function handle(SupplierBookkeepingShippingImporter $importer): int
{
$start = microtime(true);
$result = $importer->import($this->argument('file'), $this->argument('manifest'), (bool) $this->option('dry-run'));
$this->info(json_encode($result + ['seconds' => round(microtime(true) - $start, 2), 'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2)], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
return self::SUCCESS;
}
}

View File

@ -2,17 +2,13 @@
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,15 +16,11 @@ class ImportTaobaoAlipaySettlementBills extends Command
{--expected-count= : 完整账单权威笔数}
{--expected-income= : 完整账单权威收入}
{--expected-expense= : 完整账单权威支出}
{--store=* : 只替换指定原始店铺范围内的当月流水,可重复传入}
{--batch=1000 : 分批写入行数}';
protected $description = '导入并核验聚胜算淘系支付宝完整账单,可按原始店铺范围定向替换';
protected $description = '导入并核验聚胜算淘系支付宝完整账单';
public function handle(
TaobaoAlipaySettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
public function handle(TaobaoAlipaySettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -47,7 +39,6 @@ class ImportTaobaoAlipaySettlementBills extends Command
(string) $this->option('expected-income'),
(string) $this->option('expected-expense'),
(int) $this->option('batch'),
(array) $this->option('store'),
);
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
@ -75,10 +66,6 @@ class ImportTaobaoAlipaySettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->queueBillPerformanceResync($performanceResync, 'taobao-alipay', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -2,17 +2,13 @@
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}
@ -24,10 +20,7 @@ class ImportTaobaoWechatSettlementBills extends Command
protected $description = '导入并核验聚胜算淘系微信完整账单';
public function handle(
TaobaoWechatSettlementBillImporter $importer,
BillPerformanceResyncDispatcher $performanceResync,
): int
public function handle(TaobaoWechatSettlementBillImporter $importer): int
{
foreach (['from', 'to', 'expected-count', 'expected-income', 'expected-expense'] as $option) {
if (trim((string) $this->option($option)) === '') {
@ -74,10 +67,6 @@ class ImportTaobaoWechatSettlementBills extends Command
->implode(';'));
$this->line('SHA-256: ' . $result['source_sha256']);
if (! $this->queueBillPerformanceResync($performanceResync, 'taobao-wechat', $result)) {
return self::FAILURE;
}
return self::SUCCESS;
}
}

View File

@ -1,196 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use JsonException;
use RuntimeException;
use Throwable;
class ImportVipshopJxActualBills extends Command
{
protected $signature = 'vipshop-jx:import
{file : 唯品会JX账期明细 JSON}
{--period= : 账单期间,格式 YYYY-MM}
{--company=1 : 公司 ID}
{--dry-run : 只校验,不写数据库}';
protected $description = '导入唯品会JX账期明细,按账单期间写入账户账单';
public function handle(): int
{
$path = realpath((string) $this->argument('file'));
if ($path === false || ! is_file($path) || ! is_readable($path)) {
$this->error('唯品会JX账期明细文件不存在或不可读。');
return self::FAILURE;
}
$period = trim((string) $this->option('period'));
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
$this->error('账单期间必须是 YYYY-MM。');
return self::FAILURE;
}
$companyId = (int) $this->option('company');
if ($companyId < 1) {
$this->error('公司 ID 无效。');
return self::FAILURE;
}
try {
$rows = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
$this->error('唯品会JX账期明细不是有效 JSON。');
return self::FAILURE;
}
if (! is_array($rows) || $rows === []) {
$this->error('唯品会JX账期明细为空。');
return self::FAILURE;
}
try {
[$income, $expense] = $this->validateRows($rows, $period);
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$existing = DB::table('ec_account_bills')
->where('company_id', $companyId)
->where('bill_type', 'vipshop-jx')
->where('payload->settle_period', $period)
->whereNull('deleted_at')
->count();
$this->table(['账期', '状态', '明细行数', '收入', '支出', '净额', '现有行数'], [[
$period,
$this->option('dry-run') ? 'validated' : 'ready',
count($rows),
number_format($income, 2, '.', ''),
number_format($expense, 2, '.', ''),
number_format($income - $expense, 2, '.', ''),
$existing,
]]);
if ($existing > 0) {
$this->error("{$period} 已有 {$existing} 行唯品会JX账单,为避免重复写入已停止。");
return self::FAILURE;
}
if ($this->option('dry-run')) {
return self::SUCCESS;
}
$lock = Cache::lock("vipshop-jx-import-{$companyId}-{$period}", 900);
if (! $lock->get()) {
$this->error('唯品会JX账单导入正在运行,请稍后重试。');
return self::FAILURE;
}
try {
DB::transaction(function () use ($rows, $companyId, $period): void {
$now = now();
foreach (array_chunk($rows, 500) as $chunk) {
$payload = array_map(static function (array $row) use ($companyId, $period, $now): array {
return [
'company_id' => $companyId,
'bill_type' => 'vipshop-jx',
'record_code' => (string) $row['record_code'],
'store_name' => (string) $row['store_name'],
'order_no' => (string) ($row['order_no'] ?? ''),
'amount' => (string) $row['amount'],
'bill_item' => (string) $row['bill_item'],
'occurred_at' => filled($row['occurred_at'] ?? null) ? (string) $row['occurred_at'] : null,
'income' => (string) $row['income'],
'expense' => (string) $row['expense'],
'balance' => '0',
'payload' => json_encode(
$row['payload'],
JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR,
),
'modifier' => '唯品会JX账单导入',
'created_from' => 'vipshop-jx:import',
'created_at' => $now,
'updated_at' => $now,
];
}, $chunk);
DB::table('ec_account_bills')->insert($payload);
}
});
} catch (Throwable $exception) {
report($exception);
$this->error('唯品会JX账单写入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
} finally {
$lock->release();
}
$inserted = DB::table('ec_account_bills')
->where('company_id', $companyId)
->where('bill_type', 'vipshop-jx')
->where('payload->settle_period', $period)
->whereNull('deleted_at')
->selectRaw('COUNT(*) AS rows_count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense')
->first();
$this->table(['账期', '状态', '明细行数', '收入', '支出', '净额'], [[
$period,
'succeeded',
(int) $inserted->rows_count,
number_format((float) $inserted->income, 2, '.', ''),
number_format((float) $inserted->expense, 2, '.', ''),
number_format((float) $inserted->income - (float) $inserted->expense, 2, '.', ''),
]]);
return self::SUCCESS;
}
/**
* @param list<mixed> $rows
* @return array{0:float,1:float}
*/
private function validateRows(array $rows, string $period): array
{
$recordCodes = [];
$income = 0.0;
$expense = 0.0;
foreach ($rows as $index => $row) {
if (! is_array($row)) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行不是有效对象。');
}
$recordCode = trim((string) ($row['record_code'] ?? ''));
if ($recordCode === '' || isset($recordCodes[$recordCode])) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行记录编码为空或重复。');
}
$recordCodes[$recordCode] = true;
if (($row['payload']['settle_period'] ?? null) !== $period) {
throw new RuntimeException("第 " . ($index + 1) . " 行账单期间不是 {$period}。");
}
$amountRaw = $row['amount'] ?? '';
$incomeRaw = $row['income'] ?? '';
$expenseRaw = $row['expense'] ?? '';
if (! is_numeric($amountRaw) || ! is_numeric($incomeRaw) || ! is_numeric($expenseRaw)) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行金额无效。');
}
$amount = (float) $amountRaw;
$rowIncome = (float) $incomeRaw;
$rowExpense = (float) $expenseRaw;
if (abs($amount - ($rowIncome - $rowExpense)) > 0.000001) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行金额与收支不一致。');
}
$income += $rowIncome;
$expense += $rowExpense;
}
return [round($income, 6), round($expense, 6)];
}
}

View File

@ -1,186 +0,0 @@
<?php
namespace App\Console\Commands;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Database\DatabaseManager;
use JsonException;
use Modules\EcommerceFinance\Repositories\VipshopJxBankPaymentRepository;
use RuntimeException;
use Throwable;
class ImportVipshopJxBankPayments extends Command
{
protected $signature = 'vipshop-jx:import-bank-payments
{file : 唯品会结算平台“账单收付款”JSON}
{--replace : 用本次快照替换已有银行卡结算记录}
{--dry-run : 只校验,不写数据库}';
protected $description = '导入唯品会JX账单收付款中实际结算到银行卡的记录';
public function handle(DatabaseManager $databases): int
{
$path = realpath((string) $this->argument('file'));
if ($path === false || ! is_file($path) || ! is_readable($path)) {
$this->error('账单收付款文件不存在或不可读。');
return self::FAILURE;
}
try {
$sourceRows = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
$this->error('账单收付款文件不是有效 JSON。');
return self::FAILURE;
}
if (! is_array($sourceRows) || $sourceRows === []) {
$this->error('账单收付款文件为空。');
return self::FAILURE;
}
try {
[$rows, $skipped] = $this->normalize($sourceRows, hash_file('sha256', $path));
} catch (RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$connection = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
if (! $connection->getSchemaBuilder()->hasTable(VipshopJxBankPaymentRepository::TABLE)) {
$this->error('唯品会JX银行卡结算表尚未完成迁移。');
return self::FAILURE;
}
$net = '0.000000';
$byPeriod = [];
foreach ($rows as $row) {
$net = bcadd($net, $row['amount'], 6);
$byPeriod[$row['bill_period']] = bcadd($byPeriod[$row['bill_period']] ?? '0', $row['amount'], 6);
}
ksort($byPeriod);
$this->table(['状态', '源行数', '导入行数', '跳过行数', '净额'], [[
$this->option('dry-run') ? 'validated' : 'ready',
count($sourceRows),
count($rows),
$skipped,
$net,
]]);
$this->table(
['账单期间', '银行卡结算净额'],
array_map(static fn (string $period, string $amount): array => [$period, $amount], array_keys($byPeriod), array_values($byPeriod)),
);
if ($this->option('dry-run')) {
return self::SUCCESS;
}
try {
$connection->transaction(function () use ($connection, $rows): void {
if ($this->option('replace')) {
$connection->table(VipshopJxBankPaymentRepository::TABLE)->delete();
}
$now = now();
foreach (array_chunk($rows, 500) as $chunk) {
$connection->table(VipshopJxBankPaymentRepository::TABLE)->upsert(
array_map(static fn (array $row): array => $row + [
'imported_at' => $now,
'created_at' => $now,
'updated_at' => $now,
], $chunk),
['source_payment_id'],
[
'source_bill_number',
'bill_period',
'pay_date',
'batch_number',
'vendor_account_num',
'amount',
'currency_code',
'pay_status',
'source_hash',
'imported_at',
'updated_at',
],
);
}
});
} catch (Throwable $exception) {
report($exception);
$this->error('唯品会JX银行卡结算写入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->info('唯品会JX银行卡结算记录导入成功。');
return self::SUCCESS;
}
/**
* @param list<mixed> $sourceRows
* @return array{0:list<array<string,mixed>>,1:int}
*/
private function normalize(array $sourceRows, string $sourceHash): array
{
$rows = [];
$sourceIds = [];
$skipped = 0;
foreach ($sourceRows as $index => $source) {
if (! is_array($source)) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行不是有效对象。');
}
if ((string) ($source['vendorCode'] ?? '') !== '672378') {
throw new RuntimeException('第 ' . ($index + 1) . ' 行不是供应商 672378。');
}
$vendorAccount = trim((string) ($source['vendorAccountNum'] ?? ''));
if (($source['payStatus'] ?? null) !== 'SUCCESS'
|| $vendorAccount === ''
|| $vendorAccount === '银行存款-中转') {
$skipped++;
continue;
}
$sourceId = (int) ($source['id'] ?? 0);
if ($sourceId < 1 || isset($sourceIds[$sourceId])) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行来源 ID 无效或重复。');
}
$sourceIds[$sourceId] = true;
$billNumber = trim((string) ($source['billNumber'] ?? ''));
if (preg_match('/(?:^|[-_])(20\d{2})(\d{2})\d{2}(?:[-_]|$)/', $billNumber, $matches) !== 1) {
throw new RuntimeException("第 " . ($index + 1) . " 行账单编号无法识别账期:{$billNumber}");
}
$amount = $source['billPayAmount'] ?? null;
if (! is_numeric($amount)) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行已结金额无效。');
}
$payDate = $source['payDate'] ?? null;
if (! is_numeric($payDate)) {
throw new RuntimeException('第 ' . ($index + 1) . ' 行付款日期无效。');
}
$rows[] = [
'source_payment_id' => $sourceId,
'source_bill_number' => $billNumber,
'bill_period' => $matches[1] . '-' . $matches[2],
'pay_date' => CarbonImmutable::createFromTimestampMs((int) $payDate, 'Asia/Shanghai')->format('Y-m-d'),
'batch_number' => mb_substr((string) ($source['batchNumber'] ?? ''), 0, 64),
'vendor_account_num' => mb_substr($vendorAccount, 0, 64),
'amount' => number_format((float) $amount, 6, '.', ''),
'currency_code' => mb_substr((string) ($source['currencyCode'] ?? 'CNY'), 0, 8),
'pay_status' => 'SUCCESS',
'source_hash' => $sourceHash,
];
}
if ($rows === []) {
throw new RuntimeException('账单收付款文件中没有可导入的银行卡结算记录。');
}
return [$rows, $skipped];
}
}

View File

@ -1,83 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\VipshopMpBillImporter;
use RuntimeException;
use Throwable;
class ImportVipshopMpBills extends Command
{
protected $signature = 'vipshop-mp:import
{files* : 唯品会MP后台导出的订单明细 XLSX}
{--period= : 账单期间,格式 YYYY-MM}
{--store-map= : 后台店铺名到财务系统店铺全称的 JSON 映射}
{--company=1 : 公司 ID}
{--dry-run : 只校验,不写数据库}';
protected $description = '导入唯品会MP后台订单明细,按账期和店铺幂等替换';
public function handle(VipshopMpBillImporter $importer): int
{
$period = trim((string) $this->option('period'));
$mapPath = trim((string) $this->option('store-map'));
if ($period === '' || $mapPath === '') {
$this->error('缺少 --period 或 --store-map。');
return self::FAILURE;
}
$realMapPath = realpath($mapPath);
if ($realMapPath === false || ! is_file($realMapPath) || ! is_readable($realMapPath)) {
$this->error('店铺映射文件不存在或不可读。');
return self::FAILURE;
}
$storeMap = json_decode((string) file_get_contents($realMapPath), true, 512, JSON_THROW_ON_ERROR);
if (! is_array($storeMap)) {
$this->error('店铺映射文件必须是 JSON 对象。');
return self::FAILURE;
}
foreach ($storeMap as $source => $target) {
if (! is_string($source) || trim($source) === '' || ! is_string($target) || trim($target) === '') {
$this->error('店铺映射中存在无效名称。');
return self::FAILURE;
}
}
try {
$result = $importer->import(
array_values((array) $this->argument('files')),
$period,
$storeMap,
(int) $this->option('company'),
(bool) $this->option('dry-run'),
);
} catch (InvalidArgumentException|RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('唯品会MP账单导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['账期', '状态', '账单数', '店铺数', '明细行数', '收入', '支出', '商家应收'], [[
$result['period'],
$result['status'],
$result['bill_count'],
$result['store_count'],
$result['row_count'],
$result['income_total'],
$result['expense_total'],
$result['balance_total'],
]]);
return self::SUCCESS;
}
}

View File

@ -1,72 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\VipshopMpOpeningBalanceImporter;
use RuntimeException;
use Throwable;
class ImportVipshopMpOpeningBalances extends Command
{
protected $signature = 'vipshop-mp:import-opening-balances
{files* : 唯品会后台账单余额表导出的 XLSX}
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD}
{--store-map= : 后台店铺名到财务系统店铺全称的 JSON 映射}
{--dry-run : 只校验,不写数据库}';
protected $description = '导入唯品会MP后台账单余额表,保存待结算余额与实际结算给商家金额';
public function handle(VipshopMpOpeningBalanceImporter $importer): int
{
$periodEnd = trim((string) $this->option('period-end'));
$mapPath = trim((string) $this->option('store-map'));
if ($periodEnd === '' || $mapPath === '') {
$this->error('缺少 --period-end 或 --store-map。');
return self::FAILURE;
}
$realMapPath = realpath($mapPath);
if ($realMapPath === false || ! is_file($realMapPath) || ! is_readable($realMapPath)) {
$this->error('店铺映射文件不存在或不可读。');
return self::FAILURE;
}
$storeMap = json_decode((string) file_get_contents($realMapPath), true, 512, JSON_THROW_ON_ERROR);
if (! is_array($storeMap)) {
$this->error('店铺映射文件必须是 JSON 对象。');
return self::FAILURE;
}
try {
$result = $importer->import(
array_values((array) $this->argument('files')),
$periodEnd,
$storeMap,
(bool) $this->option('dry-run'),
);
} catch (InvalidArgumentException|RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
} catch (Throwable $exception) {
report($exception);
$this->error('唯品会MP期初余额导入失败,详细原因已记录到受保护日志。');
return self::FAILURE;
}
$this->table(['截止日期', '状态', '店铺数', '明细行数', '待结算待付款金额合计', '实际结算给商家合计'], [[
$result['period_end'],
$result['status'],
$result['store_count'],
$result['row_count'],
$result['balance_total'],
$result['settled_total'],
]]);
return self::SUCCESS;
}
}

View File

@ -1,61 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\WangshangBankBillImporter;
use Throwable;
class ImportWangshangBankBills extends Command
{
protected $signature = 'finance-ledger:import-wangshang-bank
{path : 网商银行批次 ZIP 或 manifest.json}
{--date= : 账单日期 YYYY-MM-DD,默认前一天}
{--dry-run : 只校验,不写入财务台账}';
protected $description = '批量导入网商银行影刀账单到银行账单';
public function handle(WangshangBankBillImporter $importer): int
{
$date = trim((string) ($this->option('date') ?: now()->subDay()->toDateString()));
try {
$result = $importer->import(
(string) $this->argument('path'),
$date,
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('网商银行影刀账单未导入,保留原有银行账单。' . $exception->getMessage());
return self::FAILURE;
}
$this->table(
['公司', '账户尾号', '页面笔数', '有效笔数', '收入合计', '支出合计'],
array_map(static fn (array $row): array => [
$row['company'],
$row['account_last4'],
$row['expected_rows'] ?? '-',
$row['rows'],
number_format((float) $row['income'], 2),
number_format((float) $row['expense'], 2),
], $result['accounts']),
);
$this->info(sprintf(
'%s网商银行账单:%d 个账户,%d 笔,收入 %.2f,支出 %.2f。',
$result['dry_run'] ? '校验完成,' : '已写入银行账单,',
count($result['accounts']),
$result['rows'],
$result['income'],
$result['expense'],
));
$this->line(sprintf(
'已同步 %d 个账户的当前余额。',
$result['synced_accounts'],
));
return self::SUCCESS;
}
}

View File

@ -1,51 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\WechatStatementImporter;
use Throwable;
class ImportWechatStatement extends Command
{
protected $signature = 'finance-ledger:import-wechat-statement
{path : 朱俊祥微信月度收支表 XLS/XLSX 文件}
{--account-short= : 独立账单账户简称,默认朱俊祥微信}
{--opening-balance= : 指定期初余额;默认读取文件期初行}
{--dry-run : 只校验,不写入财务台账}';
protected $description = '导入朱俊祥微信月度收支表,保留期初、逐笔收支和余额';
public function handle(WechatStatementImporter $importer): int
{
$opening = trim((string) $this->option('opening-balance'));
try {
$result = $importer->import(
(string) $this->argument('path'),
$this->option('account-short') ?: null,
$opening === '' ? null : (float) $opening,
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('微信收支表未导入,保留原有数据。' . $exception->getMessage());
return self::FAILURE;
}
$this->table(['项目', '值'], [
['校验模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['账户简称', $result['account_short']],
['日期范围', $result['from'] . ' 至 ' . $result['to']],
['期初余额', number_format((float) $result['opening_balance'], 2)],
['有效笔数', $result['rows']],
['收入合计', number_format((float) $result['income'], 2)],
['支出合计', number_format((float) $result['expense'], 2)],
['期末余额', number_format((float) $result['closing_balance'], 2)],
['替换原记录', $result['replaced']],
]);
$this->info($result['dry_run'] ? '微信收支表校验完成。' : '微信收支表已导入独立账单。');
return self::SUCCESS;
}
}

View File

@ -1,44 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\WorkPlatformCourierRobots;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
class ImportWorkPlatformCourierRobots extends Command
{
protected $signature = 'courier-bills:import-platform-robots {file : Private JSON export of courier payable robot rows} {--company=1} {--apply : Save the reviewed exact matches}';
protected $description = '预演或导入工作平台快递应付群机器人配置;不发送消息';
public function handle(CourierBillStore $store, WorkPlatformCourierRobots $matcher, SupplierDingTalkNotifier $notifier): int
{
$path = (string) $this->argument('file');
if (! is_file($path) || filesize($path) > 2 * 1024 * 1024) throw new RuntimeException('配置文件不存在或超过 2MB。');
$rows = json_decode(file_get_contents($path), true, 32, JSON_THROW_ON_ERROR);
if (! is_array($rows) || ! array_is_list($rows) || count($rows) > 10000) throw new RuntimeException('配置文件必须是最多 10000 条的数组。');
\App\Models\Common\Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
$result = $matcher->match($store->groups(), $rows);
$this->line('名称匹配:' . count($result['robots']) . ';未匹配:' . count($result['unmatched']) . ';有歧义:' . count($result['ambiguous']));
foreach ($result['robots'] as $name => $robot) $this->line($name . ' → ' . ($robot['group_name'] ?: '工作平台已配置群') . '(配置 ' . $robot['source_id'] . ')');
$this->line('未匹配:' . implode('、', $result['unmatched']));
$this->line('有歧义:' . implode('、', $result['ambiguous']));
if (! $this->option('apply')) return self::SUCCESS;
$backup = 'private/courier-robot-backups/' . now()->format('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.enc';
$backedUp = Storage::disk('local')->put($backup, Crypt::encryptString(json_encode([
'company_id' => (int) $this->option('company'),
'value' => setting('supplier_reconciliation.dingtalk_robots', []),
], JSON_THROW_ON_ERROR)));
if (! $backedUp || ! chmod(Storage::disk('local')->path($backup), 0600)) {
throw new RuntimeException('原配置备份失败,未修改机器人配置。');
}
$notifier->importCourierRobots($result['robots']);
$this->info('已保存 ' . count($result['robots']) . ' 家;原配置已加密备份:' . $backup . ';未发送消息。');
return self::SUCCESS;
}
}

View File

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

View File

@ -1,384 +0,0 @@
<?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', 'balance_date', 'account_balance', 'available_balance']) as $row) {
$accountNo = $this->accountNo($row->account_no);
if ($accountNo !== '') {
$snapshotBefore[$accountNo] = $row;
}
}
$openingBefore = $connection->table('fin_account_opening')
->where('opening_date', '<', $date->toDateString())
->orderBy('opening_date')
->orderBy('id')
->get(['account_short', 'opening_date', 'opening_balance'])
->keyBy('account_short');
$latestTransactionByShort = [];
$latestTransactionByAccountNo = [];
foreach ($connection->table('fin_transactions')
->whereNull('deleted_at')
->where('txn_date', '<=', $previousEnd->toDateString())
->cursor() as $row) {
$transactionDate = substr((string) $row->txn_date, 0, 10);
$short = trim((string) ($row->account_short ?? ''));
if ($short !== ''
&& ($latestTransactionByShort[$short] ?? '') < $transactionDate) {
$latestTransactionByShort[$short] = $transactionDate;
}
$accountNo = $this->accountNo($row->source_value ?? null);
if ($accountNo !== ''
&& ($latestTransactionByAccountNo[$accountNo] ?? '') < $transactionDate) {
$latestTransactionByAccountNo[$accountNo] = $transactionDate;
}
}
$existingOpenings = $connection->table('fin_account_opening')
->where('opening_date', $date->toDateString())
->get()
->keyBy('account_short');
$byShort = [];
foreach ($accounts as $account) {
$short = trim((string) $account->account_short);
$accountNo = $this->accountNo($account->account_no);
[$balance, $source, $sourceDate] = $this->actualOpening(
$accountNo,
$bankStatementBefore,
$bankBillBefore,
$snapshotBefore,
);
[$carriedBalance, $carriedSource, $carriedSourceDate] = $this->carriedOpening(
$short,
$accountNo,
$openingBefore,
$latestTransactionByShort,
$latestTransactionByAccountNo,
);
$opening = $openingBefore->get($short);
$latestOpeningDate = $opening === null
? ''
: substr((string) $opening->opening_date, 0, 10);
if ($carriedBalance !== null
&& ($balance === null || $carriedSourceDate > $sourceDate)) {
$balance = $carriedBalance;
$source = $carriedSource;
$sourceDate = $carriedSourceDate;
} elseif ($balance !== null
&& $latestOpeningDate !== ''
&& $sourceDate < $latestOpeningDate) {
// 新期初比旧账单余额更晚;若期初后还有未定价动账,不能回退使用旧余额。
$balance = null;
$source = '';
$sourceDate = '';
}
if ($balance === null) {
$byShort[$short][] = [
'account_id' => (int) $account->id,
'balance' => null,
'source' => '',
'source_date' => '',
];
continue;
}
$byShort[$short][] = [
'account_id' => (int) $account->id,
'balance' => $balance,
'source' => $source,
'source_date' => $sourceDate,
];
}
$eligibleAccounts = 0;
$skippedNoBasis = 0;
$skippedConflicts = 0;
$candidates = [];
foreach ($byShort as $short => $items) {
$missing = array_filter($items, static fn (array $item): bool => $item['balance'] === null);
if ($missing !== []) {
$skippedNoBasis += count($items);
continue;
}
$balances = array_values(array_unique(array_map(
static fn (array $item): string => number_format((float) $item['balance'], 2, '.', ''),
$items,
)));
if (count($balances) !== 1) {
$skippedConflicts += count($items);
continue;
}
$eligibleAccounts += count($items);
$candidates[$short] = [
'opening_balance' => (float) $balances[0],
'source' => (string) $items[0]['source'],
'source_date' => (string) $items[0]['source_date'],
];
}
$created = 0;
$updated = 0;
$unchanged = 0;
$preservedExisting = 0;
if ($apply) {
$connection->transaction(function () use (
$connection,
$date,
$candidates,
$existingOpenings,
&$created,
&$updated,
&$unchanged,
&$preservedExisting,
): void {
foreach ($candidates as $short => $candidate) {
$existing = $existingOpenings->get($short);
$remark = '系统锁定:' . $candidate['source_date'] . ' 最后一笔实际余额';
if ($existing === null) {
$connection->table('fin_account_opening')->insert([
'account_short' => $short,
'opening_date' => $date->toDateString(),
'opening_balance' => $candidate['opening_balance'],
'remark' => $remark,
'created_at' => now(),
'updated_at' => now(),
]);
$created++;
continue;
}
if (! str_starts_with((string) $existing->remark, '系统锁定:')) {
$preservedExisting++;
continue;
}
if (abs((float) $existing->opening_balance - (float) $candidate['opening_balance']) < 0.005
&& (string) $existing->remark === $remark) {
$unchanged++;
continue;
}
$connection->table('fin_account_opening')
->where('id', $existing->id)
->update([
'opening_balance' => $candidate['opening_balance'],
'remark' => $remark,
'updated_at' => now(),
]);
$updated++;
}
});
}
return [
'applied' => $apply,
'opening_date' => $date->toDateString(),
'previous_period_end' => $previousEnd->toDateString(),
'eligible_accounts' => $eligibleAccounts,
'unique_account_shorts' => count($candidates),
'created' => $created,
'updated' => $updated,
'unchanged' => $unchanged,
'preserved_existing' => $preservedExisting,
'skipped_no_basis' => $skippedNoBasis,
'skipped_conflicts' => $skippedConflicts,
'candidates' => array_map(
static fn (string $short, array $candidate): array => [
'account_short' => $short,
...$candidate,
],
array_keys($candidates),
array_values($candidates),
),
];
}
/**
* @return array{0:?float,1:string,2:string}
*/
private function actualOpening(
string $accountNo,
array $bankStatementBefore,
array $bankBillBefore,
array $snapshotBefore,
): array {
if ($accountNo === '') {
return [null, '', ''];
}
if (isset($bankStatementBefore[$accountNo])) {
$row = $bankStatementBefore[$accountNo];
return [
round((float) $row->balance, 2),
'bank_statement',
substr((string) $row->txn_date, 0, 10),
];
}
if (isset($bankBillBefore[$accountNo])) {
$row = $bankBillBefore[$accountNo];
return [
round((float) $row->balance, 2),
'bank_bill',
substr((string) $row->txn_date, 0, 10),
];
}
if (isset($snapshotBefore[$accountNo])) {
$row = $snapshotBefore[$accountNo];
return [
round((float) ($row->account_balance ?? $row->available_balance), 2),
'balance_snapshot',
substr((string) $row->balance_date, 0, 10),
];
}
return [null, '', ''];
}
/**
* @return array{0:?float,1:string,2:string}
*/
private function carriedOpening(
string $accountShort,
string $accountNo,
mixed $openingBefore,
array $latestTransactionByShort,
array $latestTransactionByAccountNo,
): array {
$opening = $openingBefore->get($accountShort);
if ($opening === null) {
return [null, '', ''];
}
$openingDate = substr((string) $opening->opening_date, 0, 10);
$latestTransactionDate = max(
(string) ($latestTransactionByShort[$accountShort] ?? ''),
$accountNo !== '' ? (string) ($latestTransactionByAccountNo[$accountNo] ?? '') : '',
);
if ($latestTransactionDate !== '' && $latestTransactionDate >= $openingDate) {
return [null, '', ''];
}
return [
round((float) $opening->opening_balance, 2),
'opening_carry_forward',
$openingDate,
];
}
private function accountNo(mixed $value): string
{
return preg_replace('/\D+/', '', trim((string) $value)) ?? '';
}
}

View File

@ -1,50 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\SurchargeSettlementMatcher;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Throwable;
class MatchBillSurcharges extends Command
{
protected $signature='courier-surcharge:match-bills {--month= : 账单月份 YYYY-MM,默认上月} {--statement=* : 指定快递对账单} {--factory=* : 指定代发厂家} {--all : 匹配该月全部未确认账单} {--existing-only : 只更新已建立附加费匹配的账单} {--company=1}';
protected $description='匹配指定月份账单的附加费金额及商品信息,已确认账单不变';
public function handle(SurchargeSettlementMatcher $matcher): int
{
$month=(string)($this->option('month')?:now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m'));
if(!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D',$month)){$this->error('请填写有效账单月份 YYYY-MM');return self::FAILURE;}
if(!$this->option('all')&&$this->option('statement')===[]&&$this->option('factory')===[]){$this->error('请选择对账单、厂家或 --all');return self::FAILURE;}
if(app()->environment('production')&&!env('FINANCE_BATCH_CONTAINER')){$this->error('请通过 run-finance-batch.sh 执行。');return self::FAILURE;}
$lock=Cache::lock('bill-surcharge-matching',3900);if(!$lock->get()){$this->error('附加费匹配正在运行');return self::FAILURE;}
try{
$db=DB::connection('business_mirror');$statements=[];$factories=[];
if($this->option('all')||$this->option('statement')!==[]){
$statements=$db->table('courier_bill_statements')->where('bill_month',$month)->where('status','<>','confirmed')
->when($this->option('existing-only'),fn($q)=>$q->whereIn('id',$db->table(SurchargeSettlementMatcher::TABLE)->where('scope','courier')->where('bill_month',$month)->select('owner_id')))
->when(!$this->option('all'),fn($q)=>$q->whereIn('id',array_map('intval',$this->option('statement'))))->orderBy('id')->pluck('id')->all();
foreach($statements as $id){app(CourierBillMatcher::class)->refreshSurchargeSummary((int)$id);$this->line('快递对账单 #'.$id.' 附加费已匹配');}
}
if($this->option('all')||$this->option('factory')!==[]){
$store=app(DropshipFreightStore::class);
$factories=$db->table('dropship_bill_files')->where('bill_month',$month)->where('status','parsed')->whereNotNull('factory_id')
->when($this->option('existing-only'),fn($q)=>$q->whereIn('factory_id',$db->table('dropship_bill_surcharges')->where('bill_month',$month)->select('factory_id')))
->when(!$this->option('all'),fn($q)=>$q->whereIn('factory_id',array_map('intval',$this->option('factory'))))->distinct()->pluck('factory_id')->all();
foreach($factories as $id){
$state=app(DropshipConfirmation::class)->state($month,(int)$id,(int)$this->option('company'));
if(($state['status']??'')==='confirmed'){$this->line('厂家 #'.$id.' 已确认,跳过');continue;}
$db->transaction(function()use($db,$store,$id,$month){foreach($db->table('dropship_bill_files')->where('factory_id',$id)->where('bill_month',$month)->where('status','parsed')->get() as $file)$store->storeSurchargeRows($file,(int)$id);});
$matcher->dropship((int)$id,$month);$this->line('代发厂家 #'.$id.' 附加费已匹配');
}
}
$this->info('附加费匹配完成:'.$month.';快递对账单 '.count($statements).' 张,代发厂家 '.count($factories).' 家。');return self::SUCCESS;
}catch(Throwable $e){report($e);$this->error('附加费匹配失败:'.$e->getMessage());return self::FAILURE;}
finally{$lock->release();}
}
}

View File

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

View File

@ -1,72 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Repositories\PlantingReimbursementRepository as Repository;
use Modules\EcommerceFinance\Services\PlantingReimbursementBatches as Batches;
use Modules\EcommerceFinance\Services\PlantingReimbursementGate as Gate;
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
use Throwable;
/**
* 每天 10:30 锁定当天种菜报销批次(确认本批):放行检查通过就把待处理 + 处理中的校验结果固定下来,
* 之后在聚工单整批锁单、取消、标记打款都按这份来。没通过(比如同步不新鲜)时 10:40、10:50 再试;
* 已确认的跳过。不依赖钉钉群机器人,不改聚工单。11:20 的汇总推送仍会兜底确认一次。
*/
class PlantingReimbursementAutoConfirm extends Command
{
protected $signature = 'planting-reimbursement:auto-confirm
{--date= : 报销日期 Y-m-d,默认今天}
{--dry-run : 只检查,不确认}';
protected $description = '放行检查通过后自动确认(锁定)当天种菜报销批次';
public function handle(Workbench $workbench, Batches $batches, 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();
$companyId = (int) $company->id;
if ($batches->get($companyId, $date) !== null) {
$this->line("#{$companyId}: {$date} 已确认,跳过");
continue;
}
if (! in_array($repository->syncStatus()['code'], ['ready', 'failed'], true)) {
$this->line("#{$companyId}: 聚工单镜像未就绪,跳过");
continue;
}
try {
$result = $workbench->build($companyId, $date);
$gate = Gate::check($result);
if (! $gate['ok']) {
$this->warn("#{$companyId}: {$date} 放行检查没通过,暂不确认:" . implode(';', $gate['reasons']));
$failed = true;
continue;
}
if ($this->option('dry-run')) {
$this->line("#{$companyId}: {$date} 可以确认:" . $result['summary']['source']['count'] . ' 单');
continue;
}
$batch = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
$this->info("#{$companyId}: 已确认 {$date} 批次 " . $batch['summary']['source']['count'] . ' 单');
} catch (Throwable $exception) {
report($exception);
$this->error("#{$companyId}: 确认失败:" . $exception->getMessage());
$failed = true;
}
}
return $failed ? self::FAILURE : self::SUCCESS;
}
}

View File

@ -1,134 +0,0 @@
<?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\PlantingReimbursementBatches as Batches;
use Modules\EcommerceFinance\Services\PlantingReimbursementGate as Gate;
use Modules\EcommerceFinance\Services\PlantingReimbursementRobot as Robot;
use Modules\EcommerceFinance\Services\PlantingReimbursementWorkbench as Workbench;
use Throwable;
/** 每天 11:20 生成当天种菜报销批次:把可报销合计、要取消的单和放行检查结果推到钉钉群并 @ 报销人,并自动发不予报销通知(@ 发起人)。不改聚工单。 */
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, $robot, (int) $company->id, $date, ! $this->option('dry-run'));
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, Robot $robot, int $companyId, string $date, bool $sendNotices): 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
|| \Modules\EcommerceFinance\Services\PlantingClock::minutesSince((string) $sync['last_succeeded_at']) > 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)];
}
// 已确认的批次直接用;没确认的现取现算,放行检查通过就自动确认本批(之后锁单、取消、标记打款都按这份来)。
$batches = app(Batches::class);
$result = $batches->get($companyId, $date);
$confirmedNow = false;
if ($result === null) {
$result = $workbench->build($companyId, $date);
if ($sendNotices && Gate::check($result)['ok']) {
$result = $batches->confirm($companyId, $date, $result, ['paid_from' => Workbench::defaultPaidFrom($date), 'scope' => Workbench::DEFAULT_SCOPE], null, 'auto');
$confirmedNow = true;
}
}
$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['quota_error'] ?? '') !== '') {
$lines[] = '- **种菜额度没有校验**(' . $result['quota_error'] . '),相关工单都在待复查,先别报销';
}
if (($result['shop_source'] ?? '') === 'mirror') {
$lines[] = '- 工作平台店铺信息暂时读不到,利润中心用的是前一天同步的数据';
}
if (($result['roster_source'] ?? '') === 'none') {
$lines[] = '- 取不到在职名单,收款人在职未校验';
}
// 自动发取消 / 待复查通知(@ 发起人;同一批已发过的不重发),放行检查不过就不发,等人看。
$gate = Gate::check($result, false);
if (! $gate['ok']) {
$lines[] = '- **暂不能报销**:' . implode(';', $gate['reasons']);
} elseif ($s['notices'] === []) {
$lines[] = '- 没有要取消或复查的工单';
} elseif ($sendNotices) {
$sent = $robot->sendNotices($companyId, $date, $s['notices']);
$lines[] = sprintf('- 已自动发不予报销通知:%d 人(之前已发 %d 人%s)', $sent['sent'], $sent['skipped'], $sent['failed'] > 0 ? ',失败 ' . $sent['failed'] . ' 人' : '');
}
if (isset($result['batch'])) {
$lines[] = '- 本批' . ($confirmedNow ? '已自动确认' : '已于 ' . substr((string) $result['batch']['confirmed_at'], 11, 5) . ' 确认')
. ',聚工单待处理:① 整批锁单 ' . $s['source']['count'] . ' 单 ② 取消 ' . $s['counts'][Auditor::DECISION_CANCEL] . ' 单 ③ 打款后标记打款 ' . $s['counts'][Auditor::DECISION_PASS] . ' 单';
$lines[] = '- 标记打款后在工作台点「提交钉钉流程」';
}
$lines[] = '- [打开工作台](' . $url . ')';
return [$title, implode("\n", $lines)];
}
}

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