limeng e6b9775a24 快递账单支持合并导出、原始运费表和四位金额 (#1544)
按 0006、0007、0008 顺序整合;账单相关测试及隔离 MariaDB 迁移验证通过。
2026-11-28 11:31:38 +08:00

191 lines
8.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support\CourierBills;
use Generator;
/**
* 从快递账单文件里找表头、取出每一行的单号 / 运费 / 重量,原始列整行保留。
*
* 表头可能不在第一行(上面常有标题行),所以在每个工作表前 15 行里找含单号列的那一行;
* 没有单号列的工作表(快递自己做的汇总页等)整表跳过。
*/
final class BillParser
{
public const WAYBILL_HEADERS = ['运单号', '运单编号', '快递单号', '运单号码', '面单号', '单号'];
public const AMOUNT_HEADERS = ['运费', '快递运费', '结算运费', '结算金额', '应付金额', '总运费', '金额', '费用'];
public const WEIGHT_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, skipped?:string}
* type=line: {sheet, row, waybill, amount, weight, raw}
* type=reject: {sheet, row, value, reason}
*/
public function parse(string $path, string $extension, array $overrides = []): Generator
{
[$freight, $withWaybill] = $this->freightSheets($path, $extension, $overrides);
foreach ($this->reader->sheets($path, $extension) as $sheet => $rows) {
if ($freight !== null && in_array((string) $sheet, $withWaybill, true) && ! in_array((string) $sheet, $freight, true)) {
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => '不是运费表(第一期只核运费),未读入'];
continue;
}
$header = null;
$columns = null;
$scanned = 0;
foreach ($rows as $rowNumber => $row) {
if ($columns === null) {
$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;
}
if ($scanned >= self::HEADER_SCAN_ROWS) {
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => '前 15 行没有找到单号列,整表跳过'];
break;
}
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;
}
$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 ($columns === null && $scanned < self::HEADER_SCAN_ROWS) {
yield ['type' => 'sheet', 'sheet' => (string) $sheet, 'skipped' => '没有找到单号列,整表跳过'];
}
}
}
/**
* 快递账单里常有好几张表:运费明细之外,还有附加费、上楼费、派件费用等明细(单号列、金额列都有)。
* 第一期只核运费,所以只读金额列名带「运费」的表;一张都没有时(比如金额列就叫「金额」)才读所有带单号和金额的表。
*
* @return array{0:list<string>|null,1:list<string>} [只读这些工作表(null = 不限), 找到单号列的工作表]
*/
public function freightSheets(string $path, string $extension, array $overrides = []): array
{
$freight = [];
$withWaybill = [];
foreach ($this->reader->sheets($path, $extension) as $sheet => $rows) {
$scanned = 0;
foreach ($rows as $row) {
$found = self::findColumns($row, $overrides);
if ($found !== null) {
$withWaybill[] = (string) $sheet;
$amount = $found['amount'] === null ? '' : preg_replace('/\s+/u', '', (string) ($row[$found['amount']] ?? '')) ?? '';
if (str_contains($amount, '运费') || (trim((string) ($overrides['amount_header'] ?? '')) !== '' && $found['amount'] !== null)) {
$freight[] = (string) $sheet;
}
break;
}
if (++$scanned >= self::HEADER_SCAN_ROWS) {
break;
}
}
}
return [$freight === [] ? null : $freight, $withWaybill];
}
/**
* @param array<int,string> $row
* @return array{waybill:int,amount:?int,weight:?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);
return ['waybill' => $waybill, 'amount' => $amount, 'weight' => $weight];
}
/** 先按候选顺序全等匹配,再退到包含匹配(单号列不认「订单号」「交易单号」)。 */
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;
}
}