293 lines
15 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 = ['计费重量', '结算重量', '重量', '实际重量'];
/** 表名里出现这些字,整张表当附加费表,不读。(不含「上楼」二字本身:有的分组就叫「樵舍中通-上楼」。) */
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;
}
}