Compare commits

...

74 Commits

Author SHA1 Message Date
b4ee49e7ef 发货同步保留同单号的多次真实出库 (#1551) 2026-11-29 20:46:09 +08:00
51e805ed37 发货同步排除品牌自营京仓单并统一商品名称 (#1550) 2026-11-29 14:59:04 +08:00
ca483879c9 快递账单对账支持附加费、补发扣款和运费差原因 (#1549) 2026-11-29 14:29:20 +08:00
77608ce497 快递对账保留原始工作表,应付汇总以导入金额为准 (#1548) 2026-11-29 12:38:39 +08:00
45d6707111 fix: 招商银行失败提醒改用群机器人 (#1547) 2026-11-28 14:18:45 +08:00
ffe97e458a 快递账单重复导入提示与安全重新读取 (#1546) 2026-11-28 12:27:47 +08:00
a7e7b067eb 修复发货包裹商品、数量、体积与换单同步 (#1545) 2026-11-28 12:27:14 +08:00
e6b9775a24 快递账单支持合并导出、原始运费表和四位金额 (#1544)
按 0006、0007、0008 顺序整合;账单相关测试及隔离 MariaDB 迁移验证通过。
2026-11-28 11:31:38 +08:00
6a1e7678fe 中铁客退返货线路报价及吨方取高计费 (#1543) 2026-11-28 10:51:23 +08:00
6b1ff05fee 快递账单上传逐文件按文件名识别分组 (#1542) 2026-11-28 10:48:01 +08:00
801264b4b3 支持合并账单自动拆分和重新匹配 (#1541) 2026-11-28 10:32:48 +08:00
d967420b08 支持对账分组自动生成、导入导出和补归组 (#1540) 2026-11-28 09:38:40 +08:00
52181b41d4 test(发票附件): 覆盖表格原件保存 (#1539) 2026-11-27 22:56:59 +08:00
b601a28e01 快递账单对账第一期与快递应付汇总 (#1538) 2026-11-27 22:08:45 +08:00
3374563c4f feat(发票附件): 保留无法预览的原始文件 (#1537) 2026-11-27 20:18:19 +08:00
79449e4aca fix(发票附件): 按付款月份分目录存储 (#1536) 2026-11-27 20:08:09 +08:00
a8f5e9a188 feat(供应商货款预估): 接入聚水潭采购退货明细 (#1535)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 19:18:52 +08:00
c8dfec5c85 feat: 快递合同管理支持筛选导出清单及签署原件 (#1534) 2026-11-27 18:53:55 +08:00
7e23e42a34 fix(资金余额): 京东钱包新店期初固定按零 (#1533) 2026-11-27 18:43:29 +08:00
ddbd018377 fix(供应商货款预估): 仅对无金额记录补预估 (#1532)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 18:27:25 +08:00
506f1e8784 fix(供应商货款预估): 修正筛选预估汇总并改为万元 (#1531)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 18:17:02 +08:00
684813d03b fix(资金余额): 京东钱包新增店铺期初自动按零计算 (#1530) 2026-11-27 18:15:49 +08:00
79206da614 feat(发票数据): 增加按月原始附件库 (#1529) 2026-11-27 18:00:14 +08:00
a0e4cc4380 feat(供应商货款预估): 增加商品资料成本价兜底
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:48:32 +08:00
e1178f56aa perf(供应商货款预估): 精简汇总扫描列
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:31:17 +08:00
0bb0d895d1 perf(供应商货款预估): 优化兜底取价汇总
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:20:20 +08:00
2912814931 fix(供应商货款预估): 补充当前定价兜底取价
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 17:05:38 +08:00
5f1348db4b fix(发票预览): 回扫时替换工作簿旧预览 (#1524) 2026-11-27 16:57:03 +08:00
e058927cdd perf(供应商货款预估): 增加代发发货分页索引
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 16:45:32 +08:00
5d6412ac44 fix(发票预览): 安装中文字体并校正 PDF 展示 (#1522) 2026-11-27 16:43:33 +08:00
2d4859f291 保护未发出历史补录并衔接每日同步 (#1521) 2026-11-27 16:35:58 +08:00
c7f011fc93 perf(供应商货款预估): 优化合并明细分页查询
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 16:35:24 +08:00
414d4fd3ee fix(发票数据): 修复表格附件发票预览回填 (#1519) 2026-11-27 16:33:32 +08:00
e0a3b8fd1f 接入已核实的仓内未发工单镜像 (#1518) 2026-11-27 16:20:43 +08:00
773509443d feat(供应商货款预估): 合并代发仓发货明细
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 16:09:20 +08:00
9089d8fb23 未发出明细两列展示及现场拦截分套同步 (#1515) 2026-11-27 16:04:03 +08:00
85c32fbd7d feat: 发货数据支持导入称重重量 (#1514)
替代冲突检测卡住的 #1500。移植 b8536189;发货列表、正常与重复导入、无效重量、计费重量回归及迁移回滚验证通过。生产迁移和部署待独立授权。
2026-11-27 15:44:53 +08:00
66639e19c1 feat(发票数据): 增加发票图片与PDF页内预览 (#1513)
图片和 PDF 发票原件缓存到私有业务存储,页面通过预览弹窗查看;历史附件首次点击时按需缓存。
2026-11-27 15:42:22 +08:00
92f88fb60b 每日汇总快递未发出明细 (#1512) 2026-11-27 15:40:40 +08:00
0a7cc700fb feat: 增加注销账户状态 (#1511) 2026-11-27 15:33:36 +08:00
aa99eb932e fix(部署): 使用可用 Debian 镜像并重试依赖安装
切换腾讯 Debian 镜像并为 apt 依赖安装增加续传重试。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 15:29:19 +08:00
6ca0154a22 fix(发票数据): 继续处理已到期发票积压 (#1509)
OA 同步没有新流程时仍处理已到重试时间的发票;无到期积压时不做增量抓取。
2026-11-27 15:22:17 +08:00
bec7cbdabb feat(发票数据): 合并OA同步并精简发票明细 (#1508)
发票识别并入 OA 流程同步,加入重试退避;发票页移除前置业务列和附件,流程号直达 OA 详情。
2026-11-27 15:19:07 +08:00
dcd12eca7b fix(供应商货款预估): 冻结明细表头
供应商货款预估明细改为局部纵向滚动并固定表头。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 15:16:36 +08:00
e7a73008c7 feat(推广费用): 自动同步聚水潭推广费用到共享镜像 (#1506) 2026-11-27 14:55:30 +08:00
b72b2e12bd feat(发票数据): 展示流程直抓完整发票字段 (#1505)
发票明细按 OA 流程附件直抓口径展示完整字段,打款时间移到最后,并从 2026-10 开始统计。
2026-11-27 14:42:41 +08:00
b6e06e775c fix(供应商货款预估): 补齐月份和供应商商品编码
月份按入库日期年月生成,供应商商品编码按供应商名称和商品编码拼接。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 14:41:23 +08:00
4dfed91c92 feat(资金管理): 新增月度资金余额监控并统一支付宝账户口径
合并月度资金余额监控页、店铺每日余额本页小计标识及全部/店铺支付宝账户名称区分。
2026-11-27 14:33:32 +08:00
e330d94090 fix(供应商应付): 空月份排序放到最后 (#1501)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 14:06:23 +08:00
0513146ef9 feat(供应商应付): 支持退货对账完整批量导入 (#1499)
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-27 13:50:50 +08:00
f5b797070b 凌晨发货同步补拉最近40天 (#1498) 2026-11-27 13:31:17 +08:00
cdbaf45f27 厂家记账按成本价核算沐野竹木 (#1497) 2026-11-27 11:15:22 +08:00
cc204fbb97 feat(发票数据): 自动增量抓取并补入OA发票 (#1496)
自动识别 PDF、图片、XLS/XLSX、ZIP、RAR、7Z 发票附件,每 15 分钟补扫未处理、失败和部分识别流程。
2026-11-27 10:44:37 +08:00
95731bd90b 修复退款待确认读取已退役状态镜像 (#1495) 2026-11-27 10:43:42 +08:00
6cfed8ac51 fix(供应商应付): 货款对账按最新月份和日期排序 (#1494) 2026-11-27 10:38:30 +08:00
6a6c6f94c1 发货数据还原平台和无物流仓库 (#1493) 2026-11-27 10:36:00 +08:00
b2f7a072c8 feat(财务经营分析): 接入快递运费月度店铺汇总 2026-11-27 01:12:19 +08:00
50f5c7bc64 fix(财务经营分析): 排除京东网银钱包 (#1491) 2026-11-26 22:42:16 +08:00
7de0d3370f 发货数据缺少计费重量时留空运费 (#1490) 2026-11-26 21:48:03 +08:00
8df3c3ec36 fix(供应商应付): 终版货款对账按数据库分页 (#1489) 2026-11-26 20:47:47 +08:00
1954e10b5e 发货运费从十月开始核算 (#1488) 2026-11-26 18:37:18 +08:00
56de349bfc fix: 快递共用合同证明和收款账户证明按账号核验 (#1487) 2026-11-26 18:11:18 +08:00
f8efd97115 fix: 修正安装费实际归集月份口径 (#1486) 2026-11-26 18:09:20 +08:00
2f9fd2ac1d fix: 发票数据路由随主路由加载 (#1485)
将发票数据导出、刷新状态和附件路由移入主路由,避免生产 Web 因模块状态缺失路由。
2026-11-26 18:08:09 +08:00
f49d32ca8d fix: 安装费月度对比改用实际金额 (#1484) 2026-11-26 17:58:14 +08:00
24c6b7cb51 fix: 汇总快递应付附加费映射
按交易单号从运费差、其他附加费汇总和退件费页面取数,并对同一单号的多条金额求和。
2026-11-26 17:54:07 +08:00
d112d90ed9 fix: 安装费用改为月度安装公司对比 (#1483) 2026-11-26 17:51:46 +08:00
12bc2f9efd fix: 补开发票数据页面旧权限入口 (#1482)
让已有 OA流程 权限的账号自动获得发票数据菜单和直达权限。
2026-11-26 17:45:04 +08:00
8b27e3e7aa perf(货款预估): 优化筛选汇总取价 (#1481)
筛选汇总改为批量取最新变价后聚合,减少重复回查。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 17:42:57 +08:00
832fe6399a fix: 安装费用趋势改按安装公司区分 (#1479) 2026-11-26 17:40:28 +08:00
4539031eb1 fix: 补充平提家具店铺期初余额 (#1477)
增加淘宝-平提家具源头工厂零期初余额,并补充生产数据修正迁移。
2026-11-26 17:31:25 +08:00
2ec2e7410f fix: 修复证件粘贴预览并定位签署表单错误 (#1476) 2026-11-26 17:30:28 +08:00
e1efa6812a feat(货款预估): 增加筛选金额汇总 (#1475)
筛选后展示数量、最新价金额和预估金额×0.8合计。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-11-26 17:26:11 +08:00
c333497e0b fix(快递应付): 移除停用的运费对账模块 (#1474) 2026-11-26 17:25:10 +08:00
192 changed files with 20806 additions and 2474 deletions

View File

@ -10,6 +10,7 @@ runtime
*.md
JetBrainsMono-字体
node_modules
outputs
**/__pycache__
vendor
bootstrap/cache/*

View File

@ -7,6 +7,7 @@ use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\LazyCollection;
use Throwable;
/** Read the signed snapshot directly: no duplicate contracts, attachment copies or archive backfill. */
@ -79,11 +80,17 @@ class CourierContractPageData
return $data;
}
public function supplierExportRows(): iterable
public function exportRows(string $partnerType): iterable
{
$filters = $this->filters();
foreach ($this->contractRows('supplier') as $row) {
if ($this->matchesFilters($row, $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;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,29 @@
<?php
namespace App\Console\Commands;
use App\Support\UnshippedWaybills;
use Illuminate\Console\Command;
final class SyncUnshippedWaybills extends Command
{
protected $signature = 'courier:sync-unshipped-waybills';
protected $description = '从共享镜像和已导入订单日志重算未发出明细';
public function handle(UnshippedWaybills $waybills): int
{
$failed = false;
foreach (UnshippedWaybills::SYNC_SOURCES as $source => $label) {
if (!$waybills->sync($source)) {
$warning = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->value('warning');
$this->warn($label.':'.$warning);
$failed = true;
} else {
$state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first();
$this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。');
}
}
return $failed ? self::FAILURE : self::SUCCESS;
}
}

View File

@ -48,6 +48,14 @@ class Kernel extends ConsoleKernel
->withoutOverlapping(60)
->runInBackground();
// 聚水潭推广费用按日期、平台、店铺自动汇总到共享镜像;最近 7 天覆盖迟到修订。
$schedule->command('business-mirror:sync-promotion-expenses --days=7 --quiet')
->dailyAt('03:10')
->timezone('Asia/Shanghai')
->withoutOverlapping(90)
->appendOutputTo(storage_path('logs/promotion-expense-sync.log'))
->runInBackground();
// 退款待确认四张镜像每天 06:00 专属刷新,确保 10:00 前完成;
// 同步失败状态由财务驾驶舱展示。
$schedule->command('business-mirror:sync-tables --daily-only --max-batches=0')

View File

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

View File

@ -87,11 +87,6 @@ class CourierAgreementSignatures extends Controller
}
if ($type === 'shared-contract') {
$data['contract_partner_name'] = trim((string) $data['contract_partner_name']);
if ($data['counterparty_signer_type'] === 'person') {
$data['operator_name'] = $data['contract_partner_name'];
} elseif (blank($data['operator_name'] ?? null)) {
throw ValidationException::withMessages(['operator_name' => '请填写物流商归属企业经办人的 E 签宝实名认证姓名。']);
}
$sharedCouriers = collect($data['shared_courier_names'] ?? [])
->map(static fn ($name): string => trim((string) $name))
->filter()
@ -113,7 +108,10 @@ class CourierAgreementSignatures extends Controller
$data['counterparty_signer_type'] = $data['counterparty_signer_type'] ?? 'organization';
$data['operator_name'] = trim((string) ($data['operator_name'] ?? '')) ?: null;
if ($type !== 'quote-confirmation' && $data['counterparty_signer_type'] === 'organization' && blank($data['operator_name'])) {
$usesCourierAccountLookup = $type === 'account-proof' && $data['partner_type'] === 'courier';
if ($type !== 'quote-confirmation' && ! $usesCourierAccountLookup
&& $data['counterparty_signer_type'] === 'organization' && blank($data['operator_name'])) {
throw ValidationException::withMessages(['operator_name' => '企业签署主体必须填写 E 签宝实名认证姓名。']);
}
@ -122,7 +120,7 @@ class CourierAgreementSignatures extends Controller
throw ValidationException::withMessages(['operator_name' => '请填写签署账号绑定的个人实名姓名,不能填写快递名称或企业名称。']);
}
if ($data['counterparty_signer_type'] === 'person') {
if ($data['counterparty_signer_type'] === 'person' && ! $usesCourierAccountLookup) {
// A personal signer uses the same real name for the signer and
// the E-sign identity; the UI should not require it twice.
$data['operator_name'] = trim((string) $data['counterparty_organization_name']);
@ -477,7 +475,12 @@ class CourierAgreementSignatures extends Controller
'esign_account' => ['required', 'string', 'max:255'],
'secondary_esign_account' => [Rule::excludeIf(request('document_type') === 'cooperation-contract'), 'required_if:document_type,authorization,entity-change', 'nullable', 'string', 'max:255'],
'secondary_operator_name' => ['exclude_if:document_type,entity-change', 'nullable', 'string', 'min:2', 'max:100'],
'operator_name' => ['exclude_if:document_type,cooperation-contract,entity-change', 'nullable', 'string', 'min:2', 'max:100'],
'operator_name' => [
Rule::excludeIf(in_array(request('document_type'), ['cooperation-contract', 'entity-change'], true)
|| (request('partner_type') === 'courier'
&& in_array(request('document_type'), CourierAgreementSignature::COURIER_DOCUMENTS_WITH_ACCOUNT_LOOKUP, true))),
'nullable', 'string', 'min:2', 'max:100',
],
'counterparty_organization_name' => ['required_if:document_type,account-proof,account-change,quote-confirmation', 'nullable', 'string', 'min:2', 'max:255'],
'counterparty_signer_type' => ['required_if:document_type,account-proof,account-change,entity-change,cooperation-contract,authorization,shared-contract,quote-confirmation', 'nullable', 'in:organization,person'],
'secondary_signer_type' => ['nullable', 'in:organization,person'],

View File

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

View File

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

View File

@ -16,6 +16,7 @@ use App\Business\KukaPostingQuotation\KukaPostingQuotationPageData;
use App\Business\KukaPostingReconciliation\KukaReconciliationPageData;
use App\Business\LaborExpenseWorkbookImporter;
use App\Business\LaborExpenseDataStore;
use App\Business\CourierFreightFinancialSummary;
use App\Business\CourierPayableSummaryFilter;
use App\Business\CourierPayableSummaryStore;
use App\Business\FundForecastTemplate;
@ -105,6 +106,7 @@ use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use Modules\EcommerceFinance\Services\SupplierFreeShippingStore;
use Modules\EcommerceFinance\View\PlatformPromotionAccountPageData;
use Modules\EcommerceFinance\View\OrderDataPageData;
use Modules\EcommerceFinance\View\PromotionExpensePageData;
use Modules\EcommerceFinance\View\SupplierNegativeAlertPageData;
use Modules\EcommerceFinance\View\SupplierPayableForecastPageData;
use RuntimeException;
@ -1216,14 +1218,6 @@ class Pages extends Controller
]);
}
if ($section === 'courier-payables' && $page === 'freight-reconciliation' && request()->boolean('courier_summary')) {
return response()->json([
'data' => ['count' => 0, 'freight' => 0],
'status' => 'disabled',
'message' => '原数据源已停用,本页面不再展示原运费对账数据。',
], 200, ['Cache-Control' => 'private, no-store']);
}
return view('business.pages.show', $this->viewData(
$sectionConfig,
$pageConfig,
@ -1299,6 +1293,55 @@ class Pages extends Controller
], 200, ['Cache-Control' => 'private, no-store']);
}
public function exportPromotionExpenses(Request $request): StreamedResponse
{
$filters = $request->validate([
'month' => ['nullable', 'date_format:Y-m'],
'platform' => ['nullable', 'string', 'max:64'],
'store_name' => ['nullable', 'string', 'max:255'],
]);
$month = trim((string) ($filters['month'] ?? '')) ?: now('Asia/Shanghai')->format('Y-m');
$rows = app(PromotionExpensePageData::class)->exportRows(
$month,
trim((string) ($filters['platform'] ?? '')),
trim((string) ($filters['store_name'] ?? '')),
);
return response()->streamDownload(function () use ($rows): void {
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, [
'平台',
'店铺名称',
'源记录',
'直接推广费',
'分摊推广费',
'推广费用合计',
'直接营销费',
'分摊营销费',
'营销费用合计',
'费用合计',
]);
foreach ($rows as $row) {
fputcsv($out, [
$row['platform'] ?? '',
$row['store_name'] ?? '',
(int) ($row['source_rows'] ?? 0),
number_format((float) ($row['push_fee'] ?? 0), 2, '.', ''),
number_format((float) ($row['shared_push_fee'] ?? 0), 2, '.', ''),
number_format((float) ($row['push_fee_total'] ?? 0), 2, '.', ''),
number_format((float) ($row['marketing_fee'] ?? 0), 2, '.', ''),
number_format((float) ($row['shared_marketing_fee'] ?? 0), 2, '.', ''),
number_format((float) ($row['marketing_fee_total'] ?? 0), 2, '.', ''),
number_format((float) ($row['total_fee'] ?? 0), 2, '.', ''),
]);
}
fclose($out);
}, '聚水潭推广费用_' . $month . '.csv', [
'Content-Type' => 'text/csv; charset=UTF-8',
]);
}
/**
* 账单明细导出:按页面同一套筛选条件流式导出 CSV(全部筛选结果)。
*/
@ -3615,6 +3658,8 @@ class Pages extends Controller
$billNonInvoiceExpenseTotal = 0.0;
$promotionInvoiceExpenseComplete = $rows !== [];
$promotionInvoiceExpenseTotal = 0.0;
$courierFreightExpenseComplete = $rows !== [];
$courierFreightExpenseTotal = 0.0;
$installationExpenseComplete = $rows !== [];
$installationExpenseTotal = 0.0;
$netProfitComplete = $rows !== [];
@ -3634,6 +3679,11 @@ class Pages extends Controller
} else {
$promotionInvoiceExpenseTotal += (float) $row['promotion_invoice_expense'];
}
if ($row['freight'] === null) {
$courierFreightExpenseComplete = false;
} else {
$courierFreightExpenseTotal += (float) $row['freight'];
}
if ($row['installation_fee'] === null) {
$installationExpenseComplete = false;
} else {
@ -3672,6 +3722,9 @@ class Pages extends Controller
'promotion_invoice_expense_total' => $promotionInvoiceExpenseComplete
? round($promotionInvoiceExpenseTotal, 2)
: null,
'courier_freight_expense_total' => $courierFreightExpenseComplete
? round($courierFreightExpenseTotal, 2)
: null,
'installation_expense_total' => $installationExpenseComplete
? round($installationExpenseTotal, 2)
: null,
@ -3733,6 +3786,9 @@ class Pages extends Controller
$promotionExpenseAvailable ? ($promotionExpenseBucketsByMonth[$reportMonth] ?? []) : null,
$installationExpenseAvailable ? ($installationExpenseBucketsByMonth[$reportMonth] ?? []) : null,
) as $values) {
if (in_array((string) $values['platform'], self::RECEIPT_MATCH_EXCLUDED_PLATFORMS, true)) {
continue;
}
if ($filters['platform'] !== '' && $values['platform'] !== $filters['platform']) {
continue;
}
@ -3774,7 +3830,8 @@ class Pages extends Controller
/**
* 单个月份的「时间-平台-店铺」聚合:收入来自业绩明细,成本来自商品成本表。
*
* 两张表都是几十万行,聚合结果按月份缓存 5 分钟;筛选在内存里做,避免每次开页重跑分组。
* 收入和商品成本表都在百万行级;聚合结果按月份缓存,筛选在内存里做,
* 避免每次开页重跑慢查询。快递运费导入后会通过版本号自动换缓存键。
*
* @param array<string,float>|null $promotionExpenseBuckets
* @param array<string,array{platform:string,amount:float}>|null $installationExpenseBuckets
@ -3787,10 +3844,14 @@ class Pages extends Controller
): array
{
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$courierFreightVersion = app(CourierFreightFinancialSummary::class)
->version((int) company_id());
return cache()->remember(
'financial-analysis-aggregates-v8:' . $reportMonth . ':' . $this->financialAnalysisMappingSignature(),
now()->addMinutes(5),
'financial-analysis-aggregates-v10:' . $reportMonth . ':'
. $this->financialAnalysisMappingSignature() . ':' . now()->format('Y-m-d')
. ':' . $courierFreightVersion,
now()->addHours(6),
function () use (
$connection,
$reportMonth,
@ -3888,6 +3949,23 @@ class Pages extends Controller
}
}
$courierFreightBuckets = null;
try {
$courierFreightBucketsByMonth = app(CourierFreightFinancialSummary::class)
->monthlyStoreTotals([substr($reportMonth, 0, 7)], (int) company_id());
$courierFreightBuckets = $courierFreightBucketsByMonth[substr($reportMonth, 0, 7)] ?? null;
} catch (Throwable $exception) {
report($exception);
}
if ($courierFreightBuckets !== null) {
$this->applyStoreOnlyExpense(
$rows,
$courierFreightBuckets,
'freight',
'其他',
);
}
$subjectMatcher = app(ProductCostSubjectMatcher::class);
$subjectMap = $subjectMatcher->map(
array_values(array_unique(array_column($rows, 'store_name'))),
@ -3968,6 +4046,55 @@ class Pages extends Controller
];
}
/**
* 店铺级费用归入同店铺申报收入最高的一行;店铺不存在时补一行“其他”平台,
* 保证费用总额不因缺少业绩行而丢失。
*
* @param array<string,array<string,mixed>> $rows
* @param array<string,float> $amounts
*/
private function applyStoreOnlyExpense(
array &$rows,
array $amounts,
string $field,
string $fallbackPlatform,
): void {
$preferredKeys = [];
foreach ($rows as $key => $row) {
$storeName = trim((string) $row['store_name']);
if (! array_key_exists($storeName, $amounts)) {
continue;
}
$preferredKey = $preferredKeys[$storeName] ?? null;
if ($preferredKey === null
|| [
(float) $row['declared_income'],
(string) $row['platform'],
] > [
(float) $rows[$preferredKey]['declared_income'],
(string) $rows[$preferredKey]['platform'],
]) {
$preferredKeys[$storeName] = $key;
}
}
foreach ($rows as &$row) {
$row[$field] = 0.0;
}
unset($row);
foreach ($amounts as $storeName => $amount) {
$storeName = trim((string) $storeName);
$key = $preferredKeys[$storeName] ?? null;
if ($key === null) {
$platform = $fallbackPlatform;
$key = $platform . "\0" . $storeName;
$rows[$key] ??= $this->financialAnalysisEmptyRow($platform, $storeName);
}
$rows[$key][$field] = round((float) $amount, 2);
}
}
/** 科目映射变化时自动换缓存键,避免费用拆票结果在 5 分钟缓存内继续使用旧口径。 */
private function financialAnalysisMappingSignature(): string
{
@ -4707,29 +4834,15 @@ class Pages extends Controller
}
$keyword = trim((string) request('keyword', ''));
$rows = $this->supplierPayableOverrides->listRows(
PayablesFinalActions::DATASET_PREFIX
. ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:')
. $dataset,
(int) (company_id() ?: 1),
);
if ($keyword !== '') {
$needle = mb_strtolower($keyword);
$rows = array_values(array_filter($rows, static function (array $row) use ($needle): bool {
foreach ($row as $key => $value) {
if ($key === '_action_key' || $value === null) {
continue;
}
if (str_contains(mb_strtolower((string) $value), $needle)) {
return true;
}
}
return false;
}));
}
$storeDataset = PayablesFinalActions::DATASET_PREFIX
. ($sectionSlug === PayablesFinalRegistry::SECTION_COURIER ? 'courier:' : 'supplier:')
. $dataset;
$perPage = in_array($dataset, [
'payment-reconciliation',
'return-reconciliation',
'supplier-payables-report',
], true) ? 15 : 50;
$currentPage = max((int) request('page', 1), 1);
$unpricedSummaryFields = match ($dataset) {
'delivery-unpriced' => ['qty', 'guessAmount'],
'return-unpriced' => ['qty', 'guess_amount'],
@ -4737,6 +4850,25 @@ class Pages extends Controller
};
$unpricedSummary = null;
if ($unpricedSummaryFields !== null) {
$rows = $this->supplierPayableOverrides->listRows(
$storeDataset,
(int) (company_id() ?: 1),
);
if ($keyword !== '') {
$needle = mb_strtolower($keyword);
$rows = array_values(array_filter($rows, static function (array $row) use ($needle): bool {
foreach ($row as $key => $value) {
if ($key === '_action_key' || $value === null) {
continue;
}
if (str_contains(mb_strtolower((string) $value), $needle)) {
return true;
}
}
return false;
}));
}
$quantity = 0.0;
$estimatedAmount = 0.0;
[$quantityField, $amountField] = $unpricedSummaryFields;
@ -4752,16 +4884,21 @@ class Pages extends Controller
'quantity' => $quantity,
'estimated_amount' => $estimatedAmount,
];
$pagedRows = array_slice($rows, ($currentPage - 1) * $perPage, $perPage);
$totalRows = count($rows);
} else {
$paged = $this->supplierPayableOverrides->paginateRows(
$storeDataset,
(int) (company_id() ?: 1),
$perPage,
$currentPage,
$keyword,
in_array($dataset, ['payment-reconciliation', 'return-reconciliation'], true),
);
$pagedRows = $paged['rows'];
$totalRows = $paged['total'];
}
// 宽表固定每页 15 行,减少纵向滚动并保持横向核对区稳定。
$perPage = in_array($dataset, [
'payment-reconciliation',
'return-reconciliation',
'supplier-payables-report',
], true) ? 15 : 50;
$currentPage = max((int) request('page', 1), 1);
return [
'dataset' => $dataset,
'fields' => collect($registry->fields($sectionSlug, $dataset))
@ -4769,8 +4906,8 @@ class Pages extends Controller
->values()
->all(),
'rows' => new LengthAwarePaginator(
array_slice($rows, ($currentPage - 1) * $perPage, $perPage),
count($rows),
$pagedRows,
$totalRows,
$perPage,
$currentPage,
['path' => request()->url(), 'query' => request()->query()],
@ -5524,7 +5661,10 @@ class Pages extends Controller
protected function resolveContentForSection(string $section, string $page, ?string $tab): ?array
{
if (in_array($section, self::PAYABLES_FINAL_SECTIONS, true)) {
return null;
// 终版目录目前只有快递账单对账和快递应付汇总接了数据,其余页面仍是占位。
return $section === 'courier-payables-final' && in_array($page, ['courier-bill-reconciliation', 'courier-payable-summary'], true)
? $this->resolveContent($page, $tab)
: null;
}
if ($section === 'company-management' && $page === 'company-plan') {
@ -5567,7 +5707,6 @@ class Pages extends Controller
'product-prices' => $this->contentForProductPrices(),
'courier-information' => $this->contentForCourierInformation(),
'courier-onboarding' => app(\App\Business\CourierOnboardingPageData::class)->page(),
'freight-reconciliation' => $this->contentForFreightReconciliation(),
'third-party-warehouse-storage' => $this->contentForThirdPartyWarehouseStorage(),
'warehouse-freight' => ['view' => 'business.pages.courier-payables.warehouse-freight'],
'board-deductions' => $this->contentForBoardDeductions(),
@ -5578,6 +5717,7 @@ class Pages extends Controller
'payable-cloud-warehouse-vehicle-fee' => $this->contentForDingPayableWorkflows(),
'online-daifa-price' => $this->contentForOnlineDaifaPrice(),
'product-costs' => $this->contentForProductCosts(),
'promotion-expenses' => app(PromotionExpensePageData::class)->page(),
'financial-analysis' => $this->contentForFinancialAnalysis(),
'oa-process' => $this->contentForProcessDetails(),
'invoice-data' => app(\Modules\EcommerceFinance\View\InvoiceDataPageData::class)->page(request()),
@ -5587,9 +5727,13 @@ class Pages extends Controller
'courier-surcharge-settlement' => $this->contentForCourierSurchargeSettlementPage(),
'freight-difference', 'other-surcharge-summary', 'return-fee' => $this->contentForCourierPayableSummary($page),
'accessory-reship-deductions' => app(\Modules\EcommerceFinance\View\AccessoryReshipPageData::class)->page(),
'unshipped-waybills' => app(\App\Http\Controllers\Business\UnshippedWaybillController::class)->page(request()),
'courier-bill-reconciliation' => app(\App\Http\Controllers\Business\CourierBillController::class)->page(request()),
'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()),
'shipping-data' => $this->contentForShippingData(),
'return-pickup-management' => $this->contentForReturnPickupManagement(),
'withdrawal-management' => $this->contentForWithdrawalManagement(),
'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(),
'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(),
'log-statistics' => app(\Modules\EcommerceFinance\View\DingWorklogStatisticsPageData::class)->page(request()),
'order-profit-list' => app(\Modules\EcommerceFinance\View\OrderProfitPageData::class)->page(),
@ -7354,14 +7498,6 @@ class Pages extends Controller
return $text !== '' && is_numeric($text) ? (float) $text : null;
}
protected function contentForFreightReconciliation(): array
{
// 原来源口径不适用;保留入口,但不读取明细、同步状态或汇总。
return [
'view' => 'business.pages.courier-payables.freight-reconciliation',
];
}
protected function contentForThirdPartyWarehouseStorage(): array
{
$request = request();
@ -7937,8 +8073,6 @@ class Pages extends Controller
$syncStatus = $this->nonJingxiRefunds->syncStatus($states);
if (! $this->nonJingxiRefunds->ready()) {
$pending = true;
} elseif ($pendingConfirmation && ! $this->nonJingxiRefunds->pendingConfirmationStatusReady()) {
$pending = true;
} elseif (! $this->nonJingxiRefunds->queryReady()) {
$indexPending = true;
} else {

View File

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

View File

@ -60,6 +60,54 @@ final class SupplierPayableForecastExport extends Controller
]);
}
public function returns(
Request $request,
SupplierPayableForecastPageData $pageData,
SupplierPayableForecastRepository $repository,
PayablesFinalRegistry $registry,
): StreamedResponse {
$filters = $pageData->returnFilters($request);
abort_unless(
$repository->returnSyncStatus()['ready'],
503,
'采购退货共享镜像尚未就绪,暂不能导出。',
);
$fields = $registry->fields(
PayablesFinalRegistry::SECTION_SUPPLIER,
'return-reconciliation',
);
return response()->streamDownload(function () use ($fields, $filters, $repository): void {
$stream = fopen('php://output', 'w');
if ($stream === false) {
throw new \RuntimeException('无法创建供应商退货明细导出文件。');
}
fwrite($stream, "\xEF\xBB\xBF");
fputcsv($stream, array_map(
static fn (array $field): string => (string) ($field['label'] ?? ''),
$fields,
));
foreach ($repository->returnRowsForExport($filters) as $row) {
$values = [];
foreach ($fields as $key => $field) {
$value = $row[$key] ?? '';
$values[] = ($field['type'] ?? '') === 'number'
? number_format((float) $value, 2, '.', '')
: $this->textCell($value);
}
fputcsv($stream, $values);
}
fclose($stream);
}, $this->returnFilename($filters), [
'Content-Type' => 'text/csv; charset=UTF-8',
'Cache-Control' => 'private, no-store',
]);
}
/** @param array{date_from:string,date_to:string,keyword:string} $filters */
private function filename(array $filters): string
{
@ -71,6 +119,17 @@ final class SupplierPayableForecastExport extends Controller
return '供应商货款明细_' . $from . '_' . $to . '_' . now()->format('Ymd_His') . '.csv';
}
/** @param array{date_from:string,date_to:string,keyword:string} $filters */
private function returnFilename(array $filters): string
{
$from = Carbon::parse($filters['date_from'])->format('Ymd_His');
$to = $filters['date_to'] !== ''
? Carbon::parse($filters['date_to'])->format('Ymd_His')
: '不限';
return '供应商退货明细_' . $from . '_' . $to . '_' . now()->format('Ymd_His') . '.csv';
}
private function textCell(mixed $value): string
{
$text = trim((string) $value);

View File

@ -0,0 +1,169 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use App\Support\UnshippedWaybills;
use App\Utilities\SystemAccess;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Throwable;
final class UnshippedWaybillController extends Controller
{
public function __construct(private readonly UnshippedWaybills $waybills) {}
public function page(Request $request): array
{
$data = ['view' => 'business.pages.courier-payables.unshipped-waybills', 'sources' => UnshippedWaybills::SOURCES,
'syncSources' => UnshippedWaybills::SYNC_SOURCES, 'canImport' => $this->canImport(), 'rows' => null, 'states' => collect(), 'coverage' => null, 'unavailable' => false];
try {
$data['rows'] = $this->filtered($request)->orderByDesc('evidence_time')->orderByDesc('id')->paginate(50)->withQueryString();
$db = $this->waybills->connection();
$data['history'] = $this->waybills->results()->where('evidence_no', 'like', UnshippedWaybills::HISTORY_PREFIX.'%')
->selectRaw('count(*) as row_count, max(evidence_time) as cutoff')->first();
$data['states'] = $db->table('courier_unshipped_sync')->get()->keyBy('source');
$data['coverage'] = $db->table('courier_unshipped_order_logs')->selectRaw('min(operated_at) as start_at,max(operated_at) as end_at')->first();
} catch (\Illuminate\Database\QueryException $error) {
report($error);
$data['unavailable'] = true;
}
return $data;
}
private function filtered(Request $request)
{
$filters = $request->validate([
'waybills' => ['nullable', 'string', 'max:15000'],
'sources' => ['nullable', 'array', 'max:3'],
'sources.*' => [Rule::in(array_keys(UnshippedWaybills::SOURCES))],
'courier' => ['nullable', 'string', 'max:255'],
'from' => ['nullable', 'date_format:Y-m-d'],
'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'],
]);
$query = $this->waybills->results();
$numbers = array_values(array_unique(array_filter(array_map(UnshippedWaybills::normalize(...),
preg_split('/[\r\n,,]+/u', $filters['waybills'] ?? '') ?: []), fn ($number) => $number !== '')));
if (count($numbers) > 500) throw ValidationException::withMessages(['waybills' => '最多同时查询 500 个快递单号。']);
if ($numbers !== []) $query->whereIn('waybill_no', $numbers);
if (!empty($filters['sources'])) $query->whereIn('source', UnshippedWaybills::storedSources($filters['sources']));
if (!empty($filters['courier'])) $query->where('courier_name', trim($filters['courier']));
if (!empty($filters['from'])) $query->where('evidence_time', '>=', $filters['from']);
if (!empty($filters['to'])) $query->where('evidence_time', '<', CarbonImmutable::parse($filters['to'])->addDay()->toDateString());
return $query;
}
public function export(Request $request)
{
$query = $this->filtered($request);
return response()->streamDownload(function () use ($query): void {
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->fromArray(['快递单号', '来源']);
$line = 2;
foreach ($query->orderBy('id')->lazyById(1000) as $row) {
$values = [$row->waybill_no, UnshippedWaybills::label($row->source)];
foreach ($values as $column => $value) {
$sheet->setCellValueExplicit(chr(65 + $column).$line, (string) $value, DataType::TYPE_STRING);
}
$line++;
}
(new Xlsx($book))->save('php://output');
$book->disconnectWorksheets();
}, '未发出明细.xlsx');
}
public function import(Request $request)
{
abort_unless($this->canImport(), 403);
$file = $request->validate(['log' => ['required', 'file', 'mimes:xlsx,csv,txt', 'max:10240']])['log'];
$isCsv = strtolower($file->getClientOriginalExtension()) === 'csv';
$entries = [];
$header = null;
$errors = [];
foreach ($this->fileRows($file->getRealPath(), $isCsv) as $line => $row) {
if ($header === null) {
$header = array_flip(array_map(fn ($value) => trim((string) $value, "\xEF\xBB\xBF \t"), $row));
if (array_diff(['订单编号', '类型', '操作备注', '操作时间', '操作人'], array_keys($header))) {
throw ValidationException::withMessages(['log' => '文件缺少订单编号、类型、操作备注、操作时间或操作人列。']);
}
continue;
}
if (trim((string) ($row[$header['类型']] ?? '')) !== '修改快递单号') continue;
$remark = (string) ($row[$header['操作备注']] ?? '');
$parsed = UnshippedWaybills::parseRemark($remark);
$order = trim((string) ($row[$header['订单编号']] ?? ''));
$time = $row[$header['操作时间']] ?? null;
try {
$operated = is_int($time) || is_float($time)
? CarbonImmutable::instance(Date::excelToDateTimeObject($time))
: (filled($time) ? CarbonImmutable::parse($time) : null);
} catch (Throwable) {
$operated = null;
}
if (!$parsed || !$operated || !preg_match('/^[A-Za-z0-9-]{1,96}$/', $order) || preg_match('/^\d+e[+-]?\d+$/i', $order)) {
if (count($errors) < 10) $errors[] = $line;
continue;
}
if ($operated->toDateString() < UnshippedWaybills::START || $operated->toDateString() >= today()->toDateString()) continue;
$entries[] = $parsed + ['order_no' => $order, 'operated_at' => $operated->toDateTimeString(),
'operator' => trim((string) ($row[$header['操作人']] ?? '')), 'remark' => $remark];
}
if ($errors !== []) {
throw ValidationException::withMessages(['log' => '这些行的订单编号、时间或备注格式有误(含科学计数法单号):'.implode('、', $errors).'。请修正后重新上传。']);
}
if ($entries === []) throw ValidationException::withMessages(['log' => '没有符合日期及操作类型的记录。']);
$db = $this->waybills->connection();
$count = $db->transaction(function () use ($db, $entries): int {
$count = 0;
foreach (array_chunk($entries, 500) as $batch) {
$count += $db->table('courier_unshipped_order_logs')->insertOrIgnore($batch);
}
return $count;
});
return back()->with('unshipped_import', '已新增 '.$count.' 条日志,下次每日同步后更新换单明细。');
}
private function fileRows(string $path, bool $isCsv): iterable
{
if ($isCsv) {
$file = new \SplFileObject($path);
$file->setCsvControl(',', '"', '');
$file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
foreach ($file as $index => $row) {
if ($row !== [null]) yield $index + 1 => $row;
}
return;
}
$reader = IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(true);
$book = $reader->load($path);
try {
foreach ($book->getSheet(0)->getRowIterator() as $row) {
yield $row->getRowIndex() => array_map(
fn ($cell) => $cell->getValue(),
iterator_to_array($row->getCellIterator(), false)
);
}
} finally {
$book->disconnectWorksheets();
}
}
private function canImport(): bool
{
return in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true);
}
}

View File

@ -51,7 +51,7 @@ class EnsureLimitedDingTalkPageAccess
return $next($request);
}
$allowed = SidebarPermissions::allowedKeys($user);
$allowed = SidebarPermissions::effectiveAllowedKeys($user);
$key = $route->parameter('section').'/'.$route->parameter('page');
if (in_array($key, $allowed, true)) {
return $next($request);

View File

@ -21,6 +21,8 @@ class CourierAgreementSignature extends Model
public const COOPERATION_PARTY_A_PHONE = '18052733960';
public const COURIER_DOCUMENTS_WITH_ACCOUNT_LOOKUP = ['shared-contract', 'account-proof'];
public const DOCUMENTS = [
'account-proof' => [
'code' => 'TPL-ACCOUNT-CERT-V2',

View File

@ -121,10 +121,10 @@ final class CourierAgreementSignatureService
$flowCreationStarted = false;
try {
$signers = $this->signersFor($signature);
$client = app(EsignClient::class);
$initiatorName = data_get($signature->payload, 'signing_subject');
$client->assertSignFlowInitiator($initiatorName);
$signers = $this->signersFor($signature);
$bytes = Storage::disk('uploads')->get($signature->source_pdf_path);
$fileName = 'agreement-' . $signature->business_no . '.pdf';
$fileId = $client->uploadPdf($bytes, $fileName);
@ -369,29 +369,25 @@ final class CourierAgreementSignatureService
{
$payload = $signature->payload ?? [];
if ($signature->document_type === 'shared-contract') {
if (in_array($signature->document_type, ['shared-contract', 'account-proof', 'account-change'], true)) {
$isPerson = ($payload['counterparty_signer_type'] ?? 'organization') === 'person';
if (blank($signature->operator_name)) {
throw new RuntimeException('请填写物流商归属主体签署人的 E 签宝实名认证姓名。');
}
return [[
$signer = [
'signer_type' => $isPerson ? 0 : 1,
'organization_name' => $isPerson ? null : $signature->organization_name,
'operator_name' => $signature->operator_name,
'operator_account' => $signature->operator_account,
]];
}
];
if (in_array($signature->document_type, ['account-proof', 'account-change'], true)) {
$isPerson = ($payload['counterparty_signer_type'] ?? 'organization') === 'person';
if ($signature->partnerType() === 'courier'
&& in_array($signature->document_type, CourierAgreementSignature::COURIER_DOCUMENTS_WITH_ACCOUNT_LOOKUP, true)) {
return [$this->resolveSignerIdentity($signer, '对方')];
}
return [[
'signer_type' => $isPerson ? 0 : 1,
'organization_name' => $isPerson ? null : $signature->organization_name,
'operator_name' => $isPerson ? ($signature->operator_name ?: $signature->organization_name) : $signature->operator_name,
'operator_account' => $signature->operator_account,
]];
if ($isPerson && blank($signer['operator_name'])) {
$signer['operator_name'] = $signature->organization_name;
}
return [$signer];
}
$primary = [
@ -469,8 +465,8 @@ final class CourierAgreementSignatureService
];
return [
$this->entityChangeSigner($formerSigner, '变更前主体'),
$this->entityChangeSigner($changedSigner, '变更后主体'),
$this->resolveSignerIdentity($formerSigner, '变更前主体'),
$this->resolveSignerIdentity($changedSigner, '变更后主体'),
];
}
@ -496,7 +492,7 @@ final class CourierAgreementSignatureService
return [$primary];
}
private function entityChangeSigner(array $signer, string $label): array
private function resolveSignerIdentity(array $signer, string $label): array
{
// Previously created tasks keep their saved signer names when retried.
if (filled($signer['operator_name'])) {

View File

@ -0,0 +1,65 @@
<?php
namespace App\Support\CourierBills;
use Modules\EcommerceFinance\View\AccessoryReshipPageData;
use Throwable;
/**
* 「配件补发扣款」页算好的扣款,按首发快递(快递名称1)汇总,给对账单小汇总用。
* 只取页面上「可扣款」的行(已选定首发快递、配了扣款比例、金额大于 0),和页面合计口径一致。
*/
class AccessoryDeductions
{
/** @var array<string,array<string,float>|null> 同一次请求里按月份缓存 */
private array $cache = [];
/** @return array<string,float>|null 快递名称1 => 扣款金额(元);读不到时为 null */
public function byCourier(string $month): ?array
{
if (! array_key_exists($month, $this->cache)) {
$this->cache[$month] = $this->load($month);
}
return $this->cache[$month];
}
/** @param list<string> $expressNames */
public function total(string $month, array $expressNames): ?float
{
$map = $this->byCourier($month);
if ($map === null) {
return null;
}
$sum = 0.0;
foreach (array_unique($expressNames) as $name) {
$sum += $map[$name] ?? 0.0;
}
return round($sum, 2);
}
/** @return array<string,float>|null */
protected function load(string $month): ?array
{
try {
$result = [];
$page = app(AccessoryReshipPageData::class);
foreach ($page->rows(['month' => $month, 'match_status' => 'ready']) as $row) {
if (! AccessoryReshipPageData::inCategory($row, 'ready')) {
continue;
}
$courier = trim((string) ($row['selected_courier'] ?? ($row['matches'][0]['courier'] ?? '')));
if ($courier !== '') {
$result[$courier] = ($result[$courier] ?? 0) + ((int) $row['deduction_cents']) / 100;
}
}
return $result;
} catch (Throwable $error) {
report($error);
return null;
}
}
}

View File

@ -0,0 +1,292 @@
<?php
namespace App\Support\CourierBills;
use Generator;
/**
* 从快递账单文件里找表头、取出每一行的单号 / 运费 / 重量,原始列整行保留。
*
* 表头可能不在第一行(上面常有标题行),所以在每个工作表前 15 行里找含单号列的那一行;
* 没有单号列的工作表(快递自己做的汇总页等)整表跳过。
*/
final class BillParser
{
public const WAYBILL_HEADERS = ['运单号', '运单编号', '快递单号', '运单号码', '面单号', '单号'];
public const AMOUNT_HEADERS = ['运费', '快递运费', '结算运费', '结算金额', '应付金额', '总运费', '金额', '费用'];
public const WEIGHT_HEADERS = ['计费重量', '结算重量', '重量', '实际重量'];
/** 表名里出现这些字,整张表当附加费表,不读。(不含「上楼」二字本身:有的分组就叫「樵舍中通-上楼」。) */
public const SURCHARGE_SHEET_WORDS = ['加收', '附加', '上楼费', '转件', '派送费', '派件费', '超区', '偏远', '退件', '退回', '赔付', '赔款', '理赔', '扣款', '罚款', '保价'];
/** 金额列名里出现这些字,整张表当附加费表,不读。 */
public const SURCHARGE_AMOUNT_WORDS = ['加收', '附加', '上楼', '转件', '派送', '派件', '超区', '偏远', '退件', '退回', '赔', '扣款', '罚款', '保价'];
/** 有这一列时逐行看:费用项目不是运费的行(上楼费、转件费……)不读。 */
public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目'];
private const HEADER_SCAN_ROWS = 15;
private const SKIP_WORDS = ['合计', '总计', '小计', '汇总', '总额'];
public function __construct(private readonly BillWorkbookReader $reader) {}
/**
* @param array{waybill_header?:?string,amount_header?:?string,weight_header?:?string} $overrides
* @return Generator<int, array{type:string}&array<string,mixed>>
* type=sheet: {sheet, header_row, headers, waybill, amount, weight, item, skipped?:string, rows?:int}
* type=surcharge_rows: {sheet, rows} 这张表里费用项目不是运费、没读进运费的行数
* type=surcharge: {sheet, row, waybill, item, amount} 附加费(只记金额,不核对)
* type=line: {sheet, row, waybill, amount, weight, raw}
* type=reject: {sheet, row, value, reason}
*/
public function parse(string $path, string $extension, array $overrides = []): Generator
{
[, $skip] = $this->freightSheets($path, $extension, $overrides);
foreach ($this->reader->sheets($path, $extension) as $sheet => $rows) {
if (isset($skip[(string) $sheet])) {
[$reason, $headerRow, $waybillColumn, $amountColumn, $itemColumn, $amountHeader] = $skip[(string) $sheet];
$count = 0;
foreach ($rows as $rowNumber => $row) {
if ($rowNumber <= $headerRow || trim((string) ($row[$waybillColumn] ?? '')) === '' || self::isTotalRow($row)) {
continue;
}
$count++;
// 附加费表:只取单号、费用项目、金额
if ($amountColumn !== null) {
$waybill = Waybill::parse(trim((string) $row[$waybillColumn]))['waybill'];
$item = $itemColumn === null ? '' : trim((string) ($row[$itemColumn] ?? ''));
if ($waybill !== null) {
yield ['type' => 'surcharge', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'waybill' => $waybill,
'item' => $item !== '' ? $item : self::itemName($amountHeader, (string) $sheet),
'amount' => self::number($row[$amountColumn] ?? null)];
}
}
}
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => $reason, 'rows' => $count];
continue;
}
$header = null;
$columns = null;
$scanned = 0;
$surcharge = 0;
$filled = 0;
foreach ($rows as $rowNumber => $row) {
if ($columns === null) {
$filled += implode('', array_map(static fn ($v): string => trim((string) $v), $row)) === '' ? 0 : 1;
if ($scanned >= self::HEADER_SCAN_ROWS) {
continue;
}
$scanned++;
$found = self::findColumns($row, $overrides);
if ($found !== null) {
$header = $row;
$columns = $found;
if ($columns['amount'] === null) {
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => '找到单号列但没有运费列,整表跳过'];
break;
}
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'header_row' => $rowNumber,
'headers' => array_map('strval', $row), ...$columns];
continue;
}
continue;
}
$rawWaybill = (string) ($row[$columns['waybill']] ?? '');
$amount = self::number($row[$columns['amount']] ?? null);
$weight = $columns['weight'] === null ? null : self::number($row[$columns['weight']] ?? null);
$trimmed = trim($rawWaybill);
// 空单号、合计行、公式错误值(#N/A 等,手工表里 VLOOKUP 没找到时常见)都不算账单行。
if ($trimmed === '' || self::isTotalRow($row) || preg_match('/^#(N\/A|REF!|VALUE!|DIV\/0!|NAME\?|NULL!|NUM!)$/i', $trimmed)) {
continue;
}
// 运费和附加费混在一张表、用「费用项目」区分的:只读运费行。
if ($columns['item'] !== null) {
$item = preg_replace('/\s+/u', '', (string) ($row[$columns['item']] ?? '')) ?? '';
if ($item !== '' && ! str_contains($item, '运费')) {
$surcharge++;
$waybill = Waybill::parse($trimmed)['waybill'];
if ($waybill !== null) {
yield ['type' => 'surcharge', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'waybill' => $waybill,
'item' => $item, 'amount' => $amount];
}
continue;
}
}
$result = Waybill::parse($trimmed);
if ($result['waybill'] === null) {
yield ['type' => 'reject', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'value' => $trimmed, 'reason' => $result['reason']];
continue;
}
$raw = [];
foreach ($header as $index => $_) {
$raw[] = (string) ($row[$index] ?? '');
}
yield ['type' => 'line', 'sheet' => (string) $sheet, 'row' => $rowNumber, 'waybill' => $result['waybill'],
'amount' => $amount, 'weight' => $weight, 'raw' => $raw];
}
if ($surcharge > 0) {
yield ['type' => 'surcharge_rows', 'sheet' => (string) $sheet, 'rows' => $surcharge];
}
if ($columns === null) {
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => ($scanned >= self::HEADER_SCAN_ROWS ? '前 15 行' : '')
. '没有找到单号列,整表跳过', 'rows' => $filled];
}
}
}
/**
* 快递账单里常有好几张表:运费明细之外,还有附加费、上楼费、派件费用等明细(单号列、金额列都有)。第一期只核运费:
* 1. 表名或金额列名像附加费的(加收、附加、上楼费、转件、派送、超区、偏远、退件、赔付、扣款……),整表不读;
* 2. 剩下的表里,金额列名带「运费」的、或有「费用项目」列(逐行只读运费行)的,才当运费表读;
* 3. 一张都没有时(比如金额列就叫「金额」),读剩下所有带单号和金额的表。
*
* @return array{0:list<string>,1:array<string,array{0:string,1:int,2:int,3:?int,4:?int,5:string}>}
* [运费表, 不读的表 => [原因, 表头行号, 单号列, 附加费金额列, 费用项目列, 金额列名]]
*/
public function freightSheets(string $path, string $extension, array $overrides = []): array
{
$freight = [];
$others = [];
$skip = [];
foreach ($this->reader->sheets($path, $extension) as $sheet => $rows) {
$sheet = (string) $sheet;
$scanned = 0;
foreach ($rows as $rowNumber => $row) {
$found = self::findColumns($row, $overrides);
if ($found !== null) {
$named = preg_replace('/\s+/u', '', $sheet) ?? '';
if ($found['amount'] === null && self::containsAny($named, self::SURCHARGE_SHEET_WORDS)) {
// 附加费表的金额列常直接叫「上楼费」「超长费」
foreach ($row as $index => $cell) {
$text = preg_replace('/\s+/u', '', (string) $cell) ?? '';
if ($index !== $found['waybill'] && $text !== '' && (str_ends_with($text, '费') || str_contains($text, '金额'))) {
$found['amount'] = (int) $index;
break;
}
}
}
if ($found['amount'] === null) {
break;
}
$amount = preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
if (self::containsAny($named, self::SURCHARGE_SHEET_WORDS) || self::containsAny($amount, self::SURCHARGE_AMOUNT_WORDS)) {
$skip[$sheet] = ['附加费表:只读金额进小汇总,没有逐单核对', (int) $rowNumber, $found['waybill'], $found['amount'], $found['item'], $amount];
} elseif (str_contains($amount, '运费') || $found['item'] !== null || trim((string) ($overrides['amount_header'] ?? '')) !== '') {
$freight[] = $sheet;
} else {
$others[$sheet] = [(int) $rowNumber, $found['waybill']];
}
break;
}
if (++$scanned >= self::HEADER_SCAN_ROWS) {
break;
}
}
}
if ($freight === []) {
$freight = array_keys($others);
} else {
foreach ($others as $sheet => [$headerRow, $waybill]) {
$skip[$sheet] = ['不是运费表(第一期只核运费),未读入', $headerRow, $waybill, null, null, ''];
}
}
return [$freight, $skip];
}
/** 附加费表没有费用项目列时的项目名:金额列名像「退回运费」「上楼费」就用它,太笼统(费用金额、金额)就用表名。 */
private static function itemName(string $amountHeader, string $sheet): string
{
$name = preg_replace('/(金额|(元)|\(元\))$/u', '', $amountHeader) ?? $amountHeader;
return in_array($name, ['', '费用', '应付', '结算', '合计', '总'], true) ? $sheet : $name;
}
private static function containsAny(string $text, array $words): bool
{
foreach ($words as $word) {
if (str_contains($text, $word)) {
return true;
}
}
return false;
}
/**
* @param array<int,string> $row
* @return array{waybill:int,amount:?int,weight:?int,item:?int}|null
*/
public static function findColumns(array $row, array $overrides = []): ?array
{
$headers = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
$waybill = self::locate($headers, array_filter([$overrides['waybill_header'] ?? null]) ?: self::WAYBILL_HEADERS, true);
if ($waybill === null) {
return null;
}
$amount = self::locate($headers, array_filter([$overrides['amount_header'] ?? null]) ?: self::AMOUNT_HEADERS, false);
$weight = self::locate($headers, array_filter([$overrides['weight_header'] ?? null]) ?: self::WEIGHT_HEADERS, false);
$item = null;
foreach (self::ITEM_HEADERS as $candidate) {
$index = array_search($candidate, $headers, true);
if ($index !== false) {
$item = (int) $index;
break;
}
}
return ['waybill' => $waybill, 'amount' => $amount, 'weight' => $weight, 'item' => $item];
}
/** 先按候选顺序全等匹配,再退到包含匹配(单号列不认「订单号」「交易单号」)。 */
private static function locate(array $headers, array $candidates, bool $waybill): ?int
{
foreach ($candidates as $candidate) {
$index = array_search(preg_replace('/\s+/u', '', $candidate), $headers, true);
if ($index !== false) {
return (int) $index;
}
}
foreach ($candidates as $candidate) {
foreach ($headers as $index => $header) {
if ($header === '' || ! str_contains($header, $candidate)) {
continue;
}
if ($waybill && preg_match('/订单|交易|退回|原单|换单/u', $header)) {
continue;
}
if (! $waybill && preg_match('/差|率|单价|首重|续重|附加|保价|面单/u', $header)) {
continue;
}
return (int) $index;
}
}
return null;
}
private static function isTotalRow(array $row): bool
{
foreach (array_slice($row, 0, 3) as $cell) {
$cell = preg_replace('/\s+/u', '', (string) $cell) ?? '';
if (in_array($cell, self::SKIP_WORDS, true)) {
return true;
}
}
return false;
}
public static function number(mixed $value): ?float
{
if ($value === null) {
return null;
}
$text = str_replace([',', ',', '¥', '¥', '元', ' '], '', trim((string) $value));
if ($text === '' || ! is_numeric($text)) {
return null;
}
return (float) $text;
}
}

View File

@ -0,0 +1,311 @@
<?php
namespace App\Support\CourierBills;
use Generator;
use PDO;
use PDOStatement;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
use XMLReader;
use ZipArchive;
/**
* 快递账单文件逐行读取:xlsx 流式解析(不整表进内存),csv 逐行读取(自动识别 GBK),
* 老 xls 用 PhpSpreadsheet 分块读取(单文件限 20MB)。
*
* 每行返回「列下标 => 文本」的完整数组,含表头和标题行,由调用方找表头。
*/
final class BillWorkbookReader
{
/** @return Generator<string, Generator<int, array<int,string>>> 工作表名 => 行(行号 => 列) */
public function sheets(string $path, string $extension, bool $preserveValues = false): Generator
{
$extension = strtolower($extension);
if ($extension === 'csv') {
yield 'csv' => $this->csvRows($path, $preserveValues);
return;
}
if ($extension === 'xls') {
yield from $this->xlsSheets($path, $preserveValues);
return;
}
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
throw new RuntimeException('文件不是有效的 xlsx。');
}
$stringsPath = tempnam(sys_get_temp_dir(), 'bill_strings_');
if ($stringsPath === false) {
$zip->close();
throw new RuntimeException('无法创建账单读取临时文件。');
}
try {
$shared = $this->sharedStrings($path, $zip, $stringsPath);
foreach ($this->worksheets($zip) as $name => $target) {
yield $name => $this->xlsxRows($path, $target, $shared, $preserveValues);
}
} finally {
$shared = null;
@unlink($stringsPath);
$zip->close();
}
}
/** @return array<string,string> 工作表名 => 包内路径(按工作簿顺序) */
private function worksheets(ZipArchive $zip): array
{
$workbook = (string) $zip->getFromName('xl/workbook.xml');
$relations = (string) $zip->getFromName('xl/_rels/workbook.xml.rels');
$targets = [];
if (preg_match_all('/<(?:\w+:)?Relationship\b([^>]*)\/?>/', $relations, $rels)) {
foreach ($rels[1] as $attributes) {
if (preg_match('/\bId="([^"]+)"/', $attributes, $id) && preg_match('/\bTarget="([^"]+)"/', $attributes, $target)) {
$path = ltrim(html_entity_decode($target[1], ENT_QUOTES | ENT_XML1, 'UTF-8'), '/');
$targets[$id[1]] = str_starts_with($path, 'xl/') ? $path : 'xl/' . $path;
}
}
}
$sheets = [];
if (preg_match_all('/<(?:\w+:)?sheet\b([^>]*)\/?>/', $workbook, $matches)) {
foreach ($matches[1] as $attributes) {
if (preg_match('/\bname="([^"]*)"/', $attributes, $name) && preg_match('/\br:id="([^"]+)"/', $attributes, $id)
&& isset($targets[$id[1]]) && ! preg_match('/\bstate="(hidden|veryHidden)"/', $attributes)) {
$sheets[html_entity_decode($name[1], ENT_QUOTES | ENT_XML1, 'UTF-8')] = $targets[$id[1]];
}
}
}
return $sheets;
}
/** 共享字符串逐条存临时 SQLite,避免大量不同单号把整张字符串表留在内存。 */
private function sharedStrings(string $path, ZipArchive $zip, string $stringsPath): ?PDOStatement
{
if ($zip->locateName('xl/sharedStrings.xml') === false) {
return null;
}
$reader = new XMLReader();
$reader->open('zip://' . $path . '#xl/sharedStrings.xml', 'UTF-8', LIBXML_NONET | LIBXML_COMPACT | LIBXML_PARSEHUGE);
$db = new PDO('sqlite:' . $stringsPath);
$db->exec('PRAGMA cache_size=-2048');
$db->exec('CREATE TABLE strings (id INTEGER PRIMARY KEY, value TEXT NOT NULL)');
$db->beginTransaction();
$insert = $db->prepare('INSERT INTO strings VALUES (?, ?)');
$index = 0;
$current = null;
$inPhonetic = false;
while ($reader->read()) {
if ($reader->nodeType === XMLReader::ELEMENT) {
if ($reader->localName === 'si') {
$current = '';
} elseif ($reader->localName === 'rPh') {
$inPhonetic = ! $reader->isEmptyElement;
}
} elseif ($reader->nodeType === XMLReader::END_ELEMENT) {
if ($reader->localName === 'si') {
$insert->execute([$index++, (string) $current]);
$current = null;
} elseif ($reader->localName === 'rPh') {
$inPhonetic = false;
}
} elseif (($reader->nodeType === XMLReader::TEXT || $reader->nodeType === XMLReader::SIGNIFICANT_WHITESPACE)
&& $current !== null && ! $inPhonetic) {
$current .= $reader->value;
}
}
$reader->close();
$db->commit();
return $db->prepare('SELECT value FROM strings WHERE id = ?');
}
private function xlsxRows(string $path, string $target, ?PDOStatement $shared, bool $preserveValues): Generator
{
$reader = new XMLReader();
if (! $reader->open('zip://' . $path . '#' . $target, 'UTF-8', LIBXML_NONET | LIBXML_COMPACT | LIBXML_PARSEHUGE)) {
throw new RuntimeException('无法读取工作表。');
}
try {
$row = null;
$rowNumber = 0;
$column = -1;
$type = null;
$value = '';
$inValue = false;
while ($reader->read()) {
if ($reader->nodeType === XMLReader::ELEMENT) {
switch ($reader->localName) {
case 'row':
$rowNumber = (int) ($reader->getAttribute('r') ?: $rowNumber + 1);
$row = [];
$column = -1;
if ($reader->isEmptyElement) {
yield $rowNumber => [];
$row = null;
}
break;
case 'c':
$column = self::columnIndex($reader->getAttribute('r'), $column + 1);
$type = $reader->getAttribute('t');
$value = '';
if ($reader->isEmptyElement && $row !== null) {
$row[$column] = '';
}
break;
case 'v':
case 't':
$inValue = ! $reader->isEmptyElement;
break;
case 'rPh':
if (! $reader->isEmptyElement) {
$reader->next();
}
break;
}
} elseif ($reader->nodeType === XMLReader::END_ELEMENT) {
switch ($reader->localName) {
case 'v':
case 't':
$inValue = false;
break;
case 'c':
if ($row !== null) {
if ($type === 's') {
$shared?->execute([(int) $value]);
$cell = $shared?->fetchColumn();
$cell = $cell === false || $cell === null ? '' : (string) $cell;
} else {
$cell = $preserveValues ? $value : trim($value);
if ($preserveValues && ($type === null || $type === 'n') && is_numeric($cell)) {
$cell = (float) $cell;
}
}
$row[$column] = $cell;
}
break;
case 'row':
if ($row !== null) {
yield $rowNumber => self::dense($row);
}
$row = null;
break;
}
} elseif ($inValue && ($reader->nodeType === XMLReader::TEXT || $reader->nodeType === XMLReader::SIGNIFICANT_WHITESPACE
|| $reader->nodeType === XMLReader::CDATA)) {
$value .= $reader->value;
}
}
} finally {
$reader->close();
}
}
private function csvRows(string $path, bool $preserveValues): Generator
{
$handle = fopen($path, 'rb');
if ($handle === false) {
throw new RuntimeException('无法读取 CSV 文件。');
}
try {
$head = (string) fread($handle, 65536);
rewind($handle);
// 只用前 64KB 中的完整行判断编码,避免从汉字中间截断。
$lineEnd = strlen($head) === 65536 ? strrpos($head, "\n") : false;
$sample = $lineEnd === false ? $head : substr($head, 0, $lineEnd + 1);
$gbk = $sample !== '' && ! mb_check_encoding($sample, 'UTF-8');
$line = 0;
while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) {
$line++;
if ($row === [null]) {
yield $line => [];
continue;
}
yield $line => array_map(static function ($cell) use ($gbk, $line, $preserveValues): string {
$cell = (string) $cell;
if ($gbk) {
$cell = (string) mb_convert_encoding($cell, 'UTF-8', 'GB18030');
}
if ($line === 1) {
$cell = preg_replace('/^\xEF\xBB\xBF/', '', $cell) ?? $cell;
}
return $preserveValues ? $cell : trim($cell);
}, $row);
}
} finally {
fclose($handle);
}
}
private function xlsSheets(string $path, bool $preserveValues): Generator
{
if (filesize($path) > 20 * 1024 * 1024) {
throw new RuntimeException('xls 文件超过 20MB,请另存为 xlsx 后上传。');
}
$reader = IOFactory::createReader('Xls');
$reader->setReadDataOnly(true);
foreach ($reader->listWorksheetInfo($path) as $info) {
yield $info['worksheetName'] => $this->xlsRows($path, $info, $preserveValues);
}
}
private function xlsRows(string $path, array $info, bool $preserveValues): Generator
{
$reader = IOFactory::createReader('Xls');
$reader->setReadDataOnly(true);
$reader->setLoadSheetsOnly([$info['worksheetName']]);
for ($start = 1; $start <= $info['totalRows']; $start += 500) {
$end = min($start + 499, $info['totalRows']);
$reader->setReadFilter(new class($start, $end) implements IReadFilter {
public function __construct(private int $start, private int $end) {}
public function readCell($columnAddress, $row, $worksheetName = ''): bool
{
return $row >= $this->start && $row <= $this->end;
}
});
$book = $reader->load($path);
try {
$sheet = $book->getSheet(0);
for ($number = $start; $number <= $end; $number++) {
$cells = [];
for ($column = 1; $column <= $info['totalColumns']; $column++) {
$cell = $sheet->getCell([$column, $number]);
$value = $cell->isFormula() ? $cell->getOldCalculatedValue() : $cell->getValue();
$cells[] = $preserveValues ? $value : trim((string) $value);
}
yield $number => $cells;
}
} finally {
$book->disconnectWorksheets();
}
}
}
/** @param array<int,string> $row */
private static function dense(array $row): array
{
if ($row === []) {
return [];
}
$out = array_fill(0, max(array_keys($row)) + 1, '');
return array_replace($out, $row);
}
private static function columnIndex(?string $reference, int $fallback): int
{
if ($reference === null || ! preg_match('/^([A-Z]+)/i', $reference, $m)) {
return $fallback;
}
$index = 0;
foreach (str_split(strtoupper($m[1])) as $letter) {
$index = $index * 26 + ord($letter) - 64;
}
return $index - 1;
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Support\CourierBills;
/** 账单行的对账分类。判断顺序见 CourierBillMatcher::categorize()。 */
final class Category
{
public const MATCH = 'match';
public const DIFF = 'diff';
public const UNCALCULATED = 'uncalculated';
public const PRIOR = 'prior';
public const LATER = 'later';
public const DUPLICATE = 'duplicate';
public const UNSHIPPED = 'unshipped';
public const UNMATCHED = 'unmatched';
public const MISMATCH = 'mismatch';
/** 不是账单行:发货数据有、账单里没有。 */
public const UNPROVIDED = 'unprovided';
public const LABELS = [
self::MATCH => '一致',
self::DIFF => '一致但运费有差',
self::UNCALCULATED => '一致(系统未核算)',
self::PRIOR => '前月补提供',
self::LATER => '跨月订单',
self::DUPLICATE => '重复',
self::UNSHIPPED => '未发出',
self::UNMATCHED => '匹配不到',
self::MISMATCH => '快递不符',
self::UNPROVIDED => '快递未提供',
];
/** 进「对账」子表、按核算运费结算的分类。 */
public const PAYABLE = [self::MATCH, self::DIFF, self::UNCALCULATED];
/** 处理结果。 */
public const RESOLUTIONS = ['agree' => '同意付款', 'exclude' => '已与快递确认剔除', 'defer' => '转下月'];
public static function label(string $category, ?string $month = null): string
{
$label = self::LABELS[$category] ?? $category;
if ($month !== null && in_array($category, [self::PRIOR, self::LATER], true)) {
return $label . '-' . (int) substr($month, 5, 2) . '月';
}
return $label;
}
}

View File

@ -0,0 +1,354 @@
<?php
namespace App\Support\CourierBills;
use App\Support\UnshippedWaybills;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
use RuntimeException;
/**
* 对账单自动分类:逐行判断分类、算自算金额,重算「快递未提供」和自动小汇总行。
*/
final class CourierBillMatcher
{
private ?AccessoryDeductions $deductions = null;
public function __construct(
private readonly ShippingLookup $shipping,
private readonly UnshippedWaybills $unshipped,
) {}
public static function db(): ConnectionInterface
{
return DB::connection('business_mirror');
}
public function match(int $statementId): void
{
$db = self::db();
$statement = $db->table('courier_bill_statements')->find($statementId);
if ($statement === null) {
throw new RuntimeException('对账单不存在。');
}
if ($statement->status === 'confirmed') {
throw new RuntimeException('对账单已确认结算,先撤销确认再重新匹配。');
}
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$names = array_values(array_filter(array_map('trim', (array) json_decode((string) $group->express_names, true))));
$month = (string) $statement->bill_month;
$lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->orderBy('id')
->get(['id', 'waybill_no', 'bill_amount', 'resolution'])->all();
$waybills = array_values(array_unique(array_map(static fn ($l): string => strtoupper($l->waybill_no), $lines)));
$settled = [];
foreach (array_chunk($waybills, 500) as $chunk) {
foreach ($db->table('courier_bill_ledger')->where('group_id', $statement->group_id)->whereIn('waybill_no', $chunk)
->where('settle_month', '<>', $month)->get(['waybill_no', 'settle_month']) as $row) {
$settled[strtoupper($row->waybill_no)] = $row->settle_month;
}
}
$unshipped = $this->unshipped->unshippedSources($waybills);
$unshipped = array_change_key_case($unshipped, CASE_UPPER);
$shipping = $this->shipping->summaries($waybills);
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
$unshipped[$old] = ['换单:已换成 ' . $new . ($express !== null ? '(' . $express . ')' : '')];
}
$nameSet = array_flip($names);
$seen = [];
$updates = [];
foreach ($lines as $line) {
$key = strtoupper($line->waybill_no);
$ship = $shipping[$key] ?? null;
[$category, $categoryMonth] = self::categorize(
isset($seen[$key]), $settled[$key] ?? null, isset($unshipped[$key]), $ship, $nameSet, $month,
$line->bill_amount === null ? null : (float) $line->bill_amount,
);
$seen[$key] = true;
$updates[$line->id] = [
'category' => $category,
'category_month' => $categoryMonth,
'ship_time' => $ship['ship_time'] ?? null,
'express_name' => $ship['express_name'] ?? null,
'calc_freight' => $ship['calc_freight'] ?? null,
'charge_weight' => $ship['charge_weight'] ?? null,
'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null,
'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution),
];
}
$billed = array_flip($waybills);
$unprovided = [];
foreach ($this->shipping->monthWaybills($names, $month) as $row) {
if (! isset($billed[$row['waybill']]) && ! isset($unprovided[$row['waybill']])) {
$unprovided[$row['waybill']] = $row;
}
}
$unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided));
$db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void {
foreach ($updates as $id => $values) {
$db->table('courier_bill_lines')->where('id', $id)->update($values);
}
$db->table('courier_bill_unprovided')->where('statement_id', $statementId)->delete();
foreach (array_chunk(array_values($unprovided), 500) as $chunk) {
$db->table('courier_bill_unprovided')->insert(array_map(static fn (array $row): array => [
'statement_id' => $statementId, 'waybill_no' => $row['waybill'], 'ship_time' => $row['ship_time'],
'express_name' => $row['express_name'], 'calc_freight' => $unprovidedFreight[$row['waybill']]['calc_freight'] ?? null,
], $chunk));
}
$this->refreshSummary($statementId);
$db->table('courier_bill_statements')->where('id', $statementId)->update(['matched_at' => now(), 'updated_at' => now()]);
});
}
/**
* 分类判断,命中即停:
* 重复(本账单第二次及以后出现,或结算台账里别的月份已结算)→ 未发出 → 匹配不到 → 快递不符
* → 前月补提供 / 跨月订单(按发货月份)→ 一致 / 一致但运费有差 / 一致(系统未核算)。
*
* @param array{ship_time:?string,express_name:?string,calc_freight:?float}|null $ship
* @param array<string,int> $nameSet
* @return array{0:string,1:?string}
*/
public static function categorize(bool $seenInBill, ?string $settledMonth, bool $unshipped, ?array $ship,
array $nameSet, string $month, ?float $billAmount): array
{
if ($seenInBill || $settledMonth !== null) {
return [Category::DUPLICATE, $settledMonth];
}
if ($unshipped) {
return [Category::UNSHIPPED, null];
}
if ($ship === null) {
return [Category::UNMATCHED, null];
}
if (! isset($nameSet[(string) $ship['express_name']])) {
return [Category::MISMATCH, null];
}
$shipMonth = $ship['ship_time'] !== null ? substr((string) $ship['ship_time'], 0, 7) : $month;
if ($shipMonth < $month) {
return [Category::PRIOR, $shipMonth];
}
if ($shipMonth > $month) {
return [Category::LATER, $shipMonth];
}
if ($ship['calc_freight'] === null) {
return [Category::UNCALCULATED, null];
}
if ($billAmount !== null && abs($billAmount - (float) $ship['calc_freight']) <= 0.01) {
return [Category::MATCH, null];
}
return [Category::DIFF, null];
}
/** 自算金额:处理结果优先;否则一致类和前月补提供按核算运费,其余为 0。 */
public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float
{
return match ($resolution) {
'agree' => $billAmount === null ? null : (float) $billAmount,
'exclude', 'defer' => 0.0,
default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) ? $calcFreight : 0.0,
};
}
/** 按处理结果重算一批行的自算金额,再刷新小汇总。 */
public function resolve(int $statementId, array $lineIds, ?string $resolution, string $user): int
{
$db = self::db();
if ($db->table('courier_bill_statements')->where('id', $statementId)->value('status') === 'confirmed') {
throw new RuntimeException('对账单已确认结算,先撤销确认再修改。');
}
$count = 0;
$db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void {
foreach (array_chunk($lineIds, 500) as $chunk) {
$lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk)
->get(['id', 'category', 'calc_freight', 'bill_amount']);
foreach ($lines as $line) {
$db->table('courier_bill_lines')->where('id', $line->id)->update([
'resolution' => $resolution,
'resolved_by' => $resolution === null ? null : $user,
'resolved_at' => $resolution === null ? null : now(),
'self_amount' => self::selfAmount((string) $line->category,
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution),
]);
$count++;
}
}
$this->refreshSummary($statementId);
});
return $count;
}
/**
* 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列:
* 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。
*/
public function refreshSummary(int $statementId): void
{
$db = self::db();
$month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month');
$rows = $db->table('courier_bill_lines')->where('statement_id', $statementId)
->groupBy('category', 'category_month')
->selectRaw('category, category_month, SUM(bill_amount) as bill, SUM(self_amount) as self')
->get();
$items = [];
$label = static fn (string $category, ?string $m): string => match ($category) {
Category::MATCH => (int) substr($month, 5, 2) . '月运费',
Category::DIFF => (int) substr($month, 5, 2) . '月运费-价格差',
Category::UNCALCULATED => (int) substr($month, 5, 2) . '月运费-系统未核算',
Category::PRIOR => (int) substr((string) $m, 5, 2) . '月运费(前月补提供)',
Category::LATER => '跨月订单-' . (int) substr((string) $m, 5, 2) . '月,本月不结算',
Category::DUPLICATE => '重复',
Category::UNSHIPPED => '未发出',
Category::UNMATCHED => '匹配不到',
Category::MISMATCH => '快递不符(未匹配本快递发货数据)',
default => '待匹配',
};
$order = [Category::MATCH => 1, Category::DIFF => 1, Category::UNCALCULATED => 1, Category::PRIOR => 2, Category::LATER => 3,
Category::DUPLICATE => 4, Category::UNSHIPPED => 5, Category::UNMATCHED => 6, Category::MISMATCH => 7];
foreach ($rows as $row) {
$category = (string) ($row->category ?? '');
$name = $label($category, $row->category === Category::DUPLICATE ? null : $row->category_month);
$items[$name] ??= ['bill' => 0.0, 'self' => 0.0, 'sort' => ($order[$category] ?? 9) * 100 + (int) substr((string) $row->category_month, 5, 2)];
$items[$name]['bill'] += (float) $row->bill;
$items[$name]['self'] += (float) $row->self;
}
// 运费有差的再分原因:计费重量和账单重量不一样的算「重量差」,其余算「价格差」
$weight = $db->table('courier_bill_lines')->where('statement_id', $statementId)->where('category', Category::DIFF)
->whereNotNull('bill_weight')->whereNotNull('charge_weight')->whereRaw('ROUND(ABS(bill_weight - charge_weight), 4) > 0.005')
->selectRaw('COUNT(*) as n, COALESCE(SUM(bill_amount),0) as bill, COALESCE(SUM(self_amount),0) as self')->first();
$priceLabel = (int) substr($month, 5, 2) . '月运费-价格差';
if ((int) $weight->n > 0 && isset($items[$priceLabel])) {
$weightLabel = (int) substr($month, 5, 2) . '月运费-重量差';
$items[$weightLabel] = ['bill' => (float) $weight->bill, 'self' => (float) $weight->self, 'sort' => $items[$priceLabel]['sort']];
$items[$priceLabel]['bill'] -= (float) $weight->bill;
$items[$priceLabel]['self'] -= (float) $weight->self;
if ((int) $weight->n === (int) $db->table('courier_bill_lines')->where('statement_id', $statementId)->where('category', Category::DIFF)->count()) {
unset($items[$priceLabel]);
}
}
$m = (int) substr($month, 5, 2);
foreach (['运费' => 100, '运费-重量差' => 101, '运费-价格差' => 102, '运费-系统未核算' => 103] as $suffix => $sort) {
if (isset($items[$m . '月' . $suffix])) {
$items[$m . '月' . $suffix]['sort'] = $sort;
}
}
uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']);
$this->addAccessoryDeduction($statementId, $month, $items);
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
$fees = $this->surchargeItems($statementId);
$sort = 8000;
foreach ($fees as $item => $sum) {
if (! isset($manualLabels[$item]) && ! isset($items[$item])) {
$items[$item] = ['bill' => $sum, 'self' => $sum, 'sort' => $sort++];
}
}
$db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->delete();
$sort = 0;
foreach ($items as $name => $item) {
$db->table('courier_bill_summary_items')->insert([
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4),
'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
]);
}
$totals = $db->table('courier_bill_lines')->where('statement_id', $statementId)
->selectRaw('COUNT(*) as line_count, COALESCE(SUM(bill_amount),0) as bill')->first();
$db->table('courier_bill_statements')->where('id', $statementId)->update([
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
]);
}
/**
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
*
* @param array<string,array{bill:?float,self:float,sort:int}> $items
*/
private function addAccessoryDeduction(int $statementId, string $month, array &$items): void
{
$db = self::db();
$manual = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
->contains(static fn ($label): bool => SummaryMapper::classify((string) $label) === 'AL');
if ($manual) {
return;
}
$names = (array) json_decode((string) $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->where('s.id', $statementId)->value('g.express_names'), true);
$this->deductions ??= app(AccessoryDeductions::class);
$total = $this->deductions->total($month, array_values(array_filter(array_map('trim', $names))));
if ($total === null) {
$existing = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)
->where('manual', false)->where('label', '配件补发扣款')->value('self_amount');
$total = -(float) $existing;
}
if ($total > 0) {
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
}
}
/**
* 这张对账单分到的附加费,按费用项目合计(快递开的金额,自算先按同额,不逐单核对)。
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
*
* @return array<string,float>
*/
private function surchargeItems(int $statementId): array
{
$db = self::db();
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statementId)->distinct()->pluck('file_id')
->merge($db->table('courier_bill_files')->where('statement_id', $statementId)->pluck('id'))
->map(static fn ($id): int => (int) $id)->unique()->values()->all();
if ($fileIds === []) {
return [];
}
$result = [];
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
foreach ($primaryIds as $fileId => $primaryId) {
$primary = (int) $primaryId;
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
if (! (clone $rows)->exists()) {
continue;
}
$shared = $db->table('courier_bill_lines')->where('file_id', $fileId)->distinct()->pluck('statement_id')
->map(static fn ($id): int => (int) $id)->push($primary)->filter()->unique()->values()->all();
$names = [];
if (count($shared) > 1) {
foreach ($db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->whereIn('s.id', $shared)->orderBy('s.id')->get(['s.id', 'g.express_names']) as $statement) {
foreach ((array) json_decode((string) $statement->express_names, true) as $name) {
$names[trim((string) $name)] ??= (int) $statement->id;
}
}
}
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, &$result): void {
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
foreach ($chunk as $row) {
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
if (($names[$express] ?? $primary) !== $statementId) {
continue;
}
$item = preg_replace('/\s+/u', '', (string) $row->item) ?? '';
$result[$item] = ($result[$item] ?? 0) + (float) $row->amount;
}
});
}
return array_map(static fn (float $v): float => round($v, 4), $result);
}
/** 运费差异原因(导出「对账」用):重量差 / 价格差 / 系统未核算;一致的为 null。 */
public static function diffReason(string $category, mixed $billWeight, mixed $chargeWeight): ?string
{
return match ($category) {
Category::UNCALCULATED => '系统未核算',
Category::DIFF => $billWeight !== null && $chargeWeight !== null && round(abs((float) $billWeight - (float) $chargeWeight), 4) > 0.005 ? '重量差' : '价格差',
default => null,
};
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,344 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Database\ConnectionInterface;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use RuntimeException;
use Throwable;
/**
* 快递应付汇总:格式同财务手工「快递汇总表」(汇总 sheet,A–AW 列)。
*
* 每月一套承运商行,所有承运商常驻(停运、旧账也一直挂着)。存的是手工/导入的单元格;
* 有对账单的承运商,金额列在读取时由小汇总归集(SummaryMapper)覆盖,不落库,
* 所以对账单改了、确认了,汇总随时是最新的。
*/
final class PayableSummary
{
/** 列字母 => 表头(与手工表第 2、3 行一致)。 */
public const COLUMNS = [
'A' => '合同开始时间', 'B' => '合同截止时间', 'C' => '签订公司', 'D' => '负责人', 'E' => '承运状态', 'F' => '序号',
'G' => '快递公司主体名称', 'H' => '承运商', 'I' => '月初结余', 'J' => '补给快递', 'K' => '快递提供金额',
'L' => '对账差异金额', 'M' => '核对确定金额', 'N' => '面单', 'O' => '借支', 'P' => '赔付金额', 'Q' => '其他补款',
'R' => '本月应付金额', 'S' => '本次实付金额', 'T' => '对公打款金额', 'U' => '对私打款金额', 'V' => '快递负责人',
'W' => '备注', 'X' => '备注1', 'Y' => '是否确认', 'Z' => 'e签宝签字单/纸质签字单', 'AA' => '电子签章经办人',
'AB' => '签字单到达日期', 'AC' => '收据', 'AD' => '是否打款', 'AE' => '合同',
...SummaryMapper::DIFF_COLUMNS,
'AS' => '记账补款金额', 'AT' => '补充说明', 'AU' => '仓库', 'AV' => '更改原因', 'AW' => '备注',
];
/** 金额列。 */
public const MONEY = ['I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS'];
/** 页面上可直接改的列(其余来自导入、快递资料或对账单)。 */
public const EDITABLE = ['D' => '负责人', 'E' => '承运状态', 'I' => '月初结余', 'Q' => '其他补款', 'S' => '本次实付金额', 'W' => '备注', 'AU' => '仓库'];
/** 有对账单时由小汇总覆盖的列。 */
private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT'];
public function __construct(private readonly CourierInformationMirrorRepository $couriers) {}
public function db(): ConnectionInterface
{
return CourierBillMatcher::db();
}
/** @return list<string> 已有汇总的月份(新到旧) */
public function months(): array
{
return $this->db()->table('courier_payable_summary_rows')->distinct()->orderByDesc('month')->pluck('month')->all();
}
/**
* 当月汇总行(已叠加快递资料和对账单)。
*
* @return list<array{id:int,cells:array<string,mixed>,status:string,statements:list<array{id:int,group:string,status:string}>,check:?array{K:float,M:float,diff:float},expired:bool}>
*/
public function rows(string $month): array
{
$stored = $this->db()->table('courier_payable_summary_rows')->where('month', $month)->orderBy('sort')->get();
$statements = $this->statementsByCarrier($month);
try {
$contracts = $this->couriers->contractsByName($stored->pluck('carrier')->all());
} catch (Throwable $error) {
report($error);
$contracts = [];
}
$today = now()->toDateString();
$rows = [];
foreach ($stored as $row) {
$cells = (array) json_decode((string) $row->cells, true);
$contract = $contracts[$row->carrier] ?? null;
if ($contract !== null) {
$cells['A'] = $contract['contract_start'] ?? ($cells['A'] ?? null);
$cells['B'] = $contract['contract_end'] ?? ($cells['B'] ?? null);
$cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null);
$cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null);
}
$mine = $statements[$row->carrier] ?? [];
// 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对;
// 新建的月份金额是空的,才用对账单的小汇总填。
$imported = collect(self::FROM_STATEMENTS)->contains(static fn (string $key): bool => abs((float) ($cells[$key] ?? 0)) > 0.004);
$check = null;
if ($mine !== []) {
$mapped = SummaryMapper::map($this->summaryItems(array_column($mine, 'id')));
if ($imported) {
$check = ['K' => round((float) $mapped['K'], 2), 'M' => round((float) $mapped['K'] - (float) $mapped['L'], 2),
'diff' => round((float) ($cells['K'] ?? 0) - (float) ($cells['L'] ?? 0) - (float) $mapped['K'] + (float) $mapped['L'], 2)];
} else {
foreach (self::FROM_STATEMENTS as $key) {
$cells[$key] = $mapped[$key];
}
}
}
foreach (self::MONEY as $key) {
if (isset($cells[$key]) && is_numeric($cells[$key])) {
$cells[$key] = (float) $cells[$key];
}
}
$cells = SummaryMapper::totals($cells);
$hasBill = abs((float) ($cells['K'] ?? 0)) > 0.004;
$status = match (true) {
$mine !== [] && ! $imported => collect($mine)->every(static fn (array $s): bool => $s['status'] === 'confirmed') ? '已确认' : '待处理',
$hasBill => (string) ($cells['Y'] ?? '') === '已确认' ? '已确认' : '待处理',
abs((float) ($cells['I'] ?? 0)) > 0.004 => '旧账挂账',
default => '本月无账单',
};
$end = self::date($cells['B'] ?? null);
$rows[] = [
'id' => (int) $row->id, 'cells' => $cells, 'status' => $status, 'statements' => $mine, 'check' => $check,
'expired' => $end !== null && $end < $today,
];
}
return $rows;
}
/** @return array<string,list<array{id:int,group:string,status:string}>> 承运商 => 对账单 */
private function statementsByCarrier(string $month): array
{
$result = [];
$rows = $this->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->where('s.bill_month', $month)->where('s.line_count', '>', 0)
->get(['s.id', 's.status', 'g.name', 'g.summary_carrier']);
foreach ($rows as $row) {
$carrier = trim((string) ($row->summary_carrier ?: $row->name));
$result[$carrier][] = ['id' => (int) $row->id, 'group' => (string) $row->name, 'status' => (string) $row->status];
}
return $result;
}
/** @return list<array{label:string,bill:?float,self:?float}> */
public function summaryItems(array $statementIds): array
{
return $this->db()->table('courier_bill_summary_items')->whereIn('statement_id', $statementIds)
->orderBy('statement_id')->orderBy('sort')->get()
->map(static fn ($item): array => ['label' => (string) $item->label,
'bill' => $item->bill_amount === null ? null : (float) $item->bill_amount,
'self' => $item->self_amount === null ? null : (float) $item->self_amount])
->all();
}
/**
* 生成新月份:从最近一个月复制全部承运商,月初结余 = 上月本月应付 − 上月本次实付(未付按 0 算),
* 其余金额和本月签字/打款信息清空。
*/
public function createMonth(string $month): int
{
if ($this->db()->table('courier_payable_summary_rows')->where('month', $month)->exists()) {
throw new RuntimeException($month . ' 已经有汇总。');
}
$previous = $this->db()->table('courier_payable_summary_rows')->where('month', '<', $month)->max('month');
if ($previous === null) {
throw new RuntimeException('还没有任何月份的汇总,请先导入一个月的手工快递汇总表。');
}
$keep = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'V', 'AA', 'AE', 'AU'];
$count = 0;
$this->db()->transaction(function () use ($previous, $month, $keep, &$count): void {
foreach ($this->rows($previous) as $index => $row) {
$cells = array_intersect_key($row['cells'], array_flip($keep));
$cells['I'] = round((float) ($row['cells']['R'] ?? 0) - (float) ($row['cells']['S'] ?? 0), 2);
$this->db()->table('courier_payable_summary_rows')->insert([
'month' => $month, 'sort' => $index + 1, 'carrier' => (string) ($row['cells']['H'] ?? ''),
'cells' => json_encode($cells, JSON_UNESCAPED_UNICODE), 'created_at' => now(), 'updated_at' => now(),
]);
$count++;
}
});
return $count;
}
/** 手工改一个单元格(只允许 EDITABLE 列)。 */
public function updateCell(int $rowId, string $column, ?string $value): void
{
if (! isset(self::EDITABLE[$column])) {
throw new RuntimeException('这一列不能手工修改。');
}
$row = $this->db()->table('courier_payable_summary_rows')->find($rowId);
if ($row === null) {
throw new RuntimeException('汇总行不存在。');
}
$cells = (array) json_decode((string) $row->cells, true);
if (in_array($column, self::MONEY, true)) {
$number = BillParser::number($value);
if ($value !== null && trim($value) !== '' && $number === null) {
throw new RuntimeException(self::COLUMNS[$column] . '须为数字。');
}
$cells[$column] = $number;
} else {
$cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500);
}
$this->db()->table('courier_payable_summary_rows')->where('id', $rowId)->update([
'cells' => json_encode($cells, JSON_UNESCAPED_UNICODE), 'updated_at' => now(),
]);
}
/** 新增一个承运商(排在最后)。 */
public function addCarrier(string $month, string $carrier): void
{
$carrier = trim($carrier);
if ($carrier === '' || $this->db()->table('courier_payable_summary_rows')->where('month', $month)->where('carrier', $carrier)->exists()) {
throw new RuntimeException('承运商为空或已存在。');
}
$sort = (int) $this->db()->table('courier_payable_summary_rows')->where('month', $month)->max('sort') + 1;
$this->db()->table('courier_payable_summary_rows')->insert([
'month' => $month, 'sort' => $sort, 'carrier' => $carrier,
'cells' => json_encode(['F' => $sort, 'H' => $carrier, 'E' => '承运'], JSON_UNESCAPED_UNICODE),
'created_at' => now(), 'updated_at' => now(),
]);
}
/**
* 导入手工快递汇总表的「汇总」工作表,整月替换。表头在第 2、3 行,承运商在 H 列。
*
* @return array{rows:int,title:?string}
*/
public function import(string $path, string $month): array
{
$reader = new BillWorkbookReader();
$target = null;
foreach ($reader->sheets($path, 'xlsx') as $name => $rows) {
if ($name === '汇总') {
$target = $rows;
break;
}
}
if ($target === null) {
throw new RuntimeException('文件里没有名为「汇总」的工作表。');
}
$letters = array_keys(self::COLUMNS);
$records = [];
$title = null;
$headerSeen = false;
foreach ($target as $number => $row) {
if (! $headerSeen) {
if ($title === null && trim((string) ($row[2] ?? '')) !== '') {
$title = trim((string) $row[2]);
}
if (trim((string) ($row[7] ?? '')) === '承运商') {
$headerSeen = true;
}
continue;
}
$carrier = trim((string) ($row[7] ?? ''));
if ($carrier === '' || $carrier === '承运商' || str_contains($carrier, '合计')) {
continue;
}
$cells = [];
foreach ($letters as $index => $letter) {
$value = trim((string) ($row[$index] ?? ''));
if (in_array($letter, self::MONEY, true)) {
$cells[$letter] = BillParser::number($value);
} elseif (in_array($letter, ['A', 'B', 'AB'], true)) {
$cells[$letter] = self::date($value);
} else {
$cells[$letter] = $value === '' || $value === '0' ? null : $value;
}
}
$records[$carrier] = $cells;
}
if ($records === []) {
throw new RuntimeException('没有读到承运商行(H 列「承运商」表头下面)。');
}
$this->db()->transaction(function () use ($records, $month): void {
$this->db()->table('courier_payable_summary_rows')->where('month', $month)->delete();
$sort = 0;
foreach ($records as $carrier => $cells) {
$this->db()->table('courier_payable_summary_rows')->insert([
'month' => $month, 'sort' => ++$sort, 'carrier' => (string) $carrier,
'cells' => json_encode($cells, JSON_UNESCAPED_UNICODE), 'created_at' => now(), 'updated_at' => now(),
]);
}
});
return ['rows' => count($records), 'title' => $title];
}
/** 导出:格式同手工快递汇总表(标题行 + 两行表头 + 数据 + 合计)。 */
public function export(string $month, $output): void
{
$rows = $this->rows($month);
$book = new StreamingWorkbook();
$companies = array_count_values(array_filter(array_map(static fn (array $r): string => (string) ($r['cells']['C'] ?? ''), $rows)));
arsort($companies);
$company = (string) (array_key_first($companies) ?? '');
[$year, $m] = explode('-', $month);
$title = array_fill(0, count(self::COLUMNS), null);
$title[2] = $company . $year . '年应付' . (int) $m . '月份快递、物流运费清单';
$book->row('汇总', $title, true);
$letters = array_keys(self::COLUMNS);
$groupHeader = array_fill(0, count($letters), null);
$header = [];
foreach ($letters as $index => $letter) {
$header[] = self::COLUMNS[$letter];
}
$groupHeader[array_search('AF', $letters, true)] = '差异明细';
$book->row('汇总', $groupHeader, true);
$book->row('汇总', $header, true);
$totals = array_fill_keys(self::MONEY, 0.0);
foreach ($rows as $index => $row) {
$cells = $row['cells'];
$cells['F'] = $index + 1;
$line = [];
foreach ($letters as $letter) {
$value = $cells[$letter] ?? null;
if (in_array($letter, self::MONEY, true)) {
$value = $value === null || $value === '' ? 0.0 : round((float) $value, 2);
$totals[$letter] += $value;
} elseif ($letter === 'F') {
$value = (int) $value;
} else {
$value = $value === null ? null : (string) $value;
}
$line[] = $value;
}
$book->row('汇总', $line);
}
$sum = [];
foreach ($letters as $letter) {
$sum[] = $letter === 'H' ? '合计' : (in_array($letter, self::MONEY, true) ? round($totals[$letter], 2) : null);
}
$book->row('汇总', $sum, true);
$book->writeTo($output);
}
public static function date(mixed $value): ?string
{
$value = trim((string) $value);
if ($value === '' || $value === '0') {
return null;
}
if (preg_match('/^\d{5}(\.\d+)?$/', $value)) {
return gmdate('Y-m-d', (int) round(((float) $value - 25569) * 86400));
}
if (preg_match('/^(\d{4})[\/\-.](\d{1,2})[\/\-.](\d{1,2})/', $value, $m)) {
return sprintf('%04d-%02d-%02d', $m[1], $m[2], $m[3]);
}
return $value;
}
}

View File

@ -0,0 +1,296 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
/**
* 按快递单号读发货数据(jst_oms_shipping)和报价核算结果(jst_oms_shipping_freight)。
*
* 发货数据一行一个商品;对账按单号聚合,口径同发货数据页「合并」:
* 数量/重量/体积/金额/运费求和,商品ID、条形码拼接,长宽高取最大,其余取第一个非空值。
* 一个单号对应多个包裹(source_id)时,核算运费按包裹相加;任一包裹没核算成功就算「未核算」。
*/
final class ShippingLookup
{
private const CHUNK = 500;
public const COLUMNS = [
'express_no' => '快递单号', 'trade_no' => '交易单号', 'item_id' => '商品ID', 'barcode' => '条形码',
'product_name' => '商品名称', 'qty' => '数量', 'pkg_count' => '件数', 'receiver_state' => '省',
'buyer_nick' => '买家昵称', 'receiver_name' => '收货姓名', 'shop_name' => '店铺名称', 'express_name1' => '快递名称1',
'warehouse_name' => '仓库', 'ship_time' => '发货时间', 'freight' => '运费', 'online_weight' => '线上重量',
'actual_weight' => '实称重量', 'length_cm' => '长(cm)', 'width_cm' => '宽(cm)', 'height_cm' => '高(cm)',
'volume_cm3' => '体积(cm³)', 'receiver_city' => '市', 'receiver_district' => '区', 'supplier_name' => '供应商',
'receiver_address' => '收货详细地址', 'receiver_mobile' => '手机号码', 'receiver_phone' => '座机号码',
'express_name2' => '快递名称2', 'platform' => '平台', 'buyer_memo' => '买家留言', 'seller_memo' => '卖家备注',
'package_no' => '配货单号', 'amount' => '金额', 'product_code' => '货号', 'download_time' => '下载时间',
'pay_time' => '付款时间', 'freight_rate' => '费率', 'freight_formula' => '公式', 'weight_kg' => '重量(kg)',
'settle_weight_kg' => '结算重量(kg)', 'settle_volume_cm3' => '结算体积(cm³)', 'recon_weight_kg' => '对账重量(kg)',
'recon_volume_cm3' => '对账体积(cm³)', 'finished_barcode' => '成品条码', 'finished_name' => '成品名称',
'finished_supplier' => '成品供应商', 'settle_freight' => '结算运费', 'front_no' => '换单前单号',
'qc_freight' => '核算运费', 'qc_diff' => '核算-聚水潭运费', 'qc_quote_version' => '报价版本',
'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)',
'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
];
/** 文本列:导出时保持文本,长数字不变科学计数法。 */
public const TEXT_COLUMNS = ['express_no', 'trade_no', 'item_id', 'barcode', 'receiver_mobile', 'receiver_phone',
'package_no', 'product_code', 'finished_barcode', 'front_no', 'qc_quote_version'];
private const SUM = ['qty', 'freight', 'online_weight', 'actual_weight', 'volume_cm3', 'weight_kg', 'settle_weight_kg',
'settle_volume_cm3', 'recon_weight_kg', 'recon_volume_cm3', 'amount', 'settle_freight'];
private const CONCAT = ['item_id', 'barcode', 'product_name', 'supplier_name', 'finished_barcode', 'finished_name', 'finished_supplier'];
private const MAX = ['length_cm', 'width_cm', 'height_cm'];
public function connection(): ConnectionInterface
{
return DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
}
/**
* 对账用的单号摘要。
*
* @param list<string> $waybills
* @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号
*/
public function summaries(array $waybills): array
{
$result = [];
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
$rows = $this->connection()->table('jst_oms_shipping')->whereIn('express_no', $chunk)
->orderBy('id')->get(['express_no', 'express_name1', 'ship_time', 'source_id']);
$packages = [];
foreach ($rows as $row) {
$key = strtoupper(trim((string) $row->express_no));
$item = $result[$key] ?? ['ship_time' => null, 'express_name' => null, 'calc_freight' => null, 'charge_weight' => null, '_sources' => []];
if ($row->ship_time !== null && ($item['ship_time'] === null || (string) $row->ship_time < $item['ship_time'])) {
$item['ship_time'] = (string) $row->ship_time;
}
$item['express_name'] ??= self::blank($row->express_name1);
if ($row->source_id !== null) {
$item['_sources'][(int) $row->source_id] = true;
$packages[(int) $row->source_id] = true;
}
$result[$key] = $item;
}
$freights = $this->freights(array_keys($packages));
foreach ($result as $key => $item) {
if (! isset($item['_sources'])) {
continue;
}
$total = 0.0;
$weight = 0.0;
$ok = $item['_sources'] !== [];
foreach (array_keys($item['_sources']) as $source) {
$freight = $freights[$source] ?? null;
if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) {
$ok = false;
break;
}
$total += (float) $freight->freight;
$weight += (float) $freight->charge_weight;
}
unset($item['_sources']);
$item['calc_freight'] = $ok ? round($total, 2) : null;
$item['charge_weight'] = $ok ? round($weight, 4) : null;
$result[$key] = $item;
}
}
return $result;
}
/**
* 导出用的整行发货数据(含核算列),按单号合并。
*
* @param list<string> $waybills
* @return array<string,array<string,mixed>> 键为大写单号
*/
public function details(array $waybills): array
{
$result = [];
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
$rows = $this->connection()->table('jst_oms_shipping')->whereIn('express_no', $chunk)->orderBy('id')->get();
$sources = [];
foreach ($rows as $row) {
$row = (array) $row;
// 组合件拆件后明细存部件值,合并取整行值(m_*),口径同发货数据页。
foreach (['product_name' => 'm_name', 'volume_cm3' => 'm_volume_cm3', 'length_cm' => 'm_length_cm',
'width_cm' => 'm_width_cm', 'height_cm' => 'm_height_cm'] as $column => $merged) {
if (($row[$merged] ?? null) !== null && $row[$merged] !== '') {
$row[$column] = $row[$merged];
}
}
$key = strtoupper(trim((string) $row['express_no']));
$sources[$key][(int) ($row['source_id'] ?? 0)] = true;
if (! isset($result[$key])) {
$result[$key] = array_intersect_key($row, self::COLUMNS);
foreach (self::CONCAT as $column) {
$result[$key][$column] = self::blank($row[$column] ?? null);
}
continue;
}
$merged = &$result[$key];
foreach (self::SUM as $column) {
if (($row[$column] ?? null) !== null) {
$merged[$column] = round((float) ($merged[$column] ?? 0) + (float) $row[$column], 4);
}
}
foreach (self::CONCAT as $column) {
$value = self::blank($row[$column] ?? null);
if ($value !== null && ! in_array($value, explode(',', (string) $merged[$column]), true)) {
$merged[$column] = $merged[$column] === null ? $value : $merged[$column] . ',' . $value;
}
}
foreach (self::MAX as $column) {
if (($row[$column] ?? null) !== null) {
$merged[$column] = max((float) ($merged[$column] ?? 0), (float) $row[$column]);
}
}
foreach (self::COLUMNS as $column => $_) {
if (array_key_exists($column, $row) && ($merged[$column] ?? null) === null) {
$merged[$column] = $row[$column];
}
}
unset($merged);
}
$ids = [];
foreach ($sources as $set) {
$ids += $set;
}
$freights = $this->freights(array_keys($ids));
foreach ($sources as $key => $set) {
$parts = array_values(array_filter(array_map(static fn (int $id) => $freights[$id] ?? null, array_keys($set))));
if ($parts === []) {
continue;
}
$first = $parts[0];
$sum = static fn (string $field): ?float => array_reduce($parts,
static fn (?float $carry, object $p): ?float => $p->{$field} === null ? $carry : (float) $carry + (float) $p->{$field}, null);
$freight = $sum('freight');
$jst = $sum('jst_freight');
$result[$key] += [
'qc_freight' => $freight, 'qc_diff' => $freight !== null && $jst !== null ? round($freight - $jst, 2) : null,
'qc_quote_version' => $first->quote_version, 'qc_settle_weight' => $sum('settle_weight'),
'qc_charge_weight' => $sum('charge_weight'), 'qc_first_price' => $first->first_price, 'qc_rate' => $first->rate,
'qc_miandan' => $sum('miandan'), 'qc_flat_price' => $first->flat_price, 'qc_extra_fee' => $sum('extra_fee'),
'qc_formula' => $first->formula,
'qc_status' => implode(';', array_unique(array_map(static fn (object $p): string => (string) $p->status, $parts))),
];
if (count($set) > 1) {
$result[$key]['pkg_count'] = count($set) . '个包裹';
}
}
}
return $result;
}
/**
* 当月发货、快递名称属于本分组的单号(用于找「快递未提供」)。
*
* @param list<string> $expressNames
* @return \Generator<int,array{waybill:string,ship_time:?string,express_name:?string}>
*/
public function monthWaybills(array $expressNames, string $month): \Generator
{
if ($expressNames === []) {
return;
}
// 按天走 ship_time 索引,单次只扫一天的发货行。
$day = strtotime($month . '-01');
$end = strtotime($month . '-01 +1 month');
for (; $day < $end; $day = strtotime('+1 day', $day)) {
$rows = $this->connection()->table('jst_oms_shipping')
->where('ship_time', '>=', date('Y-m-d 00:00:00', $day))
->where('ship_time', '<', date('Y-m-d 00:00:00', strtotime('+1 day', $day)))
->whereIn('express_name1', $expressNames)
->whereNotNull('express_no')->where('express_no', '<>', '')
->get(['express_no', 'ship_time', 'express_name1']);
foreach ($rows as $row) {
yield ['waybill' => strtoupper(trim((string) $row->express_no)), 'ship_time' => (string) $row->ship_time,
'express_name' => self::blank($row->express_name1)];
}
}
}
/**
* 某月发货数据里各快递名称1 的发货行数(按天走 ship_time 索引)。
*
* @return array<string,int>
*/
public function monthExpressNames(string $month): array
{
$counts = [];
$day = strtotime($month . '-01');
$end = strtotime($month . '-01 +1 month');
for (; $day < $end; $day = strtotime('+1 day', $day)) {
$rows = $this->connection()->table('jst_oms_shipping')
->where('ship_time', '>=', date('Y-m-d 00:00:00', $day))
->where('ship_time', '<', date('Y-m-d 00:00:00', strtotime('+1 day', $day)))
->whereNotNull('express_name1')->where('express_name1', '<>', '')
->groupBy('express_name1')->selectRaw('express_name1, COUNT(*) as n')->get();
foreach ($rows as $row) {
$name = trim((string) $row->express_name1);
$counts[$name] = ($counts[$name] ?? 0) + (int) $row->n;
}
}
return $counts;
}
/**
* 换单:发货数据里「换单前单号」是这些单号的包裹(快递常按换单前的旧单号开账单)。
*
* @param list<string> $waybills
* @return array<string,array{0:string,1:?string}> 旧单号(大写)=> [新快递单号, 新单号的快递名称1]
*/
public function replacedBy(array $waybills): array
{
$result = [];
try {
// front_no 没有索引,通常用一次查询覆盖一张账单的未匹配单号。
foreach (array_chunk(array_values(array_unique($waybills)), 10000) as $chunk) {
foreach ($this->connection()->table('jst_oms_shipping')->whereIn('front_no', $chunk)
->whereNotNull('express_no')->where('express_no', '<>', '')
->orderBy('id')->get(['front_no', 'express_no', 'express_name1']) as $row) {
$old = strtoupper(trim((string) $row->front_no));
$result[$old] ??= [strtoupper(trim((string) $row->express_no)), self::blank($row->express_name1)];
}
}
} catch (\Illuminate\Database\QueryException $error) {
report($error);
}
return $result;
}
/** @return array<int,object> source_id => 核算结果 */
private function freights(array $sourceIds): array
{
$result = [];
foreach (array_chunk($sourceIds, self::CHUNK) as $chunk) {
try {
foreach ($this->connection()->table('jst_oms_shipping_freight')->whereIn('source_id', $chunk)->get() as $row) {
$result[(int) $row->source_id] = $row;
}
} catch (\Illuminate\Database\QueryException $error) {
report($error);
return [];
}
}
return $result;
}
private static function blank(mixed $value): ?string
{
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}

View File

@ -0,0 +1,381 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Support\Facades\Storage;
/**
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
* 明细子表合在一起,末列注明对账分组,和财务手工做的对账表一样。
* 导出文件以快递发来的原始账单为底:原文件的每张表一个字节不改,后面追加汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、
* 匹配不到、未发出、未提供、说明;没有数据的工作表不生成。
*
* 对账类子表的列顺序:快递原始列 → 财务指定的 25 列 → 发货数据其余字段 → 处理结果。
*/
final class StatementExporter
{
/** 财务指定的 25 列 => 取值来源(发货数据字段,或 _ 开头的计算项)。 */
public const FRONT = [
'称重重量' => '_measured', '首重' => 'qc_first_price', '面单' => 'qc_miandan', '快递单号' => 'express_no',
'交易单号' => 'trade_no', '商品ID' => 'item_id', '条形码' => 'barcode', '商品名称' => 'product_name', '数量' => 'qty',
'计费重量' => 'qc_charge_weight', '续重/费率' => 'qc_rate', '核算运费' => 'qc_freight', '重量差' => '_weight_diff',
'运费差' => '_freight_diff', '省' => 'receiver_state', '买家昵称' => 'buyer_nick', '收货姓名' => 'receiver_name',
'店铺名称' => 'shop_name', '快递名称1' => 'express_name1', '仓库' => 'warehouse_name', '发货时间' => 'ship_time',
'未发出' => '_unshipped', '运费' => 'freight', '线上重量' => 'online_weight', '实称重量' => 'actual_weight',
];
private const CHUNK = 500;
public function __construct(private readonly ShippingLookup $shipping) {}
/**
* 和这张对账单同一张账单的所有对账单:它用到的账单文件拆到的各家,加上「合并账单」相同、同月的各家。本张排第一。
*
* @return list<int>
*/
public function related(int $statementId): array
{
$db = CourierBillMatcher::db();
$statement = $db->table('courier_bill_statements')->find($statementId);
if ($statement === null) {
throw new \RuntimeException('对账单不存在。');
}
$ids = collect([$statementId]);
do {
$previous = $ids->count();
$fileIds = $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->distinct()->pluck('file_id')
->merge($db->table('courier_bill_files')->whereIn('statement_id', $ids)->pluck('id'))->unique();
$fromFiles = $db->table('courier_bill_lines')->whereIn('file_id', $fileIds)->distinct()->pluck('statement_id')
->merge($db->table('courier_bill_files')->whereIn('id', $fileIds)->whereNotNull('statement_id')->pluck('statement_id'));
$bundles = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->whereIn('s.id', $ids)->pluck('g.bundle')->filter(fn ($bundle) => trim((string) $bundle) !== '')->unique();
$ids = $ids->merge($db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->where('s.bill_month', $statement->bill_month)
->where(fn ($q) => $q->whereIn('s.id', $fromFiles)->orWhere(fn ($q) => $q->whereIn('g.bundle', $bundles)->where('s.line_count', '>', 0)))
->pluck('s.id'))->map(static fn ($id): int => (int) $id)->unique();
} while ($ids->count() > $previous);
$others = $ids->map(static fn ($id): int => (int) $id)->unique()->reject(static fn (int $id): bool => $id === $statementId)->sort()->values()->all();
return [$statementId, ...$others];
}
/** @param resource $output */
public function export(int $statementId, $output): void
{
$db = CourierBillMatcher::db();
$ids = $this->related($statementId);
$multi = count($ids) > 1;
$groupNames = [];
$book = new StreamingWorkbook();
$files = $this->files($ids);
$baseFileId = null;
foreach ($files as $file) {
if (strtolower(pathinfo($file->stored_path, PATHINFO_EXTENSION)) === 'xlsx'
&& $book->base(Storage::disk('local')->path($file->stored_path)) !== null) {
$baseFileId = (int) $file->id;
break;
}
}
// 汇总:每家一个小汇总
foreach ($ids as $index => $id) {
$statement = $db->table('courier_bill_statements')->find($id);
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$groupNames[$id] = $group->name;
if ($index > 0) {
$book->row('汇总', []);
$book->row('汇总', []);
}
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
$bill = 0.0;
$self = 0.0;
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get() as $item) {
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
$s = $item->self_amount === null ? null : (float) $item->self_amount;
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
$bill += (float) $b;
$self += (float) $s;
}
$book->row('汇总', ['合计', round($bill, 4), round($self, 2), round($bill - $self, 2)], true);
}
$tail = $multi ? ['对账分组'] : [];
$groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : [];
[$sources, $original] = $this->originalHeaders($ids);
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_')));
$fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '差异原因', '处理结果', ...$tail];
// 原始账单:底文件原封不动;第 2 个及以后的文件按值复制
$originals = $this->writeOriginal($book, $files, $baseFileId);
$sheets = [
'对账' => [Category::MATCH, Category::DIFF, Category::UNCALCULATED],
];
foreach ($db->table('courier_bill_lines')->whereIn('statement_id', $ids)->whereIn('category', [Category::PRIOR, Category::LATER])
->distinct()->orderBy('category_month')->get(['category', 'category_month']) as $row) {
$sheets[Category::label((string) $row->category, (string) $row->category_month)] = [(string) $row->category, (string) $row->category_month];
}
foreach ($sheets as $name => $filter) {
$headerWritten = false;
$this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, &$headerWritten): void {
if (! $headerWritten) {
$book->row($name, $fullHeader, true);
$headerWritten = true;
}
$details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines));
foreach ($lines as $line) {
$ship = $details[strtoupper($line->waybill_no)] ?? [];
$cells = $this->originalCells($line, $sources, $original);
foreach (self::FRONT as $field) {
$cells[] = $this->front($field, $line, $ship);
}
foreach (array_keys($rest) as $field) {
$cells[] = self::value($field, $ship[$field] ?? null);
}
$cells[] = CourierBillMatcher::diffReason((string) $line->category, $line->bill_weight, $line->charge_weight);
$cells[] = Category::RESOLUTIONS[$line->resolution] ?? null;
$book->row($name, [...$cells, ...$groupCell($line)]);
}
});
}
foreach ([Category::MISMATCH => '快递不符', Category::DUPLICATE => '重复', Category::UNMATCHED => '匹配不到', Category::UNSHIPPED => '未发出'] as $category => $name) {
$extra = $category === Category::UNSHIPPED ? ['未发出来源'] : ($category === Category::MISMATCH ? ['发货数据快递名称1'] : []);
$headerWritten = false;
$this->lines($ids, [$category], function (array $lines) use ($book, $name, $category, $sources, $original, $extra, $tail, $groupCell, &$headerWritten): void {
if (! $headerWritten) {
$book->row($name, [...$original, ...$extra, '处理结果', ...$tail], true);
$headerWritten = true;
}
foreach ($lines as $line) {
$cells = $this->originalCells($line, $sources, $original);
if ($extra !== []) {
$cells[] = $category === Category::UNSHIPPED ? $line->unshipped_sources : $line->express_name;
}
$cells[] = Category::RESOLUTIONS[$line->resolution] ?? null;
$book->row($name, [...$cells, ...$groupCell($line)]);
}
});
}
// 未提供:发货数据有、账单没有
$headerWritten = false;
$db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id')
->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, &$headerWritten): void {
if (! $headerWritten) {
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true);
$headerWritten = true;
}
$details = $this->shipping->details($rows->pluck('waybill_no')->all());
foreach ($rows as $row) {
$ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no];
$book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]);
}
});
$this->writeNotes($book, $ids, $originals);
$book->writeTo($output);
}
/**
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
*
* @return list<array{string,bool,?string,int,bool}>
*/
private function writeOriginal(StreamingWorkbook $book, \Illuminate\Support\Collection $files, ?int $baseFileId): array
{
$originals = [];
$used = [];
$reader = new BillWorkbookReader();
foreach ($files->values() as $index => $file) {
$path = Storage::disk('local')->path($file->stored_path);
if (! is_file($path)) {
throw new \RuntimeException('原始账单文件缺失,无法完整导出:' . $file->original_name);
}
$info = collect((array) json_decode((string) $file->sheets, true))->keyBy('sheet');
$isBase = (int) $file->id === $baseFileId;
foreach ($reader->sheets($path, strtolower(pathinfo($path, PATHINFO_EXTENSION)), true) as $sheet => $rows) {
$name = (string) $sheet;
if (! $isBase) {
$base = '文件' . ($index + 1) . '-' . $name;
$name = $book->nameOf($base);
for ($n = 2; isset($used[mb_strtolower($name)]); $n++) {
$suffix = '-' . $n;
$name = $book->nameOf(mb_substr($base, 0, 31 - mb_strlen($suffix)) . $suffix);
}
$used[mb_strtolower($name)] = true;
}
$meta = $info->get($sheet, ['skipped' => '没有内容']);
$written = 0;
$count = 0;
foreach ($rows as $number => $row) {
if (array_filter($row, static fn ($value): bool => $value !== null && $value !== '') !== []) {
$count++;
}
if (! $isBase) {
while (++$written < $number) {
$book->row($name, []);
}
$book->row($name, $row);
}
}
$originals[] = [$name, ! isset($meta['skipped']), $meta['skipped'] ?? null, $count, $isBase];
}
}
return $originals;
}
/** 说明:每张子表是什么、各多少行,以及行数怎么对上。 */
private function writeNotes(StreamingWorkbook $book, array $ids, array $originals): void
{
$db = CourierBillMatcher::db();
$files = $this->files($ids);
$read = $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->count();
$rejected = (int) $files->sum('rejected_count');
$count = static fn (array $categories) => $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->whereIn('category', $categories)->count();
$rows = [];
foreach ($originals as [$name, $isRead, $reason, $lines, $isBase]) {
$description = $isBase ? '快递原始账单,原文件原样(内容、格式、公式都没动)' : '快递原始账单(另一个文件,按值复制,格式没保留)';
$detail = match (true) {
$isRead => '已核对运费。',
str_starts_with((string) $reason, '附加费') => '附加费表,金额按费用项目进入小汇总。',
default => '没有核对:' . preg_replace('/,?(整表跳过|未读入)$/u', '', (string) $reason) . '。',
};
$rows[] = [$name, $description . ';' . $detail, $lines];
}
$rows = [
...$rows,
[$book->nameOf('对账'), '本月发货、发货数据里找得到、属于这家快递的单号(运费一致或有差)。前面是快递原始列,后面接我方核算的 25 列(称重重量、首重、面单、计费重量、续重/费率、核算运费、重量差、运费差……)和发货数据其余字段。', $count(Category::PAYABLE)],
['前月补提供-X月', '发货时间在账单月之前、结算台账里没结算过的单号:快递之前漏报、这次补上的。', $count([Category::PRIOR])],
['跨月订单-X月', '发货时间在账单月之后的单号,本月不结算。', $count([Category::LATER])],
[$book->nameOf('快递不符'), '发货数据里有这个单号,但快递名称1 不是这家(也不在同一张合并账单里)。', $count([Category::MISMATCH])],
[$book->nameOf('重复'), '本账单里重复出现(第二次起),或之前月份已结算过的单号。', $count([Category::DUPLICATE])],
[$book->nameOf('匹配不到'), '发货数据里查不到这个单号。', $count([Category::UNMATCHED])],
[$book->nameOf('未发出'), '单号在「未发出明细」里(现场拦截、换单、仓内未发),不结算。', $count([Category::UNSHIPPED])],
[$book->nameOf('未提供'), '发货数据里本月由这家发出、但账单里没有的单号,只列出来核对,不计金额。', $db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->count()],
];
$book->row('说明', ['子表', '是什么', '行数'], true);
foreach ($rows as $row) {
$book->row('说明', $row);
}
$book->row('说明', []);
$book->row('说明', ['行数怎么对上', '运费表读入的账单行 ' . $read . ' 行 = 对账 + 前月补提供 + 跨月订单 + 快递不符 + 重复 + 匹配不到 + 未发出。'
. ($rejected > 0 ? '另有 ' . $rejected . ' 行单号格式不对(如被 Excel 截断成科学计数法)没读入。' : '')
. '运费表里的标题行、合计行、空单号行不算账单行。行数是有内容的行(含表头、标题、合计)。没有数据的子表不生成。']);
}
/** @return \Illuminate\Support\Collection<int,object> */
private function files(array $ids)
{
$db = CourierBillMatcher::db();
$fileIds = $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->distinct()->pluck('file_id');
return $db->table('courier_bill_files')->where(fn ($q) => $q->whereIn('statement_id', $ids)->orWhereIn('id', $fileIds))->orderBy('id')->get();
}
/**
* 所有账单文件各工作表表头的并集(按出现顺序;同一表里重名的列加序号)。
*
* @return array{0:array<string,list<string>>,1:list<string>} [文件:工作表 => 该表的列名, 并集列名]
*/
private function originalHeaders(array $statementIds): array
{
$sources = [];
$union = [];
$db = CourierBillMatcher::db();
$fileIds = $db->table('courier_bill_lines')->whereIn('statement_id', $statementIds)->distinct()->pluck('file_id');
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->whereIn('statement_id', $statementIds)->orWhereIn('id', $fileIds))
->orderBy('id')->get(['id', 'sheets']);
foreach ($files as $file) {
foreach ((array) json_decode((string) $file->sheets, true) as $sheet) {
if (isset($sheet['skipped'])) {
continue;
}
$names = [];
$count = [];
foreach ($sheet['headers'] as $index => $header) {
$header = trim((string) $header);
$header = $header === '' ? '列' . ($index + 1) : $header;
$count[$header] = ($count[$header] ?? 0) + 1;
$names[] = $count[$header] > 1 ? $header . $count[$header] : $header;
}
$sources[$file->id . ':' . $sheet['sheet']] = $names;
foreach ($names as $name) {
$union[$name] = true;
}
}
}
return [$sources, array_keys($union)];
}
/** @return list<string|float|null> */
private function originalCells(object $line, array $sources, array $original): array
{
$names = $sources[$line->file_id . ':' . $line->sheet] ?? [];
$raw = (array) json_decode((string) $line->raw, true);
$byName = [];
foreach ($names as $index => $name) {
$byName[$name] = $raw[$index] ?? null;
}
return array_map(static function (string $name) use ($byName) {
$value = $byName[$name] ?? null;
if ($value === null || $value === '') {
return null;
}
// 金额/重量这类纯数字写成数值;长数字(单号、手机号)保持文本。
return is_numeric($value) && strlen(preg_replace('/\D/', '', (string) $value)) < 11 && ! preg_match('/^0\d/', (string) $value)
? (float) $value : (string) $value;
}, $original);
}
private function front(string $field, object $line, array $ship): string|float|null
{
return match ($field) {
'_measured' => null,
'_unshipped' => $line->unshipped_sources,
'_weight_diff' => $line->bill_weight !== null && ($ship['qc_charge_weight'] ?? null) !== null
? round((float) $line->bill_weight - (float) $ship['qc_charge_weight'], 4) : null,
'_freight_diff' => $line->bill_amount !== null && ($ship['qc_freight'] ?? null) !== null
? round((float) $line->bill_amount - (float) $ship['qc_freight'], 2) : null,
default => self::value($field, $ship[$field] ?? null),
};
}
private static function value(string $field, mixed $value): string|float|null
{
if ($value === null || $value === '') {
return null;
}
if (in_array($field, ShippingLookup::TEXT_COLUMNS, true) || ! is_numeric($value)) {
return (string) $value;
}
return (float) $value;
}
/**
* 按 id 顺序分批读账单行。$filter:null = 全部;[分类...];或 [分类, 月份](前月补提供/跨月订单)。
*/
private function lines(array $statementIds, ?array $filter, callable $each, ?callable $onFirst = null): void
{
$query = CourierBillMatcher::db()->table('courier_bill_lines')->whereIn('statement_id', $statementIds);
if ($filter !== null) {
if (count($filter) === 2 && in_array($filter[0], [Category::PRIOR, Category::LATER], true)) {
$query->where('category', $filter[0])->where('category_month', $filter[1]);
} else {
$query->whereIn('category', $filter);
}
}
$first = true;
$query->chunkById(self::CHUNK, function ($rows) use ($each, $onFirst, &$first): void {
if ($first && $onFirst !== null) {
$onFirst();
}
$first = false;
$each($rows->all());
});
}
}

View File

@ -0,0 +1,425 @@
<?php
namespace App\Support\CourierBills;
use DOMDocument;
use DOMElement;
use RuntimeException;
use Throwable;
use ZipArchive;
/**
* 多工作表的低内存 XLSX 写出(和 App\Support\StreamingXlsxWriter 同一做法,多了工作表和表头加粗)。
*
* 行按顺序写进各表的临时文件,最后打包;内存占用与行数无关。字符串一律写成文本单元格,
* 长单号不会变成科学计数法。没有写过任何行的工作表不会出现在文件里。
*
* 可以先用 base() 指定一个原始 xlsx:导出文件就是这个原文件本身(每张表的内容、格式、公式、合并单元格都不动),
* 写出的工作表追加在它后面。
*/
final class StreamingWorkbook
{
private const MAIN_NS = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';
private const REL_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
private const PKG_REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships';
private const CT_NS = 'http://schemas.openxmlformats.org/package/2006/content-types';
/** @var array<string,array{path:string,handle:resource,row:int,widths:array<int,int>}> */
private array $sheets = [];
/** 加粗单元格用的样式序号(有原文件时是追加到原文件 styles.xml 里的那个)。 */
private int $boldStyle = 1;
/** @var array{path:string,workbook:string,rels:string,styles:?string,stylesXml:?string,names:array<string,true>}|null */
private ?array $base = null;
/**
* 以这个原始 xlsx 为底:原文件的所有工作表原封不动,后面写的表追加在它后面。必须在写任何行之前调用。
* 文件不是普通 xlsx(xls、csv、带宏的、Strict 格式、打不开的)时返回 false,照旧生成新文件。
*
* @return list<string>|null 原文件的工作表名(按顺序);用不了时为 null
*/
public function base(string $path): ?array
{
if ($this->sheets !== [] || ! is_file($path)) {
return null;
}
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
return null;
}
try {
$root = self::dom($zip, '_rels/.rels');
$workbook = null;
foreach ($root?->getElementsByTagNameNS(self::PKG_REL_NS, 'Relationship') ?? [] as $rel) {
if (str_ends_with($rel->getAttribute('Type'), '/officeDocument')) {
$workbook = ltrim($rel->getAttribute('Target'), '/');
}
}
$types = self::dom($zip, '[Content_Types].xml');
$book = $workbook === null ? null : self::dom($zip, $workbook);
if ($types === null || $book === null || $book->documentElement->namespaceURI !== self::MAIN_NS
|| $book->getElementsByTagNameNS(self::MAIN_NS, 'sheets')->length !== 1) {
return null;
}
foreach ($types->getElementsByTagNameNS(self::CT_NS, 'Override') as $override) {
if (ltrim($override->getAttribute('PartName'), '/') === $workbook && ! str_contains($override->getAttribute('ContentType'), 'sheet.main+xml')) {
return null; // 带宏的 / 模板,另存成 .xlsx 会打不开
}
}
$dir = dirname($workbook);
$relsPath = ($dir === '.' ? '' : $dir . '/') . '_rels/' . basename($workbook) . '.rels';
$rels = self::dom($zip, $relsPath);
if ($rels === null) {
return null;
}
$styles = null;
foreach ($rels->getElementsByTagNameNS(self::PKG_REL_NS, 'Relationship') as $rel) {
if (str_ends_with($rel->getAttribute('Type'), '/styles')) {
$target = $rel->getAttribute('Target');
$styles = str_starts_with($target, '/') ? ltrim($target, '/') : ($dir === '.' ? '' : $dir . '/') . $target;
}
}
$stylesXml = null;
$bold = 1;
$styleDom = $styles === null ? null : self::dom($zip, $styles);
if ($styles !== null && $styleDom === null) {
return null;
}
if ($styleDom !== null) {
$fonts = $styleDom->getElementsByTagNameNS(self::MAIN_NS, 'fonts')->item(0);
$xfs = $styleDom->getElementsByTagNameNS(self::MAIN_NS, 'cellXfs')->item(0);
if (! $fonts instanceof DOMElement || ! $xfs instanceof DOMElement) {
return null;
}
$font = $styleDom->createElementNS(self::MAIN_NS, 'font');
$font->appendChild($styleDom->createElementNS(self::MAIN_NS, 'b'));
$size = $styleDom->createElementNS(self::MAIN_NS, 'sz');
$size->setAttribute('val', '11');
$font->appendChild($size);
$fonts->appendChild($font);
$fontId = $fonts->getElementsByTagNameNS(self::MAIN_NS, 'font')->length - 1;
$fonts->setAttribute('count', (string) ($fontId + 1));
$xf = $styleDom->createElementNS(self::MAIN_NS, 'xf');
foreach (['numFmtId' => '0', 'fontId' => (string) $fontId, 'fillId' => '0', 'borderId' => '0', 'xfId' => '0', 'applyFont' => '1'] as $key => $value) {
$xf->setAttribute($key, $value);
}
$xfs->appendChild($xf);
$bold = 0;
foreach ($xfs->childNodes as $node) {
$bold += $node instanceof DOMElement && $node->localName === 'xf' ? 1 : 0;
}
$bold--;
$xfs->setAttribute('count', (string) ($bold + 1));
$stylesXml = (string) $styleDom->saveXML();
}
$names = [];
foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'sheet') as $sheet) {
$names[] = $sheet->getAttribute('name');
}
} catch (Throwable) {
return null;
} finally {
$zip->close();
}
$this->boldStyle = $bold;
$this->base = ['path' => $path, 'workbook' => $workbook, 'rels' => $relsPath, 'styles' => $styleDom === null ? null : $styles,
'stylesXml' => $stylesXml, 'names' => array_fill_keys(array_map('mb_strtolower', $names), true)];
return $names;
}
private static function dom(ZipArchive $zip, string $name): ?DOMDocument
{
$xml = $zip->getFromName($name);
if ($xml === false) {
return null;
}
$dom = new DOMDocument();
return $dom->loadXML($xml, LIBXML_NONET | LIBXML_PARSEHUGE) ? $dom : null;
}
public function __destruct()
{
foreach ($this->sheets as $sheet) {
if (is_resource($sheet['handle'])) {
fclose($sheet['handle']);
}
@unlink($sheet['path']);
}
}
/** @param list<string|int|float|null> $cells */
public function row(string $sheet, array $cells, bool $bold = false): void
{
$sheet = $this->nameOf($sheet);
if (! isset($this->sheets[$sheet])) {
$path = tempnam(sys_get_temp_dir(), 'bill_sheet_');
$handle = $path === false ? false : fopen($path, 'wb');
if ($handle === false) {
throw new RuntimeException('无法创建导出临时文件。');
}
$this->sheets[$sheet] = ['path' => $path, 'handle' => $handle, 'row' => 0, 'widths' => []];
}
$state = &$this->sheets[$sheet];
$number = ++$state['row'];
$xml = '<row r="' . $number . '">';
foreach (array_values($cells) as $index => $value) {
if ($value === null || $value === '') {
continue;
}
$reference = self::column($index + 1) . $number;
$style = $bold ? ' s="' . $this->boldStyle . '"' : '';
if (is_int($value) || is_float($value)) {
$xml .= '<c r="' . $reference . '"' . $style . '><v>' . self::number($value) . '</v></c>';
$width = strlen(self::number($value));
} else {
$text = (string) $value;
$xml .= '<c r="' . $reference . '"' . $style . ' t="inlineStr"><is><t xml:space="preserve">'
. self::escape($text) . '</t></is></c>';
$width = mb_strwidth($text);
}
if ($number <= 200) {
$state['widths'][$index] = max($state['widths'][$index] ?? 8, min($width + 2, 40));
}
}
fwrite($state['handle'], $xml . '</row>');
}
/** 写进文件时这张表实际的名字:和原文件里的表重名时加「(系统)」。 */
public function nameOf(string $sheet): string
{
$sheet = self::sheetName($sheet);
if ($this->base !== null) {
for ($n = 1, $name = $sheet; isset($this->base['names'][mb_strtolower($sheet)]); $n++) {
$suffix = '(系统' . ($n > 1 ? $n : '') . ')';
$sheet = self::sheetName(mb_substr($name, 0, 31 - mb_strlen($suffix)) . $suffix);
}
}
return $sheet;
}
public function isEmpty(): bool
{
return $this->sheets === [];
}
/** @param resource $output */
public function writeTo($output): void
{
if ($this->sheets === [] && $this->base === null) {
$this->row('Sheet1', []);
}
$zipPath = tempnam(sys_get_temp_dir(), 'bill_zip_');
if ($zipPath === false) {
throw new RuntimeException('无法创建导出文件。');
}
try {
if ($this->base !== null) {
$this->packOnBase($zipPath);
} else {
$this->packNew($zipPath);
}
$handle = fopen($zipPath, 'rb');
stream_copy_to_stream($handle, $output);
fclose($handle);
} finally {
@unlink($zipPath);
}
}
/** 把一张表的行包成完整的 worksheet XML 文件,返回文件路径。 */
private function finishSheet(string $name): string
{
$state = $this->sheets[$name];
fclose($state['handle']);
$cols = '';
foreach ($state['widths'] as $index => $width) {
$cols .= '<col min="' . ($index + 1) . '" max="' . ($index + 1) . '" width="' . $width . '" customWidth="1"/>';
}
$sheetPath = (string) tempnam(sys_get_temp_dir(), 'bill_ws_');
$out = fopen($sheetPath, 'wb');
$in = fopen($state['path'], 'rb');
fwrite($out, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<worksheet xmlns="' . self::MAIN_NS . '">'
. '<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
. ($cols !== '' ? '<cols>' . $cols . '</cols>' : '') . '<sheetData>');
stream_copy_to_stream($in, $out);
fwrite($out, '</sheetData></worksheet>');
fclose($in);
fclose($out);
@unlink($state['path']);
$this->sheets[$name]['path'] = $sheetPath;
return $sheetPath;
}
/** 原文件原样复制,只在 workbook.xml / 关系 / 内容类型 / styles.xml 里追加新表,原有工作表的 XML 一个字节都不改。 */
private function packOnBase(string $zipPath): void
{
if (! copy($this->base['path'], $zipPath)) {
throw new RuntimeException('无法创建导出文件。');
}
$zip = new ZipArchive();
if ($zip->open($zipPath) !== true) {
throw new RuntimeException('无法创建导出文件。');
}
$book = self::dom($zip, $this->base['workbook']);
$rels = self::dom($zip, $this->base['rels']);
$types = self::dom($zip, '[Content_Types].xml');
$sheetsNode = $book->getElementsByTagNameNS(self::MAIN_NS, 'sheets')->item(0);
$maxId = 0;
foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'sheet') as $sheet) {
$maxId = max($maxId, (int) $sheet->getAttribute('sheetId'));
}
$dir = dirname($this->base['workbook']);
$prefix = $dir === '.' ? '' : $dir . '/';
$relationshipIds = [];
foreach ($rels->getElementsByTagNameNS(self::PKG_REL_NS, 'Relationship') as $relationship) {
$relationshipIds[$relationship->getAttribute('Id')] = true;
}
$n = 0;
foreach (array_keys($this->sheets) as $name) {
do {
$n++;
$part = 'worksheets/cbr_sheet' . $n . '.xml';
$relationshipId = 'rIdCbr' . $n;
} while (isset($relationshipIds[$relationshipId]) || $zip->locateName($prefix . $part, ZipArchive::FL_NOCASE) !== false);
$zip->addFile($this->finishSheet($name), $prefix . $part);
$sheet = $book->createElementNS(self::MAIN_NS, 'sheet');
$sheet->setAttribute('name', $name);
$sheet->setAttribute('sheetId', (string) ($maxId + $n));
$sheet->setAttributeNS(self::REL_NS, 'r:id', $relationshipId);
$sheetsNode->appendChild($sheet);
$rel = $rels->createElementNS(self::PKG_REL_NS, 'Relationship');
$rel->setAttribute('Id', $relationshipId);
$rel->setAttribute('Type', self::REL_NS . '/worksheet');
$rel->setAttribute('Target', $part);
$rels->documentElement->appendChild($rel);
$override = $types->createElementNS(self::CT_NS, 'Override');
$override->setAttribute('PartName', '/' . $prefix . $part);
$override->setAttribute('ContentType', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml');
$types->documentElement->appendChild($override);
}
if ($this->base['styles'] === null) {
// 原文件没有 styles.xml:补一份只含普通和加粗两种样式的
$styleNumber = 0;
do {
$styleNumber++;
$stylePart = 'styles_cbr' . $styleNumber . '.xml';
$styleRelationship = 'rIdCbrStyles' . $styleNumber;
} while (isset($relationshipIds[$styleRelationship]) || $zip->locateName($prefix . $stylePart, ZipArchive::FL_NOCASE) !== false);
$zip->addFromString($prefix . $stylePart, self::STYLES);
$rel = $rels->createElementNS(self::PKG_REL_NS, 'Relationship');
$rel->setAttribute('Id', $styleRelationship);
$rel->setAttribute('Type', self::REL_NS . '/styles');
$rel->setAttribute('Target', $stylePart);
$rels->documentElement->appendChild($rel);
$override = $types->createElementNS(self::CT_NS, 'Override');
$override->setAttribute('PartName', '/' . $prefix . $stylePart);
$override->setAttribute('ContentType', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml');
$types->documentElement->appendChild($override);
} else {
$zip->addFromString($this->base['styles'], (string) $this->base['stylesXml']);
}
$zip->addFromString($this->base['workbook'], (string) $book->saveXML());
$zip->addFromString($this->base['rels'], (string) $rels->saveXML());
$zip->addFromString('[Content_Types].xml', (string) $types->saveXML());
if (! $zip->close()) {
throw new RuntimeException('无法创建导出文件。');
}
}
private const STYLES = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
. '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>'
. '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
. '<borders count="1"><border/></borders>'
. '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
. '<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
. '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>'
. '</styleSheet>';
private function packNew(string $zipPath): void
{
$zip = new ZipArchive();
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
throw new RuntimeException('无法创建导出文件。');
}
$contentTypes = '';
$workbook = '';
$relations = '';
foreach (array_keys($this->sheets) as $i => $name) {
$n = $i + 1;
$zip->addFile($this->finishSheet($name), 'xl/worksheets/sheet' . $n . '.xml');
$contentTypes .= '<Override PartName="/xl/worksheets/sheet' . $n . '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
$workbook .= '<sheet name="' . self::escape($name) . '" sheetId="' . $n . '" r:id="rId' . $n . '"/>';
$relations .= '<Relationship Id="rId' . $n . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' . $n . '.xml"/>';
}
$styles = count($this->sheets) + 1;
$zip->addFromString('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
. '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
. '<Default Extension="xml" ContentType="application/xml"/>'
. '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
. '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
. $contentTypes . '</Types>');
$zip->addFromString('_rels/.rels', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
. '</Relationships>');
$zip->addFromString('xl/workbook.xml', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
. '<sheets>' . $workbook . '</sheets></workbook>');
$zip->addFromString('xl/_rels/workbook.xml.rels', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' . $relations
. '<Relationship Id="rId' . $styles . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'
. '</Relationships>');
$zip->addFromString('xl/styles.xml', self::STYLES);
$zip->close();
}
private static function sheetName(string $name): string
{
$name = str_replace(['\\', '/', '?', '*', '[', ']', ':'], '-', $name);
return mb_substr($name === '' ? 'Sheet' : $name, 0, 31);
}
private static function number(int|float $value): string
{
if (is_int($value)) {
return (string) $value;
}
if (! is_finite($value)) {
return '0';
}
$text = rtrim(rtrim(sprintf('%.10F', $value), '0'), '.');
return ($text === '' || $text === '-' || $text === '-0') ? '0' : $text;
}
private static function escape(string $value): string
{
if (! mb_check_encoding($value, 'UTF-8')) {
$value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
}
$value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', $value) ?? $value;
return htmlspecialchars($value, ENT_QUOTES | ENT_XML1, 'UTF-8');
}
private static function column(int $index): string
{
$name = '';
while ($index > 0) {
$index--;
$name = chr(65 + ($index % 26)) . $name;
$index = intdiv($index, 26);
}
return $name;
}
}

View File

@ -0,0 +1,145 @@
<?php
namespace App\Support\CourierBills;
/**
* 对账单「小汇总」→ 快递应付汇总一行的金额列。
*
* 规则来自财务 10 月的手工做法:36 份对账表里的 42 个小汇总按这里归集,
* 与手工快递汇总表逐行、逐列一致。项目名称决定落在哪一列,所以名称按财务习惯写,系统不改名。
*/
final class SummaryMapper
{
/** 差异明细 13 列(快递汇总表 AF–AR),键 = 列字母。 */
public const DIFF_COLUMNS = [
'AF' => '运费差异-成品', 'AG' => '运费差异-配件', 'AH' => '未发出', 'AI' => '匹配不到', 'AJ' => '重复',
'AK' => '快递记账', 'AL' => '原单补发配件', 'AM' => '违约金', 'AN' => '退件费', 'AO' => '叉车电费',
'AP' => '面单费', 'AQ' => '借支', 'AR' => '其他',
];
/**
* 单个项目归到哪里:差异明细列字母,或 supplement(补给快递)/ waybill(面单)。
*/
public static function classify(string $label): string
{
$l = preg_replace('/\s+/u', '', $label) ?? '';
if (str_contains($l, '补发配件') || str_contains($l, '配件补发')) {
return 'AL';
}
if (str_starts_with($l, '补') || str_contains($l, '记账补款') || preg_match('/需补$/u', $l)) {
return 'supplement';
}
if ($l === '面单') {
return 'waybill';
}
if ($l === '借支') {
return 'AQ';
}
if (str_contains($l, '违约金')) {
return 'AM';
}
if (preg_match('/重复|查重|已结算/u', $l)) {
return 'AJ';
}
if (str_contains($l, '记账')) {
return 'AK';
}
if (str_contains($l, '未发出') && ! str_contains($l, '实际已发出')) {
return 'AH';
}
if (preg_match('/匹配不到|查不到|未匹配|未提供|无发货数据|不结算|匹配失败/u', $l)) {
return 'AI';
}
if (in_array($l, ['退件费', '退货费用', '未退回运费'], true)) {
return 'AN';
}
if ($l === '叉车电费') {
return 'AO';
}
if ($l === '面单费') {
return 'AP';
}
if (preg_match('/运费|入库管理费|出库费用|仓储|订单操作费|装卸费/u', $l) && ! preg_match('/车费|保费/u', $l)) {
return 'AF';
}
return 'AR';
}
/**
* @param iterable<array{label:string,bill:?float,self:?float}> $items 小汇总各行(不含合计行)
* @return array<string,float|string> 快递汇总表列字母 => 值(J、K、L、N、O、P、AF–AR、AS、AT)
*/
public static function map(iterable $items): array
{
$diff = array_fill_keys(array_keys(self::DIFF_COLUMNS), 0.0);
$provided = 0.0;
$supplement = 0.0;
$bookkeepingSupplement = 0.0;
$waybill = 0.0;
$advance = 0.0;
$notes = [];
foreach ($items as $item) {
$label = (string) $item['label'];
$bill = $item['bill'];
$self = $item['self'];
$provided += (float) $bill;
$d = (float) $bill - (float) $self;
$target = self::classify($label);
if ($target === 'supplement') {
$supplement -= $d;
if (str_contains($label, '记账')) {
$bookkeepingSupplement -= $d;
}
continue;
}
if ($target === 'waybill') {
$waybill += $d;
continue;
}
// 快递未报、我方代垫要抵扣的车费:算借支,同时照常列在「其他」里说明。
if ($target === 'AR' && ($bill === null || (float) $bill == 0.0) && (float) $self < 0 && str_contains($label, '车费')) {
$advance += -(float) $self;
}
$diff[$target] += $d;
if ($target === 'AR' && abs($d) > 0.005) {
$notes[] = $label . self::number($d) . '元';
}
}
$penalty = $diff['AM'];
$advance += $diff['AQ'];
$reconDiff = array_sum($diff) - $penalty - $advance;
return [
'J' => round($supplement, 2),
'K' => round($provided, 2),
'L' => round($reconDiff, 2),
'N' => round($waybill, 2),
'O' => round($advance, 2),
'P' => round($penalty, 2),
...array_map(static fn (float $v): float => round($v, 2), $diff),
'AS' => round($bookkeepingSupplement, 2),
'AT' => implode(';', $notes),
];
}
/** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L。 */
public static function totals(array $cells): array
{
$n = static fn (string $key): float => (float) ($cells[$key] ?? 0);
$cells['M'] = round($n('K') - $n('L'), 2);
$cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2);
return $cells;
}
private static function number(float $value): string
{
$text = rtrim(rtrim(number_format(round($value, 2), 2, '.', ''), '0'), '.');
return $text === '-0' ? '0' : $text;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Support\CourierBills;
final class Waybill
{
/**
* 单号规范化:去空白、前导 @ 和撇号、末尾 .0。
*
* 科学计数法要分两种:xlsx 数字单元格里存的是完整值(如 7.9150812345678E+13,有效位够),
* 可以还原;文本或 CSV 里的「7.91508E+13」是 Excel 显示截断后的值,末几位已经丢了,必须拒收。
*
* @return array{waybill:?string,reason:?string}
*/
public static function parse(string $value): array
{
$text = preg_replace('/\s+/u', '', $value) ?? '';
$text = ltrim($text, "@''`");
if (preg_match('/^(\d+)\.0+$/', $text, $m)) {
$text = $m[1];
}
if (preg_match('/^(\d)(?:\.(\d+))?E\+?(\d+)$/i', $text, $m)) {
$fraction = $m[2] ?? '';
$exponent = (int) $m[3];
if (strlen($fraction) + 1 < 12 || strlen($fraction) > $exponent) {
return ['waybill' => null, 'reason' => '单号是科学计数法,已被 Excel 截断'];
}
$text = $m[1] . str_pad($fraction, $exponent, '0');
}
if (! preg_match('/^[A-Za-z0-9-]{4,96}$/', $text)) {
return ['waybill' => null, 'reason' => '单号格式不对'];
}
return ['waybill' => strtoupper($text), 'reason' => null];
}
public static function normalize(?string $value): ?string
{
return self::parse((string) $value)['waybill'];
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Support;
final class ReturnRouteFreightCalculator
{
private const CARRIER_MAP = ['中铁客退' => '中铁客退'];
public function __construct(private readonly ReverseLogisticsQuoteSnapshot $snapshot) {}
public function calculate(?string $carrier, string $warehouse, string $destination, ?float $weightKg, ?float $volumeCm3): array
{
$carrier = self::CARRIER_MAP[trim((string) $carrier)] ?? null;
if ($carrier === null) return $this->missing('该快递公司不在返货线路报价范围内');
if ($weightKg === null || $volumeCm3 === null || !is_finite($weightKg) || !is_finite($volumeCm3) || $weightKg <= 0 || $volumeCm3 <= 0) {
return $this->missing('缺少重量或体积,无法计算运费');
}
$warehouse = trim($warehouse);
$origin = config('return_route_freight.warehouse_aliases', [])[$warehouse] ?? $warehouse;
$destination = trim($destination);
$rates = array_filter($this->snapshot->load()['rates'], static fn ($rate) =>
($rate['layout'] ?? null) === ReverseLogisticsQuoteSnapshot::LAYOUT_ROUTE_TON_VOLUME
&& $rate['carrier'] === $carrier && $rate['origin'] === $origin && $rate['destination'] === $destination);
if (!$rates) return $this->missing('报价未覆盖该路线');
if (count($rates) !== 1) return $this->missing('该路线存在多条报价,请核对报价版本');
$rate = reset($rates);
if (!$rate['available']) return $this->missing('该线路缺少有效吨价或方价');
$tons = $weightKg / 1000;
$cubicMeters = $volumeCm3 / 1000000;
$byTon = round($tons * $rate['ton_price'], 2);
$byVolume = round($cubicMeters * $rate['volume_price'], 2);
$freight = max($byTon, $byVolume);
$delivery = $cubicMeters < 15 ? 50.0 : 0.0;
return [
'covered' => true, 'reason' => null, 'carrier' => $carrier, 'origin' => $origin, 'destination' => $destination,
'tons' => $tons, 'cubic_meters' => $cubicMeters, 'by_ton' => $byTon, 'by_volume' => $byVolume,
'freight' => $freight, 'delivery_fee' => $delivery, 'payable' => round($freight + $delivery, 2),
'pending_confirmation' => $rate['pending_confirmation'], 'effective_date' => $rate['effective_date'],
];
}
public function calculateShipment(array $shipment, string $destination, ?float $weightKg, ?float $volumeCm3): array
{
$carrier = trim((string) ($shipment['express_name1'] ?? ''));
if ($carrier === '') $carrier = $shipment['express_name2'] ?? null;
return $this->calculate($carrier, (string) ($shipment['warehouse_name'] ?? ''), $destination, $weightKg, $volumeCm3);
}
private function missing(string $reason): array
{
return ['covered' => false, 'reason' => $reason, 'payable' => null];
}
}

View File

@ -23,6 +23,8 @@ final class ReverseLogisticsQuoteSnapshot
/** 单一到达仓,每行一个出发省份,按重量段给出费率(如中通快运逆向)。 */
private const LAYOUT_WEIGHT_BAND = 'weight-band';
public const LAYOUT_ROUTE_TON_VOLUME = 'route-ton-volume';
public function __construct(private readonly ?string $path = null)
{
}
@ -145,6 +147,7 @@ final class ReverseLogisticsQuoteSnapshot
];
return match ($layout) {
self::LAYOUT_ROUTE_TON_VOLUME => $this->extractRouteTonVolumeRates($values, $context),
self::LAYOUT_MATRIX => $this->extractMatrixRates($values, $context),
self::LAYOUT_SINGLE_DESTINATION => $this->extractSingleDestinationRates($values, $context),
self::LAYOUT_WEIGHT_BAND => $this->extractWeightBandRates($values, $context),
@ -157,6 +160,11 @@ final class ReverseLogisticsQuoteSnapshot
{
$header = $values[1] ?? [];
$routeHeaders = ['出发仓', '出发省份', '到达地', '到达省份', '吨价(元/吨)', '方价(元/方)', '来源', '备注'];
if (array_map(static fn ($cell) => trim((string) $cell), array_slice($header, 0, 8)) === $routeHeaders) {
return self::LAYOUT_ROUTE_TON_VOLUME;
}
foreach ($header as $index => $label) {
if (! is_string($label)) {
continue;
@ -180,6 +188,56 @@ final class ReverseLogisticsQuoteSnapshot
return null;
}
private function extractRouteTonVolumeRates(array $values, array $context): array
{
$rates = [];
foreach (array_slice($values, 2, null, true) as $index => $row) {
$origin = trim((string) ($row[0] ?? ''));
$destination = trim((string) ($row[2] ?? ''));
if ($origin === '' || $destination === '') continue;
$ton = $this->amount($row[4] ?? null);
$volume = $this->amount($row[5] ?? null);
$source = trim((string) ($row[6] ?? ''));
$rates[] = array_replace($this->rateRow($context, count($rates) + 1, [
'origin' => $origin,
'destination' => $destination,
'weight_band' => null,
'base_amount' => $ton,
'increment_amount' => $volume,
'source' => $source,
]), [
'layout' => self::LAYOUT_ROUTE_TON_VOLUME,
'effective_date' => $context['effective_date'],
'origin_key' => $origin,
'destination_key' => $destination,
'origin_province' => trim((string) ($row[1] ?? '')),
'destination_province' => trim((string) ($row[3] ?? '')),
'ton_price' => $ton,
'volume_price' => $volume,
'ton_unit' => '元/吨',
'volume_unit' => '元/方',
'pending_confirmation' => $source === '待物流确认',
'remark' => trim((string) ($row[7] ?? '')),
'source_cells' => $this->cellRef(4, $index).':'.$this->cellRef(5, $index),
'available' => $ton !== null && $ton >= 0 && $volume !== null && $volume >= 0,
]);
}
return [
'rule' => array_replace($this->rateRule($context, [
'pricing_mode' => self::LAYOUT_ROUTE_TON_VOLUME,
'pricing_label' => '按吨与按方分别四舍五入到分后取高,不足 15 方加收 50 元/票,含卸货',
'base_label' => '吨价',
'increment_label' => '方价',
'route_label' => '出发仓 → 到达地,按完整名称匹配',
'weight_bands' => [],
'rates' => $rates,
]), ['base_unit' => '元/吨', 'increment_unit' => '元/方']),
'rates' => $rates,
];
}
/**
* 矩阵版式:列方向按“到达省份”成组,每组两列(面单价格、续重价格),行方向为出发省份。
*
@ -448,6 +506,7 @@ final class ReverseLogisticsQuoteSnapshot
private function noteLines(array $values, string $layout): array
{
[$startRow, $column] = match ($layout) {
self::LAYOUT_ROUTE_TON_VOLUME => [2, 7],
self::LAYOUT_MATRIX => [3, 0],
self::LAYOUT_SINGLE_DESTINATION => [3, 3],
self::LAYOUT_WEIGHT_BAND => [2, 5],
@ -566,6 +625,8 @@ final class ReverseLogisticsQuoteSnapshot
$values = $this->normalizeMatrix($sheet['values'] ?? []);
$formulas = $this->normalizeMatrix($sheet['formulas'] ?? []);
$columnCount = max(array_map('count', $values ?: [[]]));
$dateValues = $this->detectLayout($values) === self::LAYOUT_ROUTE_TON_VOLUME ? array_slice($values, 0, 1) : $values;
$effectiveDate = $this->extractEffectiveDate($dateValues);
return [
'id' => sprintf('RL-%03d', $position + 1),
@ -574,12 +635,12 @@ final class ReverseLogisticsQuoteSnapshot
'company_name' => $this->inferCompanyName($name),
'carrier' => $this->inferCarrier($name),
'quote_type' => $this->inferQuoteType($name),
'effective_date' => $this->extractEffectiveDate($values),
'effective_date' => $effectiveDate,
'source_range' => trim((string) ($sheet['address'] ?? '')),
'row_count' => count($values),
'column_count' => $columnCount,
'formula_count' => $this->formulaCount($formulas),
'status' => $this->extractEffectiveDate($values) === null ? '未标执行日期' : '已标执行日期',
'status' => $effectiveDate === null ? '未标执行日期' : '已标执行日期',
'signature_status' => 'Excel 未提供',
'values' => $values,
'formulas' => $formulas,
@ -595,6 +656,8 @@ final class ReverseLogisticsQuoteSnapshot
private function inferCarrier(string $name): string
{
if (str_contains($name, '中铁')) return '中铁客退';
foreach ([
'中通快运', '顺心捷达', '安能快运', '京广', 'EMS', '中通', '圆通', '德邦',
'申通', '极兔', '安能', '邮政', '韵达', '顺丰',
@ -609,6 +672,8 @@ final class ReverseLogisticsQuoteSnapshot
private function inferQuoteType(string $name): string
{
if (str_contains($name, '返货')) return '返货线路报价';
if (str_contains($name, '退货')) {
return '退货报价';
}
@ -624,7 +689,7 @@ final class ReverseLogisticsQuoteSnapshot
{
foreach ($values as $row) {
foreach ($row as $cell) {
if (! is_string($cell)) {
if (! is_string($cell) || preg_match('/执行日期\s*[::]\s*待填/u', $cell)) {
continue;
}

View File

@ -0,0 +1,298 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
final class UnshippedWaybills
{
public const START = '2026-09-01';
public const HISTORY_PREFIX = 'history:';
public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发'];
private const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F';
private const WAREHOUSE_EXCLUDED_STATUSES = [
'REJECT_AUDIT', 'DISABLED', 'REJECTED', 'REFUSED', 'CANCELED', 'CANCELLED', '已拒绝', '已取消',
];
private const INTERCEPT_TABLES = [
'intercept_regular' => ['ops_jst_return_refund_info', 'ops_jst_return_refund_item', 'ops_jst_orders'],
'intercept_taobao' => ['ops_jst_qmcust_refunds', 'ops_jst_qmcust_refund_items', 'ops_jst_qmcust_orders'],
];
public const SYNC_SOURCES = [
'intercept_regular' => '现场拦截入库签收 · 普通店铺',
'intercept_taobao' => '现场拦截入库签收 · 淘系店铺',
'replacement' => '换单未发出',
'warehouse' => '仓内未发',
];
public static function label(string $source): string
{
return self::SOURCES[isset(self::INTERCEPT_TABLES[$source]) ? 'intercept' : $source];
}
public static function storedSources(array $sources): array
{
if (in_array('intercept', $sources, true)) {
return [...$sources, ...array_keys(self::INTERCEPT_TABLES)];
}
return $sources;
}
public function connection()
{
return DB::connection('business_mirror');
}
public static function normalize(?string $number): string
{
return ltrim(preg_replace('/\s+/u', '', $number ?? '') ?? '', '@');
}
public static function parseRemark(string $remark): ?array
{
if (!preg_match('/^\s*([^::]+)[::]([^::]+?)\s*->\s*([^::]+)[::]([^::]+)\s*$/u', $remark, $parts)) {
return null;
}
$old = self::normalize($parts[2]);
$new = self::normalize($parts[4]);
foreach ([$old, $new] as $number) {
if (!preg_match('/^[A-Za-z0-9-]{1,96}$/', $number) || preg_match('/^\d+(?:\.\d+)?e[+-]?\d+$/i', $number)) return null;
}
return ['old_waybill' => $old, 'new_waybill' => $new, 'old_courier' => trim($parts[1]), 'new_courier' => trim($parts[3])];
}
public function results()
{
return $this->connection()->table('courier_unshipped_waybills');
}
public function unshippedSources(array $waybills): array
{
$result = [];
foreach (array_chunk(array_unique(array_filter(array_map(self::normalize(...), $waybills))), 500) as $chunk) {
foreach ($this->results()->whereIn('waybill_no', $chunk)->distinct()->get(['waybill_no', 'source']) as $row) {
$label = self::label($row->source);
$result[$row->waybill_no][$label] = $label;
}
}
return array_map(array_values(...), $result);
}
public function sync(string $source): bool
{
$db = $this->connection();
try {
// Read all dependencies before replacing a source's last successful result.
[$rows, $missing] = match ($source) {
'intercept_regular', 'intercept_taobao' => $this->intercepts($source),
'replacement' => $this->replacements(),
'warehouse' => $this->warehouse(),
};
$historySource = isset(self::INTERCEPT_TABLES[$source]) ? 'intercept' : $source;
$history = $this->results()->where('source', $historySource)->where('evidence_no', 'like', self::HISTORY_PREFIX.'%');
$cutoff = (clone $history)->max('evidence_time');
if ($cutoff !== null) {
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
$rows = array_filter($rows, fn ($row) => substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10)
&& !isset($covered[$row['waybill_no']]));
}
$db->transaction(function () use ($db, $source, $rows, $missing): void {
$this->results()->where('source', $source)->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->delete();
foreach (array_chunk(array_values($rows), 500) as $chunk) {
$this->results()->insert($chunk);
}
$db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], [
'last_success_at' => now(), 'row_count' => count($rows), 'missing_count' => $missing, 'warning' => null,
]);
if (isset(self::INTERCEPT_TABLES[$source]) && $db->table('courier_unshipped_sync')
->whereIn('source', array_keys(self::INTERCEPT_TABLES))->whereNotNull('last_success_at')->count() === 2) {
$this->results()->where('source', 'intercept')->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->delete();
}
});
return true;
} catch (Throwable $error) {
if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) {
report($error);
$warning = '读取失败,保留上次同步结果。';
} else {
$warning = $error->getMessage();
}
$db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], ['warning' => $warning]);
return false;
}
}
private function assertMirrorReady(array $tables): void
{
$db = $this->connection();
foreach ($tables as $table) {
if (!$db->table($table)->exists()) throw new RuntimeException('依赖镜像暂无数据。');
}
$datasets = array_keys(array_filter(config('upstream_mirrors.datasets', []),
fn ($dataset) => in_array($dataset['target'] ?? null, $tables, true)));
if ($datasets !== [] && $db->getSchemaBuilder()->hasTable('business_mirror_table_states')
&& $db->table('business_mirror_table_states')->whereIn('dataset_key', $datasets)
->where(fn ($query) => $query->whereNull('initial_completed_at')->orWhere('status', 'failed'))->exists()) {
throw new RuntimeException('依赖镜像尚未完成同步。');
}
}
private function intercepts(string $source): array
{
$db = $this->connection();
$rows = [];
$missing = 0;
[$refunds, $items, $orders] = self::INTERCEPT_TABLES[$source];
$this->assertMirrorReady([$refunds, $items, $orders]);
$refundRows = $db->table($refunds.' as r')->where('r.question_type', self::SOURCES['intercept'])
->join($items.' as i', 'i.as_id', '=', 'r.as_id')->where('i.receive_date', '>=', self::START)
->groupBy('r.as_id', 'r.o_id', 'r.so_id', 'r.shop_name')
->get(['r.as_id', 'r.o_id', 'r.so_id', 'r.shop_name', DB::raw('min('.$db->getQueryGrammar()->wrap('i.receive_date').') as received')]);
foreach ($refundRows->chunk(500) as $batch) {
$ordersById = $db->table($orders)->whereIn('o_id', $batch->pluck('o_id')->filter()->unique()->all())
->orderBy('l_id')->get(['o_id', 'l_id', 'logistics_company'])
->filter(fn ($order) => self::normalize($order->l_id) !== '')->groupBy('o_id');
foreach ($batch as $refund) {
$order = $ordersById->get($refund->o_id)?->first();
if (!$order) {
$missing++;
continue;
}
$number = self::normalize($order->l_id);
$key = $refund->as_id.'|'.$number;
if (isset($rows[$key]) && $rows[$key]['evidence_time'] <= $refund->received) continue;
$rows[$key] = [
'source' => $source, 'waybill_no' => $number, 'evidence_no' => $refund->as_id,
'evidence_time' => $refund->received, 'courier_name' => $order->logistics_company,
'o_id' => $refund->o_id, 'trade_no' => $refund->so_id, 'shop_name' => $refund->shop_name,
'evidence_text' => self::SOURCES['intercept'],
];
}
}
return [$rows, $missing];
}
private function replacements(): array
{
$logs = $this->connection()->table('courier_unshipped_order_logs')->where('operated_at', '>=', self::START)
->where('operated_at', '<', today())->orderBy('order_no')->orderByDesc('operated_at')->orderByDesc('id')->cursor();
$rows = [];
$currentOrder = null;
$finalNumber = null;
foreach ($logs as $log) {
if ($currentOrder !== $log->order_no) {
$currentOrder = $log->order_no;
$finalNumber = $log->new_waybill;
}
if ($log->old_waybill === $finalNumber) continue;
$key = $log->order_no.'|'.$log->old_waybill;
$rows[$key] ??= [
'source' => 'replacement', 'waybill_no' => $log->old_waybill, 'courier_name' => $log->old_courier,
'evidence_no' => $log->order_no, 'o_id' => $log->order_no, 'evidence_time' => $log->operated_at,
'evidence_text' => $log->remark, 'operator' => $log->operator,
'new_courier_name' => $log->new_courier, 'new_waybill_no' => $log->new_waybill,
];
}
if ($currentOrder === null) throw new RuntimeException('未导入订单操作日志。');
return [$rows, 0];
}
private function warehouse(): array
{
$db = $this->connection();
$this->assertMirrorReady(['ops_work_order_form_config', 'ops_work_order_main', 'ops_work_order_form_value']);
$latest = $db->table('ops_work_order_form_config')->selectRaw('work_type, max(id) as id')->groupBy('work_type');
$types = $db->table('ops_work_order_form_config as c')->joinSub($latest, 'latest', 'latest.id', '=', 'c.id')
->where('c.work_type_name', self::SOURCES['warehouse'])->pluck('c.work_type');
if ($types->isEmpty()) {
return [$this->withWarehouseCouriers($this->warehouseFromJiansun()), 0];
}
$workFields = $db->table('ops_work_order_main as w')->join('ops_work_order_form_value as v', 'v.main_order_no', '=', 'w.order_no')
->whereIn('w.work_type', $types)->where('w.create_time', '>=', self::START)
->where(fn ($q) => $q->whereNull('w.is_deleted')->orWhere('w.is_deleted', 0))
->where(fn ($q) => $q->whereNull('v.is_deleted')->orWhere('v.is_deleted', 0));
$numberField = static fn ($q) => $q->where('v.field_code', 'lIdField')->orWhereIn('v.field_name', ['快递单号', '运单号', '物流单号']);
if (!(clone $workFields)->where($numberField)->exists()) {
throw new RuntimeException('未找到仓内未发工单类型或单号字段。');
}
$workOrders = (clone $workFields)->where($numberField)
->where(fn ($q) => $q->whereNull('w.status')->orWhereNotIn('w.status', ['已拒绝', '已取消']))
->orderByDesc('v.id')->get(['w.order_no', 'w.status', 'w.title', 'w.create_time', 'v.field_value']);
$couriers = (clone $workFields)->whereIn('v.field_name', ['快递名称', '快递公司', '物流公司'])
->orderBy('v.id')->pluck('v.field_value', 'w.order_no');
$rows = [];
foreach ($workOrders as $order) {
$number = self::normalize($order->field_value);
if ($number === '') continue;
$rows[$order->order_no.'|'.$number] ??= [
'source' => 'warehouse', 'waybill_no' => $number, 'courier_name' => trim($couriers[$order->order_no] ?? ''),
'evidence_no' => $order->order_no, 'evidence_time' => $order->create_time,
'evidence_text' => trim(($order->status ?? '').' '.$order->title),
];
}
return [$this->withWarehouseCouriers($rows), 0];
}
private function warehouseFromJiansun(): array
{
// The verified warehouse work orders are mirrored from jst_workOrderInfo.
$table = 'js_jst_work_order_info';
$this->assertMirrorReady([$table]);
$workOrders = $this->connection()->table($table)->where('woTypeId', self::WAREHOUSE_WORK_TYPE)
->where('createTime', '>=', self::START)
->where(fn ($q) => $q->whereNull('status')->orWhereNotIn('status', self::WAREHOUSE_EXCLUDED_STATUSES))
->select(['Id', 'woNo', 'status', 'title', 'createTime', 'businessFieldList']);
$rows = [];
foreach ($workOrders->lazyById(500, 'Id') as $order) {
$fields = [];
foreach (json_decode((string) $order->businessFieldList, true) ?? [] as $field) {
if (is_array($field) && isset($field['fieldId']) && is_scalar($field['value'] ?? null)) {
$fields[$field['fieldId']] = (string) $field['value'];
}
}
$number = self::normalize($fields['lIdField'] ?? null);
if ($number === '') continue;
$rows[$order->woNo.'|'.$number] = [
'source' => 'warehouse', 'waybill_no' => $number, 'courier_name' => '',
'evidence_no' => $order->woNo, 'evidence_time' => $order->createTime,
'o_id' => $fields['o_id'] ?? null, 'evidence_text' => trim(($order->status ?? '').' '.$order->title),
];
}
return $rows;
}
private function withWarehouseCouriers(array $rows): array
{
$db = $this->connection();
$numbers = array_unique(array_column(array_filter($rows, fn ($row) => $row['courier_name'] === ''), 'waybill_no'));
$shipping = [];
if ($numbers !== [] && !$db->getSchemaBuilder()->hasTable('jst_oms_shipping')) {
return $rows;
}
foreach (array_chunk($numbers, 500) as $chunk) {
foreach ($db->table('jst_oms_shipping')->whereIn('express_no', $chunk)->get(['express_no', 'express_name1', 'express_name2']) as $item) {
$shipping[$item->express_no] = $item->express_name1 ?: $item->express_name2;
}
}
foreach ($rows as &$row) {
$row['courier_name'] = $row['courier_name'] ?: ($shipping[$row['waybill_no']] ?? null);
}
return $rows;
}
}

View File

@ -8,12 +8,14 @@ final class FinanceLedgerAccountStatus
public const ONLINE_BANKING_ABNORMAL = 'online_banking_abnormal';
public const LIMITED = 'limited';
public const BUSINESS_DEREGISTERED = 'business_deregistered';
public const DEREGISTERED = 'deregistered';
public const OPTIONS = [
self::NORMAL => '正常',
self::ONLINE_BANKING_ABNORMAL => '网银异常',
self::LIMITED => '限额',
self::BUSINESS_DEREGISTERED => '工商注销',
self::DEREGISTERED => '注销',
];
public static function normalize(?string $status): string

View File

@ -111,6 +111,25 @@ class SidebarPermissions
return self::normalizeAllowedKeys((array) ($settings['subjects'][$subject] ?? []));
}
/**
* Runtime permissions include pages inherited from an existing sibling page.
* Keep allowedKeys() as the raw configured permission list for settings screens.
*/
public static function effectiveAllowedKeys(User $user): ?array
{
$allowed = self::allowedKeys($user);
if ($allowed === null) {
return null;
}
if (in_array('process-data/oa-process', $allowed, true)) {
$allowed[] = 'process-data/invoice-data';
}
return array_values(array_unique($allowed));
}
public static function hasLimitedDingTalkAccess(User $user): bool
{
return SupplierPortalAccess::isSupplierUser($user)
@ -127,7 +146,7 @@ class SidebarPermissions
public static function navigationFor(User $user): array
{
$navigation = BusinessNavigation::all();
$allowed = self::allowedKeys($user);
$allowed = self::effectiveAllowedKeys($user);
if ($allowed === null) {
return self::applyPageViewerAllowlists($navigation, $user);

View File

@ -563,6 +563,7 @@ $navigation = [
'route_page' => 'fund-ledger',
'permission_key' => 'financial-operations/fund-ledger',
],
['slug' => 'fund-balance-monitor', 'title' => '资金余额监控'],
[
'slug' => 'store-receiving-accounts',
'title' => '店铺收款账户',
@ -591,7 +592,7 @@ $navigation = [
'title' => '店铺收款账户账单',
'tabs' => [
['slug' => 'balance-overview', 'title' => '账户余额总览'],
['slug' => 'taobao-alipay', 'title' => '淘系支付宝账户'],
['slug' => 'taobao-alipay', 'title' => '全部支付宝账户'],
['slug' => 'taobao-wechat', 'title' => '淘系微信账户'],
['slug' => 'pinduoduo', 'title' => '拼多多账户'],
['slug' => 'jd-wallet', 'title' => '京东网银钱包账户'],
@ -824,9 +825,10 @@ $navigation = [
['slug' => 'quote-management', 'title' => '报价管理'],
['slug' => 'courier-information', 'title' => '快递资料'],
['slug' => 'agreement-signing', 'title' => '协议签署'],
['slug' => 'freight-reconciliation', 'title' => '运费对账'],
['slug' => 'courier-payable-summary', 'title' => '快递应付汇总'],
['slug' => 'shipping-data', 'title' => '发货数据'],
['slug' => 'accessory-reship-deductions', 'title' => '配件补发扣款'],
['slug' => 'unshipped-waybills', 'title' => '未发出明细'],
['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'],
['slug' => 'bookkeeping-details', 'title' => '记账明细'],
['slug' => 'compensation-details', 'title' => '赔偿明细'],
@ -834,6 +836,7 @@ $navigation = [
['slug' => 'other-adjustments', 'title' => '其他扣款补款'],
['slug' => 'courier-surcharge', 'title' => '附加费报价维护'],
['slug' => 'payable-cloud-warehouse-vehicle-fee', 'title' => '应付云仓车费'],
['slug' => 'courier-bill-reconciliation', 'title' => '快递账单对账'],
['slug' => 'courier-payables-report', 'title' => '快递应付表'],
['slug' => 'freight-difference', 'title' => '运费差'],
['slug' => 'other-surcharge-summary', 'title' => '其他附加费汇总'],
@ -891,9 +894,10 @@ $navigation = [
],
],
],
['slug' => 'freight-reconciliation', 'title' => '运费对账'],
['slug' => 'courier-payable-summary', 'title' => '快递应付汇总'],
['slug' => 'shipping-data', 'title' => '发货数据'],
['slug' => 'accessory-reship-deductions', 'title' => '配件补发扣款'],
['slug' => 'unshipped-waybills', 'title' => '未发出明细'],
['slug' => 'return-pickup-management', 'title' => '退货取件管理'],
['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'],
['slug' => 'warehouse-freight', 'title' => '仓储费'],
@ -902,6 +906,7 @@ $navigation = [
['slug' => 'advance-details', 'title' => '借支明细'],
['slug' => 'other-adjustments', 'title' => '其他扣款补款'],
['slug' => 'payable-cloud-warehouse-vehicle-fee', 'title' => '应付云仓车费'],
['slug' => 'courier-bill-reconciliation', 'title' => '快递账单对账'],
['slug' => 'courier-payables-report', 'title' => '快递应付表'],
['slug' => 'freight-difference', 'title' => '运费差'],
['slug' => 'other-surcharge-summary', 'title' => '其他附加费汇总'],

View File

@ -6,9 +6,23 @@ return [
'max_files_per_flow' => (int) env('DING_INVOICE_MAX_FILES_PER_FLOW', 30),
'max_file_bytes' => (int) env('DING_INVOICE_MAX_FILE_BYTES', 60 * 1024 * 1024),
'max_pdf_pages' => (int) env('DING_INVOICE_MAX_PDF_PAGES', 5),
'comment_fallback_limit' => (int) env('DING_INVOICE_COMMENT_FALLBACK_LIMIT', 20),
'comment_fallback_limit' => (int) env('DING_INVOICE_COMMENT_FALLBACK_LIMIT', 5),
'auto_scan_limit' => (int) env('DING_INVOICE_AUTO_SCAN_LIMIT', 5),
'failed_retry_minutes' => (int) env('DING_INVOICE_FAILED_RETRY_MINUTES', 60),
'partial_retry_minutes' => (int) env('DING_INVOICE_PARTIAL_RETRY_MINUTES', 360),
'max_scan_attempts' => (int) env('DING_INVOICE_MAX_SCAN_ATTEMPTS', 3),
'sync_with_oa_process' => filter_var(
env('DING_INVOICE_SYNC_WITH_OA_PROCESS', true),
FILTER_VALIDATE_BOOL,
),
'pdftotext_binary' => env('DING_INVOICE_PDFTOTEXT_BINARY', '/usr/bin/pdftotext'),
'pdftoppm_binary' => env('DING_INVOICE_PDFTOPPM_BINARY', '/usr/bin/pdftoppm'),
'tesseract_binary' => env('DING_INVOICE_TESSERACT_BINARY', '/usr/bin/tesseract'),
'tesseract_languages' => env('DING_INVOICE_TESSERACT_LANGUAGES', 'chi_sim+eng'),
'seven_zip_binary' => env('DING_INVOICE_7Z_BINARY', '/usr/bin/7z'),
'unar_binary' => env('DING_INVOICE_UNAR_BINARY', '/usr/bin/unar'),
'libreoffice_binary' => env('DING_INVOICE_LIBREOFFICE_BINARY', '/usr/bin/libreoffice'),
'max_archive_files' => (int) env('DING_INVOICE_MAX_ARCHIVE_FILES', 100),
'ocr' => [
'api_key' => env('DING_INVOICE_OCR_API_KEY', env('DEEPSEEK_API_KEY', '')),
'base_url' => env(

View File

@ -38,17 +38,8 @@ return [
'retry_sleep_ms' => (int) env('JST_RETRY_SLEEP_MS', 1000),
],
// 发货数据「导出明细」体积口径(对齐工作平台 OmsDataDay:明细体积默认 = 数量 × 长×宽×高)。
// 依据:工作平台 9.1-9.16 导出明细,非代发仓 8421/8421 行乘数量;代发仓走简尚线路快递的不乘数量。
// 合并口径体积不受此影响(单独存 m_volume_cm3)。
// 发货明细统一按单件尺寸体积 × 实发数量;合并优先使用出库视图已汇总的体积。
'detail_volume' => [
// 这些发货仓的明细体积不乘数量(工厂代发虚拟仓)
'no_qty_warehouses' => ['常州简尚家居有限公司'],
// 上述仓库中,用这些标准承运商发货时仍乘数量
'qty_carriers_in_no_qty_warehouses' => [
'中通快运', '韵达快递', '申通E物流', '安能物流', '邮政电商标快', '邮政快递包裹POSTB',
'壹米滴答', '百世物流', '德邦快递', '中通速递', '圆通速递',
],
// 这些快递的明细体积一律为 0
'zero_volume_expresses' => ['白云韵达-天猫亿家达', '中通礼品单'],
],

View File

@ -0,0 +1,7 @@
<?php
return [
'warehouse_aliases' => [
'简尚-山东青岗集仓' => '山东曹县',
],
];

View File

@ -447,6 +447,36 @@ return [
],
'operations_replica.rpt.jst_warehouseInfo' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_warehouseInfo', 'target' => 'ops_jst_warehouse_info', 'keys' => ['Id'], 'watermark' => 'updateTime', 'indexes' => [['wms_co_id', 'Id']]],
'operations_replica.rpt.jst_skumap' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_skumap', 'target' => 'ops_jst_sku_map', 'keys' => ['shop_id', 'shop_i_id', 'shop_sku_id'], 'watermark' => 'modifiedTime'],
// 供应商货款预估 › 退货明细:聚水潭采购退货主表与商品明细。
// 主表按更新时间和 2026-11-01 日期下限增量;明细无更新时间,每周全量校准。
'operations_replica.rpt.jst_purchaseout' => [
'source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_purchaseout',
'target' => 'ops_jst_purchaseout', 'keys' => ['Id'], 'watermark' => 'updateTime',
'minimum_datetime' => ['column' => 'io_date', 'value' => '2026-11-01 00:00:00'],
'full_reconcile_hours' => 168,
'indexes' => [['io_date', 'Id'], ['updateTime', 'Id']],
'columns' => [
'Id', 'io_id', 'io_date', 'status', 'so_id', 'warehouse', 'wms_co_id',
'remark', 'labels', 'l_id', 'creator_name', 'updateTime',
],
],
'operations_replica.rpt.jst_purchaseoutItem' => [
'source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_purchaseoutItem',
'target' => 'ops_jst_purchaseout_item', 'keys' => ['Id'], 'watermark' => null,
'parent_minimum_datetime' => [
'column' => 'io_date',
'value' => '2026-11-01 00:00:00',
'parent_dataset' => 'operations_replica.rpt.jst_purchaseout',
'child_key' => 'io_id',
'parent_key' => 'io_id',
],
'full_reconcile_hours' => 168,
'indexes' => [['io_id', 'Id'], ['sku_id', 'Id'], ['i_id', 'Id']],
'columns' => [
'Id', 'ioi_id', 'sku_id', 'i_id', 'name', 'properties_value', 'qty',
'cost_price', 'cost_amount', 'remark', 'io_id',
],
],
// item_id 是 nvarchar(100),镜像中按宽表策略保存为 LONGTEXT,不能进入普通索引。
'operations_replica.rpt.ads_itemid_sales_cost_ratio_v2_di' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'ads_itemid_sales_cost_ratio_v2_di', 'target' => 'ops_item_sales_cost_ratio', 'keys' => ['stat_date', 'item_id'], 'watermark' => 'item_id_update', 'indexes' => [['stat_date', 'push_fee']]],
'operations_replica.rpt.jst_returnAndRefundInfo' => [

View File

@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\TaobaoWechatOpeningBalanceRepository;
use Modules\EcommerceFinance\Support\TaobaoWechatBackofficeJuneEndingBalances;
return new class extends Migration
{
private const STORE_NAME = '淘宝-平提家具源头工厂';
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
if (! $connection->getSchemaBuilder()->hasTable(TaobaoWechatOpeningBalanceRepository::TABLE)) {
return;
}
$balance = TaobaoWechatBackofficeJuneEndingBalances::balances()[self::STORE_NAME] ?? null;
if ($balance === null) {
return;
}
$importedAt = now();
$connection->table(TaobaoWechatOpeningBalanceRepository::TABLE)->updateOrInsert(
[
'balance_date' => TaobaoWechatBackofficeJuneEndingBalances::AS_OF_DATE,
'store_name' => self::STORE_NAME,
],
[
'balance' => $balance,
'source' => TaobaoWechatBackofficeJuneEndingBalances::SOURCE,
'source_note' => TaobaoWechatBackofficeJuneEndingBalances::SOURCE_NOTE,
'imported_at' => $importedAt,
'updated_at' => $importedAt,
'created_at' => $importedAt,
],
);
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'))
->table(TaobaoWechatOpeningBalanceRepository::TABLE)
->where('balance_date', TaobaoWechatBackofficeJuneEndingBalances::AS_OF_DATE)
->where('store_name', self::STORE_NAME)
->delete();
}
};

View File

@ -0,0 +1,72 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private const TABLE = 'supplier_payable_overrides';
private const INDEX = 'supplier_payable_override_latest';
public function up(): void
{
$schema = Schema::connection(config('database.supplier_payable_maintenance_connection'));
if ($schema->getConnection()->getDriverName() !== 'mysql' || ! $schema->hasTable(self::TABLE)) {
return;
}
$connection = $schema->getConnection();
if (! $schema->hasColumn(self::TABLE, 'summary_month_key')) {
$connection->statement(
"ALTER TABLE `" . self::TABLE . "`
ADD COLUMN `summary_month_key` VARCHAR(7)
GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.summary_month'))) STORED,
ADD COLUMN `record_date_key` VARCHAR(10)
GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.date'))) STORED"
);
}
$indexes = collect($connection->select('SHOW INDEX FROM `' . self::TABLE . '`'))
->pluck('Key_name')
->map(static fn (mixed $name): string => (string) $name);
if (! $indexes->contains(self::INDEX)) {
$schema->table(self::TABLE, function (Blueprint $table): void {
$table->index(
['company_id', 'dataset', 'summary_month_key', 'record_date_key', 'id'],
self::INDEX,
);
});
}
}
public function down(): void
{
$schema = Schema::connection(config('database.supplier_payable_maintenance_connection'));
if ($schema->getConnection()->getDriverName() !== 'mysql' || ! $schema->hasTable(self::TABLE)) {
return;
}
$indexes = collect($schema->getConnection()->select('SHOW INDEX FROM `' . self::TABLE . '`'))
->pluck('Key_name')
->map(static fn (mixed $name): string => (string) $name);
if ($indexes->contains(self::INDEX)) {
$schema->table(self::TABLE, function (Blueprint $table): void {
$table->dropIndex(self::INDEX);
});
}
$columns = [];
foreach (['summary_month_key', 'record_date_key'] as $column) {
if ($schema->hasColumn(self::TABLE, $column)) {
$columns[] = 'DROP COLUMN `' . $column . '`';
}
}
if ($columns !== []) {
$schema->getConnection()->statement(
'ALTER TABLE `' . self::TABLE . '` ' . implode(', ', $columns)
);
}
}
};

View File

@ -0,0 +1,70 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if ($schema->hasTable('promotion_expense_daily_rows')) {
return;
}
$schema->create('promotion_expense_daily_rows', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->date('report_date');
$table->string('platform', 64);
$table->string('store_name', 255);
$table->unsignedBigInteger('source_rows')->default(0);
$table->decimal('push_fee', 20, 2)->default(0);
$table->decimal('shared_push_fee', 20, 2)->default(0);
$table->decimal('push_fee_total', 20, 2)->default(0);
$table->decimal('marketing_fee', 20, 2)->default(0);
$table->decimal('shared_marketing_fee', 20, 2)->default(0);
$table->decimal('marketing_fee_total', 20, 2)->default(0);
$table->decimal('total_fee', 20, 2)->default(0);
$table->timestamp('synced_at')->useCurrent();
$table->unique(
['report_date', 'platform', 'store_name'],
'promotion_expense_daily_unique',
);
$table->index(
['report_date', 'platform'],
'promotion_expense_date_platform_index',
);
$table->index(
['platform', 'report_date'],
'promotion_expense_platform_date_index',
);
$table->index(
['store_name', 'report_date'],
'promotion_expense_store_date_index',
);
});
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
Schema::connection($this->connection())->dropIfExists('promotion_expense_daily_rows');
}
};

View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('ding_invoice_flow_mirror')) {
return;
}
$schema->table('ding_invoice_flow_mirror', function (Blueprint $table) use ($schema): void {
if (! $schema->hasColumn('ding_invoice_flow_mirror', 'scan_attempts')) {
$table->unsignedInteger('scan_attempts')->default(0);
}
if (! $schema->hasColumn('ding_invoice_flow_mirror', 'next_scan_at')) {
$table->dateTime('next_scan_at', 6)->nullable();
}
});
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('ding_invoice_flow_mirror')) {
return;
}
$columns = [];
foreach (['scan_attempts', 'next_scan_at'] as $column) {
if ($schema->hasColumn('ding_invoice_flow_mirror', $column)) {
$columns[] = $column;
}
}
if ($columns !== []) {
$schema->table('ding_invoice_flow_mirror', function (Blueprint $table) use ($columns): void {
$table->dropColumn($columns);
});
}
}
};

View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('ding_invoice_record_mirror')) {
return;
}
$schema->table('ding_invoice_record_mirror', function (Blueprint $table) use ($schema): void {
if (! $schema->hasColumn('ding_invoice_record_mirror', 'preview_path')) {
$table->string('preview_path', 1024)->nullable();
}
if (! $schema->hasColumn('ding_invoice_record_mirror', 'preview_mime')) {
$table->string('preview_mime', 100)->nullable();
}
});
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('ding_invoice_record_mirror')) {
return;
}
$columns = [];
foreach (['preview_path', 'preview_mime'] as $column) {
if ($schema->hasColumn('ding_invoice_record_mirror', $column)) {
$columns[] = $column;
}
}
if ($columns !== []) {
$schema->table('ding_invoice_record_mirror', function (Blueprint $table) use ($columns): void {
$table->dropColumn($columns);
});
}
}
};

View File

@ -0,0 +1,51 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
$schema = Schema::connection('business_mirror');
$schema->create('courier_unshipped_waybills', function (Blueprint $table): void {
$table->id();
$table->string('source', 32);
$table->string('waybill_no', 96)->index();
$table->string('evidence_no', 96);
$table->dateTime('evidence_time')->index();
foreach (['courier_name', 'trade_no', 'o_id', 'shop_name', 'new_courier_name', 'new_waybill_no', 'operator'] as $column) {
$table->string($column)->nullable();
}
$table->text('evidence_text')->nullable();
$table->unique(['source', 'evidence_no', 'waybill_no'], 'unshipped_source_evidence_waybill');
});
$schema->create('courier_unshipped_sync', function (Blueprint $table): void {
$table->string('source', 32)->primary();
$table->dateTime('last_success_at')->nullable();
$table->unsignedInteger('row_count')->default(0);
$table->unsignedInteger('missing_count')->default(0);
$table->string('warning')->nullable();
});
$schema->create('courier_unshipped_order_logs', function (Blueprint $table): void {
$table->id();
$table->string('order_no', 96);
$table->dateTime('operated_at')->index();
$table->string('old_waybill', 96);
$table->string('new_waybill', 96);
$table->string('old_courier');
$table->string('new_courier');
$table->string('operator')->nullable();
$table->text('remark');
$table->unique(['order_no', 'operated_at', 'old_waybill'], 'unshipped_log_identity');
});
}
public function down(): void
{
$schema = Schema::connection('business_mirror');
$schema->dropIfExists('courier_unshipped_order_logs');
$schema->dropIfExists('courier_unshipped_sync');
$schema->dropIfExists('courier_unshipped_waybills');
}
};

View File

@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('shipping_measured_weights', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('company_id');
$table->string('carrier_name', 128);
$table->string('barcode', 128);
$table->decimal('weight_kg', 12, 4);
$table->unsignedBigInteger('updated_by');
$table->timestamps();
$table->unique(['company_id', 'carrier_name', 'barcode'], 'shipping_measured_weights_lookup');
});
}
public function down(): void
{
Schema::dropIfExists('shipping_measured_weights');
}
};

View File

@ -0,0 +1,74 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if ($schema->hasTable('ding_invoice_attachment_mirror')) {
return;
}
$schema->create('ding_invoice_attachment_mirror', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('source_scope', 40)->default('personal_permission');
$table->string('business_id', 32);
$table->string('paid_month', 7)->default('');
$table->string('attachment_key', 64);
$table->string('process_instance_id', 100)->nullable();
$table->string('source_file_id', 100)->nullable();
$table->string('source_file_name', 255);
$table->string('source_file_type', 32)->nullable();
$table->string('source_field', 255)->nullable();
$table->string('source_origin', 24)->default('form');
$table->unsignedBigInteger('source_size')->default(0);
$table->string('source_hash', 64)->nullable();
$table->string('source_path', 1024)->nullable();
$table->string('preview_path', 1024)->nullable();
$table->string('preview_mime', 100)->nullable();
$table->string('ocr_status', 24)->default('pending');
$table->string('ocr_provider', 100)->nullable();
$table->unsignedInteger('invoice_count')->default(0);
$table->text('last_error')->nullable();
$table->dateTime('downloaded_at', 6)->nullable();
$table->timestamps();
$table->unique(
['source_scope', 'business_id', 'attachment_key'],
'ding_invoice_attachment_scope_business_key_unique',
);
$table->index(
['source_scope', 'paid_month', 'business_id'],
'ding_invoice_attachment_scope_month_business_index',
);
$table->index(
['source_scope', 'ocr_status'],
'ding_invoice_attachment_scope_status_index',
);
});
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
Schema::connection($this->connection())->dropIfExists('ding_invoice_attachment_mirror');
}
};

View File

@ -0,0 +1,47 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('ding_invoice_attachment_mirror')
|| $schema->hasColumn('ding_invoice_attachment_mirror', 'raw_path')) {
return;
}
$schema->table('ding_invoice_attachment_mirror', function (Blueprint $table): void {
$table->string('raw_path', 1024)->nullable()->after('source_path');
});
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if ($schema->hasTable('ding_invoice_attachment_mirror')
&& $schema->hasColumn('ding_invoice_attachment_mirror', 'raw_path')) {
$schema->table('ding_invoice_attachment_mirror', function (Blueprint $table): void {
$table->dropColumn('raw_path');
});
}
}
};

View File

@ -0,0 +1,141 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 快递账单对账(第一期:运费)与快递应付汇总的结果表。
*
* 只存本功能自己产生的数据:上传的账单行、对账分类、小汇总、结算台账和月度应付汇总;
* 发货数据、核算运费、未发出明细都按需从已有镜像表读取,不复制。
*/
return new class extends Migration {
public function up(): void
{
$schema = Schema::connection('business_mirror');
$schema->create('courier_bill_groups', function (Blueprint $table): void {
$table->id();
$table->string('name', 128)->unique()->comment('对账分组名称');
$table->text('express_names')->comment('JSON:发货数据快递名称1 列表');
$table->string('summary_carrier', 128)->nullable()->comment('小汇总落到快递应付汇总的承运商');
$table->string('owner', 64)->nullable()->comment('负责人');
$table->string('keywords', 255)->nullable()->comment('文件名识别关键字,逗号分隔');
$table->string('waybill_header', 64)->nullable()->comment('账单单号列表头(不填自动识别)');
$table->string('amount_header', 64)->nullable()->comment('账单运费列表头(不填自动识别)');
$table->string('weight_header', 64)->nullable()->comment('账单重量列表头(不填自动识别)');
$table->timestamps();
});
$schema->create('courier_bill_statements', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('group_id');
$table->char('bill_month', 7)->comment('账单月份 YYYY-MM');
$table->string('status', 16)->default('open')->comment('open 对账中 / confirmed 已确认结算');
$table->unsignedInteger('line_count')->default(0);
$table->decimal('bill_amount', 16, 2)->default(0);
$table->dateTime('matched_at')->nullable();
$table->dateTime('confirmed_at')->nullable();
$table->string('confirmed_by', 64)->nullable();
$table->timestamps();
$table->unique(['group_id', 'bill_month'], 'courier_bill_statement_group_month');
$table->index('bill_month');
});
$schema->create('courier_bill_files', function (Blueprint $table): void {
$table->id();
$table->char('bill_month', 7)->index();
$table->unsignedBigInteger('group_id')->nullable();
$table->unsignedBigInteger('statement_id')->nullable()->index();
$table->string('original_name', 255);
$table->string('stored_path', 255);
$table->string('status', 16)->comment('pending_group 待选分组 / parsed 已读入 / failed 读取失败');
$table->text('sheets')->nullable()->comment('JSON:各工作表表头行与识别出的列');
$table->unsignedInteger('row_count')->default(0);
$table->decimal('amount', 16, 2)->default(0);
$table->unsignedInteger('rejected_count')->default(0);
$table->text('rejected_rows')->nullable()->comment('JSON:拒收行(最多 50 条)');
$table->string('message', 255)->nullable();
$table->string('uploaded_by', 64)->nullable();
$table->timestamps();
});
$schema->create('courier_bill_lines', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('statement_id');
$table->unsignedBigInteger('file_id');
$table->string('sheet', 64);
$table->unsignedInteger('row_no');
$table->string('waybill_no', 96)->index();
$table->decimal('bill_amount', 14, 2)->nullable();
$table->decimal('bill_weight', 14, 4)->nullable();
$table->longText('raw')->comment('JSON:账单原始列(与文件表头对应)');
$table->string('category', 32)->nullable();
$table->char('category_month', 7)->nullable()->comment('前月补提供/跨月订单的发货月份');
$table->dateTime('ship_time')->nullable();
$table->string('express_name', 128)->nullable()->comment('发货数据快递名称1');
$table->decimal('calc_freight', 14, 2)->nullable()->comment('核算运费');
$table->decimal('charge_weight', 14, 4)->nullable()->comment('计费重量');
$table->string('unshipped_sources', 128)->nullable();
$table->decimal('self_amount', 14, 2)->nullable()->comment('自算金额');
$table->string('resolution', 16)->nullable()->comment('agree 同意付款 / exclude 剔除 / defer 转下月');
$table->string('resolved_by', 64)->nullable();
$table->dateTime('resolved_at')->nullable();
$table->index(['statement_id', 'category'], 'courier_bill_lines_statement_category');
});
$schema->create('courier_bill_unprovided', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('statement_id')->index();
$table->string('waybill_no', 96);
$table->dateTime('ship_time')->nullable();
$table->string('express_name', 128)->nullable();
$table->decimal('calc_freight', 14, 2)->nullable();
});
$schema->create('courier_bill_summary_items', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('statement_id')->index();
$table->string('label', 255);
$table->decimal('bill_amount', 16, 2)->nullable()->comment('快递提供金额');
$table->decimal('self_amount', 16, 2)->nullable()->comment('自算金额');
$table->boolean('manual')->default(false);
$table->unsignedInteger('sort')->default(0);
});
$schema->create('courier_bill_ledger', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('group_id');
$table->string('waybill_no', 96)->index();
$table->char('settle_month', 7);
$table->decimal('amount', 14, 2)->nullable();
$table->unsignedBigInteger('statement_id')->nullable()->index()->comment('空 = 历史导入');
$table->dateTime('created_at')->nullable();
$table->unique(['group_id', 'waybill_no', 'settle_month'], 'courier_bill_ledger_identity');
});
$schema->create('courier_payable_summary_rows', function (Blueprint $table): void {
$table->id();
$table->char('month', 7);
$table->unsignedInteger('sort');
$table->string('carrier', 128)->comment('承运商');
$table->longText('cells')->comment('JSON:快递汇总表各列(按表头)');
$table->string('statement_ids', 255)->nullable()->comment('已归集的对账单');
$table->timestamps();
$table->unique(['month', 'sort'], 'courier_payable_summary_month_sort');
$table->index(['month', 'carrier'], 'courier_payable_summary_month_carrier');
});
}
public function down(): void
{
$schema = Schema::connection('business_mirror');
foreach ([
'courier_payable_summary_rows', 'courier_bill_ledger', 'courier_bill_summary_items', 'courier_bill_unprovided',
'courier_bill_lines', 'courier_bill_files', 'courier_bill_statements', 'courier_bill_groups',
] as $name) {
$schema->dropIfExists($name);
}
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 快递账单对账:分组加「合并账单」,账单文件记下额外指定的分组。
*
* 有的快递把几家的账单放在一张表里发来(10 月手工对账里一个文件做了几个小汇总),
* 「合并账单」相同的分组,上传后按发货数据的快递名称1 拆到各自分组。
*/
return new class extends Migration {
public function up(): void
{
$schema = Schema::connection('business_mirror');
if (! $schema->hasColumn('courier_bill_groups', 'bundle')) {
$schema->table('courier_bill_groups', function (Blueprint $table): void {
$table->string('bundle', 128)->nullable()->after('summary_carrier')->comment('合并账单:同名的分组账单放在一张表里发来');
});
}
if (! $schema->hasColumn('courier_bill_files', 'extra_group_ids')) {
$schema->table('courier_bill_files', function (Blueprint $table): void {
$table->text('extra_group_ids')->nullable()->after('group_id')->comment('JSON:上传时额外指定、可拆入的分组');
});
}
}
public function down(): void
{
$schema = Schema::connection('business_mirror');
$schema->table('courier_bill_files', fn (Blueprint $table) => $table->dropColumn('extra_group_ids'));
$schema->table('courier_bill_groups', fn (Blueprint $table) => $table->dropColumn('bundle'));
}
};

View File

@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 快递账单的运费常带 3 位小数(如 20.408),按 2 位存会逐行四舍五入,合计和账单对不上。
* 账单行与小汇总的快递提供金额改存 4 位小数;保留原整数位数,不回填历史金额。
*/
return new class extends Migration {
public function up(): void
{
Schema::connection('business_mirror')->table('courier_bill_lines', function (Blueprint $table): void {
$table->decimal('bill_amount', 16, 4)->nullable()->change();
});
Schema::connection('business_mirror')->table('courier_bill_summary_items', function (Blueprint $table): void {
$table->decimal('bill_amount', 18, 4)->nullable()->comment('快递提供金额')->change();
});
}
public function down(): void
{
// 精度加宽向后兼容,不回缩,避免截断已有数据。
}
};

View File

@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::connection('business_mirror')->table('courier_bill_lines', function (Blueprint $table): void {
$table->index(['file_id', 'waybill_no'], 'courier_bill_lines_file_waybill');
});
}
public function down(): void
{
Schema::connection('business_mirror')->table('courier_bill_lines', function (Blueprint $table): void {
$table->dropIndex('courier_bill_lines_file_waybill');
});
}
};

View File

@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 快递账单里的附加费(上楼费、拦截费、超长费……):第一期不逐单核对,只把快递开的金额按单号存下来,
* 按费用项目进对账单小汇总,让「快递提供金额」和账单总额一致。
*/
return new class extends Migration {
public function up(): void
{
Schema::connection('business_mirror')->create('courier_bill_surcharges', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('file_id')->index();
$table->string('sheet', 100);
$table->unsignedInteger('row_no');
$table->string('waybill_no', 96)->index();
$table->string('item', 100)->comment('费用项目');
$table->decimal('amount', 16, 4)->nullable();
});
}
public function down(): void
{
Schema::connection('business_mirror')->dropIfExists('courier_bill_surcharges');
}
};

View File

@ -1,14 +1,15 @@
FROM m.daocloud.io/docker.io/library/php:8.3.36-apache-bookworm@sha256:cbd3b3d9011668443d54ab40ec31db56c73d91b4c8198935d639aa80d2d815c1 AS php-base
# 国内构建机访问 deb.debian.org 常被代理拦截(502),统一改用清华 Debian 镜像。
# 国内构建机访问 Debian 官方源常被代理拦截(502),统一改用腾讯云镜像。
RUN set -eu; \
for f in /etc/apt/sources.list /etc/apt/sources.list.d/*.sources /etc/apt/sources.list.d/*.list; do \
[ -f "$f" ] || continue; \
sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g; s|security.debian.org|mirrors.tuna.tsinghua.edu.cn|g' "$f"; \
sed -i 's|deb.debian.org|mirrors.cloud.tencent.com|g; s|security.debian.org|mirrors.cloud.tencent.com|g; s|http://mirrors.cloud.tencent.com|https://mirrors.cloud.tencent.com|g' "$f"; \
done
RUN apt-get -o Acquire::Retries=3 update \
&& apt-get -o Acquire::Retries=3 install -y --no-install-recommends \
RUN set -eu; \
apt-get -o Acquire::Retries=5 update; \
apt_packages="\
curl \
libcurl4-openssl-dev \
libfreetype6-dev \
@ -18,14 +19,28 @@ RUN apt-get -o Acquire::Retries=3 update \
libpng-dev \
libxml2-dev \
libzip-dev \
libreoffice-calc \
p7zip-full \
poppler-data \
poppler-utils \
tesseract-ocr \
tesseract-ocr-chi-sim \
unar \
freetds-bin \
freetds-dev \
tdsodbc \
unixodbc-dev \
unzip \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
unzip"; \
attempt=1; \
while ! apt-get -o Acquire::Retries=5 install -y --no-install-recommends $apt_packages; do \
if [ "$attempt" -ge 3 ]; then \
exit 1; \
fi; \
attempt=$((attempt + 1)); \
sleep 3; \
apt-get -o Acquire::Retries=5 update; \
done; \
docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-configure pdo_odbc --with-pdo-odbc=unixODBC,/usr \
&& docker-php-ext-install -j2 \
bcmath \
@ -92,6 +107,7 @@ FROM php-base AS runtime
RUN apt-get -o Acquire::Retries=3 update \
&& apt-get -o Acquire::Retries=3 install -y --no-install-recommends \
acl \
fonts-wqy-zenhei \
libpq-dev \
&& docker-php-ext-install -j2 pdo_pgsql \
&& rm -rf /var/lib/apt/lists/*

View File

@ -30,8 +30,13 @@ RUN apt-get update \
libpng-dev \
libxml2-dev \
libzip-dev \
libreoffice-calc \
p7zip-full \
poppler-data \
poppler-utils \
tesseract-ocr \
tesseract-ocr-chi-sim \
unar \
freetds-bin \
tdsodbc \
unixodbc-dev \

View File

@ -215,6 +215,8 @@ CRON_TZ=Asia/Shanghai
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1
0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1
# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。
10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。
10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1
# 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。
@ -222,6 +224,7 @@ CRON_TZ=Asia/Shanghai
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。
50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1
@ -250,7 +253,8 @@ CRON_TZ=Asia/Shanghai
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=3 >/dev/null 2>&1
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1
# 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。
28 21 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=3 >/dev/null 2>&1
# 头条放心购(店铺收款账户账单 › 抖音账户)资金流水:每天 09:30 定点把该渠道所用
@ -263,8 +267,8 @@ CRON_TZ=Asia/Shanghai
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转,
# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。
# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票;
# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。
cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'
CRON_TZ=Asia/Shanghai

View File

@ -219,6 +219,8 @@ CRON_TZ=Asia/Shanghai
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1
0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1
# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。
10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。
10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1
# 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。
@ -226,6 +228,7 @@ CRON_TZ=Asia/Shanghai
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。
50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1
@ -254,7 +257,8 @@ CRON_TZ=Asia/Shanghai
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=3 >/dev/null 2>&1
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1
# 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。
28 21 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=3 >/dev/null 2>&1
# 头条放心购(店铺收款账户账单 › 抖音账户)资金流水:每天 09:30 定点把该渠道所用
@ -267,8 +271,8 @@ CRON_TZ=Asia/Shanghai
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转,
# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。
# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票;
# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。
cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'
CRON_TZ=Asia/Shanghai

View File

@ -39,6 +39,7 @@
"business-mirror:import-pdd-platform-balances",
"ding:import-process-details",
"ding-invoices:import",
"ding-invoices:import-attachments",
"jst-order-labels:import-planting-rules",
"jst-order-labels:import",
"jst-order-labels:sync-daily",
@ -47,6 +48,7 @@
"planting-details:sync-work-orders",
"planting-details:import",
"payables:unpriced-cycle",
"payables:final-import",
"product-catalog:import-authoritative-export",
"product:monthly-weighted-average:base",
"store-violations:import-rules",

View File

@ -8,8 +8,9 @@ is_import=0
CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
*:import|*:import-*|*:import:*|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
esac
case "${1:-}" in

View File

@ -16,10 +16,12 @@
| 状态 | 说明 |
| --- | --- |
| 本次修正 | “发票数据 → 发票明细”继续读取共享镜像 `ding_invoice_flow_mirror` 与 `ding_invoice_record_mirror`。钉钉附件抓取改为增量合并:已确认的台账发票不会被后续 OCR 失败或空附件覆盖,新识别附件只补充来源链接和缺失字段;同销售方同金额但发票号码不同的记录不下沉为同一张。识别支持 PDF 文本、图片 OCR(外部视觉接口或服务器 Tesseract)、XLSX 内嵌图片、ZIP/RAR/7Z 压缩包,XLS 通过 LibreOffice 转为 PDF 后识别。页面手动抓取仍可强制刷新;后台每 15 分钟自动选取最近一个待抓月份,每轮最多处理 20 个流程。 |
| 本次接入 | 票聚“销方管理”的 `可用发票额度(税局)`、`可用额度最新获取时间`、授权状态和纳税人识别号通过 `https://api.erp321.com/fp/fms/company/seller/page` 同步到 `piaoju_seller_quota_snapshots`;同步命令为 `piaoju:sync-invoice-quotas`,每 15 分钟执行一次,失败保留上一版。发票额度页按开票主体名称匹配票聚销方,不再用“本地开票额度 - 销项金额”冒充最新可用额度;未授权、授权过期、未匹配或票聚未返回值时显示明确状态。会话 Cookie 只放被 Git 忽略的 `runtime/private/piaoju-cookie.txt` 或服务器私有环境变量,不进入代码、日志和 PR。 |
| 本次接入 | 顾家过账基础数据读取聚水潭“销售主题分析(新版)→ 商品利润 → 明细(订单商品)”10 月导出,仅保留天猫、京东、拼多多和抖音的 12 家 HX 旗舰店,写入 `kuka_posting_base_rows`;导入摘要写入 `kuka_posting_base_imports`。只保存前 40 个聚水潭原始字段,后续成本映射、报价和过账分类不混入基础数据。XLSX 通过 `business-mirror:import-kuka-posting-base` 流式读取,校验 12 家店铺均有数据后,在单一事务内整月替换;文件缺失、字段错误或中断时保留上一版。当前 2026 年 10 月导出为 13,949 行。 |
| 本次接入 | `furniture3d_prod` PostgreSQL 只读库用于顾家发货明细映射:物料编号优先使用 `public.BarcodePrintImportRecord.updates.materialNo`,其次用 `public.SupplyChainProductArchive.sku` 对应聚水潭“货号”并校验候选 `barcode`,最后按 `updates.brandSkuCode` 对应报价单物料描述前缀回退;命中后必须存在报价单生效 `MaterialNumber`。同一物料编号允许多个货号共用,只要求单个货号内部候选唯一。页面“货号”先用聚水潭“款式编码”匹配 `BarcodePrintImportRecord.normalizedSku` 并取最新非空 `updates.brandSkuCode`;款式编码未命中时再用原始“货号”匹配同一张表;两级都未命中时保留聚水潭原货号。因此同一款式编码下的多个原始货号共享款式品牌货号,个别只有货号品牌映射的记录也能回退命中。物料编号和成本始终按聚水潭原始货号计算。款式和货号的品牌紧凑结果分别写入 `kuka_posting_brand_item_map_rows`、`kuka_posting_item_brand_item_map_rows`,物料映射写入 `kuka_posting_material_map_rows`;不复制整库、不在页面直连上游。每日 05:50 执行 `business-mirror:sync-kuka-posting-material-map`。 |
| 本次接入 | 钉钉考勤 `attendance/list` 按财务中心在职成员同步到 `ding_attendance_records`,保留打卡记录 ID、用户、工作日期、上下班类型、打卡结果、审批标识、审批实例和打卡时间;每 15 分钟回看 35 天,按 7 天窗口和 50 人上限分页。钉钉排班通过 `getScheduleByRange` 同步到 `ding_attendance_schedule_records`,保留逐日排班 ID、用户、考勤组、班次、是否休息、变更状态和完整源数据;本机脚本为 `scripts/sync-ding-attendance-schedules.py`,导入命令为 `business-mirror:import-ding-attendance-schedules`,默认覆盖最近 95 天,查询不完整时拒绝覆盖旧镜像。日志漏写扣分只统计钉钉排班明确为工作日的日期,并继续排除没有日志但有“请假 / 休息 / 调休”等审批标记的日期;排班或考勤镜像未完成时扣分暂不计算,周五、周末或法定班次调整均以公司真实排班为准。依赖权限 `qyapi_attendance_isv_query_result`、`qyapi_get_attendance_data`。 |
| 本次接入 | 供应商货款预估 › 退货明细读取 `operations_replica/rpt.jst_purchaseout + rpt.jst_purchaseoutItem`,镜像为 `ops_jst_purchaseout`、`ops_jst_purchaseout_item`。主表按 `updateTime` 增量、明细按稳定 `Id` 追加并每周全量校准,两个数据集均固定 `io_date >= 2026-11-01`;页面只展示已确认记录,剔除商品编码 `DF-` 前缀,供应商从 `ops_jst_sku` 同条码最新普通商品资料补齐。备注含“质检退厂”时“标记多标签”固定为该值,其余保留源标签。表头沿用供应商应付(终版)退货对账 21 列;工作平台单价优先取变价后价格,其次当前定价,没有金额的记录才按采购退货成本及商品资料成本补预估。 |
| 已完成 | `operations_replica/rpt.Bulk_Price_Limit` 已进入类型化表 `product_price_mirror_rows`,商品价格页面已读取镜像并支持完整分页。 |
| 已完成 | `operations_replica/rpt.jst_sku` 已进入 `ops_jst_sku`,普通商品资料页面固定读取 `sku_type = normal` 的共享镜像,并支持稳定分页和业务筛选。 |
| 本次接入 | 聚水潭进销存共享镜像读取 `jiansun/dbo.jst_inoutWater + dbo.jst_inoutWaterItem + dbo.jst_inventoryInfo` 的全部仓库,保留 2026-08-01 起的已确认流水与库存锚点。“快递应付 / 三方仓进销存”在查询层继续固定 `wms_co_id = 15045364`;“商品价格管理 / 进销存报表”按所有仓库、商品和月份汇总。 |
@ -43,6 +45,7 @@
| 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 |
| 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 |
| 待有效凭据后首次同步 | 普通商品当前成本价、商品类型和更新时间继续读取 `operations_replica.rpt.jst_sku`;`rpt.fys_skuCostPriceUpdate` 是一 SKU 一行的旧快照,不能充当变价历史。完整成本价变更仍读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;经典接口必须在服务器私有配置中使用同一应用的 `JUSHUITAN_PARTNER_ID / JUSHUITAN_PARTNER_KEY / JUSHUITAN_TOKEN`,不得把新开放平台的 App Key / App Secret / Access Token 混用。页面在首次同步完成前明确显示待同步或失败,不把 0 条解释为真实无历史。 |
| 本次接入 | 财务经营报表 › 推广费用从 `operations_replica.rpt.dws_sn_sales_full_info_di` 按“日期 + 平台 + 店铺”汇总推广费用、营销费用及各自直接/分摊金额,写入 `promotion_expense_daily_rows`;页面只读共享镜像。生产每天 03:10 自动重算最近 7 天并整日替换,覆盖迟到改单与删除;首次历史从 2026-01-01 起用 `business-mirror:sync-promotion-expenses --full` 补入。 |
| 本次接入 | 流程明细读取 `operations_replica/rpt.ding_Workflow + rpt.ding_WorkflowScheme` 的结构化审批主表、费用明细和付款明细,写入 `ding_process_detail_mirror`、`ding_process_payment_mirror` 与付款按明细行分摊的 `ding_process_payment_line_mirror`;主表的 `originatorDeptName` 作为发起人部门单独保留,费用明细行的“店铺”字段规范化写入 `store_name`。审批表单表头的 `收款人全称 / 开户银行 / 银行账号` 分别写入 `payee_name / payee_bank_name / payee_bank_account`,同一审批下的每条费用明细继承对应值;行级或付款明细存在更具体值时优先使用。禁止先把明细表和付款表铺平成 CSV 后逐行求和;付款明细必须按“对应序号”关联到代表明细行,但合计始终读取独立付款事实。管理费用按分摊后的付款月份统计,跨月分笔付款不会把整张审批重复计入多月。每个纳入范围的源审批至少保留一条页面记录,没有费用金额的审批以空金额显示,不静默隐藏。首次全量先运行 `business-mirror:sync-ding-process-details --full --dry-run` 校验,再使用 `business-mirror:sync-ding-process-details --full` 发布;日常通过 `updateAt/createAt` 48 小时重叠增量同步。当前纳入日常报销、应付、线上代发、种菜、快递面单、固定资产、日常物品、样品、一次性采买、板材、工资、外贸费用和种菜充值等 14 个财务流程;发现新的明细流程编码时全量同步报错并保留上一版。 |
| 本次接入 | 财务经营报表 › 管理费用使用 `oa_process_account_mapping` 保存流程科目映射;当前快照包含原工作簿 191 个科目和补充的 `5601.11.01 货代费`、`1221.07 种菜备用金`、`5602.11.03.19 AI阿里云软件费`,共 194 个科目,其中 37 个进费比科目和 126 个分摊规则。页面按打款时间提供整月选择并默认展示上个月 OA 流程中审批状态为“已完成”、涉及付款且出纳已打款的明细,不涉及付款或出纳未打款的数据不进入汇总,按费用大类和二级汇总进费比/不进费比/未映射金额,点击二级查看三级汇总与 9 列明细模板。审批完成时间写入 `ding_process_detail_mirror.approval_finished_at`,页面月份筛选使用 `ding_process_detail_mirror.paid_at`;钉钉副本把费用明细表保存为未命名字段时,按配置中的金额列识别包含该列的未命名表格组件,避免只抓到付款明细而漏掉费用科目和金额。明细行没有科目时,使用同一审批表单表头的 `科目编码 / 科目名称` 回填;行级科目始终优先。 |
| 本次接入 | 订单利润的包材费、快递费、账单费用直接读取聚胜算订单利润页面接口 `pf.erp321.com/WebApi/PF/OrderSku/GetOrderSkuList`(支付/发货时间口径各分页抓取),导入 `ops_shengsuan_order_profit_rows`,页面按“店铺 + 线上/内部单号”原样回填,不把 0 或推算值写入缺口。异常订单再通过 `GetPfOrderDetList` 按每批最多 50 单抓取完整订单商品明细,保存至 `ops_shengsuan_order_profit_detail_snapshots`,包括全部订单字段、销售商品明细、退货商品明细和缺成本商品编码。主表抓取脚本为 `scripts/order-profit-shengsuan-sync.py`,明细补同步脚本为 `scripts/order-profit-shengsuan-details-sync.py`;导入命令分别为 `order-profit:import-shengsuan-rows`、`order-profit:import-shengsuan-details`。脚本依赖本机已登录胜算的 Chrome 调试窗口,不能由服务器容器直连页面。`成本/运费异常`按主表“商品成本或快递费任一为0/空”筛选,分别标记“成本异常”“运费异常”,并在订单下按具体商品编码展示缺成本条码,以发货时间为监控日期。 |
@ -112,7 +115,7 @@
| 板材 | `dbo.finance_boardDeduction`、`dbo.pm_plainPlateData`、`dbo.pm_boardPurchasePrice`、`dbo.pm_boardPriceChangeImport`、`dbo.pm_boardApplyDetail` |
| 封边条 | `dbo.pm_edgeBandData`、`dbo.pm_edgeBandApplyDetail`、`dbo.pm_edgeBandProfitInfo`、`dbo.finance_edgeBandDeductio`、`dbo.pm_averageUnitPrice` |
| 库存与货款对账 | `dbo.pm_boardInventoryDetail_snapshot`、`dbo.fys_supplierGoods_sttlement_purchase`、`dbo.fys_supplierGoods_sttlement_sale`、`dbo.pm_purchaseIn` |
| 供应商货款预估 | `dbo.jst_purchaseReceiving`(`io_date >= 2026-10-01`,`Id` 稳定键、`updateTime` 增量)与 `dbo.jst_purchaseReceivingItem`(按 `io_id` 关联父表,`Id` 稳定键,按父表日期下限断点同步);页面固定剔除仓库“配件单仓”、采购单号为空、供应商“虚拟/简尚送货”及商品编码 `DF-` 前缀。单价取 `dbo.pm_priceAdjustment_log` 同 SKU 最新 `priceType=1` 的 `afterPrice`,未匹配按 0 展示。 |
| 供应商货款预估 | `dbo.jst_purchaseReceiving`(`io_date >= 2026-10-01`,`Id` 稳定键、`updateTime` 增量)与 `dbo.jst_purchaseReceivingItem`(按 `io_id` 关联父表,`Id` 稳定键,按父表日期下限断点同步);页面固定剔除仓库“配件单仓”、采购单号为空、供应商“虚拟/简尚送货”及商品编码 `DF-` 前缀。货款明细同时合并共享镜像 `jst_oms_shipping` 的逐商品发货明细,只保留 `warehouse_name LIKE '%代发仓%'` 且 `barcode NOT LIKE 'DF-%'` 的记录,日期取 `ship_time`,表头沿用货款对账固定列。工作平台“单价/金额”先取 `dbo.pm_priceAdjustment_log` 同商品编码最新 `priceType=1` 的 `afterPrice`,没有变价记录时取 `dbo.pm_priceAdjustment` 当前已生效的 `purchasePrice`,仍未匹配按 0;采购入库已有预估成本时保留,否则工作平台无价格的行再取 `operations_replica.rpt.jst_sku → ops_jst_sku` 中同编码、`sku_type=normal` 的最新正数 `cost_price`,仅填入“预估单价/预估金额”。 |
| 采购单价 | `dbo.jst_purchase`、`dbo.jst_purchaseItem`(受控字段联表镜像,不复制其他采购业务字段) |
| 工作平台采购价格 | `dbo.pm_priceAdjustment`(`Id` 稳定键;按 `skuCode` 匹配 `jst_sku.sku_id`,页面取当前已生效的最新 `purchasePrice` / `effectTime`) |
| 快递资料 | `dbo.wp_express`、`dbo.wp_express_expNet`、`dbo.wp_express_account`、`dbo.wp_express_extension`。`wp_express.tradebody` 为合作合同乙方(合同主体),`signcom` 为甲方(签订公司),主资料列表与导出读取这两个原始镜像字段。协议签署选择快递后按确切名称带入唯一乙方主体,缺失或同名主体冲突时保留空值并提示核对,不以快递简称替代,也不改写已签归档合同。 |

View File

@ -11,6 +11,8 @@
4. 补偿、全款按原单商品的实际发货数量乘普通商品资料当前成本单价,再加实际包裹运费,与原金额取较小值。成本按商品编码精确匹配商品资料的当前 `cost_price`,不代表历史月份成本。
5. 运费损耗优先按正数实际运费记账,不受原金额限制;原金额为0也需要匹配。原单包裹运费为空或0时,按对应工单商品的当前成本单价×实际发货数量×0.2替代。多个包裹中只替代缺运费的包裹,其余仍取实际运费。替代需要有效商品成本与逐商品发货数量,缺失或数量含糊时待确认;已有正数实际运费不要求商品成本和数量。
6. 供应商为「沐野竹木」的工单只记成本价:补偿款项、记账全款、运费损耗均按原单实际发货数量×商品资料当前成本单价记账,不加运费、不与原金额比较,也不要求原单运费;缺发货、数量或成本价时仍待确认。前面的配置、小额归零和代发仓限制照常适用。同一工单同时含沐野竹木和其他供应商时待确认。
金额等于50元或比例等于40%均不满足小额免记账。金额计算使用十进制运算,在最终金额处四舍五入到分。
## 发货匹配

View File

@ -0,0 +1,52 @@
<?php
namespace Modules\EcommerceFinance\Console;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DingInvoiceLocalAttachmentImporter;
use Throwable;
class ImportDingInvoiceAttachments extends Command
{
protected $signature = 'ding-invoices:import-attachments
{manifest : 附件清单 JSON 路径}
{--month= : 付款月份 YYYY-MM}
{--base-dir= : 清单中 relative_path 的基础目录}
{--scope=personal_permission : 镜像来源范围}';
protected $description = '按月导入已经下载的发票附件并保留原始截图';
public function handle(DingInvoiceLocalAttachmentImporter $importer): int
{
$month = trim((string) $this->option('month'));
$baseDirectory = trim((string) $this->option('base-dir'));
if ($baseDirectory === '') {
$this->error('必须指定 --base-dir。');
return self::FAILURE;
}
try {
$result = $importer->import(
(string) $this->argument('manifest'),
$month,
$baseDirectory,
(string) $this->option('scope'),
);
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
if ($result['errors'] !== []) {
foreach (array_slice($result['errors'], 0, 20) as $error) {
$this->warn($error);
}
}
return $result['stored'] > 0 || $result['skipped'] === 0
? self::SUCCESS
: self::FAILURE;
}
}

View File

@ -11,15 +11,25 @@ class SyncDingInvoices extends Command
protected $signature = 'ding-invoices:sync
{--month= : 付款月份 YYYY-MM}
{--limit=20 : 本轮最多扫描的流程数}
{--force : 已扫描流程也重新抓取附件}';
{--force : 已扫描流程也重新抓取附件}
{--auto : 自动选择最近一个仍需抓取的月份}';
protected $description = '抓取钉钉 OA 审批附件并识别发票,写入发票数据镜像';
public function handle(DingInvoiceSyncService $service): int
{
try {
$month = (string) ($this->option('month') ?: '');
if ($month === '' && $this->option('auto')) {
$month = $service->latestPendingMonth() ?? '';
if ($month === '') {
$this->info('没有待抓取的发票月份。');
return self::SUCCESS;
}
}
$result = $service->syncMonth(
(string) ($this->option('month') ?: now()->format('Y-m')),
$month !== '' ? $month : now()->format('Y-m'),
(int) $this->option('limit'),
(bool) $this->option('force'),
);

View File

@ -0,0 +1,18 @@
<?php
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
public function up(): void
{
// The original migration may have run before the shipping connection moved to the shared mirror.
$create = require __DIR__ . '/2026_11_15_000001_create_jst_oms_shipping_freight_table.php';
$create->up();
}
public function down(): void
{
// The table may already have existed when this repair ran.
}
};

View File

@ -0,0 +1,45 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 供应商货款预估按发货时间读取代发仓逐商品明细;复合索引让最新店铺页面
* 可以沿索引倒序扫描,避免对全部日期命中记录做 filesort。
*/
return new class extends Migration
{
private const TABLE = 'jst_oms_shipping';
private const INDEX = 'jst_oms_shipping_forecast_page_index';
private function schema(): \Illuminate\Database\Schema\Builder
{
return Schema::connection((string) config('jushuitan.connection', 'jushuitan_local'));
}
public function up(): void
{
$schema = $this->schema();
if (! $schema->hasTable(self::TABLE) || $schema->hasIndex(self::TABLE, self::INDEX)) {
return;
}
$schema->table(self::TABLE, function (Blueprint $table): void {
$table->index(['ship_time', 'id', 'sku_source_id'], self::INDEX);
});
}
public function down(): void
{
$schema = $this->schema();
if (! $schema->hasTable(self::TABLE) || ! $schema->hasIndex(self::TABLE, self::INDEX)) {
return;
}
$schema->table(self::TABLE, function (Blueprint $table): void {
$table->dropIndex(self::INDEX);
});
}
};

View File

@ -2,12 +2,12 @@
namespace Modules\EcommerceFinance\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Repositories\DingInvoiceDataMirrorRepository;
use Modules\EcommerceFinance\Services\DingTalkApprovalAttachmentDownloader;
use Modules\EcommerceFinance\Services\DingInvoicePreviewStore;
use Modules\EcommerceFinance\Services\DingInvoiceRefreshQueue;
use Symfony\Component\HttpFoundation\StreamedResponse;
@ -33,7 +33,6 @@ class InvoiceData extends Controller
'报销类型',
'费用类型',
'收款人',
'打款时间',
'本月付款金额',
'付款合计',
'发票张数',
@ -41,6 +40,7 @@ class InvoiceData extends Controller
'付款差额',
'扫描状态',
'扫描说明',
'打款时间',
]);
foreach ($this->repository->exportRows($filters) as $row) {
$payment = (float) ($row['payment_amount'] ?? 0);
@ -52,7 +52,6 @@ class InvoiceData extends Controller
(string) ($row['document_type'] ?? ''),
(string) ($row['expense_type'] ?? ''),
(string) ($row['payee_name'] ?? ''),
(string) ($row['paid_at'] ?? ''),
number_format($payment, 2, '.', ''),
number_format((float) ($row['payment_total'] ?? 0), 2, '.', ''),
(int) ($row['invoice_count'] ?? 0),
@ -60,6 +59,7 @@ class InvoiceData extends Controller
number_format(round($payment - $invoice, 2), 2, '.', ''),
(string) ($row['scan_status'] ?? ''),
(string) ($row['last_error'] ?? ''),
(string) ($row['paid_at'] ?? ''),
]);
}
} else {
@ -68,9 +68,8 @@ class InvoiceData extends Controller
'标题',
'提交人',
'报销类型',
'费用类型',
'收款人',
'打款时间',
'本月付款金额',
'发票类型',
'销售方名称',
'销售方税号',
@ -83,8 +82,14 @@ class InvoiceData extends Controller
'金额',
'税率',
'税额',
'付款差额',
'本月付款金额',
'付款合计',
'发票张数',
'金额校对',
'差异金额',
'附件名称',
'识别来源',
'打款时间',
]);
foreach ($this->repository->exportRows($filters) as $row) {
$payment = (float) ($row['payment_amount'] ?? 0);
@ -94,9 +99,8 @@ class InvoiceData extends Controller
(string) ($row['title'] ?? ''),
(string) ($row['originator_name'] ?? ''),
(string) ($row['document_type'] ?? ''),
(string) ($row['expense_type'] ?? ''),
(string) ($row['payee_name'] ?? ''),
(string) ($row['paid_at'] ?? ''),
number_format($payment, 2, '.', ''),
(string) ($row['invoice_type'] ?? ''),
(string) ($row['seller_name'] ?? ''),
(string) ($row['seller_tax_no'] ?? ''),
@ -113,8 +117,17 @@ class InvoiceData extends Controller
$row['tax_amount'] === null
? ''
: number_format((float) $row['tax_amount'], 2, '.', ''),
number_format(round($payment - $invoice, 2), 2, '.', ''),
number_format($payment, 2, '.', ''),
number_format((float) ($row['payment_total'] ?? 0), 2, '.', ''),
(int) ($row['invoice_count'] ?? 0),
abs(round($payment - $invoice, 2)) <= 0.005 ? '一致' : '有差异',
number_format(round(
$payment - (float) ($row['flow_invoice_total'] ?? 0),
2,
), 2, '.', ''),
(string) ($row['source_file_name'] ?? ''),
(string) ($row['ocr_provider'] ?? ''),
(string) ($row['paid_at'] ?? ''),
]);
}
}
@ -125,11 +138,8 @@ class InvoiceData extends Controller
]);
}
public function attachment(int $invoice): RedirectResponse
public function attachment(int $invoice): StreamedResponse
{
// The row endpoint is intentionally not used for arbitrary IDs. Query the
// exact invoice record, then let DingTalk enforce whether the current app
// can mint a temporary download URL for that process attachment.
$invoiceRow = \Illuminate\Support\Facades\DB::connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
)->table('ding_invoice_record_mirror')
@ -138,15 +148,54 @@ class InvoiceData extends Controller
->first();
abort_if($invoiceRow === null, 404);
$processInstanceId = trim((string) ($invoiceRow->process_instance_id ?? ''));
$fileId = trim((string) ($invoiceRow->source_file_id ?? ''));
abort_if($processInstanceId === '' || $fileId === '', 404, '该发票没有可下载的原始附件。');
$preview = app(DingInvoicePreviewStore::class)->ensureStored($invoiceRow);
abort_if($preview === null, 404, '该发票暂无图片或 PDF 原件可预览。');
$uri = app(DingTalkApprovalAttachmentDownloader::class)
->downloadUri($processInstanceId, $fileId);
abort_if($uri === null, 404, '原始发票附件暂时无法下载。');
$disk = Storage::disk('uploads');
abort_unless($disk->exists($preview['path']), 404);
return redirect()->away($uri);
$name = trim((string) ($invoiceRow->source_file_name ?? ''));
if ($name === '') {
$name = 'invoice-preview.' . $preview['extension'];
} elseif (strtolower((string) pathinfo($name, PATHINFO_EXTENSION)) !== $preview['extension']) {
$name = pathinfo($name, PATHINFO_FILENAME) . '.' . $preview['extension'];
}
return $disk->response($preview['path'], basename($name), [
'Content-Type' => $preview['mime'],
'Cache-Control' => 'private, max-age=300',
'X-Content-Type-Options' => 'nosniff',
], 'inline');
}
public function rawAttachment(int $attachment): StreamedResponse
{
$attachmentRow = \Illuminate\Support\Facades\DB::connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
)->table('ding_invoice_attachment_mirror')
->where('id', $attachment)
->where('source_scope', $this->repository->scope())
->first();
abort_if($attachmentRow === null, 404);
$preview = app(DingInvoicePreviewStore::class)->ensureAttachmentStored($attachmentRow);
abort_if($preview === null, 404, '该附件暂无可预览的图片或 PDF。');
$disk = Storage::disk('uploads');
abort_unless($disk->exists($preview['path']), 404);
$name = trim((string) ($attachmentRow->source_file_name ?? ''));
if ($name === '') {
$name = 'attachment-preview.' . $preview['extension'];
} elseif (strtolower((string) pathinfo($name, PATHINFO_EXTENSION)) !== $preview['extension']) {
$name = pathinfo($name, PATHINFO_FILENAME) . '.' . $preview['extension'];
}
return $disk->response($preview['path'], basename($name), [
'Content-Type' => $preview['mime'],
'Cache-Control' => 'private, max-age=300',
'X-Content-Type-Options' => 'nosniff',
], 'inline');
}
public function requestRefresh(Request $request): JsonResponse

View File

@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\Providers;
use Illuminate\Support\ServiceProvider as Provider;
use Modules\EcommerceFinance\Console\ExportShengsuanAnomalyOrders;
use Modules\EcommerceFinance\Console\ImportDingInvoiceAttachments;
use Modules\EcommerceFinance\Console\ImportDingInvoiceWorkbook;
use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitDetails;
use Modules\EcommerceFinance\Console\ProcessDingRefreshRequests;
@ -33,6 +34,7 @@ class Main extends Provider
SyncJushuitanShipping::class,
CalcShippingFreight::class,
ImportDingInvoiceWorkbook::class,
ImportDingInvoiceAttachments::class,
ProcessDingRefreshRequests::class,
ProcessDingInvoiceRefreshRequests::class,
SyncDingInvoices::class,

View File

@ -1,420 +0,0 @@
<?php
namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\BusinessMirrorDatasetRegistry;
use RuntimeException;
use Throwable;
/** 快递应付运费对账的共享业务镜像只读访问。 */
class CourierFreightReconciliationMirrorRepository
{
/** 保留旧契约,供现有结算同步和调用方识别。 */
public const DATASET = 'jiansun.dbo.fys_express_courier_settlement';
public const DETAILS_DATASET = 'jiansun.dbo.jst_order_express_details';
public const EXTENSION_DATASET = 'jiansun.dbo.Jst_SendData_View_extension';
public const OUTBOUND_DATASET = 'jiansun.dbo.jst_salesOutboundInfo';
/** @var list<string> */
private const REQUIRED_DATASETS = [
self::DETAILS_DATASET,
self::EXTENSION_DATASET,
self::OUTBOUND_DATASET,
];
/** 仅暴露附件中有演示值、且已经核对来源的字段。 */
private const COLUMNS = [
'detail_id', 'waybill', 'product_id', 'send_time', 'transaction_order_no',
'province', 'city', 'district', 'barcode', 'express_name', 'express_name_2', 'quantity',
'product_name', 'platform', 'shop_name', 'warehouse', 'volume', 'supplier',
'length', 'width', 'height', 'freight', 'reconciliation_weight',
'reconciliation_volume', 'month', 'status',
];
private readonly ConnectionInterface $connection;
public function __construct(
private readonly BusinessMirrorDatasetRegistry $datasets,
private readonly GenericBusinessMirrorRepository $mirror,
) {
$this->connection = $mirror->connection();
}
public function available(): bool
{
try {
$schema = Schema::connection($this->connection->getName());
if (! $schema->hasTable('business_mirror_table_states')) {
return false;
}
foreach (self::REQUIRED_DATASETS as $key) {
if (! $schema->hasTable($this->datasets->get($key)->targetTable())) {
return false;
}
}
return true;
} catch (Throwable) {
return false;
}
}
public function ready(): bool
{
try {
foreach (self::REQUIRED_DATASETS as $key) {
if (! $this->mirror->ready($this->datasets->get($key))) {
return false;
}
}
return true;
} catch (Throwable) {
return false;
}
}
/** @return array<string,mixed>|null */
public function state(): ?array
{
try {
$states = [];
foreach (self::REQUIRED_DATASETS as $key) {
$state = $this->mirror->state($this->datasets->get($key));
if (is_array($state)) {
$states[$key] = $state;
}
}
if ($states === []) {
return null;
}
$first = $states[self::DETAILS_DATASET] ?? reset($states);
$initial = array_values(array_filter(array_map(
static fn (array $state): ?string => $state['initial_completed_at'] ?? null,
$states,
)));
$succeeded = array_values(array_filter(array_map(
static fn (array $state): ?string => $state['last_succeeded_at'] ?? null,
$states,
)));
$statuses = array_map(static fn (array $state): string => (string) ($state['status'] ?? 'pending'), $states);
$first['initial_completed_at'] = count($initial) === count(self::REQUIRED_DATASETS) ? min($initial) : null;
$first['last_succeeded_at'] = count($succeeded) === count(self::REQUIRED_DATASETS) ? min($succeeded) : null;
$first['status'] = in_array('failed', $statuses, true)
? 'failed'
: (in_array('running', $statuses, true) ? 'running' : (count(array_filter($statuses, static fn (string $value): bool => $value === 'succeeded')) === count(self::REQUIRED_DATASETS) ? 'succeeded' : 'pending'));
$first['datasets'] = $states;
return $first;
} catch (Throwable) {
return null;
}
}
/** @return array{code:string,last_succeeded_at:?string,lag_minutes:?int} */
public function syncStatus(?array $state = null): array
{
$state ??= $this->state();
if (! is_array($state)) {
return ['code' => 'unavailable', 'last_succeeded_at' => null, 'lag_minutes' => null];
}
$lastSucceeded = $state['last_succeeded_at'] ?? null;
$lagMinutes = null;
if (is_string($lastSucceeded) && $lastSucceeded !== '') {
try {
$lagMinutes = (int) ceil(max(0, now()->getTimestamp() - Carbon::parse($lastSucceeded)->getTimestamp()) / 60);
} catch (Throwable) {
$lagMinutes = null;
}
}
$status = (string) ($state['status'] ?? 'pending');
if (($state['initial_completed_at'] ?? null) === null) {
$code = $status === 'failed' ? 'initial_failed' : ($status === 'running' ? 'initializing' : 'pending');
} elseif ($status === 'failed') {
$code = 'failed';
} elseif ($status === 'running') {
$code = 'syncing';
} elseif ($lagMinutes === null || $lagMinutes > max((int) config('upstream_mirrors.courier_information.stale_after_minutes', 60), 1)) {
$code = 'stale';
} else {
$code = 'fresh';
}
return ['code' => $code, 'last_succeeded_at' => $lastSucceeded, 'lag_minutes' => $lagMinutes];
}
/**
* @param array<string,string> $filters
* @return array{data:list<array<string,mixed>>,total:?int,has_more:bool,summary:?array,state:array<string,mixed>|null,sync:array<string,mixed>}
*/
public function paginate(array $filters, int $page, int $perPage): array
{
if (! $this->ready()) {
throw new RuntimeException('courier_freight_reconciliation_mirror_not_ready');
}
$page = max($page, 1);
$perPage = min(max($perPage, 1), 100);
$summary = Cache::get($this->summaryCacheKey($filters));
// Select page identifiers before loading the wide optional details. A
// contains-waybill filter can then scan the compact covering index.
$candidates = $this->filteredQuery($filters, trim((string) ($filters['express_name'] ?? '')) !== '')
->select('d.id')
->orderByDesc('d.id')
->offset(($page - 1) * $perPage)->limit($perPage + 1);
$rows = $this->detailQuery($candidates)->select($this->selectColumns())
->orderByDesc('d.id')
->get()
->map(fn (object $row): array => $this->mapRow($row))
->all();
$state = $this->state();
return [
'data' => array_slice($rows, 0, $perPage),
'total' => $summary['count'] ?? null,
'has_more' => count($rows) > $perPage,
'summary' => $summary,
'state' => $state,
'sync' => $this->syncStatus($state),
];
}
/** Send a small pending response before starting the bounded calculation. */
public function requestSummary(array $filters): ?array
{
$key = $this->summaryCacheKey($filters);
if (is_array($cached = Cache::get($key))) return $cached;
if (Cache::has($key . ':failed')) throw new RuntimeException('courier_summary_recently_failed');
app()->terminating(function () use ($filters, $key): void {
try {
$this->summarize($filters);
} catch (Throwable $exception) {
Cache::put($key . ':failed', true, 60);
report($exception);
}
});
return null;
}
/** The separate summary request preserves full-filter totals without delaying rows. */
public function summarize(array $filters): ?array
{
if (! $this->ready()) throw new RuntimeException('courier_freight_reconciliation_mirror_not_ready');
$key = $this->summaryCacheKey($filters);
if (is_array($cached = Cache::get($key))) return $cached;
// One expensive aggregate at a time, including requests for different filters.
$lock = Cache::lock('courier-freight-summary:calculation', 360);
if (! $lock->get()) return null;
$previousSettings = [];
try {
if (is_array($cached = Cache::get($key))) return $cached;
$unfiltered = array_filter($filters, static fn ($value): bool => trim((string) $value) !== '') === [];
if ($this->connection->getDriverName() === 'mysql') {
$settings = ['max_statement_time' => 300];
if ($unfiltered) {
$settings += [
'optimizer_switch' => 'derived_merge=off,derived_with_keys=off',
'join_cache_level' => 8,
// 全量汇总要把 300 万行左右的明细和 400 万行的最新关联表做哈希
// 关联;16MB 的哈希表装不下会退化成磁盘多趟扫描(实测超过
// max_statement_time 也跑不完)。128MB 缓冲约 110 秒出结果。
'join_buffer_size' => 134217728,
'join_buffer_space_limit' => 402653184,
];
}
foreach ($settings as $name => $value) {
$previousSettings[$name] = $this->connection->selectOne('SELECT @@SESSION.' . $name . ' AS value')->value;
$this->setSummarySessionSetting($name, $value);
}
}
$asOf = now()->toDateTimeString();
$row = $this->summaryQuery($filters)->selectRaw(
'COUNT(d.id) AS aggregate_count, COALESCE(SUM(o.freight), 0) AS freight',
)->first();
$summary = ['count' => (int) $row->aggregate_count, 'freight' => (float) $row->freight, 'computed_at' => $asOf];
// 全量(无筛选)汇总要跑两分钟左右,缓存久一点,避免频繁重算;
// 带筛选的汇总走索引,很快,保持原来的 15 分钟。
Cache::put($key, $summary, $unfiltered ? 3600 : 900);
return $summary;
} finally {
try {
foreach (array_reverse($previousSettings, true) as $name => $value) {
$this->setSummarySessionSetting($name, $value);
}
} finally {
$lock->release();
}
}
}
private function setSummarySessionSetting(string $name, mixed $value): void
{
if ($name === 'optimizer_switch') {
$this->connection->statement('SET SESSION optimizer_switch=?', [$value]);
return;
}
// MariaDB rejects quoted numeric values for these session variables.
// Names come only from the fixed settings map above.
$this->connection->statement('SET SESSION ' . $name . '=' . (float) $value);
}
private function summaryCacheKey(array $filters): string
{
$filters = array_filter(array_map(static fn ($value): string => trim((string) $value), $filters), static fn (string $value): bool => $value !== '');
ksort($filters);
return 'courier-freight-summary:v3:' . hash('sha256', json_encode($filters));
}
/** Materialize latest associations once; use compact collation-aware hash joins for the full scan. */
private function summaryQuery(array $filters = []): Builder
{
$activeFilters = array_filter($filters, static fn ($value): bool => trim((string) $value) !== '');
if ($activeFilters !== []) {
$ids = $this->filteredQuery($filters, ($filters['express_name'] ?? '') !== '')->select('d.id')->distinct();
return $this->detailQuery($ids);
}
$columns = ['so_id', 'io_id'];
$lookup = fn (string $column): string => $this->connection->getDriverName() === 'mysql'
? 'CRC32(WEIGHT_STRING(RTRIM(' . $column . ')))'
: 'SUBSTR(' . $column . ', 1, 64)';
$extension = $this->latestSummaryProjection(self::EXTENSION_DATASET, 'so_id', $columns)
->selectRaw($lookup('candidate.so_id') . ' AS lookup_key');
$outbound = $this->latestSummaryProjection(self::OUTBOUND_DATASET, 'io_id', ['io_id', 'freight']);
$query = $this->connection->table($this->datasets->get(self::DETAILS_DATASET)->targetTable() . ' as d')
->leftJoinSub($extension, 'x', static function ($join) use ($lookup): void {
$join->whereRaw('x.lookup_key = ' . $lookup('d.so_id'))
// Keep the full comparison: a hash collision must never
// combine different orders or multiply freight amounts.
->whereRaw("COALESCE(x.so_id, '') = COALESCE(d.so_id, '')");
})
->leftJoinSub($outbound, 'o', 'o.io_id', '=', 'x.io_id');
return $this->filteredQuery([], true, $query);
}
private function latestSummaryProjection(string $dataset, string $relation, array $columns): Builder
{
$table = $this->datasets->get($dataset)->targetTable();
$ids = $this->connection->table($table)->select($relation)->selectRaw('MAX(Id) AS latest_id')->groupBy($relation)->orderByRaw('NULL');
return $this->connection->query()->fromSub($ids, 'latest_ids')
->join($table . ' as candidate', static function ($join) use ($relation): void {
$join->on('latest_ids.' . $relation, '=', 'candidate.' . $relation)->on('latest_ids.latest_id', '=', 'candidate.Id');
})->select(array_map(static fn (string $column): string => 'candidate.' . $column, $columns));
}
private function filteredQuery(array $filters, bool $includeRelations = true, ?Builder $base = null): Builder
{
$query = ($base ?? ($includeRelations ? $this->detailQuery() : $this->connection->table($this->datasets->get(self::DETAILS_DATASET)->targetTable() . ' as d')))
->whereNotNull('d.logistic_id')->where('d.logistic_id', '!=', '');
$this->containsFilter($query, 'd.logistic_id', $filters['express_no'] ?? '');
if (($filters['express_name'] ?? '') !== '') {
$needle = $this->contains((string) $filters['express_name']);
$query->where(function (Builder $name) use ($needle): void {
$name->whereRaw("d.logistic_company_name LIKE ? ESCAPE '!'", [$needle])
->orWhereRaw("x.expressName LIKE ? ESCAPE '!'", [$needle]);
});
}
if (($filters['month'] ?? '') !== '' && preg_match('/^\d{4}-\d{2}$/', (string) $filters['month']) === 1) {
$from = (string) $filters['month'] . '-01';
$query->where('d.send_time', '>=', $from . ' 00:00:00')
->where('d.send_time', '<', date('Y-m-d 00:00:00', strtotime($from . ' +1 month')));
}
if (($filters['status'] ?? '') !== '') {
$query->where('d.logistic_status_name', '=', $filters['status']);
}
if (($filters['modified_from'] ?? '') !== '') {
$query->where('d.updatedAt', '>=', $filters['modified_from'] . ' 00:00:00');
}
if (($filters['modified_to'] ?? '') !== '') {
$query->where('d.updatedAt', '<', date('Y-m-d 00:00:00', strtotime($filters['modified_to'] . ' +1 day')));
}
return $query;
}
private function detailQuery(?Builder $pageIds = null): Builder
{
$details = $this->datasets->get(self::DETAILS_DATASET)->targetTable();
$extension = $this->datasets->get(self::EXTENSION_DATASET)->targetTable();
$outbound = $this->datasets->get(self::OUTBOUND_DATASET)->targetTable();
$query = $pageIds === null ? $this->connection->table($details . ' as d')
: $this->connection->query()->fromSub($pageIds, 'page_ids')->join($details . ' as d', 'd.id', '=', 'page_ids.id');
return $query
->leftJoinSub($this->latestBy($extension, 'so_id', 'Id'), 'x', 'x.so_id', '=', 'd.so_id')
->leftJoinSub($this->latestBy($outbound, 'io_id', 'Id'), 'o', 'o.io_id', '=', 'x.io_id');
}
/** 固定取关联键下 Id 最大的一行,避免一对多重复页面行和运费汇总。 */
private function latestBy(string $table, string $relationColumn, string $idColumn): Builder
{
return $this->connection->table($table . ' as candidate')
->whereNotExists(function (Builder $query) use ($table, $relationColumn, $idColumn): void {
$query->selectRaw('1')
->from($table . ' as newer')
->whereColumn('newer.' . $relationColumn, '=', 'candidate.' . $relationColumn)
->whereColumn('newer.' . $idColumn, '>', 'candidate.' . $idColumn);
});
}
/** @return list<string> */
private function selectColumns(): array
{
return [
'd.id as detail_id', 'd.logistic_id as waybill', 'x.shop_i_id as product_id',
'd.send_time', $this->connection->raw('COALESCE(x.so_id, d.so_id) as transaction_order_no'), 'x.receiver_state as province',
'x.receiver_city as city', 'x.receiver_district as district',
'x.sku_ids as barcode',
'd.logistic_company_name as express_name', 'x.expressName as express_name_2',
'x.qty as quantity', 'x.sku_name as product_name', 'd.platform_name as platform',
$this->connection->raw('COALESCE(x.shop_name, d.shop_name) as shop_name'),
$this->connection->raw('COALESCE(x.wareHoursName, d.warehouse_name) as warehouse'), 'x.volume as volume',
'x.supplier_name as supplier', 'x.l as length', 'x.w as width', 'x.h as height',
'o.freight as freight', 'd.f_weight as reconciliation_weight',
'x.volume as reconciliation_volume', 'd.logistic_status_name as status',
];
}
/** @return array<string,mixed> */
private function mapRow(object $row): array
{
$mapped = [];
foreach (self::COLUMNS as $column) {
$mapped[$column] = $row->{$column} ?? null;
}
$sendTime = $mapped['send_time'];
$mapped['month'] = is_string($sendTime) ? substr($sendTime, 0, 7) : null;
foreach (['length', 'width', 'height', 'volume', 'freight', 'reconciliation_weight', 'reconciliation_volume'] as $number) {
$mapped[$number] = $mapped[$number] === null || $mapped[$number] === '' ? null : (float) $mapped[$number];
}
if ($mapped['quantity'] !== null && $mapped['quantity'] !== '') {
$mapped['quantity'] = (int) $mapped['quantity'];
}
return $mapped;
}
private function containsFilter(Builder $query, string $column, mixed $value): void
{
$value = trim((string) $value);
if ($value !== '') {
$query->whereRaw($column . " LIKE ? ESCAPE '!'", [$this->contains($value)]);
}
}
private function contains(string $value): string
{
return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value) . '%';
}
}

View File

@ -309,6 +309,46 @@ class CourierInformationMirrorRepository
->all();
}
/**
* 快递应付汇总用:按快递名称取合同开始/截止时间、签订公司、合同主体和停运时间。
* 同名多条时取 Id 最大(最新)的一条;镜像未就绪时返回空数组。
*
* @param list<string> $expnames
* @return array<string,array{contract_start:?string,contract_end:?string,company:string,body:string,stopped_at:?string}>
*/
public function contractsByName(array $expnames): array
{
$expnames = array_values(array_unique(array_filter(array_map(
static fn ($name): string => trim((string) $name),
$expnames,
), static fn (string $name): bool => $name !== '')));
if ($expnames === [] || ! $this->ready()) {
return [];
}
$result = [];
foreach (array_chunk($expnames, 500) as $chunk) {
$rows = $this->connection->table($this->dataset()->targetTable())
->select(['Id', 'expname', 'tradebtime', 'tradeetime', 'signcom', 'tradebody', 'stopdate'])
->whereIn('expname', $chunk)
->where(static fn (Builder $query) => $query->whereNull('is_delete')->orWhere('is_delete', '<>', 1))
->orderBy('Id')
->get();
foreach ($rows as $row) {
$date = static fn ($value): ?string => filled($value) ? substr((string) $value, 0, 10) : null;
$result[trim((string) $row->expname)] = [
'contract_start' => $date($row->tradebtime),
'contract_end' => $date($row->tradeetime),
'company' => trim((string) $row->signcom),
'body' => trim((string) $row->tradebody),
'stopped_at' => $date($row->stopdate),
];
}
}
return $result;
}
/** 报价签署预填:优先按公司代码,旧报价只按完整名称唯一匹配。 */
public function signingAccountSource(string $code, string $name): ?object
{

View File

@ -11,12 +11,16 @@ use RuntimeException;
class DingInvoiceDataMirrorRepository
{
public const FIRST_SUPPORTED_MONTH = '2026-10';
public const PER_PAGE_OPTIONS = [50, 100, 200];
public const VIEW_DETAIL = 'detail';
public const VIEW_FLOWS = 'flows';
public const VIEW_ATTACHMENTS = 'attachments';
public const INVOICE_STATES = [
'all' => '全部状态',
'has_invoice' => '有发票',
@ -86,6 +90,7 @@ class DingInvoiceDataMirrorRepository
->where('source_scope', $this->scope())
->whereNotNull('paid_month')
->where('paid_month', '!=', '')
->where('paid_month', '>=', self::FIRST_SUPPORTED_MONTH)
->distinct()
->orderByDesc('paid_month')
->pluck('paid_month')
@ -123,6 +128,27 @@ class DingInvoiceDataMirrorRepository
];
}
/**
* @param array<string,mixed> $filters
* @return array{data:list<object>,total:int}
*/
public function paginateAttachments(array $filters, int $page, int $perPage): array
{
$schema = Schema::connection($this->connection->getName());
if (! $schema->hasTable('ding_invoice_attachment_mirror')) {
return ['data' => [], 'total' => 0];
}
$page = max(1, $page);
$perPage = in_array($perPage, self::PER_PAGE_OPTIONS, true) ? $perPage : 50;
$query = $this->attachmentQuery($filters);
$total = (clone $query)->count();
return [
'data' => $query->forPage($page, $perPage)->get()->all(),
'total' => $total,
];
}
/** @param array<string,mixed> $filters */
public function filterOptions(array $filters): array
{
@ -230,6 +256,8 @@ class DingInvoiceDataMirrorRepository
'r.source_file_type',
'r.source_field',
'r.ocr_provider',
'r.preview_path',
'r.preview_mime',
'f.title',
'f.originator_name',
'f.document_type',
@ -260,6 +288,7 @@ class DingInvoiceDataMirrorRepository
'r.buyer_name',
'r.buyer_tax_no',
'r.item_name',
'r.invoice_date',
'f.title',
'f.originator_name',
'f.payee_name',
@ -275,6 +304,59 @@ class DingInvoiceDataMirrorRepository
->orderBy('r.id');
}
/** @param array<string,mixed> $filters */
private function attachmentQuery(array $filters): Builder
{
$query = $this->connection->table('ding_invoice_attachment_mirror as a')
->join('ding_invoice_flow_mirror as f', function ($join): void {
$join->on('f.business_id', '=', 'a.business_id')
->on('f.source_scope', '=', 'a.source_scope');
})
->select([
'a.id',
'a.business_id',
'a.paid_month',
'a.source_file_name',
'a.source_file_type',
'a.source_field',
'a.source_origin',
'a.source_size',
'a.preview_path',
'a.preview_mime',
'a.ocr_status',
'a.ocr_provider',
'a.invoice_count',
'a.last_error',
'a.downloaded_at',
'f.title',
'f.originator_name',
'f.paid_at',
'f.payment_amount',
])
->where('a.source_scope', $this->scope());
$this->applyFlowFilters($query, $filters, 'f');
if (($filters['keyword'] ?? '') !== '') {
$keyword = '%' . $filters['keyword'] . '%';
$query->where(function (Builder $nested) use ($keyword): void {
foreach ([
'a.business_id',
'a.source_file_name',
'a.source_field',
'a.ocr_provider',
'a.last_error',
'f.title',
'f.originator_name',
] as $column) {
$nested->orWhere($column, 'like', $keyword);
}
});
}
return $query
->orderByDesc('f.paid_at')
->orderByDesc('a.id');
}
/** @param array<string,mixed> $filters */
private function applyFlowFilters(Builder $query, array $filters, string $alias = 'f'): void
{
@ -333,7 +415,13 @@ class DingInvoiceDataMirrorRepository
->whereColumn('rk.source_scope', 'f.source_scope')
->whereColumn('rk.business_id', 'f.business_id')
->where(function (Builder $invoiceSearch) use ($keyword): void {
foreach (['invoice_number', 'seller_name', 'buyer_name', 'item_name'] as $column) {
foreach ([
'invoice_number',
'seller_name',
'buyer_name',
'item_name',
'invoice_date',
] as $column) {
$invoiceSearch->orWhere("rk.{$column}", 'like', $keyword);
}
});
@ -410,6 +498,7 @@ class DingInvoiceDataMirrorRepository
'buyer_name',
'buyer_tax_no',
'item_name',
'invoice_date',
] as $column) {
$invoiceSearch->orWhere(
'summary_invoice_search.' . $column,
@ -435,6 +524,9 @@ class DingInvoiceDataMirrorRepository
return [
'flows' => $rows->count(),
'invoice_flows' => $rows->filter(
static fn (object $row): bool => (int) $row->invoice_count > 0,
)->count(),
'payment_amount' => $payment,
'invoice_count' => (int) $rows->sum('invoice_count'),
'invoice_total' => $invoice,

View File

@ -225,23 +225,19 @@ class InstallationDetailMirrorRepository
}
/**
* 按发货月份、平台和安装公司汇总安装单量,并返回已审核结算金额。
*
* 平台与安装公司用于分析供应商切换;审核状态用于区分已确认金额和待审核单量。
* 按客服审核月份和安装公司汇总实际安装单量及结算明细金额。
*
* @return array{
* ready:bool,
* rows:list<array{
* period:string,
* platform:string,
* installation_company:string,
* orders:int,
* reviewed_orders:int,
* settled_amount:float
* amount:float
* }>
* }
*/
public function platformFeeUsageTrend(string $fromMonth, string $toMonth): array
public function installationCompanyActualFeeTrend(string $fromMonth, string $toMonth): array
{
$dataset = $this->datasets->get(self::DATASET);
$items = $this->datasets->get(self::ITEM_DATASET);
@ -260,54 +256,32 @@ class InstallationDetailMirrorRepository
$endExclusive = \Illuminate\Support\Carbon::parse($toMonth . '-01')
->addMonth()
->toDateString();
$latest = $connection->table($dataset->targetTable())
->selectRaw('MAX(Id) AS id')
->groupBy('SourceGuid');
$main = $connection->table($dataset->targetTable() . ' AS install_main')
->joinSub($latest, 'latest', static fn ($join) =>
$join->on('latest.id', '=', 'install_main.Id'))
->select([
'install_main.SourceGuid',
'install_main.ShipTIme',
'install_main.shop_name',
'install_main.installCompanyName',
])
->whereNotNull('install_main.ShipTIme')
->where('install_main.ShipTIme', '>=', $start)
->where('install_main.ShipTIme', '<', $endExclusive);
$itemReview = $connection->table($items->targetTable() . ' AS item')
->selectRaw('item.guid')
->selectRaw('ROUND(SUM(CAST(item.settleItemAmount AS DECIMAL(18,2))), 2) AS settled_amount')
->selectRaw('MAX(CASE WHEN item.kfshTime IS NOT NULL THEN 1 ELSE 0 END) AS reviewed')
->groupBy('item.guid');
$main = $this->latestFeeMainQuery($connection, $dataset);
$periodSql = $connection->getDriverName() === 'sqlite'
? "strftime('%Y-%m', install_main.ShipTIme)"
: "DATE_FORMAT(install_main.ShipTIme, '%Y-%m')";
$platformSql = $this->platformSql('install_main');
? "strftime('%Y-%m', i.kfshTime)"
: "DATE_FORMAT(i.kfshTime, '%Y-%m')";
$companySql = "COALESCE(NULLIF(TRIM(install_main.installCompanyName), ''), '未填写安装公司')";
$rows = (clone $main)
->leftJoinSub($itemReview, 'item_review', static fn ($join) =>
$join->on('item_review.guid', '=', 'install_main.SourceGuid'))
$base = $connection->table($items->targetTable() . ' AS i')
->joinSub($main, 'install_main', static fn ($join) =>
$join->on('install_main.SourceGuid', '=', 'i.guid'))
->whereNotNull('i.kfshTime')
->where('i.kfshTime', '>=', $start)
->where('i.kfshTime', '<', $endExclusive);
$rows = (clone $base)
->selectRaw($periodSql . ' AS period')
->selectRaw($platformSql . ' AS platform')
->selectRaw($companySql . ' AS installation_company')
->selectRaw('COUNT(*) AS orders')
->selectRaw('SUM(CASE WHEN item_review.reviewed = 1 THEN 1 ELSE 0 END) AS reviewed_orders')
->selectRaw('ROUND(COALESCE(SUM(item_review.settled_amount), 0), 2) AS settled_amount')
->groupByRaw($periodSql . ', ' . $platformSql . ', ' . $companySql)
->selectRaw('COUNT(DISTINCT install_main.SourceGuid) AS orders')
->selectRaw('ROUND(SUM(CAST(i.settleItemAmount AS DECIMAL(18,2))), 2) AS amount')
->groupByRaw($periodSql . ', ' . $companySql)
->orderByRaw($periodSql)
->orderByRaw($platformSql)
->orderByRaw($companySql)
->get()
->map(static fn (object $row): array => [
'period' => trim((string) ($row->period ?? '')),
'platform' => trim((string) ($row->platform ?? '其他')),
'installation_company' => trim((string) ($row->installation_company ?? '未填写安装公司')),
'orders' => (int) ($row->orders ?? 0),
'reviewed_orders' => (int) ($row->reviewed_orders ?? 0),
'settled_amount' => round((float) ($row->settled_amount ?? 0), 2),
'amount' => round((float) ($row->amount ?? 0), 2),
])
->filter(static fn (array $row): bool =>
preg_match('/^\d{4}-\d{2}$/', $row['period']) === 1)

View File

@ -23,8 +23,6 @@ class NonJingxiRefundMirrorRepository
public const SHOP_DATASET = 'operations_replica.rpt.jst_shopInfo';
public const STATUS_DATASET = 'jiansun.dbo.jst_refund_view';
private const PENDING_CONFIRMATION_STATUS = 'WaitConfirm';
private const PENDING_CONFIRMATION_ONLINE_STATUS = 'SUCCESS';
@ -42,7 +40,6 @@ class NonJingxiRefundMirrorRepository
self::SUPPLEMENT_DATASET => [['as_id'], ['as_date', 'as_id'], ['so_id'], ['outer_as_id'], ['status', 'shop_status', 'as_date', 'as_id']],
self::SUPPLEMENT_ITEM_DATASET => [['as_id', 'asi_id']],
self::SHOP_DATASET => [['shop_id', 'Id']],
self::STATUS_DATASET => [['as_id'], ['status', 'shop_status', 'as_id']],
'operations_replica.rpt.jst_Orders' => [['o_id', 'Id']],
'operations_replica.rpt.jst_OrderItem' => [['o_id', 'Id']],
];
@ -62,8 +59,6 @@ class NonJingxiRefundMirrorRepository
private ?bool $queryReadyCache = null;
private ?bool $pendingStatusReadyCache = null;
public function __construct(
private readonly BusinessMirrorDatasetRegistry $datasets,
private readonly GenericBusinessMirrorRepository $mirror,
@ -104,24 +99,6 @@ class NonJingxiRefundMirrorRepository
);
}
public function pendingConfirmationStatusReady(): bool
{
if ($this->pendingStatusReadyCache !== null) {
return $this->pendingStatusReadyCache;
}
try {
return $this->pendingStatusReadyCache = cache()->remember(
'refund-pending.status-ready.v1',
now()->addMinute(),
fn (): bool => Schema::connection($this->connection->getName())->hasTable('ops_jst_refund_status')
&& $this->mirror->ready($this->dataset(self::STATUS_DATASET)),
);
} catch (\Throwable) {
return $this->pendingStatusReadyCache = false;
}
}
public function queryReady(): bool
{
if ($this->queryReadyCache !== null) {
@ -180,7 +157,6 @@ class NonJingxiRefundMirrorRepository
self::SUPPLEMENT_DATASET => $this->mirror->state($this->dataset(self::SUPPLEMENT_DATASET)),
self::SUPPLEMENT_ITEM_DATASET => $this->mirror->state($this->dataset(self::SUPPLEMENT_ITEM_DATASET)),
self::SHOP_DATASET => $this->mirror->state($this->dataset(self::SHOP_DATASET)),
self::STATUS_DATASET => $this->mirror->state($this->dataset(self::STATUS_DATASET)),
];
}
@ -196,7 +172,6 @@ class NonJingxiRefundMirrorRepository
self::ITEM_DATASET,
self::SUPPLEMENT_DATASET,
self::SUPPLEMENT_ITEM_DATASET,
self::STATUS_DATASET,
];
$states = $this->connection->table('business_mirror_table_states')
->whereIn('dataset_key', $keys)
@ -215,7 +190,7 @@ class NonJingxiRefundMirrorRepository
public function syncStatus(?array $states = null, ?CarbonInterface $at = null): array
{
$states ??= $this->states();
if (count(array_filter($states, 'is_array')) !== 6) {
if (count(array_filter($states, 'is_array')) !== 5) {
return ['code' => 'unavailable', 'last_succeeded_at' => null];
}
@ -285,7 +260,6 @@ class NonJingxiRefundMirrorRepository
*/
public function paginatePendingConfirmation(array $filters, int $page, int $perPage): array
{
$this->assertPendingStatusReady();
if (! $this->ready() || ! $this->queryReady()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
@ -314,7 +288,6 @@ class NonJingxiRefundMirrorRepository
*/
public function pagePendingConfirmation(array $filters, int $page, int $perPage): array
{
$this->assertPendingStatusReady();
if (! $this->ready() || ! $this->queryReady()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
@ -340,7 +313,6 @@ class NonJingxiRefundMirrorRepository
*/
public function pendingConfirmationMonthlySummary(string $from, string $to): array
{
$this->assertPendingStatusReady();
if (! $this->ready() || ! $this->queryReady()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
@ -400,7 +372,6 @@ class NonJingxiRefundMirrorRepository
*/
public function pendingConfirmationApplicationDailySummary(array $filters): array
{
$this->assertPendingStatusReady();
if (! $this->ready() || ! $this->queryReady()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
@ -453,7 +424,6 @@ class NonJingxiRefundMirrorRepository
*/
public function pendingConfirmationPlatformMonthlySummary(string $from, string $to): array
{
$this->assertPendingStatusReady();
if (! $this->ready() || ! $this->queryReady()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
@ -567,7 +537,6 @@ class NonJingxiRefundMirrorRepository
*/
public function exportPendingConfirmationRows(array $filters, int $chunkSize = 1000): iterable
{
$this->assertPendingStatusReady();
if (! $this->ready() || ! $this->queryReady()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
@ -642,12 +611,8 @@ class NonJingxiRefundMirrorRepository
private function sourceQuery(array $filters, bool $supplement, bool $withItems = true): Builder
{
$table = $supplement ? 'ops_jst_qmcust_refunds' : 'ops_jst_return_refund_info';
$statusAuthoritative = (bool) ($filters['_status_authoritative'] ?? false);
$query = $statusAuthoritative
? $this->connection->table('ops_jst_refund_status as current_refund')
->join($table . ' as r', 'r.as_id', '=', 'current_refund.as_id')
: $this->connection->table($table . ' as r');
if (! $statusAuthoritative && $supplement && $filters['order_no'] === '' && $this->supplementDateIndex !== null
$query = $this->connection->table($table . ' as r');
if ($supplement && $filters['order_no'] === '' && $this->supplementDateIndex !== null
&& $this->connection->getDriverName() === 'mysql') {
// The legacy text payload makes a full table scan very expensive;
// keep date windows on the verified shared-mirror lookup index.
@ -705,16 +670,8 @@ class NonJingxiRefundMirrorRepository
});
});
}
$statusAlias = null;
if (trim((string) ($filters['status'] ?? '')) !== ''
|| trim((string) ($filters['shop_status'] ?? '')) !== '') {
$statusAlias = 'current_refund';
if (! $statusAuthoritative) {
$query->leftJoin('ops_jst_refund_status as current_refund', 'current_refund.as_id', '=', 'r.as_id');
}
}
$this->applyPlatformFilter($query, $filters, $supplement);
$this->applyFilters($query, $filters, $statusAlias, $statusAuthoritative);
$this->applyFilters($query, $filters);
$this->applyApplicationDateFilter($query, $filters, $supplement);
if ($filters['sku_id'] !== '') {
if ($withItems) {
@ -1059,36 +1016,19 @@ class NonJingxiRefundMirrorRepository
}
/** @param array{from:string,to:string,order_no:string,waybill_no:string,shop_name:string,sku_id:string,platform?:string} $filters */
private function applyFilters(
Builder $query,
array $filters,
?string $statusAlias = null,
bool $statusAuthoritative = false,
): void
private function applyFilters(Builder $query, array $filters): void
{
$query->where('r.as_date', '>=', $filters['from'] . ' 00:00:00')
->where('r.as_date', '<', Carbon::parse($filters['to'])->addDay()->format('Y-m-d 00:00:00'));
$status = trim((string) ($filters['status'] ?? ''));
if ($status !== '') {
if ($statusAlias === null) {
$query->where('r.status', $status);
} elseif ($statusAuthoritative) {
$query->where("{$statusAlias}.status", $status);
} else {
$query->whereRaw("COALESCE({$statusAlias}.status, r.status) = ?", [$status]);
}
$query->where('r.status', $status);
}
$shopStatus = trim((string) ($filters['shop_status'] ?? ''));
if ($shopStatus !== '') {
if ($statusAlias === null) {
$query->where('r.shop_status', $shopStatus);
} elseif ($statusAuthoritative) {
$query->where("{$statusAlias}.shop_status", $shopStatus);
} else {
$query->whereRaw("COALESCE({$statusAlias}.shop_status, r.shop_status) = ?", [$shopStatus]);
}
$query->where('r.shop_status', $shopStatus);
}
if ($filters['shop_name'] !== '') {
@ -1185,17 +1125,9 @@ class NonJingxiRefundMirrorRepository
return array_replace($filters, [
'status' => self::PENDING_CONFIRMATION_STATUS,
'shop_status' => self::PENDING_CONFIRMATION_ONLINE_STATUS,
'_status_authoritative' => true,
]);
}
private function assertPendingStatusReady(): void
{
if (! $this->pendingConfirmationStatusReady()) {
throw new RuntimeException('business_mirror_pending_status_not_ready');
}
}
private function normalizePendingConfirmationLabels(object $row): void
{
$row->status = '待确认';

View File

@ -0,0 +1,405 @@
<?php
namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* 聚水潭推广费用日汇总镜像。
*
* 页面只读此表;上游按“日期 + 平台 + 店铺”聚合后再落库,避免订单级
* 大表在页面请求中现场扫描。
*/
class PromotionExpenseMirrorRepository
{
public const TABLE = 'promotion_expense_daily_rows';
public const STATE_TABLE = 'business_mirror_table_states';
public const DATASET_KEY = 'derived.promotion-expenses-daily';
private readonly ConnectionInterface $connection;
public function __construct()
{
$this->connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
}
public function available(): bool
{
try {
return Schema::connection($this->connection->getName())->hasTable(self::TABLE);
} catch (Throwable) {
return false;
}
}
/** @return array{code:string,status:string,last_succeeded_at:?string,last_error:?string,latest_date:?string,row_count:int} */
public function syncStatus(): array
{
if (! $this->available()) {
return [
'code' => 'unavailable',
'status' => 'unavailable',
'last_succeeded_at' => null,
'last_error' => null,
'latest_date' => null,
'row_count' => 0,
];
}
$state = Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)
? $this->connection->table(self::STATE_TABLE)
->where('dataset_key', self::DATASET_KEY)
->first()
: null;
$latestDate = $this->connection->table(self::TABLE)->max('report_date');
$status = (string) ($state->status ?? 'pending');
$lastSucceededAt = $state->last_succeeded_at ?? null;
return [
'code' => match (true) {
$state === null => 'pending',
$status === 'failed' => 'failed',
$lastSucceededAt === null => 'pending',
default => 'ready',
},
'status' => $status,
'last_succeeded_at' => $lastSucceededAt === null ? null : (string) $lastSucceededAt,
'last_error' => $state->last_error_code ?? null,
'latest_date' => $latestDate === null ? null : substr((string) $latestDate, 0, 10),
'row_count' => (int) ($state->mirror_row_count ?? 0),
];
}
/** @return list<string> */
public function monthOptions(string $fromMonth, string $toMonth): array
{
if (! $this->available()) {
return [];
}
$month = $this->monthExpression();
$months = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$fromMonth . '-01', $this->monthEnd($toMonth)])
->selectRaw($month . ' AS report_month')
->distinct()
->orderByDesc('report_month')
->pluck('report_month')
->map(static fn (mixed $value): string => substr((string) $value, 0, 7))
->filter(static fn (string $value): bool => preg_match('/^\d{4}-\d{2}$/', $value) === 1)
->values()
->all();
return array_values(array_unique($months));
}
/** @return list<string> */
public function platforms(): array
{
if (! $this->available()) {
return [];
}
return $this->connection->table(self::TABLE)
->whereNotNull('platform')
->where('platform', '<>', '')
->distinct()
->orderBy('platform')
->pluck('platform')
->map(static fn (mixed $value): string => trim((string) $value))
->filter()
->values()
->all();
}
/** @return list<string> */
public function stores(string $month, string $platform = ''): array
{
if (! $this->available()) {
return [];
}
$query = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$month . '-01', $this->monthEnd($month)])
->whereNotNull('store_name')
->where('store_name', '<>', '');
if ($platform !== '') {
$query->where('platform', $platform);
}
return $query->distinct()
->orderBy('store_name')
->pluck('store_name')
->map(static fn (mixed $value): string => trim((string) $value))
->filter()
->values()
->all();
}
/** @return array<int,array{period:string,source_rows:int,push_fee_total:float,marketing_fee_total:float,total_fee:float}> */
public function periods(
string $fromMonth,
string $toMonth,
string $platform = '',
string $store = '',
): array {
if (! $this->available()) {
return [];
}
$query = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$fromMonth . '-01', $this->monthEnd($toMonth)]);
$this->applyScope($query, $platform, $store);
$month = $this->monthExpression();
$rows = $query
->selectRaw($month . ' AS period')
->selectRaw('COALESCE(SUM(source_rows), 0) AS source_rows')
->selectRaw('COALESCE(SUM(push_fee_total), 0) AS push_fee_total')
->selectRaw('COALESCE(SUM(marketing_fee_total), 0) AS marketing_fee_total')
->selectRaw('COALESCE(SUM(total_fee), 0) AS total_fee')
->groupByRaw($month)
->orderBy('period')
->get();
return $rows->map(static fn (object $row): array => [
'period' => substr((string) $row->period, 0, 7),
'source_rows' => (int) $row->source_rows,
'push_fee_total' => round((float) $row->push_fee_total, 2),
'marketing_fee_total' => round((float) $row->marketing_fee_total, 2),
'total_fee' => round((float) $row->total_fee, 2),
])->values()->all();
}
/**
* @return array{
* rows:list<array<string,mixed>>,
* total:int,
* current_page:int,
* last_page:int,
* per_page:int,
* totals:array{push_fee:float,shared_push_fee:float,push_fee_total:float,marketing_fee:float,shared_marketing_fee:float,marketing_fee_total:float,total_fee:float}
* }
*/
public function details(
string $month,
string $platform = '',
string $store = '',
int $page = 1,
int $limit = 50,
): array {
$page = max(1, $page);
$limit = min(max($limit, 1), 100);
if (! $this->available()) {
return $this->emptyDetails($page, $limit);
}
$aggregated = $this->aggregateDetails($month, $platform, $store);
$total = $aggregated['total'];
return [
'rows' => array_slice($aggregated['rows'], ($page - 1) * $limit, $limit),
'total' => $total,
'current_page' => $page,
'last_page' => max(1, (int) ceil($total / $limit)),
'per_page' => $limit,
'totals' => $aggregated['totals'],
];
}
/** @return list<array<string,mixed>> */
public function exportDetails(string $month, string $platform = '', string $store = ''): array
{
if (! $this->available()) {
return [];
}
return $this->aggregateDetails($month, $platform, $store)['rows'];
}
/**
* @return array{
* rows:list<array<string,mixed>>,
* total:int,
* totals:array{push_fee:float,shared_push_fee:float,push_fee_total:float,marketing_fee:float,shared_marketing_fee:float,marketing_fee_total:float,total_fee:float}
* }
*/
private function aggregateDetails(string $month, string $platform, string $store): array
{
$query = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$month . '-01', $this->monthEnd($month)]);
$this->applyScope($query, $platform, $store);
$rows = $query
->select(['platform', 'store_name'])
->selectRaw('COALESCE(SUM(source_rows), 0) AS source_rows')
->selectRaw('COALESCE(SUM(push_fee), 0) AS push_fee')
->selectRaw('COALESCE(SUM(shared_push_fee), 0) AS shared_push_fee')
->selectRaw('COALESCE(SUM(push_fee_total), 0) AS push_fee_total')
->selectRaw('COALESCE(SUM(marketing_fee), 0) AS marketing_fee')
->selectRaw('COALESCE(SUM(shared_marketing_fee), 0) AS shared_marketing_fee')
->selectRaw('COALESCE(SUM(marketing_fee_total), 0) AS marketing_fee_total')
->selectRaw('COALESCE(SUM(total_fee), 0) AS total_fee')
->groupBy('platform', 'store_name')
->get()
->map(static fn (object $row): array => [
'platform' => (string) $row->platform,
'store_name' => (string) $row->store_name,
'source_rows' => (int) $row->source_rows,
'push_fee' => round((float) $row->push_fee, 2),
'shared_push_fee' => round((float) $row->shared_push_fee, 2),
'push_fee_total' => round((float) $row->push_fee_total, 2),
'marketing_fee' => round((float) $row->marketing_fee, 2),
'shared_marketing_fee' => round((float) $row->shared_marketing_fee, 2),
'marketing_fee_total' => round((float) $row->marketing_fee_total, 2),
'total_fee' => round((float) $row->total_fee, 2),
])
->sort(static function (array $left, array $right): int {
return ([$right['total_fee'], $right['push_fee_total']]
<=> [$left['total_fee'], $left['push_fee_total']])
?: strcmp($left['platform'], $right['platform'])
?: strcmp($left['store_name'], $right['store_name']);
})
->values();
$totals = [
'push_fee' => round((float) $rows->sum('push_fee'), 2),
'shared_push_fee' => round((float) $rows->sum('shared_push_fee'), 2),
'push_fee_total' => round((float) $rows->sum('push_fee_total'), 2),
'marketing_fee' => round((float) $rows->sum('marketing_fee'), 2),
'shared_marketing_fee' => round((float) $rows->sum('shared_marketing_fee'), 2),
'marketing_fee_total' => round((float) $rows->sum('marketing_fee_total'), 2),
'total_fee' => round((float) $rows->sum('total_fee'), 2),
];
return [
'rows' => $rows->all(),
'total' => $rows->count(),
'totals' => $totals,
];
}
/** @param list<array<string,mixed>> $rows */
public function replaceDate(string $date, array $rows): int
{
$now = now();
$normalized = array_map(fn (array $row): array => [
'report_date' => $date,
'platform' => (string) ($row['platform'] ?? '未标记'),
'store_name' => (string) ($row['store_name'] ?? '未标记'),
'source_rows' => (int) ($row['source_rows'] ?? 0),
'push_fee' => round((float) ($row['push_fee'] ?? 0), 2),
'shared_push_fee' => round((float) ($row['shared_push_fee'] ?? 0), 2),
'push_fee_total' => round((float) ($row['push_fee_total'] ?? 0), 2),
'marketing_fee' => round((float) ($row['marketing_fee'] ?? 0), 2),
'shared_marketing_fee' => round((float) ($row['shared_marketing_fee'] ?? 0), 2),
'marketing_fee_total' => round((float) ($row['marketing_fee_total'] ?? 0), 2),
'total_fee' => round(
(float) ($row['push_fee_total'] ?? 0) + (float) ($row['marketing_fee_total'] ?? 0),
2,
),
'synced_at' => $now,
], $rows);
$this->connection->transaction(function () use ($date, $normalized): void {
$this->connection->table(self::TABLE)->where('report_date', $date)->delete();
foreach (array_chunk($normalized, 1000) as $chunk) {
$this->connection->table(self::TABLE)->insert($chunk);
}
});
return count($normalized);
}
public function recordSyncState(string $status, int $rowCount, ?string $error = null): void
{
if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) {
return;
}
$now = now();
$values = [
'source_key' => 'operations_replica',
'source_object' => 'rpt.dws_sn_sales_full_info_di',
'target_table' => self::TABLE,
'status' => $status,
'last_attempted_at' => $now,
'mirror_row_count' => $rowCount,
'last_error_code' => $error,
'updated_at' => $now,
];
if ($status === 'succeeded') {
$values['last_succeeded_at'] = $now;
$values['initial_completed_at'] = $now;
}
$query = $this->connection->table(self::STATE_TABLE)
->where('dataset_key', self::DATASET_KEY);
if ($query->exists()) {
$query->update($values);
return;
}
$this->connection->table(self::STATE_TABLE)->insert($values + [
'dataset_key' => self::DATASET_KEY,
'created_at' => $now,
]);
}
public function count(): int
{
return $this->available() ? (int) $this->connection->table(self::TABLE)->count() : 0;
}
private function applyScope(Builder $query, string $platform, string $store): void
{
if ($platform !== '') {
$query->where('platform', $platform);
}
if ($store !== '') {
$query->where('store_name', $store);
}
}
private function monthExpression(): string
{
return $this->connection->getDriverName() === 'sqlite'
? "strftime('%Y-%m', report_date)"
: "DATE_FORMAT(report_date, '%Y-%m')";
}
private function monthEnd(string $month): string
{
return Carbon::createFromFormat('Y-m-d', $month . '-01', 'Asia/Shanghai')
->endOfMonth()
->toDateString();
}
/** @return array{rows:list<mixed>,total:int,current_page:int,last_page:int,per_page:int,totals:array<string,float>} */
private function emptyDetails(int $page, int $limit): array
{
return [
'rows' => [],
'total' => 0,
'current_page' => $page,
'last_page' => 1,
'per_page' => $limit,
'totals' => [
'push_fee' => 0.0,
'shared_push_fee' => 0.0,
'push_fee_total' => 0.0,
'marketing_fee' => 0.0,
'shared_marketing_fee' => 0.0,
'marketing_fee_total' => 0.0,
'total_fee' => 0.0,
],
];
}
}

View File

@ -1,7 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\EcommerceFinance\Http\Controllers\InvoiceData;
use Modules\EcommerceFinance\Http\Controllers\ProcessDetails;
Route::admin('ecommerce-finance', function () {
@ -42,30 +41,6 @@ Route::admin('ecommerce-finance', function (): void {
->defaults('page', 'oa-process')
->name('business.process-details.pending-payment-summary');
Route::get('workspace/process-data/invoice-data/export', [InvoiceData::class, 'export'])
->middleware('business.page:process-data,invoice-data')
->name('business.invoice-data.export');
Route::post('workspace/process-data/invoice-data/refresh', [InvoiceData::class, 'requestRefresh'])
->middleware(['business.page:process-data,invoice-data', 'throttle:10,1'])
->name('business.invoice-data.refresh');
Route::get(
'workspace/process-data/invoice-data/refresh/{token}',
[InvoiceData::class, 'refreshStatus'],
)
->where('token', '[0-9a-f-]{36}')
->middleware(['business.page:process-data,invoice-data', 'throttle:120,1'])
->name('business.invoice-data.refresh-status');
Route::get(
'workspace/process-data/invoice-data/invoices/{invoice}/attachment',
[InvoiceData::class, 'attachment'],
)
->whereNumber('invoice')
->middleware('business.page:process-data,invoice-data')
->name('business.invoice-data.attachment');
Route::get('workspace/financial-operations/process-details', function (\Illuminate\Http\Request $request) {
return redirect()->route('business.pages.show', array_merge($request->query(), [
'section' => 'process-data',

View File

@ -0,0 +1,124 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
class DingInvoiceAttachmentStore
{
private ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* Persist the source file even when OCR does not find an invoice.
*
* @param array<string,mixed> $file
* @param array{path:string,mime:string,extension:string}|null $preview
* @param list<array{path:string,mime:string,extension:string}> $derivedPreviews
*/
public function record(
object $flow,
array $file,
string $origin,
?array $preview,
string $ocrStatus,
int $invoiceCount,
string $ocrProvider,
?string $error,
?string $hash = null,
array $derivedPreviews = [],
?string $rawPath = null,
): void {
$scope = (string) $flow->source_scope;
$businessId = (string) $flow->business_id;
$fileId = trim((string) ($file['file_id'] ?? ''));
$fileName = trim((string) ($file['file_name'] ?? 'OA附件'));
$fileType = strtolower(trim((string) ($file['file_type'] ?? '')));
$sourceField = trim((string) ($file['source_field'] ?? ''));
$sourcePath = trim((string) ($file['source_path'] ?? ''));
$baseKey = hash('sha256', implode('|', [
$origin,
$fileId,
$fileName,
$sourceField,
$hash ?? '',
]));
$now = now();
$downloadedAt = $file['downloaded_at'] ?? $now;
$baseRow = [
'source_scope' => $scope,
'business_id' => $businessId,
'paid_month' => (string) ($flow->paid_month ?? ''),
'attachment_key' => $baseKey,
'process_instance_id' => mb_substr(trim((string) (
$file['process_instance_id'] ?? $flow->process_instance_id ?? ''
)), 0, 100) ?: null,
'source_file_id' => mb_substr($fileId, 0, 100) ?: null,
'source_file_name' => mb_substr($fileName, 0, 255),
'source_file_type' => mb_substr($fileType, 0, 32) ?: null,
'source_field' => mb_substr($sourceField, 0, 255) ?: null,
'source_origin' => mb_substr($origin, 0, 24),
'source_size' => max(0, (int) ($file['file_size'] ?? 0)),
'source_hash' => $hash === null ? null : mb_substr($hash, 0, 64),
'source_path' => mb_substr($sourcePath, 0, 1024) ?: null,
'raw_path' => $rawPath,
'preview_path' => $preview['path'] ?? null,
'preview_mime' => $preview['mime'] ?? null,
'ocr_status' => mb_substr($ocrStatus, 0, 24),
'ocr_provider' => mb_substr($ocrProvider, 0, 100) ?: null,
'invoice_count' => max(0, $invoiceCount),
'last_error' => $error === null ? null : mb_substr($error, 0, 4000),
'downloaded_at' => $downloadedAt,
'updated_at' => $now,
];
$this->connection->table('ding_invoice_attachment_mirror')->updateOrInsert(
[
'source_scope' => $scope,
'business_id' => $businessId,
'attachment_key' => $baseKey,
],
[...$baseRow, 'created_at' => $now],
);
foreach ($derivedPreviews as $index => $derived) {
if (! isset($derived['path'], $derived['mime'])) {
continue;
}
$extension = strtolower((string) ($derived['extension'] ?? ''));
$baseName = pathinfo($fileName, PATHINFO_FILENAME) ?: 'OA附件';
$displayName = $extension === 'pdf'
? $baseName . '.pdf'
: $baseName . ' · 图片' . ($index + 1) . '.' . ($extension ?: 'jpg');
$derivedKey = hash('sha256', $baseKey . '|preview|' . $derived['path']);
$this->connection->table('ding_invoice_attachment_mirror')->updateOrInsert(
[
'source_scope' => $scope,
'business_id' => $businessId,
'attachment_key' => $derivedKey,
],
[
...$baseRow,
'attachment_key' => $derivedKey,
'source_file_id' => mb_substr($fileId . ':preview:' . $index, 0, 100) ?: null,
'source_file_name' => mb_substr($displayName, 0, 255),
'source_file_type' => mb_substr($extension, 0, 32) ?: null,
'source_size' => 0,
'source_hash' => null,
'raw_path' => null,
'preview_path' => $derived['path'],
'preview_mime' => $derived['mime'],
'last_error' => null,
'created_at' => $now,
],
);
}
}
}

View File

@ -12,6 +12,7 @@ class DingInvoiceFileRecognizer
public function __construct(
private readonly DingInvoiceTextParser $textParser,
private readonly DingInvoiceVisionClient $vision,
private readonly DingInvoicePreviewStore $previewStore,
) {}
/**
@ -34,7 +35,9 @@ class DingInvoiceFileRecognizer
'pdf' => $this->recognizePdf($path, $tempDir),
'jpg', 'jpeg', 'png', 'webp', 'bmp' => $this->recognizeImage($path),
'xlsx' => $this->recognizeXlsx($path, $tempDir),
'xls' => $this->recognizeLegacyXls($path, $tempDir),
'zip' => $this->recognizeZip($path, $tempDir),
'rar', '7z' => $this->recognizeArchive($path, $tempDir, $extension),
default => [
'invoices' => [],
'errors' => ['暂不支持识别 .' . ($extension ?: '未知') . ' 附件'],
@ -46,6 +49,15 @@ class DingInvoiceFileRecognizer
}
}
public function ocrConfigured(): bool
{
return $this->vision->configured()
|| is_executable((string) config(
'ding_invoice_data.tesseract_binary',
'/usr/bin/tesseract',
));
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizePdf(string $path, string $tempDir): array
{
@ -58,15 +70,17 @@ class DingInvoiceFileRecognizer
}
}
if (! $this->vision->configured()) {
if (! $this->ocrConfigured()) {
return [
'invoices' => [],
'errors' => ['PDF 未提取到结构化发票,且未配置 OCR API。'],
'errors' => ['PDF 未提取到结构化发票,且未配置 OCR。'],
'provider' => 'pdf_text',
];
}
$invoices = [];
$errors = [];
$providers = [];
for ($page = 1; $page <= max(1, (int) config('ding_invoice_data.max_pdf_pages', 5)); $page++) {
$prefix = $tempDir . '/page-' . $page;
if (! $this->renderPdfPage($path, $prefix, $page)) {
@ -74,43 +88,343 @@ class DingInvoiceFileRecognizer
}
$imagePath = $prefix . '.png';
try {
$invoice = $this->vision->recognize(
(string) file_get_contents($imagePath),
'image/png',
);
if ($invoice !== null) {
$invoices[] = $invoice;
$result = $this->recognizeImage($imagePath);
array_push($invoices, ...$result['invoices']);
array_push($errors, ...array_map(
static fn (string $error): string => 'PDF 第 ' . $page . ' 页:' . $error,
$result['errors'],
));
if ($result['provider'] !== '') {
$providers[] = $result['provider'];
}
} catch (Throwable $exception) {
$errors[] = 'PDF 第 ' . $page . ' 页:' . $exception->getMessage();
}
}
return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'vision'];
return [
'invoices' => $invoices,
'errors' => $errors,
'provider' => implode('+', array_values(array_unique($providers))),
];
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizeImage(string $path): array
{
if (! $this->vision->configured()) {
$errors = [];
$localOcrAvailable = is_executable((string) config(
'ding_invoice_data.tesseract_binary',
'/usr/bin/tesseract',
));
$ocrAttempted = $this->vision->configured() || $localOcrAvailable;
if ($this->vision->configured()) {
try {
$mime = mime_content_type($path) ?: 'image/jpeg';
$invoice = $this->vision->recognize(
(string) file_get_contents($path),
$mime,
);
if ($invoice !== null) {
return [
'invoices' => [$invoice],
'errors' => [],
'provider' => 'vision',
];
}
} catch (Throwable $exception) {
$errors[] = '图片 OCR API:' . $exception->getMessage();
}
}
try {
$invoice = $this->recognizeLocalImage($path);
if ($invoice !== null) {
return [
'invoices' => [$invoice],
'errors' => $errors,
'provider' => 'local_ocr',
];
}
} catch (Throwable $exception) {
$errors[] = '本地 OCR:' . $exception->getMessage();
}
return [
'invoices' => [],
'errors' => $ocrAttempted
? $errors
: ['图片发票需要配置 OCR API 或本地 Tesseract。'],
'provider' => '',
];
}
/** @return array<string,mixed>|null */
private function recognizeLocalImage(string $path): ?array
{
$binary = (string) config(
'ding_invoice_data.tesseract_binary',
'/usr/bin/tesseract',
);
if (! is_executable($binary)) {
return null;
}
$best = null;
$bestScore = -1;
foreach ([0, 90, 180, 270] as $degrees) {
$imagePath = $degrees === 0
? $path
: $this->rotateImage($path, $degrees);
if ($imagePath === null) {
continue;
}
try {
$text = $this->tesseractText($binary, $imagePath);
$invoice = $this->textParser->parse($text);
if ($invoice === null) {
continue;
}
$score = ($invoice['invoice_number'] !== '' ? 30 : 0)
+ ((float) $invoice['invoice_total'] > 0 ? 30 : 0)
+ ($invoice['invoice_date'] !== null ? 10 : 0)
+ ($invoice['seller_name'] !== '' ? 5 : 0)
+ min(20, substr_count((string) $invoice['item_name'], "\n") * 2);
if ($score > $bestScore) {
$best = $invoice;
$bestScore = $score;
}
} finally {
if ($degrees !== 0 && is_file($imagePath)) {
@unlink($imagePath);
}
}
if (($best['invoice_number'] ?? '') !== ''
&& (float) ($best['invoice_total'] ?? 0) > 0) {
break;
}
}
return $best;
}
private function tesseractText(string $binary, string $path): string
{
$languages = trim((string) config(
'ding_invoice_data.tesseract_languages',
'chi_sim+eng',
)) ?: 'chi_sim+eng';
$process = new Process([
$binary,
$path,
'stdout',
'-l',
$languages,
'--psm',
'3',
]);
$process->setTimeout(90);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException(
trim($process->getErrorOutput()) ?: 'Tesseract OCR 执行失败。',
);
}
return $process->getOutput();
}
private function rotateImage(string $path, int $degrees): ?string
{
$bytes = @file_get_contents($path);
if ($bytes === false || $bytes === '') {
return null;
}
$image = @imagecreatefromstring($bytes);
if ($image === false) {
return null;
}
$background = imagecolorallocate($image, 255, 255, 255);
$rotated = imagerotate($image, -$degrees, $background);
imagedestroy($image);
if ($rotated === false) {
return null;
}
$target = $path . '.rot' . $degrees . '.png';
$saved = imagepng($rotated, $target);
imagedestroy($rotated);
return $saved ? $target : null;
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizeLegacyXls(string $path, string $tempDir): array
{
$binary = (string) config(
'ding_invoice_data.libreoffice_binary',
'/usr/bin/libreoffice',
);
if (! is_executable($binary)) {
return [
'invoices' => [],
'errors' => ['图片发票需要配置 OCR API。'],
'provider' => 'vision',
'errors' => ['XLS 附件需要服务器安装 LibreOffice 后转换识别。'],
'provider' => '',
];
}
$converted = $this->convertOfficeFileToPdf($binary, $path, $tempDir);
if ($converted === null) {
return [
'invoices' => [],
'errors' => ['XLS 转换为 PDF 失败。'],
'provider' => 'libreoffice',
];
}
$pdf = $converted['path'];
$result = $this->recognizePdf($pdf, $converted['output_dir']);
$result['provider'] = $this->joinProviders([
'libreoffice',
$result['provider'],
]);
$preview = $this->persistPreview($pdf, 'converted-invoice.pdf');
if ($preview !== null) {
$result['previews'] = [$preview];
$result['invoices'] = $this->attachPreviewToInvoices($result['invoices'], $preview);
}
return $result;
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizeArchive(
string $path,
string $tempDir,
string $extension,
): array {
$sevenZip = (string) config(
'ding_invoice_data.seven_zip_binary',
'/usr/bin/7z',
);
$unar = (string) config(
'ding_invoice_data.unar_binary',
'/usr/bin/unar',
);
$useUnar = $extension === 'rar' && is_executable($unar);
$binary = $useUnar ? $unar : $sevenZip;
if (! is_executable($binary)) {
return [
'invoices' => [],
'errors' => ['压缩附件需要服务器安装对应的解压工具。'],
'provider' => $extension,
];
}
$outputDir = $tempDir . '/archive-' . bin2hex(random_bytes(4));
if (! mkdir($outputDir, 0755, true) && ! is_dir($outputDir)) {
throw new RuntimeException('无法创建压缩附件临时目录。');
}
$process = new Process($useUnar
? [$binary, '-q', '-f', '-o', $outputDir, $path]
: [$binary, 'x', '-y', '-bd', '-o' . $outputDir, $path]);
$process->setTimeout(120);
$process->run();
$extractedFiles = 0;
if (is_dir($outputDir)) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($outputDir, \FilesystemIterator::SKIP_DOTS),
);
foreach ($iterator as $item) {
if ($item->isFile()) {
$extractedFiles++;
}
}
}
if ($extractedFiles === 0) {
return [
'invoices' => [],
'errors' => [
trim($process->getErrorOutput()) ?: '压缩附件解压失败。',
],
'provider' => $extension,
];
}
$mime = mime_content_type($path) ?: 'image/jpeg';
$bytes = (string) file_get_contents($path);
$invoice = $this->vision->recognize($bytes, $mime);
$invoices = [];
$errors = [];
$previews = [];
if (! $process->isSuccessful()) {
$errors[] = trim($process->getErrorOutput())
?: '压缩附件部分文件解压失败。';
}
$providers = [$extension];
$files = 0;
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($outputDir, \FilesystemIterator::SKIP_DOTS),
);
foreach ($iterator as $item) {
if (! $item->isFile()) {
continue;
}
$files++;
if ($files > max(1, (int) config('ding_invoice_data.max_archive_files', 100))) {
$errors[] = '压缩附件文件数量超过限制。';
break;
}
$extension = strtolower($item->getExtension());
if (! in_array($extension, [
'pdf',
'png',
'jpg',
'jpeg',
'webp',
'bmp',
'xlsx',
'xls',
], true)) {
continue;
}
try {
$result = $this->recognize($item->getPathname(), $item->getFilename());
$preview = $this->persistPreview($item->getPathname(), $item->getFilename());
if ($preview !== null) {
if (($result['previews'] ?? []) === []) {
$result['previews'] = [$preview];
}
if (($result['invoices'] ?? []) !== []) {
$result['invoices'] = $this->attachPreviewToInvoices(
$result['invoices'],
$preview,
);
}
}
array_push($invoices, ...$result['invoices']);
array_push($errors, ...array_map(
static fn (string $error): string =>
$item->getFilename() . ':' . $error,
$result['errors'],
));
$providers[] = $result['provider'];
array_push($previews, ...($result['previews'] ?? []));
} catch (Throwable $exception) {
$errors[] = $item->getFilename() . ':' . $exception->getMessage();
}
}
return [
'invoices' => $invoice === null ? [] : [$invoice],
'errors' => [],
'provider' => 'vision',
'invoices' => $invoices,
'errors' => $errors,
'provider' => $this->joinProviders($providers),
'previews' => $previews,
];
}
/** @param list<string> $providers */
private function joinProviders(array $providers): string
{
return implode('+', array_values(array_unique(array_filter(
array_map('trim', $providers),
))));
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizeXlsx(string $path, string $tempDir): array
{
@ -121,6 +435,7 @@ class DingInvoiceFileRecognizer
$invoices = [];
$errors = [];
$previews = [];
try {
for ($index = 0; $index < $zip->numFiles; $index++) {
$name = (string) $zip->getNameIndex($index);
@ -141,6 +456,14 @@ class DingInvoiceFileRecognizer
try {
$result = $this->recognizeImage($target);
$preview = $this->persistPreview($target, basename($name));
if ($preview !== null) {
$previews[] = $preview;
$result['invoices'] = $this->attachPreviewToInvoices(
$result['invoices'],
$preview,
);
}
array_push($invoices, ...$result['invoices']);
array_push($errors, ...$result['errors']);
} catch (Throwable $exception) {
@ -151,10 +474,47 @@ class DingInvoiceFileRecognizer
$zip->close();
}
return [
$result = [
'invoices' => $invoices,
'errors' => $errors,
'provider' => 'xlsx_media',
'previews' => $previews,
];
if ($invoices !== []) {
return $result;
}
$binary = (string) config(
'ding_invoice_data.libreoffice_binary',
'/usr/bin/libreoffice',
);
if (! is_executable($binary)) {
return $result;
}
$converted = $this->convertOfficeFileToPdf($binary, $path, $tempDir);
if ($converted === null) {
return $result;
}
$pdfResult = $this->recognizePdf($converted['path'], $converted['output_dir']);
$preview = $this->persistPreview($converted['path'], 'converted-invoice.pdf');
if ($preview !== null) {
$pdfResult['previews'] = [$preview];
$pdfResult['invoices'] = $this->attachPreviewToInvoices(
$pdfResult['invoices'],
$preview,
);
$previews[] = $preview;
}
return [
'invoices' => $pdfResult['invoices'],
'errors' => [...$errors, ...$pdfResult['errors']],
'provider' => $this->joinProviders([
'xlsx_media',
'libreoffice',
$pdfResult['provider'],
]),
'previews' => $previews,
];
}
@ -168,6 +528,7 @@ class DingInvoiceFileRecognizer
$invoices = [];
$errors = [];
$previews = [];
try {
for ($index = 0; $index < $zip->numFiles; $index++) {
$name = (string) $zip->getNameIndex($index);
@ -185,8 +546,21 @@ class DingInvoiceFileRecognizer
try {
$result = $this->recognize($target, $name);
$preview = $this->persistPreview($target, basename($name));
if ($preview !== null) {
if (($result['previews'] ?? []) === []) {
$result['previews'] = [$preview];
}
if (($result['invoices'] ?? []) !== []) {
$result['invoices'] = $this->attachPreviewToInvoices(
$result['invoices'],
$preview,
);
}
}
array_push($invoices, ...$result['invoices']);
array_push($errors, ...$result['errors']);
array_push($previews, ...($result['previews'] ?? []));
} catch (Throwable $exception) {
$errors[] = $name . ':' . $exception->getMessage();
}
@ -195,7 +569,91 @@ class DingInvoiceFileRecognizer
$zip->close();
}
return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'zip'];
return [
'invoices' => $invoices,
'errors' => $errors,
'provider' => 'zip',
'previews' => $previews,
];
}
/**
* @param list<array<string,mixed>> $invoices
* @param array{path:string,mime:string,extension:string} $preview
* @return list<array<string,mixed>>
*/
private function attachPreviewToInvoices(array $invoices, array $preview): array
{
foreach ($invoices as &$invoice) {
$invoice['_preview'] = $preview;
}
return $invoices;
}
/** @return array{path:string,mime:string,extension:string}|null */
private function persistPreview(string $path, string $fileName): ?array
{
try {
return $this->previewStore->persistLocalFile(
$path,
[
'file_name' => $fileName,
'file_type' => strtolower(pathinfo($fileName, PATHINFO_EXTENSION)),
],
hash_file('sha256', $path) ?: null,
);
} catch (Throwable $exception) {
report($exception);
return null;
}
}
/** @return array{path:string,output_dir:string}|null */
private function convertOfficeFileToPdf(
string $binary,
string $path,
string $tempDir,
): ?array {
$outputDir = $tempDir . '/office-pdf';
$profileDir = $tempDir . '/libreoffice-profile';
foreach ([
$outputDir,
$profileDir,
$tempDir . '/cache',
$tempDir . '/config',
] as $directory) {
if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) {
throw new RuntimeException('无法创建 Office 转换临时目录。');
}
}
$process = new Process([
$binary,
'--headless',
'--nologo',
'--nodefault',
'--nofirststartwizard',
'-env:UserInstallation=file://' . $profileDir,
'--convert-to',
'pdf',
'--outdir',
$outputDir,
$path,
]);
$process->setEnv([
'HOME' => $tempDir,
'TMPDIR' => $tempDir,
'XDG_CACHE_HOME' => $tempDir . '/cache',
'XDG_CONFIG_HOME' => $tempDir . '/config',
]);
$process->setTimeout(180);
$process->run();
$pdf = $outputDir . '/' . pathinfo($path, PATHINFO_FILENAME) . '.pdf';
return $process->isSuccessful() && is_file($pdf)
? ['path' => $pdf, 'output_dir' => $outputDir]
: null;
}
private function pdfText(string $path): string

View File

@ -0,0 +1,149 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use RuntimeException;
use Throwable;
class DingInvoiceLocalAttachmentImporter
{
private ConnectionInterface $connection;
public function __construct(
DatabaseManager $database,
private readonly DingInvoicePreviewStore $previewStore,
private readonly DingInvoiceAttachmentStore $attachmentStore,
) {
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* @return array{flows:int,files:int,stored:int,skipped:int,errors:list<string>}
*/
public function import(
string $manifestPath,
string $month,
string $baseDirectory,
string $scope = 'personal_permission',
): array {
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
throw new RuntimeException('月份格式应为 YYYY-MM。');
}
$manifest = json_decode((string) file_get_contents($manifestPath), true);
if (! is_array($manifest)) {
throw new RuntimeException('附件清单不是有效 JSON。');
}
$base = realpath($baseDirectory);
if ($base === false) {
throw new RuntimeException('附件基础目录不存在。');
}
$manifestRows = array_is_list($manifest) ? $manifest : (array) ($manifest['flows'] ?? []);
$businessIds = array_values(array_filter(array_map(
static fn (mixed $row): string => is_array($row)
? trim((string) ($row['business_id'] ?? $row['审批编号'] ?? ''))
: '',
$manifestRows,
)));
$flows = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->whereIn('business_id', $businessIds)
->get()
->keyBy('business_id');
$result = [
'flows' => 0,
'files' => 0,
'stored' => 0,
'skipped' => 0,
'errors' => [],
];
$seenFlows = [];
foreach ($manifestRows as $row) {
if (! is_array($row)) {
continue;
}
$businessId = trim((string) ($row['business_id'] ?? $row['审批编号'] ?? ''));
$flow = $flows->get($businessId);
if ($flow === null) {
$result['skipped']++;
continue;
}
$seenFlows[$businessId] = true;
foreach ((array) ($row['files'] ?? []) as $file) {
if (! is_array($file)) {
continue;
}
$result['files']++;
$relativePath = trim((string) ($file['relative_path'] ?? $file['path'] ?? ''));
$candidate = str_starts_with($relativePath, DIRECTORY_SEPARATOR)
? $relativePath
: $base . DIRECTORY_SEPARATOR . $relativePath;
$realPath = realpath($candidate);
if ($realPath === false
|| ! is_file($realPath)
|| ! str_starts_with($realPath, $base . DIRECTORY_SEPARATOR)) {
$result['skipped']++;
$result['errors'][] = $businessId . ':附件不存在或超出基础目录';
continue;
}
$fileName = trim((string) (
$file['file_name']
?? $file['name']
?? basename($realPath)
));
$extension = strtolower((string) pathinfo($fileName, PATHINFO_EXTENSION));
$hash = hash_file('sha256', $realPath) ?: null;
$preview = null;
try {
$rawPath = $this->previewStore->persistRawFile(
$realPath,
['file_name' => $fileName, 'file_type' => $extension],
$hash,
'invoice-attachment-sources/' . $month,
);
$preview = $this->previewStore->persistLocalFile(
$realPath,
[
'file_name' => $fileName,
'file_type' => $extension,
],
$hash,
'invoice-attachments/' . $month,
);
$this->attachmentStore->record(
$flow,
[
'file_id' => (string) ($file['file_id'] ?? ''),
'file_name' => $fileName,
'file_type' => $extension,
'source_field' => (string) ($file['source_field'] ?? $file['source'] ?? '历史附件'),
'source_path' => 'local-import:' . substr($hash ?? '', 0, 16),
'file_size' => filesize($realPath) ?: 0,
'downloaded_at' => now(),
],
'local_import',
$preview,
'pending',
0,
'',
null,
$hash,
[],
$rawPath,
);
$result['stored']++;
} catch (Throwable $exception) {
report($exception);
$result['errors'][] = $businessId . ':' . $exception->getMessage();
}
}
}
$result['flows'] = count($seenFlows);
return $result;
}
}

View File

@ -0,0 +1,253 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
class DingInvoicePreviewStore
{
private const PREVIEW_MIMES = [
'application/pdf' => 'pdf',
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
'image/bmp' => 'bmp',
];
private ConnectionInterface $connection;
public function __construct(
DatabaseManager $database,
private readonly DingTalkApprovalAttachmentDownloader $downloads,
) {
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* Cache image/PDF source attachments in the private business file store.
*
* @param array<string,mixed> $file
* @return array{path:string,mime:string,extension:string}|null
*/
public function persistLocalFile(
string $localPath,
array $file,
?string $hash = null,
string $directory = 'invoice-previews',
): ?array
{
$mime = $this->previewMime($localPath, $file);
if ($mime === null) {
return null;
}
$hash = $hash ?: (hash_file('sha256', $localPath) ?: '');
if ($hash === '') {
return null;
}
$extension = self::PREVIEW_MIMES[$mime];
$path = implode('/', [
trim($directory, '/'),
substr($hash, 0, 2),
$hash . '.' . $extension,
]);
$disk = Storage::disk('uploads');
if (! $disk->exists($path)) {
$stream = fopen($localPath, 'rb');
if ($stream === false) {
return null;
}
try {
if (! $disk->put($path, $stream)) {
return null;
}
} finally {
fclose($stream);
}
}
return [
'path' => $path,
'mime' => $mime,
'extension' => $extension,
];
}
/**
* Preserve the original attachment regardless of whether it can be previewed.
*
* @param array<string,mixed> $file
*/
public function persistRawFile(
string $localPath,
array $file,
?string $hash = null,
string $directory = 'invoice-attachment-sources',
): ?string {
$hash = $hash ?: (hash_file('sha256', $localPath) ?: '');
if ($hash === '') {
return null;
}
$extension = strtolower((string) pathinfo(
(string) ($file['file_name'] ?? $localPath),
PATHINFO_EXTENSION,
));
if (preg_match('/^[a-z0-9]{1,10}$/', $extension) !== 1) {
$extension = 'bin';
}
$path = implode('/', [
trim($directory, '/'),
substr($hash, 0, 2),
$hash . '.' . $extension,
]);
$disk = Storage::disk('uploads');
if ($disk->exists($path)) {
return $path;
}
$stream = fopen($localPath, 'rb');
if ($stream === false) {
return null;
}
try {
return $disk->put($path, $stream) ? $path : null;
} finally {
fclose($stream);
}
}
/**
* Cache a historical invoice attachment on first preview request.
*
* @return array{path:string,mime:string,extension:string}|null
*/
public function ensureStored(object $invoice): ?array
{
return $this->ensureRecordStored($invoice, 'ding_invoice_record_mirror');
}
/**
* Cache a historical raw attachment on first preview request.
*
* @return array{path:string,mime:string,extension:string}|null
*/
public function ensureAttachmentStored(object $attachment): ?array
{
return $this->ensureRecordStored($attachment, 'ding_invoice_attachment_mirror');
}
/** @return array{path:string,mime:string,extension:string}|null */
private function ensureRecordStored(object $record, string $table): ?array
{
$existingPath = trim((string) ($record->preview_path ?? ''));
$existingMime = trim((string) ($record->preview_mime ?? ''));
if ($existingPath !== ''
&& $existingMime !== ''
&& Storage::disk('uploads')->exists($existingPath)) {
return [
'path' => $existingPath,
'mime' => $existingMime,
'extension' => pathinfo($existingPath, PATHINFO_EXTENSION),
];
}
$processInstanceId = trim((string) ($record->process_instance_id ?? ''));
$fileId = trim((string) ($record->source_file_id ?? ''));
if ($processInstanceId === '' || $fileId === '') {
return null;
}
$uri = $this->downloads->downloadUri($processInstanceId, $fileId);
if ($uri === null) {
return null;
}
$tempRoot = storage_path('app/temp/invoice-preview');
if (! is_dir($tempRoot) && ! mkdir($tempRoot, 0755, true) && ! is_dir($tempRoot)) {
throw new RuntimeException('无法创建发票预览临时目录。');
}
$tempPath = $tempRoot . '/' . bin2hex(random_bytes(8));
try {
$response = Http::timeout(120)
->withOptions(['sink' => $tempPath])
->get($uri);
if (! $response->successful() || ! is_file($tempPath)) {
return null;
}
if (filesize($tempPath) > (int) config('ding_invoice_data.max_file_bytes')) {
return null;
}
$preview = $this->persistLocalFile(
$tempPath,
[
'file_name' => (string) ($record->source_file_name ?? ''),
'file_type' => (string) ($record->source_file_type ?? ''),
],
trim((string) ($record->source_hash ?? '')),
);
if ($preview === null) {
return null;
}
$this->connection->table($table)
->where('id', (int) $record->id)
->where('source_scope', (string) $record->source_scope)
->update([
'preview_path' => $preview['path'],
'preview_mime' => $preview['mime'],
'updated_at' => now(),
]);
return $preview;
} finally {
if (is_file($tempPath)) {
@unlink($tempPath);
}
}
}
/** @param array<string,mixed> $file */
private function previewMime(string $path, array $file): ?string
{
$mime = '';
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if ($finfo !== false) {
$mime = strtolower((string) finfo_file($finfo, $path));
finfo_close($finfo);
}
}
if (! isset(self::PREVIEW_MIMES[$mime])) {
$fileType = strtolower((string) ($file['file_type'] ?? ''));
$extension = strtolower(pathinfo(
(string) ($file['file_name'] ?? ''),
PATHINFO_EXTENSION,
));
$mime = match ($extension) {
'pdf' => 'application/pdf',
'jpg', 'jpeg' => 'image/jpeg',
'png' => 'image/png',
'webp' => 'image/webp',
'bmp' => 'image/bmp',
default => match (true) {
$fileType === 'pdf' || str_contains($fileType, 'pdf') => 'application/pdf',
in_array($fileType, ['jpg', 'jpeg', 'image/jpeg'], true) => 'image/jpeg',
in_array($fileType, ['png', 'image/png'], true) => 'image/png',
in_array($fileType, ['webp', 'image/webp'], true) => 'image/webp',
in_array($fileType, ['bmp', 'image/bmp'], true) => 'image/bmp',
default => '',
},
};
}
return isset(self::PREVIEW_MIMES[$mime]) ? $mime : null;
}
}

View File

@ -0,0 +1,143 @@
<?php
namespace Modules\EcommerceFinance\Services;
class DingInvoiceRecordNormalizer
{
/**
* @param list<array<string,mixed>> $invoices
* @return list<array<string,mixed>>
*/
public function deduplicate(array $invoices): array
{
$unique = [];
foreach ($invoices as $invoice) {
$key = $this->invoiceKey($invoice);
$unique[$key] = isset($unique[$key])
? $this->mergeMissing($unique[$key], $invoice)
: $invoice;
}
return array_values($unique);
}
/** @param array<string,mixed> $invoice */
public function invoiceKey(array $invoice): string
{
$number = $this->invoiceNumber($invoice);
if ($number !== '') {
return hash('sha256', 'number:' . $number);
}
return hash('sha256', implode('|', [
'fallback',
mb_strtolower($this->text($invoice['seller_name'] ?? '')),
number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''),
$this->text($invoice['invoice_date'] ?? ''),
$this->text($invoice['item_name'] ?? ''),
]));
}
/** @param array<string,mixed> $invoice */
public function invoiceNumber(array $invoice): string
{
return mb_strtoupper((string) preg_replace(
'/[^0-9A-Za-z]/',
'',
$this->text($invoice['invoice_number'] ?? ''),
));
}
/**
* @param array<string,mixed> $existing
* @param array<string,mixed> $incoming
* @return array<string,mixed>
*/
public function mergeScanned(array $existing, array $incoming): array
{
$provider = (string) ($existing['ocr_provider'] ?? '');
if (str_starts_with($provider, 'imported_workbook')) {
$merged = $existing;
foreach ([
'invoice_type',
'seller_name',
'seller_tax_no',
'buyer_name',
'buyer_tax_no',
'invoice_total',
'invoice_number',
'invoice_date',
'item_name',
'amount_without_tax',
'tax_rate',
'tax_amount',
] as $field) {
if ($this->empty($merged[$field] ?? null)
&& ! $this->empty($incoming[$field] ?? null)) {
$merged[$field] = $incoming[$field];
}
}
foreach ([
'process_instance_id',
'source_file_id',
'source_file_name',
'source_file_type',
'source_field',
'source_path',
'source_hash',
'preview_path',
'preview_mime',
] as $field) {
if (! $this->empty($incoming[$field] ?? null)) {
$merged[$field] = $incoming[$field];
}
}
$merged['updated_at'] = $incoming['updated_at'];
return $merged;
}
$merged = $existing;
foreach ($incoming as $field => $value) {
if (in_array($field, ['id', 'created_at'], true)) {
continue;
}
if ($field === 'invoice_total' && (float) $value <= 0) {
continue;
}
if (! $this->empty($value)) {
$merged[$field] = $value;
}
}
return $merged;
}
/**
* @param array<string,mixed> $left
* @param array<string,mixed> $right
* @return array<string,mixed>
*/
private function mergeMissing(array $left, array $right): array
{
foreach ($right as $key => $value) {
if ($this->empty($left[$key] ?? null) && ! $this->empty($value)) {
$left[$key] = $value;
}
}
return $left;
}
private function empty(mixed $value): bool
{
return $value === null
|| (is_string($value) && trim($value) === '')
|| (is_array($value) && $value === []);
}
private function text(mixed $value): string
{
return trim((string) ($value ?? ''));
}
}

View File

@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
@ -11,6 +12,8 @@ use Throwable;
class DingInvoiceSyncService
{
private const DIRECT_SOURCE_NAME = 'OA attachment scan';
private ConnectionInterface $connection;
public function __construct(
@ -18,6 +21,9 @@ class DingInvoiceSyncService
private readonly UpstreamReadOnlyQueryFactory $queries,
private readonly DingTalkApprovalAttachmentDownloader $downloads,
private readonly DingInvoiceFileRecognizer $recognizer,
private readonly DingInvoiceRecordNormalizer $normalizer,
private readonly DingInvoicePreviewStore $previewStore,
private readonly DingInvoiceAttachmentStore $attachmentStore,
private readonly DingTalkProcessInstanceClient $approvalClient,
) {
$this->connection = $database->connection(
@ -44,6 +50,8 @@ class DingInvoiceSyncService
->update([
'scan_status' => 'pending',
'scanned_at' => null,
'scan_attempts' => 0,
'next_scan_at' => null,
'updated_at' => now(),
]);
}
@ -52,8 +60,8 @@ class DingInvoiceSyncService
->where('source_scope', $scope)
->where('paid_month', $month)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->whereNull('scanned_at');
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($query);
$flows = $query
->orderByDesc('paid_at')
->orderByDesc('business_id')
@ -62,19 +70,20 @@ class DingInvoiceSyncService
->all();
if ($flows === []) {
$remaining = (int) $this->connection->table('ding_invoice_flow_mirror')
$remainingQuery = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->whereNull('scanned_at')
->count();
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($remainingQuery);
$remaining = (int) $remainingQuery->count();
return [
'status' => 'succeeded',
'month' => $month,
'processed_flows' => 0,
'recognized_invoices' => 0,
'preserved_invoices' => 0,
'failed_flows' => 0,
'remaining_flows' => $remaining,
'ocr_configured' => $this->recognizerOcrConfigured(),
@ -82,7 +91,7 @@ class DingInvoiceSyncService
}
$businessIds = array_values(array_filter(array_column($flows, 'business_id')));
[$workflows, $attachmentRows] = $this->loadUpstreamWorkflowsAndAttachments($businessIds);
[$workflows, $attachmentRows] = $this->loadWorkflowAttachments($flows);
$attachmentsByBusiness = $this->groupAttachmentsByBusiness($attachmentRows, $workflows);
$attachmentsByBusiness = $this->addCommentAttachmentFallback(
$businessIds,
@ -93,6 +102,7 @@ class DingInvoiceSyncService
$metrics = [
'processed_flows' => 0,
'recognized_invoices' => 0,
'preserved_invoices' => 0,
'failed_flows' => 0,
'remaining_flows' => 0,
'ocr_configured' => $this->recognizerOcrConfigured(),
@ -114,7 +124,8 @@ class DingInvoiceSyncService
$tempRoot . '/' . preg_replace('/[^A-Za-z0-9_-]/', '_', $businessId),
);
$metrics['processed_flows']++;
$metrics['recognized_invoices'] += $flowResult['invoice_count'];
$metrics['recognized_invoices'] += $flowResult['recognized_invoices'];
$metrics['preserved_invoices'] += $flowResult['preserved_invoices'];
if ($flowResult['scan_status'] === 'failed') {
$metrics['failed_flows']++;
}
@ -123,13 +134,13 @@ class DingInvoiceSyncService
$this->removeDirectory($tempRoot);
}
$metrics['remaining_flows'] = (int) $this->connection->table('ding_invoice_flow_mirror')
$remainingQuery = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->whereNull('scanned_at')
->count();
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($remainingQuery);
$metrics['remaining_flows'] = (int) $remainingQuery->count();
$this->updateState($metrics);
return [
@ -139,6 +150,67 @@ class DingInvoiceSyncService
];
}
public function latestPendingMonth(): ?string
{
$monthQuery = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope())
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($monthQuery);
$month = $monthQuery->max('paid_month');
return trim((string) $month) ?: null;
}
private function applyScanCandidates(Builder $query): void
{
$now = now();
$maxAttempts = max(
1,
(int) config('ding_invoice_data.max_scan_attempts', 3),
);
$query->where(function (Builder $candidate) use ($now, $maxAttempts): void {
$candidate
->whereNull('scanned_at')
->orWhere('scan_status', 'pending')
->orWhere(function (Builder $imported) use ($now): void {
$imported->whereIn('scan_status', ['recognized', 'no_invoice'])
->where(function (Builder $source): void {
$source->whereNull('source_name')
->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME);
})
->where(function (Builder $due) use ($now): void {
$due->whereNull('next_scan_at')
->orWhere('next_scan_at', '<=', $now);
});
})
->orWhere(function (Builder $retry) use ($now, $maxAttempts): void {
$retry->whereIn('scan_status', ['failed', 'partial'])
->where('scan_attempts', '<', $maxAttempts)
->where(function (Builder $due) use ($now): void {
$due->whereNull('next_scan_at')
->orWhere('next_scan_at', '<=', $now);
});
})
->orWhere(function (Builder $attachmentBackfill): void {
$attachmentBackfill->where('attachment_count', '>', 0)
->whereNotExists(function (Builder $exists): void {
$exists->selectRaw('1')
->from('ding_invoice_attachment_mirror as attachment')
->whereColumn(
'attachment.source_scope',
'ding_invoice_flow_mirror.source_scope',
)
->whereColumn(
'attachment.business_id',
'ding_invoice_flow_mirror.business_id',
);
});
});
});
}
private function assertReady(): void
{
if (! Schema::connection($this->connection->getName())->hasTable('ding_invoice_flow_mirror')
@ -226,37 +298,58 @@ class DingInvoiceSyncService
}
/**
* @param list<string> $businessIds
* @param list<object> $flows
* @return array{0:array<string,array<string,mixed>>,1:list<array<string,mixed>>}
*/
private function loadUpstreamWorkflowsAndAttachments(array $businessIds): array
private function loadWorkflowAttachments(array $flows): array
{
if ($businessIds === []) {
if ($flows === []) {
return [[], []];
}
$query = $this->queries->forSourceWithTimeout('operations_replica', 120);
$placeholders = implode(',', array_fill(0, count($businessIds), '?'));
$workflowRows = $query->select(
'SELECT businessId, processInstanceId, title, status, result '
. 'FROM rpt.ding_Workflow '
. "WHERE businessId IN ({$placeholders}) ORDER BY businessId",
$businessIds,
);
$workflows = [];
foreach ($workflowRows as $row) {
$businessId = trim((string) ($row['businessId'] ?? ''));
if ($businessId !== '') {
$workflows[$businessId] = $row;
$missingProcessIds = [];
foreach ($flows as $flow) {
$businessId = trim((string) ($flow->business_id ?? ''));
if ($businessId === '') {
continue;
}
$workflows[$businessId] = [
'businessId' => $businessId,
'processInstanceId' => trim((string) ($flow->process_instance_id ?? '')),
'title' => $flow->title ?? null,
'status' => null,
'result' => null,
];
if ($workflows[$businessId]['processInstanceId'] === '') {
$missingProcessIds[] = $businessId;
}
}
if ($missingProcessIds !== []) {
$localRows = $this->connection->table('ding_process_detail_mirror')
->where('source_scope', $this->scope())
->whereIn('business_id', $missingProcessIds)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->get(['business_id', 'process_instance_id']);
foreach ($localRows as $row) {
$businessId = trim((string) ($row->business_id ?? ''));
if (isset($workflows[$businessId])) {
$workflows[$businessId]['processInstanceId'] = trim(
(string) ($row->process_instance_id ?? ''),
);
}
}
}
$processIds = array_values(array_unique(array_filter(array_map(
static fn (array $row): string => trim((string) ($row['processInstanceId'] ?? '')),
$workflowRows,
array_values($workflows),
))));
if ($processIds === []) {
return [$workflows, []];
}
$query = $this->queries->forSourceWithTimeout('operations_replica', 120);
$processPlaceholders = implode(',', array_fill(0, count($processIds), '?'));
$attachmentRows = $query->select(
'SELECT processInstanceId, name, value '
@ -431,7 +524,14 @@ class DingInvoiceSyncService
/**
* @param array<string,mixed> $workflow
* @param list<array<string,mixed>> $files
* @return array{scan_status:string,invoice_count:int,invoice_total:float,error:?string}
* @return array{
* scan_status:string,
* invoice_count:int,
* recognized_invoices:int,
* preserved_invoices:int,
* invoice_total:float,
* error:?string
* }
*/
private function scanFlow(object $flow, array $workflow, array $files, string $tempDir): array
{
@ -449,6 +549,7 @@ class DingInvoiceSyncService
$invoices = [];
$errors = [];
$scannedFiles = 0;
$flowPreviewFallbacks = [];
foreach ($files as $index => $file) {
if ((int) ($file['file_size'] ?? 0) > (int) config('ding_invoice_data.max_file_bytes')) {
@ -466,7 +567,19 @@ class DingInvoiceSyncService
$extension = strtolower(pathinfo($file['file_name'], PATHINFO_EXTENSION));
if ($extension === '' && in_array(
strtolower((string) ($file['file_type'] ?? '')),
['pdf', 'jpg', 'jpeg', 'png', 'webp', 'bmp', 'xlsx', 'zip'],
[
'pdf',
'jpg',
'jpeg',
'png',
'webp',
'bmp',
'xlsx',
'xls',
'zip',
'rar',
'7z',
],
true,
)) {
$extension = strtolower((string) $file['file_type']);
@ -484,8 +597,59 @@ class DingInvoiceSyncService
}
$scannedFiles++;
$hash = hash_file('sha256', $path) ?: null;
$preview = null;
$rawPath = null;
try {
$rawPath = $this->previewStore->persistRawFile(
$path,
$file,
$hash,
'invoice-attachment-sources/' . ((string) $flow->paid_month ?: 'unknown'),
);
} catch (Throwable $exception) {
report($exception);
}
try {
$preview = $this->previewStore->persistLocalFile(
$path,
$file,
$hash,
'invoice-attachments/' . ((string) $flow->paid_month ?: 'unknown'),
);
} catch (Throwable $exception) {
report($exception);
}
$recognized = $this->recognizer->recognize($path, $file['file_name']);
if ($preview !== null && ($recognized['invoices'] ?? []) !== []) {
$flowPreviewFallbacks[$preview['path']] = [
'preview_path' => $preview['path'],
'preview_mime' => $preview['mime'],
'source_file_id' => $file['file_id'],
'source_file_name' => $file['file_name'],
'source_file_type' => $extension ?: $file['file_type'],
'source_field' => $file['source_field'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
];
}
foreach (($recognized['previews'] ?? []) as $derivedPreview) {
if (! is_array($derivedPreview) || empty($derivedPreview['path'])) {
continue;
}
$flowPreviewFallbacks[$derivedPreview['path']] = [
'preview_path' => $derivedPreview['path'],
'preview_mime' => $derivedPreview['mime'] ?? null,
'source_file_id' => $file['file_id'],
'source_file_name' => $file['file_name'],
'source_file_type' => $extension ?: $file['file_type'],
'source_field' => $file['source_field'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
];
}
foreach ($recognized['invoices'] as $invoice) {
$invoicePreview = $invoice['_preview'] ?? $preview;
unset($invoice['_preview']);
$invoice['_source'] = [
'file_id' => $file['file_id'],
'file_name' => $file['file_name'],
@ -494,57 +658,119 @@ class DingInvoiceSyncService
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
'ocr_provider' => $recognized['provider'],
'preview_path' => $invoicePreview['path'] ?? null,
'preview_mime' => $invoicePreview['mime'] ?? null,
];
$invoices[] = $invoice;
}
$fileError = $recognized['errors'] === []
? null
: implode("\n", $recognized['errors']);
try {
$this->attachmentStore->record(
$flow,
[
...$file,
'file_type' => $extension ?: $file['file_type'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'downloaded_at' => now(),
],
str_contains((string) $file['source_field'], '评论') ? 'comment' : 'form',
$preview,
$recognized['invoices'] !== []
? 'recognized'
: ($recognized['errors'] !== [] ? 'failed' : 'not_invoice'),
count($recognized['invoices']),
(string) $recognized['provider'],
$fileError,
$hash,
$recognized['previews'] ?? [],
$rawPath,
);
} catch (Throwable $exception) {
report($exception);
}
array_push($errors, ...array_map(
static fn (string $error): string => $file['file_name'] . ':' . $error,
$recognized['errors'],
));
} catch (Throwable $exception) {
$errors[] = $file['file_name'] . ':' . $exception->getMessage();
$message = $file['file_name'] . ':' . $exception->getMessage();
$errors[] = $message;
try {
$this->attachmentStore->record(
$flow,
[
...$file,
'source_path' => 'dingtalk:' . $processInstanceId . '/' . ($file['file_id'] ?? ''),
'downloaded_at' => now(),
],
str_contains((string) ($file['source_field'] ?? ''), '评论') ? 'comment' : 'form',
null,
'failed',
0,
'',
$message,
);
} catch (Throwable $storeException) {
report($storeException);
}
}
}
$invoices = $this->deduplicate($invoices);
$invoiceTotal = round(array_sum(array_map(
static fn (array $invoice): float => (float) $invoice['invoice_total'],
$invoices,
)), 2);
$scanStatus = match (true) {
$errors !== [] && $invoices !== [] => 'partial',
$errors !== [] && $invoices === [] => 'failed',
$invoices !== [] => 'recognized',
default => 'no_invoice',
};
$invoices = $this->normalizer->deduplicate($invoices);
$error = $errors === [] ? null : mb_substr(implode("\n", array_slice($errors, 0, 8)), 0, 4000);
$scope = $this->scope();
$businessId = (string) $flow->business_id;
$processInstanceId = (string) (
$workflow['processInstanceId']
?? $flow->process_instance_id
?? ''
);
$existingRows = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->get()
->mapWithKeys(static fn (object $row): array => [
(string) $row->invoice_key => (array) $row,
])
->all();
$invoiceCount = count($existingRows);
$invoiceTotal = round((float) array_sum(array_map(
static fn (array $record): float => (float) ($record['invoice_total'] ?? 0),
$existingRows,
)), 2);
$preservedInvoices = 0;
$scanStatus = 'no_invoice';
$this->connection->transaction(function () use (
$flow,
$invoices,
$invoiceTotal,
$scanStatus,
$error,
$files,
$scannedFiles,
$workflow,
$scope,
$businessId,
$processInstanceId,
$existingRows,
$flowPreviewFallbacks,
&$invoiceCount,
&$invoiceTotal,
&$preservedInvoices,
&$scanStatus,
): void {
$scope = $this->scope();
$businessId = (string) $flow->business_id;
$this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->delete();
$now = now();
$records = [];
$remainingExisting = $existingRows;
$newRecords = [];
foreach ($invoices as $invoice) {
$source = $invoice['_source'];
$records[] = [
$record = [
'source_scope' => $scope,
'business_id' => $businessId,
'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''),
'process_instance_id' => $processInstanceId,
'paid_month' => (string) $flow->paid_month,
'invoice_key' => $this->invoiceKey($invoice),
'invoice_key' => $this->normalizer->invoiceKey($invoice),
'invoice_type' => mb_substr((string) $invoice['invoice_type'], 0, 100),
'seller_name' => mb_substr((string) $invoice['seller_name'], 0, 255),
'seller_tax_no' => mb_substr((string) $invoice['seller_tax_no'], 0, 64),
@ -564,6 +790,8 @@ class DingInvoiceSyncService
'source_path' => mb_substr((string) $source['source_path'], 0, 1024),
'source_hash' => $source['source_hash'],
'ocr_provider' => mb_substr((string) $source['ocr_provider'], 0, 32),
'preview_path' => $source['preview_path'] ?? null,
'preview_mime' => $source['preview_mime'] ?? null,
'recognition_payload' => json_encode(
array_diff_key($invoice, ['_source' => true]),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
@ -571,22 +799,88 @@ class DingInvoiceSyncService
'created_at' => $now,
'updated_at' => $now,
];
$key = (string) $record['invoice_key'];
if (isset($remainingExisting[$key])) {
$merged = $this->normalizer->mergeScanned(
$remainingExisting[$key],
$record,
);
$id = (int) $merged['id'];
unset($merged['id'], $merged['created_at']);
$this->connection->table('ding_invoice_record_mirror')
->where('id', $id)
->update($merged);
unset($remainingExisting[$key]);
continue;
}
$newRecords[] = $record;
}
if ($records !== []) {
$this->connection->table('ding_invoice_record_mirror')->insert($records);
if ($newRecords !== []) {
$this->connection->table('ding_invoice_record_mirror')->insert($newRecords);
}
if (count($flowPreviewFallbacks) === 1) {
$fallback = reset($flowPreviewFallbacks);
foreach ($remainingExisting as $existing) {
if (! str_starts_with((string) ($existing['ocr_provider'] ?? ''), 'imported_workbook')) {
continue;
}
$this->connection->table('ding_invoice_record_mirror')
->where('id', (int) $existing['id'])
->update([
'source_file_id' => $fallback['source_file_id'],
'source_file_name' => $fallback['source_file_name'],
'source_file_type' => $fallback['source_file_type'],
'source_field' => $fallback['source_field'],
'source_path' => mb_substr((string) $fallback['source_path'], 0, 1024),
'source_hash' => $fallback['source_hash'],
'preview_path' => $fallback['preview_path'],
'preview_mime' => $fallback['preview_mime'],
'updated_at' => $now,
]);
}
}
$persistedRows = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->get(['invoice_total']);
$invoiceCount = $persistedRows->count();
$invoiceTotal = round((float) $persistedRows->sum('invoice_total'), 2);
$preservedInvoices = count($remainingExisting);
$scanStatus = match (true) {
$error !== null && $invoiceCount > 0 => 'partial',
$error !== null && $invoiceCount === 0 => 'failed',
$invoiceCount > 0 => 'recognized',
default => 'no_invoice',
};
$scanAttempts = (int) ($flow->scan_attempts ?? 0) + 1;
$maxAttempts = max(
1,
(int) config('ding_invoice_data.max_scan_attempts', 3),
);
$nextScanAt = match (true) {
$scanStatus === 'failed' && $scanAttempts < $maxAttempts => $now->copy()->addMinutes(
max(1, (int) config('ding_invoice_data.failed_retry_minutes', 60)),
),
$scanStatus === 'partial' && $scanAttempts < $maxAttempts => $now->copy()->addMinutes(
max(1, (int) config('ding_invoice_data.partial_retry_minutes', 360)),
),
default => null,
};
$this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->update([
'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''),
'process_instance_id' => $processInstanceId,
'title' => $flow->title ?: ($workflow['title'] ?? null),
'invoice_count' => count($records),
'invoice_count' => $invoiceCount,
'invoice_total' => $invoiceTotal,
'scan_status' => $scanStatus,
'attachment_count' => count($files),
'scanned_file_count' => $scannedFiles,
'last_error' => $error,
'source_name' => self::DIRECT_SOURCE_NAME,
'scan_attempts' => $scanAttempts,
'next_scan_at' => $nextScanAt,
'scanned_at' => $now,
'updated_at' => $now,
]);
@ -594,81 +888,17 @@ class DingInvoiceSyncService
return [
'scan_status' => $scanStatus,
'invoice_count' => count($invoices),
'invoice_count' => $invoiceCount,
'recognized_invoices' => count($invoices),
'preserved_invoices' => $preservedInvoices,
'invoice_total' => $invoiceTotal,
'error' => $error,
];
}
/** @param list<array<string,mixed>> $invoices @return list<array<string,mixed>> */
private function deduplicate(array $invoices): array
{
$unique = [];
foreach ($invoices as $invoice) {
$number = preg_replace(
'/[^0-9A-Za-z]/',
'',
(string) ($invoice['invoice_number'] ?? ''),
) ?? '';
$seller = trim((string) ($invoice['seller_name'] ?? ''));
$amount = number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', '');
$key = $number !== ''
? 'number:' . $number
: 'near:' . mb_strtolower($seller) . '|' . $amount;
foreach ($unique as $existingKey => $existing) {
$existingSeller = trim((string) ($existing['seller_name'] ?? ''));
$existingAmount = number_format((float) ($existing['invoice_total'] ?? 0), 2, '.', '');
if ($seller !== ''
&& $existingSeller !== ''
&& mb_strtolower($seller) === mb_strtolower($existingSeller)
&& $amount === $existingAmount) {
$key = $existingKey;
break;
}
}
if (! isset($unique[$key])) {
$unique[$key] = $invoice;
} else {
$unique[$key] = $this->mergeInvoice($unique[$key], $invoice);
}
}
return array_values($unique);
}
/** @param array<string,mixed> $left @param array<string,mixed> $right */
private function mergeInvoice(array $left, array $right): array
{
foreach ($right as $key => $value) {
if (($left[$key] ?? null) === null
|| (is_string($left[$key]) && trim($left[$key]) === '')
|| (is_array($left[$key]) && $left[$key] === [])) {
$left[$key] = $value;
}
}
return $left;
}
/** @param array<string,mixed> $invoice */
private function invoiceKey(array $invoice): string
{
$number = preg_replace('/[^0-9A-Za-z]/', '', (string) ($invoice['invoice_number'] ?? '')) ?? '';
return hash('sha256', $number !== ''
? 'number:' . $number
: implode('|', [
'near',
(string) ($invoice['seller_name'] ?? ''),
number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''),
(string) ($invoice['invoice_date'] ?? ''),
(string) ($invoice['item_name'] ?? ''),
]));
}
private function recognizerOcrConfigured(): bool
{
return trim((string) config('ding_invoice_data.ocr.api_key', '')) !== '';
return $this->recognizer->ocrConfigured();
}
/** @param array<string,mixed> $metrics */

View File

@ -14,31 +14,52 @@ class DingInvoiceTextParser
if ($text === '') {
return null;
}
if (class_exists(\Normalizer::class)) {
$text = \Normalizer::normalize($text, \Normalizer::FORM_KC) ?: $text;
}
$text = preg_replace('/(?<=\d)\.\s+(?=\d{2})/u', '.', $text) ?? $text;
$invoiceNumber = $this->invoiceNumber($text);
$invoiceTotal = $this->invoiceTotal($text);
if ($invoiceNumber === '' && $invoiceTotal <= 0) {
if ($invoiceNumber === ''
|| $invoiceTotal <= 0
|| ! in_array(strlen($invoiceNumber), [8, 20], true)) {
return null;
}
$taxNumbers = [];
if (preg_match_all(
'/(?:统一社会信用代码|纳税人识别号|税号)\s*[::]\s*([0-9A-Z]{15,20})/u',
$text,
$matches,
)) {
$taxNumbers = array_values(array_unique($matches[1]));
$taxPatterns = [
'/(?:统一社会信用代码|纳税人识别号|税号)[^\nA-Z0-9]{0,16}([0-9A-Z]{15,20})/u',
'/(?<![0-9A-Z])([0-9A-Z]{18})(?![0-9A-Z])/u',
];
foreach ($taxPatterns as $pattern) {
if (preg_match_all($pattern, $text, $matches)) {
foreach ($matches[1] as $value) {
$taxNumbers[] = strtoupper($value);
}
}
if ($taxNumbers !== []) {
break;
}
}
$taxNumbers = array_values(array_unique($taxNumbers));
$names = [];
if (preg_match_all('/名称\s*[::]\s*([^\n]{2,120})/u', $text, $matches)) {
$names = array_values(array_unique(array_filter(array_map(
static fn (string $value): string => trim(
preg_replace('/\s{2,}.*$/u', '', $value) ?? $value,
),
$matches[1],
))));
$segments = preg_split('/(?<!项目)名称\s*[::]/u', $text) ?: [];
foreach (array_slice($segments, 1) as $segment) {
$value = preg_split(
'/(?:\n|统一社会信用代码|纳税人识别号|税号)/u',
$segment,
2,
)[0] ?? '';
$value = preg_replace('/\s*\|.*$/u', '', $value) ?? $value;
$value = preg_replace('/\s+(?:SS|FS|OS|S)\s*$/u', '', $value) ?? $value;
$value = trim((string) preg_replace('/\s+/u', '', $value));
if ($value !== '' && mb_strlen($value) <= 120) {
$names[] = $value;
}
}
$names = array_values(array_unique($names));
$invoiceDate = null;
if (preg_match('/开票日期\s*[::]?\s*(\d{4})[年\-\/](\d{1,2})[月\-\/](\d{1,2})/u', $text, $matches)) {
@ -52,6 +73,18 @@ class DingInvoiceTextParser
$invoiceDate = null;
}
}
if ($invoiceDate === null
&& preg_match('/(?<!\d)(20\d{2})[年\-\/](\d{1,2})[月\-\/](\d{1,2})(?!\d)/u', $text, $matches)) {
try {
$invoiceDate = Carbon::createFromDate(
(int) $matches[1],
(int) $matches[2],
(int) $matches[3],
)->format('Y-m-d');
} catch (Throwable) {
$invoiceDate = null;
}
}
$items = [];
if (preg_match_all('/^\s*(\*[^\n]{2,180})$/mu', $text, $matches)) {
@ -66,8 +99,8 @@ class DingInvoiceTextParser
return [
'is_invoice' => true,
'invoice_type' => $this->invoiceType($text),
'seller_name' => $names[1] ?? ($names[0] ?? ''),
'seller_tax_no' => $taxNumbers[1] ?? ($taxNumbers[0] ?? ''),
'seller_name' => $names[1] ?? '',
'seller_tax_no' => $taxNumbers[1] ?? '',
'buyer_name' => $names[0] ?? '',
'buyer_tax_no' => $taxNumbers[0] ?? '',
'invoice_total' => $invoiceTotal,
@ -83,8 +116,25 @@ class DingInvoiceTextParser
private function invoiceNumber(string $text): string
{
if (preg_match('/发票号码\s*[::]?\s*([0-9A-Z]{8,32})/u', $text, $matches)) {
return strtoupper($matches[1]);
foreach ([
'/发票号码\s*[::]?\s*([0-9A-Z][0-9A-Z ::]{7,40})/u',
'/发[买米来][号玛码]?\s*[::]?\s*([0-9A-Z][0-9A-Z ::]{7,40})/u',
'/(?<!\\d)([0-9]{20})(?!\\d)/u',
] as $pattern) {
if (preg_match($pattern, $text, $matches)) {
$number = strtoupper((string) preg_replace(
'/[^0-9A-Z]/',
'',
$matches[1],
));
if (strlen($number) >= 8) {
return $number;
}
}
}
if ((str_contains($text, '发票号码') || str_contains($text, '定额发票'))
&& preg_match('/(?<!\\d)([0-9]{8})(?!\\d)/u', $text, $matches)) {
return $matches[1];
}
return '';
@ -92,18 +142,31 @@ class DingInvoiceTextParser
private function invoiceTotal(string $text): float
{
$values = [];
if (preg_match_all(
'/(?:价税合计(?:\s*(?:\(小写\)|(小写)))?|小写)\s*[::]?\s*[¥¥]?\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/u',
$text,
$matches,
)) {
foreach ($matches[1] as $value) {
$values[] = round((float) str_replace(',', '', $value), 2);
foreach ([
'/(?:\(小写\)|(小写))\s*[::]?\s*[^\n0-9]{0,4}([0-9][0-9,]*\.[0-9]{2})/u',
'/[零壹贰叁肆伍陆柒捌玖拾佰仟万圆元角分整]{4,}\s*[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u',
'/票价\s*[::]?\s*[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u',
'/(?:价税合计|合计)[^\n]{0,25}[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u',
] as $pattern) {
if (preg_match_all($pattern, $text, $matches) && $matches[1] !== []) {
$values = array_map(
static fn (string $value): float =>
round((float) str_replace(',', '', $value), 2),
$matches[1],
);
return max($values);
}
}
if ($values !== []) {
return max($values);
if (str_contains($text, '发票')
&& preg_match_all('/[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u', $text, $matches)
&& $matches[1] !== []) {
return max(array_map(
static fn (string $value): float =>
round((float) str_replace(',', '', $value), 2),
$matches[1],
));
}
return 0.0;

View File

@ -61,7 +61,7 @@ class DingInvoiceWorkbookImporter
public function import(
string $path,
string $scope = 'personal_permission',
bool $replaceMonths = true,
bool $replaceImportedRecords = true,
): array {
if (! is_file($path)) {
throw new RuntimeException('发票台账文件不存在。');
@ -247,30 +247,117 @@ class DingInvoiceWorkbookImporter
$this->connection->transaction(function () use (
$scope,
$months,
$replaceMonths,
$replaceImportedRecords,
$flows,
$invoiceRows,
$invoiceTotal,
): void {
if ($replaceMonths) {
$businessIds = array_keys($flows);
$existingFlows = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->whereIn('business_id', $businessIds)
->get()
->keyBy('business_id');
foreach ($flows as $businessId => $flow) {
$existing = $existingFlows->get($businessId);
$values = $flow;
if ($existing !== null) {
$values['process_instance_id'] = $existing->process_instance_id;
$values['attachment_count'] = (int) $existing->attachment_count;
$values['scanned_file_count'] = (int) $existing->scanned_file_count;
$values['last_error'] = $existing->last_error;
$values['source_name'] = $existing->source_name ?: $flow['source_name'];
$values['scanned_at'] = $existing->scanned_at ?: $flow['scanned_at'];
$values['created_at'] = $existing->created_at;
if (in_array((string) $existing->scan_status, ['partial', 'failed'], true)) {
$values['scan_status'] = $existing->scan_status;
}
}
$this->connection->table('ding_invoice_flow_mirror')->updateOrInsert(
[
'source_scope' => $scope,
'business_id' => $businessId,
],
$values,
);
}
if ($replaceImportedRecords) {
$this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->whereIn('paid_month', $months)
->whereIn('business_id', $businessIds)
->where('ocr_provider', 'imported_workbook')
->delete();
// Legacy OCR could persist a "number only" row with no amount.
// Once an audited ledger covers the flow, such a row is noise.
$this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->whereIn('business_id', $businessIds)
->where('invoice_total', '<=', 0)
->delete();
}
$existingRecords = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->whereIn('business_id', $businessIds)
->get()
->keyBy(static fn (object $row): string =>
$row->business_id . '|' . $row->invoice_key
);
foreach ($invoiceRows as $record) {
$key = $record['business_id'] . '|' . $record['invoice_key'];
$existing = $existingRecords->get($key);
if ($existing === null) {
$this->connection->table('ding_invoice_record_mirror')->insert($record);
continue;
}
$merged = $this->mergeImportedRecord((array) $existing, $record);
unset($merged['id'], $merged['created_at']);
$this->connection->table('ding_invoice_record_mirror')
->where('id', $existing->id)
->update($merged);
}
$recordTotals = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->whereIn('business_id', $businessIds)
->get(['business_id', 'invoice_total'])
->groupBy('business_id');
$now = now();
foreach ($businessIds as $businessId) {
$records = $recordTotals->get($businessId, collect());
$lastError = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->value('last_error');
$count = $records->count();
$status = match (true) {
$lastError !== null && $lastError !== '' && $count > 0 => 'partial',
$lastError !== null && $lastError !== '' => 'failed',
$count > 0 => 'recognized',
default => 'no_invoice',
};
$this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->whereIn('paid_month', $months)
->delete();
->where('business_id', $businessId)
->update([
'invoice_count' => $count,
'invoice_total' => round((float) $records->sum('invoice_total'), 2),
'scan_status' => $status,
'updated_at' => $now,
]);
}
foreach (array_chunk(array_values($flows), 250) as $chunk) {
$this->connection->table('ding_invoice_flow_mirror')->insert($chunk);
}
foreach (array_chunk($invoiceRows, 250) as $chunk) {
$this->connection->table('ding_invoice_record_mirror')->insert($chunk);
}
$this->updateState(count($invoiceRows), count($flows), $invoiceTotal);
$this->updateState(
count($invoiceRows),
count($flows),
$invoiceTotal,
$months,
$scope,
);
});
return [
@ -282,7 +369,13 @@ class DingInvoiceWorkbookImporter
];
}
private function updateState(int $invoiceRows, int $flowRows, float $invoiceTotal): void
private function updateState(
int $invoiceRows,
int $flowRows,
float $invoiceTotal,
array $months,
string $scope,
): void
{
if (! $this->connection->getSchemaBuilder()->hasTable('business_mirror_table_states')) {
return;
@ -307,7 +400,10 @@ class DingInvoiceWorkbookImporter
'last_attempted_at' => $now,
'last_succeeded_at' => $now,
'last_upserted_rows' => $invoiceRows,
'mirror_row_count' => $invoiceRows,
'mirror_row_count' => $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->whereIn('paid_month', $months)
->count(),
'mirror_row_count_is_exact' => true,
'last_error_code' => null,
'updated_at' => $now,
@ -392,4 +488,35 @@ class DingInvoiceWorkbookImporter
return $existing;
}
/**
* @param array<string,mixed> $existing
* @param array<string,mixed> $record
* @return array<string,mixed>
*/
private function mergeImportedRecord(array $existing, array $record): array
{
foreach ($record as $key => $value) {
if (in_array($key, [
'source_file_id',
'source_file_name',
'source_file_type',
'source_field',
'source_path',
'source_hash',
'ocr_provider',
'recognition_payload',
'created_at',
], true)) {
continue;
}
if ($value === null || (is_string($value) && trim($value) === '')) {
continue;
}
$existing[$key] = $value;
}
return $existing;
}
}

View File

@ -26,7 +26,7 @@ final class FreightCarrierRules
];
/** 发货日期早于此日不核算(报价核算从 2026-11 起)。 */
public const START_DATE = '2026-11-01';
public const START_DATE = '2026-10-01';
/** @return array<string,array<string,mixed>> */
public static function all(): array

View File

@ -176,6 +176,12 @@ final class ShippingFreightCalculator
}
}
if ($settle <= 0 && ! in_array($m, ['F', 'PERQTY'], true)) {
$d['settle_w'] = null;
return $bad('缺少有效计费重量');
}
switch ($m) {
case '_PERKG':
break;

View File

@ -44,7 +44,7 @@ class ShippingReplicaSynchronizer
];
private const PRESERVED_CONTACT_FIELDS = ['receiver_name', 'receiver_mobile', 'receiver_phone'];
private const REFRESHED_PACKAGE_FIELDS = [
'trade_no', 'express_name1', 'warehouse_name', 'shop_name', 'platform', 'pay_time', 'ship_time',
'express_no', 'trade_no', 'express_name1', 'warehouse_name', 'shop_name', 'platform', 'pay_time', 'ship_time',
'receiver_state', 'receiver_city', 'receiver_district',
];
private const PRESERVED_ITEM_FIELDS = ['finished_barcode', 'finished_name', 'finished_supplier'];
@ -127,8 +127,10 @@ class ShippingReplicaSynchronizer
/** @var array<string,bool> 本次已吐出包裹的交易单号 */
private array $emittedSo = [];
/** 快递单号(去@) => [交易单号 => true]:同一单号被不同交易单号共用(合包/拼单)时,按交易单号区分是否已处理 */
/** 快递单号 => 交易单号 => 首包来源键;0 表示已经处理,但无法确认所有包裹对应的出库单。 */
private array $doneTrackSo = [];
/** @var array<int,true> 已确认是同一快递单号下不同出库单的包裹。 */
private array $repeatedOutboundSources = [];
/** @var array<int,true> 本轮按规则排除的包裹 source_id(取消/拆分/合并/线上发货),窗口内旧记录需清掉 */
private array $excludedSourceIds = [];
@ -199,6 +201,8 @@ class ShippingReplicaSynchronizer
throw new InvalidArgumentException('跳过运费仅支持指定起止日期的历史补录。');
}
$this->skipFreight = $skipFreight;
// Only an explicit date window is a replacement run. The regular incremental
// path keeps its existing fast upsert semantics and does not rescan old parcels.
$this->replaceWindow = (bool) $windowed;
$this->packagesProcessed = 0;
$this->packagesWithoutItems = 0;
@ -237,6 +241,7 @@ class ShippingReplicaSynchronizer
$this->emittedTrack = [];
$this->emittedSo = [];
$this->doneTrackSo = [];
$this->repeatedOutboundSources = [];
$this->excludedSourceIds = [];
$this->ioDate = [];
$this->ioLc = [];
@ -264,6 +269,10 @@ class ShippingReplicaSynchronizer
$outb = $this->syncOutbound($fromS, $toS, $now, $progress);
$pout = $this->syncPurchaseOut($fromS, $toS, $now, $progress);
$purged = $this->purgeExcludedPackages($fromS, $toS);
$platformFixed = $this->normalizePlatformCodes($fromS, $toS);
if ($progress && $platformFixed > 0) {
$progress('平台代码(AS/IMPORT/历史等)按店铺还原:' . $platformFixed . ' 行');
}
if ($progress && $purged > 0) {
$progress('清除已排除包裹(取消/拆分/合并/线上发货):' . $purged . ' 行');
}
@ -384,6 +393,7 @@ class ShippingReplicaSynchronizer
$this->dwsFailedDays = [];
$this->seenSourceIds = [];
$this->expressOrderIds = [];
$this->repeatedOutboundSources = [];
gc_collect_cycles();
}
}
@ -414,7 +424,7 @@ class ShippingReplicaSynchronizer
}
$toDel = [];
foreach ($prefixed as $sourceId => [$tradeNo, $shipDate, $expressNo]) {
if ($expressNo !== '' && isset($clean[$tradeNo][$shipDate][$expressNo])) {
if (! isset($this->repeatedOutboundSources[$sourceId]) && $expressNo !== '' && isset($clean[$tradeNo][$shipDate][$expressNo])) {
$toDel[] = $sourceId;
}
}
@ -551,7 +561,7 @@ class ShippingReplicaSynchronizer
// 订单已取消/已拆分/已合并:实际发货在子单或合并单上,工作平台不出此行。
// 只登记本行自己的单号,不登记订单单号(可能是子单真实单号,需留给出库单兜底)
$this->markDone('', (string) ($r['logistic_id'] ?? ''));
$this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['logistic_id'] ?? ''));
$this->markTrackSo((string) ($r['so_id'] ?? ''), 0, (string) ($r['logistic_id'] ?? ''));
$this->excludeSource($pkgId);
continue;
}
@ -560,29 +570,28 @@ class ShippingReplicaSynchronizer
// 换单:快递明细仍是旧单号,出库单已换成新单号 → 用新单号与对应出库单(工作平台口径)
$r['logistic_id'] = $sw['l_id'];
}
$this->markDone(
$sw !== null ? $sw['io'] : $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), (string) ($r['inner_order_id'] ?? '')),
(string) ($r['logistic_id'] ?? ''),
(string) ($r['jo_lid'] ?? ''),
$sw !== null ? $sw['old'] : ''
);
$this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['logistic_id'] ?? ''), (string) ($r['jo_lid'] ?? ''));
if ($this->excludedByLabel($r['order_labels'] ?? null) || $this->excludedByLabel($r['jo_labels'] ?? null)) {
$so = (string) ($r['so_id'] ?? '');
$oid = (string) ($r['inner_order_id'] ?? '');
$lid = (string) ($r['logistic_id'] ?? '');
$orderLid = (string) ($r['jo_lid'] ?? '');
$io = $sw !== null ? $sw['io'] : $this->ioFor($ioMap, $lid, $oid);
$this->markDone($io, $lid, $orderLid, $sw['old'] ?? '');
$excluded = $this->excludedByLabel($r['order_labels'] ?? null) || $this->excludedByLabel($r['jo_labels'] ?? null);
if ($excluded) {
$this->markTrackSo($so, 0, $lid, $orderLid);
$this->excludeSource($pkgId);
continue; // 线上发货(平台代发/云仓):工作平台不拉,对齐排除(发货明细标签可能滞后,订单标签一并判断)
}
$so = (string) ($r['so_id'] ?? '');
$oid = (string) ($r['inner_order_id'] ?? '');
$io = $sw !== null ? $sw['io'] : $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), $oid);
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, (string) ($r['logistic_id'] ?? ''));
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, $lid);
if (trim((string) ($r['logistic_id'] ?? '')) === '') {
// 发货明细无单号:出库单单号 → 订单单号 → 空(不借运费表里同订单其它包裹的单号)
$ioLid = ($io !== '') ? (string) ($ioMap['ioL'][$io] ?? '') : '';
$joLid = trim((string) ($r['jo_lid'] ?? ''));
$tracking = $ioLid !== '' ? $ioLid : ($joLid !== '' ? $joLid : null);
} else {
$tracking = $this->tracking((string) ($r['logistic_id'] ?? ''), (string) ($r['jo_lid'] ?? ''), $freight, $so);
$tracking = $this->tracking($lid, $orderLid, $freight, $so);
}
$this->markTrackSo($so, $io !== '' ? $pkgId : 0, (string) $tracking, $lid, $orderLid);
// 发货时间 = 出库单 io_date(工作平台口径,样本 400/400 一致),缺失时回落发货明细时间
$shipTime = ($io !== '' ? $this->ts($this->ioDate[$io] ?? null) : null)
?? $this->ts($r['send_time'] ?? null) ?? $this->ts($r['jo_send'] ?? null);
@ -631,7 +640,7 @@ class ShippingReplicaSynchronizer
continue;
}
$ph = implode(',', array_fill(0, count($chunk), '?'));
$sql = "SELECT o_id, l_id, send_date, status, labels FROM rpt.jst_Orders om WHERE om.o_id IN ({$ph})";
$sql = "SELECT o_id, l_id, send_date, status, labels, shop_name FROM rpt.jst_Orders om WHERE om.o_id IN ({$ph})";
foreach ($this->selectWithReconnect($sql, $chunk) as $row) {
$oid = (string) ($row['o_id'] ?? '');
if ($oid === '') {
@ -642,6 +651,7 @@ class ShippingReplicaSynchronizer
$this->orderMetadata[$oid] = [
'l_id' => $row['l_id'] ?? null,
'send_date' => $row['send_date'] ?? null,
'shop_name' => $row['shop_name'] ?? null,
'status' => in_array($st, ['Cancelled', 'Split', 'Merged'], true) ? $st : null,
'online' => $this->excludedByLabel($row['labels'] ?? null),
];
@ -664,6 +674,9 @@ class ShippingReplicaSynchronizer
if (($row['jo_send'] ?? '') === '' && ($metadata['send_date'] ?? '') !== '') {
$row['jo_send'] = $metadata['send_date'];
}
if (trim((string) ($row['shop_name'] ?? '')) === '' && ! empty($metadata['shop_name'])) {
$row['shop_name'] = $metadata['shop_name'];
}
// 订单状态/标签:取消/拆分/合并 与 订单级"线上发货"标签的排除判断用
if (($row['jo_status'] ?? '') === '' && ($metadata['status'] ?? '') !== '') {
$row['jo_status'] = $metadata['status'];
@ -792,20 +805,22 @@ class ShippingReplicaSynchronizer
if ($tracking !== null && isset($this->emittedTrack[ltrim(trim($tracking), '@')])) {
$tracking = null;
}
$this->markDone($this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), $oid), (string) ($r['l_id'] ?? ''));
$this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['l_id'] ?? ''));
if ($this->excludedByLabel($r['labels'] ?? null)) {
$this->excludeSource(self::AUTOSHIP_OFFSET + (int) $oid);
$so = (string) ($r['so_id'] ?? '');
$lid = (string) ($r['l_id'] ?? '');
$io = $this->ioFor($ioMap, $lid, $oid);
$pkgId = self::AUTOSHIP_OFFSET + (int) $oid;
$this->markDone($io, $lid);
$excluded = $this->excludedByLabel($r['labels'] ?? null);
$this->markTrackSo($so, ! $excluded && $io !== '' && $tracking !== null ? $pkgId : 0, $lid);
if ($excluded) {
$this->excludeSource($pkgId);
continue; // 线上发货:对齐排除
}
$so = (string) ($r['so_id'] ?? '');
$io = $this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), $oid);
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, (string) ($r['l_id'] ?? ''));
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, $lid);
$shipTime = ($io !== '' ? $this->ts($this->ioDate[$io] ?? null) : null) ?? $this->ts($r['send_date'] ?? null);
$pkg = $this->pkgFromOrder($r, $tracking, $shipTime);
$pkg['platform'] = $this->platformOf($io, $pkg['platform']);
$pkg = $this->withViewAddr($io, $pkg);
$pkgId = self::AUTOSHIP_OFFSET + (int) $oid;
$pkg = $this->withViewCarrier($io, $pkg, $pkgId);
$total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now, true);
}
@ -847,6 +862,87 @@ class ShippingReplicaSynchronizer
return $map[$base] ?? $raw;
}
/** 订单来源代码(售后补发/导入/历史单等):工作平台显示的是店铺所属平台,不显示代码。 */
private const PLATFORM_CODES = ['AS', '历史AS', 'IMPORT', '历史', 'ERP', 'JDDROPSHIP'];
private const PLATFORM_CODE_DIRECT = ['JDDROPSHIP' => '京东厂家直送'];
private const SHOP_PREFIX_PLATFORM = [
'京喜' => '京东商城', '京东' => '京东商城', '天猫' => '淘宝天猫', '淘宝' => '淘宝天猫',
'拼多多' => '拼多多', '阿里巴巴' => '阿里巴巴', '抖音' => '头条放心购', '得物' => '得物',
];
private static function isPlatformCode(?string $p): bool
{
$p = trim((string) $p);
if ($p === '') {
return false;
}
foreach (explode(',', $p) as $part) {
if (! in_array(trim($part), self::PLATFORM_CODES, true)) {
return false;
}
}
return true;
}
/**
* 平台为订单来源代码的包裹:按同店铺最常见的平台还原(11 月 53 个对上工作平台 52 个);
* JDDROPSHIP 直接为京东厂家直送;店铺无历史时按店铺名前缀;都判断不了则不动。
*/
public function normalizePlatformCodes(string $fromS, string $toS): int
{
$rows = $this->db->table('jst_oms_shipping')
->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS)
->where(function ($q): void {
$q->whereIn('platform', self::PLATFORM_CODES)->orWhere('platform', 'like', '%,%');
})
->select('platform', 'shop_name')->distinct()->get();
$fixed = 0;
$byShop = [];
foreach ($rows as $r) {
if (! self::isPlatformCode($r->platform)) {
continue;
}
$codes = array_map('trim', explode(',', (string) $r->platform));
$shop = trim((string) $r->shop_name);
$target = null;
foreach ($codes as $c) {
if (isset(self::PLATFORM_CODE_DIRECT[$c])) {
$target = self::PLATFORM_CODE_DIRECT[$c];
}
}
if ($target === null && $shop !== '') {
if (! array_key_exists($shop, $byShop)) {
$top = $this->db->table('jst_oms_shipping')->where('shop_name', $shop)
->whereNotNull('platform')->where('platform', '!=', '')
->whereNotIn('platform', self::PLATFORM_CODES)->where('platform', 'not like', '%,%')
->groupBy('platform')->orderByRaw('COUNT(*) DESC')->limit(1)
->selectRaw('platform, COUNT(*) AS n')->first();
$byShop[$shop] = $top ? (string) $top->platform : null;
}
$target = $byShop[$shop];
if ($target === null) {
foreach (self::SHOP_PREFIX_PLATFORM as $prefix => $pf) {
if (str_starts_with($shop, $prefix)) {
$target = $pf;
break;
}
}
}
}
if ($target === null) {
continue;
}
$q = $this->db->table('jst_oms_shipping')
->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS)
->where('platform', $r->platform);
$shop === '' ? $q->where(fn ($w) => $w->whereNull('shop_name')->orWhere('shop_name', '')) : $q->where('shop_name', $r->shop_name);
$fixed += $q->update(['platform' => $target]);
}
return $fixed;
}
/** 记下按规则排除的包裹;同步结束后清掉它在本窗口里的旧记录(此前版本可能写入过)。 */
private function excludeSource(int $sourceId): void
{
@ -880,13 +976,14 @@ class ShippingReplicaSynchronizer
}
/** 登记 单号×交易单号 已处理。 */
private function markTrackSo(string $so, string ...$tracks): void
private function markTrackSo(string $so, int $sourceId, string $tracking, string ...$aliases): void
{
$so = trim($so);
foreach ($tracks as $t) {
$trackKey = ltrim(trim($tracking), '@');
foreach ([$tracking, ...$aliases] as $t) {
$t = ltrim(trim($t), '@');
if ($t !== '') {
$this->doneTrackSo[$t][$so] = true;
$this->doneTrackSo[$t][$so] = $sourceId === 0 || $t !== $trackKey ? 0 : ($this->doneTrackSo[$t][$so] ?? $sourceId);
}
}
}
@ -936,7 +1033,7 @@ class ShippingReplicaSynchronizer
for ($a = $lo; $a <= $hi; $a += $step) {
$page++;
$rows = $this->selectWithReconnect(
"SELECT {$cols} FROM " . self::OUTBOUND . ' WHERE Id >= ? AND Id < ? AND io_date >= ? AND io_date < ?',
"SELECT {$cols} FROM " . self::OUTBOUND . ' WHERE Id >= ? AND Id < ? AND io_date >= ? AND io_date < ? ORDER BY Id',
[$a, $a + $step, $fromS, $toS]
);
$scanned += count($rows);
@ -959,8 +1056,6 @@ class ShippingReplicaSynchronizer
$skip['done']++;
continue;
}
// 单号已处理过:若是别的交易单号共用此单号(合包/拼单),仍要补吐;交易单号要等视图表头加载后判断
$r['_trk_done'] = $lid !== '' && isset($this->doneTrack[ltrim($lid, '@')]);
$st = (string) ($r['status'] ?? '');
if (stripos($st, 'cancel') !== false || stripos($st, 'delete') !== false) {
$skip['status']++;
@ -994,16 +1089,22 @@ class ShippingReplicaSynchronizer
$h = $heads[$io] ?? [];
$so = $this->outboundSo($r, $h);
$tracking = trim((string) ($r['l_id'] ?? ''));
if (! empty($r['_trk_done'])) {
$t0 = ltrim($tracking, '@');
if ($so === '' || empty($this->doneTrackSo[$t0]) || isset($this->doneTrackSo[$t0][$so])) {
$skip['done']++;
continue;
}
$trackKey = ltrim($tracking, '@');
// 即时读取同批已处理记录。当前 io_id 已在前面去重;旧包裹来源明确才可补同交易单号的另一次出库。
$previous = $this->doneTrackSo[$trackKey] ?? [];
if (isset($this->doneTrack[$trackKey]) && ($so === '' || $previous === [] || ($previous[$so] ?? null) === 0)) {
$skip['done']++;
continue;
}
$sameTrackAgain = isset($previous[$so]);
$pkgId = self::OUTBOUND_OFFSET + (int) $io;
if ($sameTrackAgain) {
$this->repeatedOutboundSources[$previous[$so]] = true;
$this->repeatedOutboundSources[$pkgId] = true;
}
$pkg = $this->pkgFromOutbound($r, $tracking !== '' ? $tracking : null, $this->ts($r['io_date'] ?? null), $h, $so);
$pkg = $this->withViewAddr($io, $pkg);
$pkg = $this->withViewCarrier($io, $pkg, self::OUTBOUND_OFFSET + (int) $io);
$pkg = $this->withViewCarrier($io, $pkg, $pkgId);
if (trim((string) ($pkg['express_name1'] ?? '')) === self::NO_LOGISTICS) {
if (empty($this->ioWare[$io])) {
$pkg['warehouse_name'] = self::NO_LOGISTICS_WAREHOUSE;
@ -1011,9 +1112,9 @@ class ShippingReplicaSynchronizer
$virtualEmitted++;
}
$this->itemsFromView = true;
$total += $this->emitPackage(self::OUTBOUND_OFFSET + (int) $io, $pkg, $viewItems[$io], $skus, $freight, $so, $tracking !== '' ? $tracking : null, $now, true);
$total += $this->emitPackage($pkgId, $pkg, $viewItems[$io], $skus, $freight, $so, $tracking !== '' ? $tracking : null, $now, true, $sameTrackAgain);
$this->markDone($io, $tracking);
$this->markTrackSo($so, $tracking);
$this->markTrackSo($so, $pkgId, $tracking);
$emitted++;
}
unset($viewItems, $heads, $skus, $freight);
@ -1064,6 +1165,8 @@ class ShippingReplicaSynchronizer
'l' => null, 'w' => null, 'h' => null, 'vol' => null, 'weight' => null, 'supplier' => null,
];
$it['qty'] = $qty;
// A purchase-out correction changes quantity; discard the old view total.
unset($it['vol'], $it['mvol'], $it['volume_is_total']);
$out[] = $it;
}
@ -1234,7 +1337,7 @@ class ShippingReplicaSynchronizer
* 输出一个包裹的所有明细行(每件一行;无商品则一行空商品)。
* @return int 组装行数
*/
private function emitPackage(int $pkgId, array $pkg, array $items, array $skus, array $freight, string $so, ?string $tracking, $now, bool $auto = false): int
private function emitPackage(int $pkgId, array $pkg, array $items, array $skus, array $freight, string $so, ?string $tracking, $now, bool $auto = false, bool $sameTrackAgain = false): int
{
$items = array_values(array_filter($items, fn ($it) => ! $this->isPricePatch($it['name'] ?? null)));
$items = $this->dropZeroQtyPlaceholders($items);
@ -1252,6 +1355,16 @@ class ShippingReplicaSynchronizer
$items = $virtualItems;
}
}
if ($this->whName($pkg['warehouse_name'] ?? null) === null) {
// 包裹级仓库为空:取第一个有效商品行仓库,整包统一(避免同一包裹一行 "0"、一行仓库名)
foreach ($items as $it) {
$w = $this->whName($it['warehouse'] ?? null);
if ($w !== null) {
$pkg['warehouse_name'] = $w;
break;
}
}
}
$n = count($items);
$tk = ltrim(trim((string) ($tracking ?? '')), '@');
if ($tk !== '') {
@ -1269,6 +1382,11 @@ class ShippingReplicaSynchronizer
// 进而误用同交易单号其它包裹的运费和快递名称。
$f = $freight[$so . '|' . $tk] ?? ($freight[$so . '|'] ?? []);
$hasFreight = isset($f['cost']);
// 聚水潭按「交易单号+单号」返回运费合计。同单号补吐使用本包裹重量,合计只留在首包。
// 已取到上游合计时继续标记运费完整,以免重跑时把旧的重复运费带回来。
if ($sameTrackAgain) {
$f = [];
}
$packageRows = [];
if ($n === 0) {
@ -1282,7 +1400,7 @@ class ShippingReplicaSynchronizer
$syntheticSkuIds = [];
foreach ($items as $idx => $it) {
$first = ($idx === 0);
$sk = (! empty($it['sku']) && isset($skus[(string) $it['sku']])) ? $skus[(string) $it['sku']] : [];
$sk = $skus[mb_strtolower(trim((string) ($it['sku'] ?? '')))] ?? [];
$skuSid = (int) ($it['id'] ?? ($pkgId * 100 + $idx));
if (($it['id'] ?? null) === null) {
$syntheticSkuIds[$skuSid] = true;
@ -1298,7 +1416,7 @@ class ShippingReplicaSynchronizer
/**
* 导出明细体积(对齐工作平台 OmsDataDay):默认 数量×长×宽×高;
* 代发仓(配置)且非标准承运商 → 长×宽×高;特定快递 → 0;无尺寸 → 空。
* 特定虚拟快递 → 0;无尺寸 → 空。仓库和承运商不再改变数量倍率。
*/
private function detailVolume(mixed $L, mixed $W, mixed $H, float $qty, string $warehouse, string $express): ?float
{
@ -1314,13 +1432,24 @@ class ShippingReplicaSynchronizer
return null;
}
$unit = $l * $w * $h;
$noQty = in_array(trim($warehouse), (array) ($cfg['no_qty_warehouses'] ?? []), true)
&& ! in_array($express, (array) ($cfg['qty_carriers_in_no_qty_warehouses'] ?? []), true);
return round($noQty ? $unit : $unit * max($qty, 1), 4);
return round($unit * max($qty, 0), 4);
}
/**
* 商品名称按工作平台口径取商品资料名称(同一条码各店铺一致);商品资料没有名称时才用订单明细名称(京东、得物等是平台标题)。
* 虚拟/补差类明细(信誉订单虚拟条码、补差价等)保留订单明细名称,下游按名称识别。
*/
private function productName(mixed $itemName, mixed $skuName): ?string
{
$item = trim((string) ($itemName ?? ''));
$sku = trim((string) ($skuName ?? ''));
if ($item !== '' && preg_match('/虚拟条码|透明挂钩|无实物|补差价|差价专用|补收差价/u', $item)) {
return (string) $itemName;
}
return $sku !== '' ? (string) $skuName : ($item !== '' ? (string) $itemName : null);
}
/** 组装一件明细行。包裹级字段(实称重量/运费)仅首件携带。 */
/** 文本对齐工作平台:工作平台入库时把 & 替换成 ^(如 "&gt;" 导出为 "^gt;",样本 22/22)。 */
private function wpText(mixed $v): ?string
{
@ -1336,9 +1465,11 @@ class ShippingReplicaSynchronizer
{
$w = trim((string) ($w ?? ''));
return ($w === '' || $w === '{未指定发货仓}') ? null : $w;
// 聚水潭部分虚拟/补差单的仓库字段是 "0"(无仓库),工作平台不显示 "0"
return ($w === '' || $w === '0' || $w === '{未指定发货仓}') ? null : $w;
}
/** 组装一件明细行。包裹级字段(实称重量/运费)仅首件携带。 */
private function buildRow(array $pkg, array $it, array $sk, array $f, bool $first, string $countStr, $now, bool $auto): array
{
$qty = (float) ($it['qty'] ?? 0);
@ -1347,7 +1478,12 @@ class ShippingReplicaSynchronizer
$L = ($it['l'] ?? null) ?: ($sk['l'] ?? null);
$W = ($it['w'] ?? null) ?: ($sk['w'] ?? null);
$H = ($it['h'] ?? null) ?: ($sk['h'] ?? null);
$vol = ($it['vol'] ?? null) ? round((float) $it['vol'], 4) : (($L && $W && $H) ? round((float) $L * (float) $W * (float) $H, 4) : null);
$detailVol = $this->detailVolume($L, $W, $H, $qty, (string) ($pkg['warehouse_name'] ?: ($it['warehouse'] ?? '')), (string) ($pkg['express_name1'] ?? ''));
// The view carries a parcel total, while a split combo part carries a unit volume.
// Keep an explicit total once; multiply unit volumes by the shipped quantity.
$vol = isset($it['vol'])
? round((float) $it['vol'] * (($it['volume_is_total'] ?? false) ? 1 : max($qty, 0)), 4)
: $detailVol;
$pkgWeight = (float) ($pkg['weight'] ?? 0) ?: null;
$freightW = (float) ($f['w'] ?? 0);
@ -1358,7 +1494,7 @@ class ShippingReplicaSynchronizer
'trade_no' => $pkg['so_id'],
'item_id' => $it['shopid'] ?? null,
'barcode' => $it['sku'] ?? null,
'product_name' => $this->wpText(($it['name'] ?? null) ?: ($sk['name'] ?? null)),
'product_name' => $this->wpText($this->productName($it['name'] ?? null, $sk['name'] ?? null)),
'qty' => $it['qty'] ?? null,
'pkg_count' => $countStr,
'product_code' => ($it['iid'] ?? null) ?: ($sk['iid'] ?? null),
@ -1369,7 +1505,8 @@ class ShippingReplicaSynchronizer
'shop_name' => $pkg['shop_name'],
'platform' => $pkg['platform'],
'supplier_name' => ($it['supplier'] ?? null) ?: (($sk['supplier'] ?? null) ?: $pkg['dis_co_name']),
'warehouse_name' => $this->whName($pkg['warehouse_name'] ?: ($it['warehouse'] ?? null)),
'warehouse_name' => $this->whName($pkg['warehouse_name'] ?: ($it['warehouse'] ?? null))
?? (trim((string) ($pkg['express_name1'] ?? '')) === self::NO_LOGISTICS ? self::NO_LOGISTICS_WAREHOUSE : null),
'receiver_state' => $pkg['r_state'],
'receiver_city' => $pkg['r_city'],
'receiver_district' => $pkg['r_district'],
@ -1382,7 +1519,7 @@ class ShippingReplicaSynchronizer
'length_cm' => $L,
'width_cm' => $W,
'height_cm' => $H,
'volume_cm3' => $this->detailVolume($L, $W, $H, $qty, (string) ($pkg['warehouse_name'] ?: ($it['warehouse'] ?? '')), (string) ($pkg['express_name1'] ?? '')),
'volume_cm3' => $detailVol,
'm_name' => $this->wpText($it['mname'] ?? null),
'm_volume_cm3' => isset($it['mvol']) ? round((float) $it['mvol'], 4) : $vol,
'm_length_cm' => $it['ml'] ?? null,
@ -1685,10 +1822,8 @@ class ShippingReplicaSynchronizer
/**
* 包裹实发商品:
* 1. 出库单实发商品(发货数据视图);
* 2. 多包裹订单:聚水潭运费明细里本快递单号的商品;
* 3. 内部订单(o_id)商品;
* 4. 运费明细里本快递单号的商品(单包裹订单);
* 5. 交易单号整单商品。
* 2. 聚水潭运费明细里本快递单号的商品;
* 3. 没有出库单且没有多包裹证据时,才使用内部订单/交易单号商品。
*
* 运费明细(fys_jstFreightCostDetail)按 交易单号+快递单号 记录每个包裹的 sku。工厂代发仓等找不到出库单的包裹,
* 内部订单/交易单号商品是整单口径,多包裹时会把同订单其它包裹的商品挂到本单号上
@ -1706,10 +1841,12 @@ class ShippingReplicaSynchronizer
$tk = ltrim(trim($tracking), '@');
$packageSkus = ($so !== '' && $tk !== '') ? ($this->fysPackageSkus[$so . '|' . $tk] ?? []) : [];
$multiPackage = ($this->fysSoTrackCount[$so] ?? 0) > 1;
if ($oid !== '' && ! empty($byOid[$oid]) && ! ($multiPackage && $packageSkus !== [])) {
return $byOid[$oid];
}
if ($packageSkus === []) {
// An identified outbound package without item detail must remain incomplete.
// Whole-order lines may describe a different parcel or the original full item.
if ($io !== '' || $multiPackage) {
return [];
}
return $this->itemsFor($byOid, $bySo, $dws, $oid, $so);
}
@ -2030,6 +2167,9 @@ class ShippingReplicaSynchronizer
if ($logisticId !== '' && ! empty($ioMap['byL'][$logisticId])) {
return (string) $ioMap['byL'][$logisticId];
}
if ($logisticId !== '') {
return ''; // A different parcel on the same order is not a match.
}
if ($oid !== '' && ! empty($ioMap['byO'][$oid])) {
return (string) $ioMap['byO'][$oid];
}
@ -2166,7 +2306,7 @@ class ShippingReplicaSynchronizer
'id' => null, 'sku' => $a['sku'], 'iid' => null,
'shopid' => $a['shopid'], 'name' => $a['name'],
'qty' => $qty, 'amount' => null, 'warehouse' => $a['wh'],
'l' => $a['l'], 'w' => $a['w'], 'h' => $a['h'], 'vol' => $vol,
'l' => $a['l'], 'w' => $a['w'], 'h' => $a['h'], 'vol' => $vol, 'volume_is_total' => true,
'weight' => $a['weight'], 'supplier' => $a['supplier'],
];
}
@ -2508,12 +2648,18 @@ class ShippingReplicaSynchronizer
foreach ($packageRows as &$packageRow) {
$skuId = (int) $packageRow['sku_source_id'];
$oldItem = $previousItems[$id][$skuId] ?? null;
$barcodeKey = mb_strtolower(trim((string) ($packageRow['barcode'] ?? '')));
if (isset($syntheticSkuIds[$id][$skuId]) && $oldItem !== null
&& mb_strtolower(trim((string) ($oldItem['barcode'] ?? ''))) !== $barcodeKey) {
// Synthetic IDs depend on row order, which the upstream view does not promise.
// Match the amount by barcode before deciding whether an update is unsafe.
$oldItem = null;
}
if ($packageRow['amount'] !== null) {
unset($unmatchedOldAmounts[$skuId]);
continue;
}
if ($oldItem === null || $oldItem['amount'] === null) {
$barcodeKey = mb_strtolower(trim((string) ($packageRow['barcode'] ?? '')));
if ($barcodeKey !== '' && isset($oldAmountByBarcode[$barcodeKey])) {
[$matchedOldSkuId, $matchedAmount] = $oldAmountByBarcode[$barcodeKey];
$packageRow['amount'] = $matchedAmount;
@ -2522,16 +2668,8 @@ class ShippingReplicaSynchronizer
}
continue;
}
if (isset($syntheticSkuIds[$id][$skuId])) {
$oldBarcode = trim((string) $oldItem['barcode']);
$newBarcode = trim((string) ($packageRow['barcode'] ?? ''));
if ($oldBarcode === '' || $newBarcode === '' || $oldBarcode !== $newBarcode) {
$unsafeAmount = true;
break;
}
}
$packageRow['amount'] = $oldItem['amount'];
unset($unmatchedOldAmounts[$skuId]);
unset($unmatchedOldAmounts[$skuId], $oldAmountByBarcode[$barcodeKey]);
}
unset($packageRow);
if (! $unsafeAmount && $unmatchedOldAmounts !== []) {
@ -2573,6 +2711,10 @@ class ShippingReplicaSynchronizer
foreach (self::PRESERVED_PACKAGE_FIELDS as $field) {
$packageRows[0][$field] = $previous[$id][$field] ?? null;
}
if (! empty($previous[$id]['express_no']) && ! empty($packageRows[0]['express_no'])
&& ltrim($previous[$id]['express_no'], '@') !== ltrim($packageRows[0]['express_no'], '@')) {
$packageRows[0]['front_no'] = $previous[$id]['express_no'];
}
foreach (self::PRESERVED_CONTACT_FIELDS as $field) {
if (($packageRows[0][$field] ?? null) === null || $packageRows[0][$field] === '') {
$packageRows[0][$field] = $previous[$id][$field] ?? null;
@ -2586,7 +2728,7 @@ class ShippingReplicaSynchronizer
}
array_push($rows, ...$packageRows);
}
$this->refreshRetainedPackages($refresh);
$this->refreshRetainedPackages($refresh, $previous);
if ($replaceIds === []) {
return;
}
@ -2624,9 +2766,8 @@ class ShippingReplicaSynchronizer
/**
* 线上发货标签排除口径(对齐工作平台):
* 工作平台只排除"刷单/批发/纯售后"这类无实物的线上发货虚拟单;
* 云仓/京仓(CLPS/ECLP)真实发货工作平台是收进的,不能排除。
* 实测(9.1-9.16):该口径误排 2、误收 0。
* 工作平台只排除"刷单/批发/纯售后"这类无实物的线上发货虚拟单,以及京东品牌自营的京仓单(京东仓发货);
* 其余云仓/京仓(CLPS/ECLP)真实发货工作平台是收进的,不能排除。
*/
private function excludedByLabel(?string $labels): bool
{
@ -2636,6 +2777,15 @@ class ShippingReplicaSynchronizer
if (! str_contains($labels, '线上发货')) {
return false;
}
// 京东品牌自营的京仓单(ECLP/京仓订单 + 品牌自营):货由京东仓发出,子订单状态是「外部发货」,
// 工作平台不收(2026-11 比对 1–27 日 32 单全部如此),排除。
if (str_contains($labels, '品牌自营')) {
$tags = array_map('trim', preg_split('/[,,;;|]+/u', $labels) ?: []);
if (in_array('线上发货', $tags, true) && in_array('品牌自营', $tags, true)
&& array_intersect(['京仓订单', 'ECLP订单', 'ECLP'], $tags) !== []) {
return true;
}
}
// 云仓/京仓真实发货:工作平台收进,保留
if (str_contains($labels, '云仓订单') || str_contains($labels, '京仓订单')
|| str_contains($labels, 'CLPS') || str_contains($labels, 'ECLP')) {
@ -2655,7 +2805,7 @@ class ShippingReplicaSynchronizer
}
$ph = implode(',', array_fill(0, count($chunk), '?'));
foreach ($this->selectWithReconnect("SELECT sku_id, l, w, h, pack_volume, weight, supplier_name, name, i_id FROM rpt.jst_sku WHERE sku_id IN ({$ph})", $chunk) as $r) {
$out[(string) $r['sku_id']] = [
$out[mb_strtolower(trim((string) $r['sku_id']))] = [
'l' => $r['l'] ?? null, 'w' => $r['w'] ?? null, 'h' => $r['h'] ?? null,
'vol' => $r['pack_volume'] ?? null, 'weight' => $r['weight'] ?? null,
'supplier' => $r['supplier_name'] ?? null,
@ -2796,7 +2946,7 @@ class ShippingReplicaSynchronizer
}
/** 因商品/金额无法安全替换而保留的旧包裹:包裹级字段(省市区、快递、仓库、店铺等)仍按本次上游刷新,商品与金额不动。 */
private function refreshRetainedPackages(array $refresh): void
private function refreshRetainedPackages(array $refresh, array $previous): void
{
foreach ($refresh as $id => $new) {
$set = [];
@ -2806,6 +2956,10 @@ class ShippingReplicaSynchronizer
$set[$field] = $v;
}
}
$oldTracking = trim((string) ($previous[$id]['express_no'] ?? ''));
if ($oldTracking !== '' && isset($set['express_no']) && ltrim($oldTracking, '@') !== ltrim($set['express_no'], '@')) {
$set['front_no'] = $oldTracking;
}
if ($set !== []) {
$this->db->table('jst_oms_shipping')->where('source_id', (int) $id)->update($set);
}
@ -2815,9 +2969,7 @@ class ShippingReplicaSynchronizer
private function withPreservedFreight(array $payload, array $previous): array
{
$payload = $this->withPreservedCharges($payload, $previous);
if (! empty($previous['express_no'])) {
$payload['express_no'] = $previous['express_no'];
}
// Preserving freight must not restore the old tracking number after a waybill change.
$payload['express_name2'] = $previous['express_name2'] ?? $payload['express_name2'];
return $payload;
@ -2891,7 +3043,7 @@ class ShippingReplicaSynchronizer
/**
* 发货时间校正:仓库次日才出库的包裹,同步时出库单还没生成,发货时间先落成发货明细(打单)时间;
* 后续同步若走"保留旧包裹"分支不会改写。这里按快递单号对齐出库单 io_date(=聚水潭发货/出库时间),
* 只把偏早的发货时间往后校正(相差 1 分钟~7 天),同一单号多张出库单时有效单优先、再取最新。
* 只把偏早的发货时间往后校正(相差 1 分钟~7 天)。同一单号有多张有效出库单时须先确认对应包裹。
*/
public function fixShipTimes(string $fromS, string $toS): int
{
@ -2936,7 +3088,7 @@ class ShippingReplicaSynchronizer
if ($withWeight) {
try {
$part = $this->selectWithReconnect(
'SELECT so.l_id, so.io_date, so.status, so.weight, so.f_weight FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
'SELECT so.l_id, so.io_date, so.status, so.weight, so.f_weight, so.io_id FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
$bind,
);
} catch (Throwable $e) {
@ -2948,7 +3100,7 @@ class ShippingReplicaSynchronizer
}
if ($part === null) {
$part = $this->selectWithReconnect(
'SELECT so.l_id, so.io_date, so.status FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
'SELECT so.l_id, so.io_date, so.status, so.io_id FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
$bind,
);
}
@ -2958,6 +3110,7 @@ class ShippingReplicaSynchronizer
$cur = $next;
}
$best = [];
$multiple = [];
foreach ($rows as $r) {
$r = (array) $r;
$l = ltrim(trim((string) ($r['l_id'] ?? '')), '@');
@ -2968,11 +3121,17 @@ class ShippingReplicaSynchronizer
$st = strtolower(trim((string) ($r['status'] ?? '')));
$ok = ! in_array($st, ['delete', 'deleted', 'cancelled', 'cancel', 'canceled', '作废'], true);
$rk = ($ok ? '1' : '0') . '|' . $d;
$io = (int) ($r['io_id'] ?? 0);
$hasW = $withWeight && array_key_exists('weight', $r);
$w = $hasW ? (float) ($r['weight'] ?? 0) : 0.0;
$fw = $hasW ? (float) ($r['f_weight'] ?? 0) : 0.0;
$candidate = [$rk, $d, $hasW, $w > 0 ? round($w, 4) : null, $fw > 0 ? round($fw, 4) : null, $io];
if ($ok && $io > 0 && isset($best[$l]) && $best[$l][0][0] === '1' && $best[$l][5] > 0 && $best[$l][5] !== $io) {
$multiple[$l] ??= [$best[$l][5] => $best[$l]];
$multiple[$l][$io] = $candidate;
}
if (! isset($best[$l]) || strcmp($rk, $best[$l][0]) > 0) {
$hasW = $withWeight && array_key_exists('weight', $r);
$w = $hasW ? (float) ($r['weight'] ?? 0) : 0.0;
$fw = $hasW ? (float) ($r['f_weight'] ?? 0) : 0.0;
$best[$l] = [$rk, $d, $hasW, $w > 0 ? round($w, 4) : null, $fw > 0 ? round($fw, 4) : null];
$best[$l] = $candidate;
}
}
unset($rows);
@ -2988,14 +3147,17 @@ class ShippingReplicaSynchronizer
->select(['id', 'source_id', 'express_no', 'ship_time', 'online_weight', 'actual_weight'])
->where('ship_time', '>=', $mirrorFrom)->where('ship_time', '<', $toS)
->whereNotNull('express_no')
->chunkById(20000, function ($chunk) use (&$fixTime, &$first, &$clearIds, $best): void {
->chunkById(20000, function ($chunk) use (&$fixTime, &$first, &$clearIds, $best, $multiple): void {
foreach ($chunk as $row) {
$sid = (int) $row->source_id;
$l = ltrim(trim((string) $row->express_no), '@');
if ($l === '' || ! isset($best[$l])) {
continue;
}
$b = $best[$l];
$b = $this->outboundForMirrorRow($sid, (string) $row->ship_time, $best[$l], $multiple[$l] ?? []);
if ($b === null) {
continue;
}
if (isset($first[$sid])) {
if ($b[2] && ($row->online_weight !== null || $row->actual_weight !== null)) {
$clearIds[] = (int) $row->id;
@ -3016,7 +3178,7 @@ class ShippingReplicaSynchronizer
}
}
}, 'id');
unset($best);
unset($best, $multiple);
$nTime = 0;
foreach ($fixTime as $new => $ids) {
@ -3046,6 +3208,26 @@ class ShippingReplicaSynchronizer
return ['ship_time' => $nTime, 'weight' => $nWeight];
}
private function outboundForMirrorRow(int $sourceId, string $shipTime, array $best, array $multiple): ?array
{
if ($sourceId >= self::OUTBOUND_OFFSET && $sourceId < self::PURCHASE_OUT_OFFSET) {
$io = $sourceId - self::OUTBOUND_OFFSET;
if ($multiple !== []) {
return $multiple[$io] ?? null;
}
return $best[5] === 0 || ($best[5] === $io && $best[0][0] === '1') ? $best : null;
}
if ($multiple === []) {
return $best;
}
// 发货明细和代发订单使用各自的来源键,只有唯一的出库时间能把它们匹配到某张出库单。
$matches = array_filter($multiple, static fn (array $row): bool => $row[1] === $shipTime);
return count($matches) === 1 ? reset($matches) : null;
}
/**
* 清理历史残留的订单占位行:包裹已有实发商品(数量>0)时,删除数量 0、金额 0/空 的订单商品行
* (被替换的原商品、组合装原套装等,聚水潭销售出库单不显示),商品行数(件数 1/N)随之更正。

View File

@ -219,6 +219,10 @@ class PayablesFinalImportRunner
'import' => $this->rowMessage($firstRow, $line, $exception),
]);
}
if ($dataset === 'final:supplier:return-reconciliation' && isset($normalized['send_time'])) {
$normalized['summary_month'] = substr((string) $normalized['send_time'], 0, 7);
$normalized['date'] = $normalized['send_time'];
}
$key = $recordKey !== ''
? $recordKey

View File

@ -105,6 +105,10 @@ class PayablesFinalImporter
'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(),
]);
}
if ($storeDataset === 'final:supplier:return-reconciliation' && isset($values['send_time'])) {
$values['summary_month'] = substr((string) $values['send_time'], 0, 7);
$values['date'] = $values['send_time'];
}
if ($key === '') {
$key = $preserveSourceRows

View File

@ -85,7 +85,8 @@ class PayablesFinalRegistry
* - insert:锚点列之后插入的列(锚点列名 => 列定义);
* - append:追加到末尾的列。
* 货款对账在「月份」后补入库单号、采购单号、日期,末尾补未发出、对账人;
* 退货对账去掉「快递名称」,在「标题」后插入 wms 配货单号,在「标记多标签」后补创建人。
* 退货对账去掉「快递名称」,在「标题」后插入 wms 配货单号,
* 在「快递单号」后补第二次发货时间和原条码,在「标记多标签」后补创建人。
*/
private const SUPPLIER_FIELD_PATCHES = [
'payment-reconciliation' => [
@ -103,6 +104,10 @@ class PayablesFinalRegistry
'remove' => ['express_name'],
'insert' => [
'title' => ['wms_pick_no' => ['label' => 'wms配货单号', 'type' => 'text']],
'express_no' => [
'io_date' => ['label' => '发货时间', 'type' => 'date'],
'original_barcode' => ['label' => '原条码', 'type' => 'text'],
],
'labels' => ['creator' => ['label' => '创建人', 'type' => 'text']],
],
],
@ -180,7 +185,9 @@ class PayablesFinalRegistry
if ($inserts !== []) {
$ordered = [];
foreach ($fields as $key => $definition) {
$ordered[$key] = $definition;
if (! array_key_exists($key, $ordered)) {
$ordered[$key] = $definition;
}
foreach ($inserts[$key] ?? [] as $insertedKey => $insertedDefinition) {
$ordered[$insertedKey] = $insertedDefinition;
}

View File

@ -0,0 +1,146 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Repositories\PromotionExpenseMirrorRepository;
use RuntimeException;
use Throwable;
/**
* 从聚水潭经营分析副本按日期聚合推广费用,写入页面专用共享镜像。
*/
class PromotionExpenseMirrorSynchronizer
{
private const SOURCE = 'operations_replica';
private const SOURCE_OBJECT = 'rpt.dws_sn_sales_full_info_di';
private const CHUNK_DAYS = 3;
private readonly UpstreamReadOnlyQuery $upstream;
public function __construct(
UpstreamReadOnlyQueryFactory $factory,
private readonly PromotionExpenseMirrorRepository $repository,
) {
$this->upstream = $factory->forSourceWithTimeout(self::SOURCE, 120);
}
/**
* @return array{
* from:string,to:string,effective_to:?string,days:int,source_rows:int,stored_rows:int
* }
*/
public function sync(Carbon $from, Carbon $to): array
{
if ($from->gt($to)) {
throw new RuntimeException('推广费用同步开始日期不能晚于结束日期。');
}
$this->repository->recordSyncState('running', $this->repository->count());
try {
$latestDate = $this->latestSourceDate();
$effectiveTo = $latestDate === null
? null
: Carbon::parse(min($to->toDateString(), $latestDate), 'Asia/Shanghai')->startOfDay();
if ($effectiveTo === null || $from->gt($effectiveTo)) {
$this->repository->recordSyncState('succeeded', $this->repository->count());
return [
'from' => $from->toDateString(),
'to' => $to->toDateString(),
'effective_to' => $effectiveTo?->toDateString(),
'days' => 0,
'source_rows' => 0,
'stored_rows' => 0,
];
}
$cursor = $from->copy()->startOfDay();
$sourceRows = 0;
$storedRows = 0;
$days = 0;
while ($cursor->lte($effectiveTo)) {
$chunkEnd = $cursor->copy()->addDays(self::CHUNK_DAYS - 1)->startOfDay();
if ($chunkEnd->gt($effectiveTo)) {
$chunkEnd = $effectiveTo->copy();
}
$rows = $this->fetchAggregates($cursor->toDateString(), $chunkEnd->toDateString());
$byDate = [];
foreach ($rows as $row) {
$date = substr((string) ($row['report_date'] ?? ''), 0, 10);
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) {
continue;
}
$byDate[$date][] = $row;
$sourceRows += (int) ($row['source_rows'] ?? 0);
}
for ($date = $cursor->copy(); $date->lte($chunkEnd); $date->addDay()) {
$storedRows += $this->repository->replaceDate(
$date->toDateString(),
$byDate[$date->toDateString()] ?? [],
);
$days++;
}
$cursor = $chunkEnd->addDay()->startOfDay();
}
$this->repository->recordSyncState('succeeded', $this->repository->count());
return [
'from' => $from->toDateString(),
'to' => $to->toDateString(),
'effective_to' => $effectiveTo->toDateString(),
'days' => $days,
'source_rows' => $sourceRows,
'stored_rows' => $storedRows,
];
} catch (Throwable $exception) {
$this->repository->recordSyncState(
'failed',
$this->repository->count(),
class_basename($exception),
);
throw $exception;
}
}
/** @return list<array<string,mixed>> */
protected function fetchAggregates(string $from, string $to): array
{
$sql = 'SELECT CONVERT(varchar(10), c.stat_date, 23) AS report_date,'
. " ISNULL(NULLIF(LTRIM(RTRIM(c.platform)), N''), N'未标记') AS platform,"
. " ISNULL(NULLIF(LTRIM(RTRIM(c.shop_name)), N''), N'未标记') AS store_name,"
. ' COUNT_BIG(*) AS source_rows,'
. ' COALESCE(SUM(CAST(COALESCE(c.push_fee, 0) AS decimal(38,2))), 0) AS push_fee,'
. ' COALESCE(SUM(CAST(COALESCE(c.shared_push_fee_sum, 0) AS decimal(38,2))), 0) AS shared_push_fee,'
. ' COALESCE(SUM(CAST(COALESCE(c.push_fee_total, 0) AS decimal(38,2))), 0) AS push_fee_total,'
. ' COALESCE(SUM(CAST(COALESCE(c.marketing_fee, 0) AS decimal(38,2))), 0) AS marketing_fee,'
. ' COALESCE(SUM(CAST(COALESCE(c.shared_market_fee_sum, 0) AS decimal(38,2))), 0) AS shared_marketing_fee,'
. ' COALESCE(SUM(CAST(COALESCE(c.marketing_fee_total, 0) AS decimal(38,2))), 0) AS marketing_fee_total'
. ' FROM rpt.dws_sn_sales_full_info_di c'
. ' WHERE c.stat_date >= CAST(? AS date)'
. ' AND c.stat_date < DATEADD(day, 1, CAST(? AS date))'
. ' GROUP BY CONVERT(varchar(10), c.stat_date, 23),'
. " ISNULL(NULLIF(LTRIM(RTRIM(c.platform)), N''), N'未标记'),"
. " ISNULL(NULLIF(LTRIM(RTRIM(c.shop_name)), N''), N'未标记')";
return $this->upstream->select($sql, [$from, $to]);
}
protected function latestSourceDate(): ?string
{
$value = $this->upstream->scalar(
'SELECT CONVERT(varchar(10), MAX(c.stat_date), 23) FROM rpt.dws_sn_sales_full_info_di c',
);
return $value === null || trim((string) $value) === ''
? null
: substr(trim((string) $value), 0, 10);
}
}

View File

@ -14,7 +14,6 @@ class RefundPendingSyncStatus
NonJingxiRefundMirrorRepository::ITEM_DATASET => '售后商品明细',
NonJingxiRefundMirrorRepository::SUPPLEMENT_DATASET => '淘系退款清单',
NonJingxiRefundMirrorRepository::SUPPLEMENT_ITEM_DATASET => '淘系退款明细',
NonJingxiRefundMirrorRepository::STATUS_DATASET => '聚水潭当前退款状态',
];
public function __construct(
@ -132,7 +131,7 @@ class RefundPendingSyncStatus
'title' => $running ? '退款待确认正在同步' : '退款待确认同步正常',
'message' => $running
? '退款镜像正在同步,完成后会自动更新。'
: '基础退款镜像每日 06:00 同步,当前退款状态每分钟刷新。',
: '基础退款镜像每日 06:00 同步,状态直接读取当前售后主表。',
'last_succeeded_at' => $this->latest($successTimes),
'last_attempted_at' => $this->latest($attemptTimes),
'issues' => [],

View File

@ -0,0 +1,109 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use RuntimeException;
class ShippingMeasuredWeightImporter
{
private const HEADERS = ['条形码', '称重重量', '适用快递名称'];
private const MAX_KEYS = 50000;
/** @return array{source_rows:int, keys:int} */
public function import(string $path, int $companyId, int $userId): array
{
$rows = $this->read($path);
$now = now();
DB::transaction(static function () use ($rows, $companyId, $userId, $now): void {
foreach (array_chunk($rows['weights'], 500) as $chunk) {
DB::table('shipping_measured_weights')->upsert(
array_map(static fn (array $weight): array => $weight + [
'company_id' => $companyId,
'updated_by' => $userId,
'created_at' => $now,
'updated_at' => $now,
], $chunk),
['company_id', 'carrier_name', 'barcode'],
['weight_kg', 'updated_by', 'updated_at'],
);
}
}, 3);
return ['source_rows' => $rows['source_rows'], 'keys' => count($rows['weights'])];
}
/** @return array{source_rows:int, weights:array<string,array{carrier_name:string,barcode:string,weight_kg:float}>} */
private function read(string $path): array
{
$reader = PayablesWorkbookStreamReader::forFile($path, 'xlsx');
$weights = [];
$sourceRows = 0;
$hasHeader = false;
try {
foreach ($reader->rows(0, null, 10002) as $number => $cells) {
$row = array_map(static fn ($value): string => trim((string) $value), $cells);
$nonBlank = array_filter($row, static fn (string $value): bool => $value !== '');
if ($number === 1) {
if (array_values($nonBlank) !== self::HEADERS || array_keys($nonBlank) !== [0, 1, 2]) {
$this->invalid('第一行表头须依次为「条形码」「称重重量」「适用快递名称」。');
}
$hasHeader = true;
continue;
}
if (! $hasHeader) {
$this->invalid('第一行缺少导入表头。');
}
if ($number > 10001) {
$this->invalid('一次最多导入 10,000 行称重数据。');
}
if ($nonBlank === []) {
continue;
}
$barcode = mb_strtoupper($row[0] ?? '');
$weight = $row[1] ?? '';
$carriers = preg_split('/[、,,;;\r\n]+/u', $row[2] ?? '');
$carriers = array_unique(array_filter(array_map('trim', $carriers ?: []), static fn (string $name): bool => $name !== ''));
if ($barcode === '' || mb_strlen($barcode) > 128 || str_contains($barcode, "\0")) {
$this->invalid("第 {$number} 行条形码为空或无效。");
}
$kg = is_numeric($weight) ? round((float) $weight, 4) : 0;
if (! is_finite((float) $kg) || $kg <= 0 || $kg >= 100000000) {
$this->invalid("第 {$number} 行称重重量须为大于 0 的公斤数。");
}
if ($carriers === [] || array_diff_key($nonBlank, [0 => true, 1 => true, 2 => true]) !== []) {
$this->invalid("第 {$number} 行请填写适用快递名称,并只使用模板的三列。");
}
foreach ($carriers as $carrier) {
if (mb_strlen($carrier) > 128 || str_contains($carrier, "\0")) {
$this->invalid("第 {$number} 行适用快递名称无效。");
}
$weights[$carrier . "\0" . $barcode] = ['carrier_name' => $carrier, 'barcode' => $barcode, 'weight_kg' => $kg];
}
if (count($weights) > self::MAX_KEYS) {
$this->invalid('拆分多家快递后最多保存 50,000 条称重记录。');
}
$sourceRows++;
}
} catch (RuntimeException $exception) {
$this->invalid('无法读取此 XLSX 文件,请确认文件完整后重试。');
}
if ($weights === []) {
$this->invalid('文件中没有可导入的称重数据。');
}
return ['source_rows' => $sourceRows, 'weights' => $weights];
}
private function invalid(string $message): never
{
throw ValidationException::withMessages(['measured_weight_file' => $message]);
}
}

View File

@ -48,7 +48,7 @@ class StoreReceivingBalanceOverviewService
/** @var array<int,array{slug:string,name:string}> */
public const PLATFORMS = [
['slug' => 'taobao-alipay', 'name' => '淘系支付宝账户'],
['slug' => 'taobao-alipay', 'name' => '店铺支付宝账户'],
['slug' => 'taobao-wechat', 'name' => '淘系微信账户'],
['slug' => 'pinduoduo', 'name' => '拼多多账户'],
['slug' => 'jd-wallet', 'name' => '京东网银钱包账户'],
@ -1300,9 +1300,54 @@ class StoreReceivingBalanceOverviewService
}
}
$opening += $this->jdWalletNewStoreOpeningBalances(
$connection,
$generations,
$activity,
$opening,
$cutoff,
$periodEnd,
);
return $this->mergeStoreBalances($opening, $activity);
}
/**
* 新店铺首次出现时没有历史余额,期初直接按 0 处理。
* 已有历史记录但余额字段缺失的店铺仍保持未就绪,不能静默按 0 处理。
*
* @param list<string> $generations
* @param array<string,array{income:float,expense:float}> $activity
* @param array<string,float|int> $opening
* @return array<string,float>
*/
private function jdWalletNewStoreOpeningBalances(
ConnectionInterface $connection,
array $generations,
array $activity,
array $opening,
string $cutoff,
string $periodEnd,
): array {
$historicalStores = $connection->table(self::JD_WALLET_ROW_TABLE)
->whereIn('generation', $generations)
->where('occurred_at', '<', $cutoff)
->distinct()
->pluck('store_name')
->map(fn (mixed $value): string => $this->storeName($value))
->flip()
->all();
$newStoreNames = array_values(array_filter(
array_diff(array_keys($activity), array_keys($opening)),
static fn (string $storeName): bool => ! isset($historicalStores[$storeName]),
));
if ($newStoreNames === []) {
return [];
}
return array_fill_keys($newStoreNames, 0.0);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/

View File

@ -8,6 +8,9 @@ use Throwable;
/** 两轮免记账之后,按原单发货记录核算实际可记账金额。 */
class SupplierBookkeepingValuation
{
/** 只记成本价的供应商:补偿、全款、运费损耗均按发货数量×商品成本价记账,不加运费、不与原金额比较。 */
public const COST_ONLY_SUPPLIERS = ['沐野竹木'];
public function __construct(private readonly Repository $repository) {}
/** @param list<array<string,mixed>> $rows @return list<array<string,mixed>> */
@ -100,7 +103,9 @@ class SupplierBookkeepingValuation
$quantity = '0';
$cost = '0';
$wanted = array_fill_keys(array_map([Repository::class, 'sku'], Repository::numbers(($row['resolved_product_code'] ?? '') !== '' ? $row['resolved_product_code'] : ($row['product_code'] ?? ''))), false);
$freightOnly = $row['bookkeeping_type'] === '运费损耗';
$costOnly = self::costOnlyMode($row);
if ($costOnly === null) return $this->review($row, '多个供应商中含只记成本价的' . implode('、', self::COST_ONLY_SUPPLIERS) . ',请人工确认');
$freightOnly = !$costOnly && $row['bookkeeping_type'] === '运费损耗';
$lines = [];
if (!$freightOnly && $wanted === []) return $this->review($row, '工单没有商品编码,无法匹配成本');
foreach ($pool as $shipment) {
@ -108,7 +113,7 @@ class SupplierBookkeepingValuation
if (trim((string) $shipment['express_no']) === '' || count(Repository::numbers($shipment['express_no'])) !== 1) return $this->review($row, '包裹快递单号缺失或不唯一,请核对');
$package = (string) $shipment['source_id'];
$packages[$package] ??= ['amount' => '0', 'has_freight' => false];
if ($shipment['freight'] !== null && $shipment['freight'] !== '') {
if (!$costOnly && $shipment['freight'] !== null && $shipment['freight'] !== '') {
if (!self::decimal($shipment['freight'])) return $this->review($row, '原单运费无效,请核对');
// 汇总表的包裹运费可能随每件商品重复关联,只取一次;冲突值不能相加。
if ($packages[$package]['has_freight']
@ -119,7 +124,7 @@ class SupplierBookkeepingValuation
$packages[$package]['has_freight'] = true;
}
}
$estimatedPackages = array_filter($packages, static fn ($package) => !$package['has_freight'] || bccomp($package['amount'], '0', 6) === 0);
$estimatedPackages = $costOnly ? [] : array_filter($packages, static fn ($package) => !$package['has_freight'] || bccomp($package['amount'], '0', 6) === 0);
if ($freightOnly && $estimatedPackages !== []) {
$shippedSkus = [];
foreach ($pool as $shipment) array_push($shippedSkus, ...array_map([Repository::class, 'sku'], Repository::numbers($shipment['barcode'])));
@ -135,6 +140,7 @@ class SupplierBookkeepingValuation
$bundle = count($components) > 1;
foreach ($components as $sku) {
if (!array_key_exists($sku, $wanted)) continue;
if ($costOnly && $bundle) return $this->review($row, '组合装缺少逐商品实际发货数量,无法按成本价记账');
// 组合装导出只有合计数量,财务确认按各商品条码1件核价。
$lineQuantity = $bundle ? '1' : (string) ($shipment['qty'] ?? '');
if (!self::decimal($lineQuantity) || bccomp($lineQuantity, '0', 6) <= 0) {
@ -163,14 +169,19 @@ class SupplierBookkeepingValuation
$packages[$package]['has_freight'] = true;
}
$freight = '0';
foreach ($packages as $package) {
foreach ($costOnly ? [] : $packages as $package) {
if (!$package['has_freight']) return $this->review($row, '原单运费尚未补齐,不能按0记账');
$freight = bcadd($freight, $package['amount'], 6);
}
$row['matched_freight'] = self::money($freight);
$row['matched_quantity'] = $freightOnly && $estimatedPackages === [] ? '' : rtrim(rtrim($quantity, '0'), '.');
$row['matched_tracking_no'] = implode("\n", array_values(array_unique(array_column($pool, 'express_no'))));
if ($freightOnly) {
if ($costOnly) {
$row['matched_cost'] = self::money($cost);
$row['matched_freight'] = null;
$row['amount'] = self::money($cost);
$basis = implode('、', self::COST_ONLY_SUPPLIERS) . '只记成本价:按发货数量×商品成本价记账,不含运费';
} elseif ($freightOnly) {
$row['amount'] = self::money($freight);
if ($estimatedPackages !== []) {
$row['matched_cost'] = self::money($cost);
@ -198,6 +209,15 @@ class SupplierBookkeepingValuation
return $row;
}
/** true=全部为只记成本价供应商;false=不含;null=与其他供应商混合,需人工确认。 */
private static function costOnlyMode(array $row): ?bool
{
$suppliers = array_values(array_unique(array_filter(array_map('trim', explode("\n", (string) ($row['supplier'] ?? ''))), static fn ($name) => $name !== '')));
$hits = array_intersect($suppliers, self::COST_ONLY_SUPPLIERS);
if ($hits === []) return false;
return count($hits) === count($suppliers) ? true : null;
}
private function review(array $row, string $reason): array
{
$row['deduction_status'] = SupplierBookkeepingDeductionRule::STATUS_REVIEW;

View File

@ -321,6 +321,71 @@ class SupplierPayableOverrideStore
->all();
}
/**
* 按数据库分页读取终版明细,避免宽表在历史数据较多时整表解码。
*
* @return array{rows:list<array<string,mixed>>,total:int}
*/
public function paginateRows(
string $dataset,
int $companyId,
int $perPage,
int $page,
string $keyword = '',
bool $latestFirst = false,
): array {
$perPage = max(1, min($perPage, 200));
$page = max(1, $page);
$query = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
$keyword = trim($keyword);
if ($keyword !== '') {
$query->where('values', 'like', '%' . $keyword . '%');
}
$total = (int) (clone $query)->count();
if ($latestFirst && $this->connection()->getDriverName() === 'sqlite') {
$query->orderByRaw(
"(json_extract(`values`, '$.summary_month') IS NULL"
. " OR json_extract(`values`, '$.summary_month') IN ('', 'null'))"
)
->orderByRaw("json_extract(`values`, '$.summary_month') DESC")
->orderByRaw(
"(json_extract(`values`, '$.date') IS NULL"
. " OR json_extract(`values`, '$.date') IN ('', 'null'))"
)
->orderByRaw("json_extract(`values`, '$.date') DESC")
->orderByDesc('id');
} elseif ($latestFirst) {
$query->orderByRaw(
"(summary_month_key IS NULL OR summary_month_key IN ('', 'null'))"
)
->orderByDesc('summary_month_key')
->orderByRaw(
"(record_date_key IS NULL OR record_date_key IN ('', 'null'))"
)
->orderByDesc('record_date_key')
->orderByDesc('id');
} else {
$query->orderBy('id');
}
$rows = $query
->forPage($page, $perPage)
->get()
->map(static function (object $record): array {
$values = json_decode((string) $record->values, true) ?: [];
$values['_action_key'] = (string) $record->record_key;
return $values;
})
->all();
return ['rows' => $rows, 'total' => $total];
}
/**
* 按记录键读取一条本地业务记录,找不到时返回 null。
*

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