CaiWuXiTong/app/Support/CourierBills/SummaryTemplate.php

217 lines
10 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;
/**
* 小汇总类目模板:照手工做法,本月的小汇总类目从同一家上月的小汇总搬过来(顺序不变,类目名里的月份顺延),
* 系统算得出的金额填进对应类目,算不出的空着留给手工回填,上月没有的新类目排在后面。
*/
final class SummaryTemplate
{
/** 上月小汇总里这些是系统按当月情况生成的临时行,不搬到下月。 */
private const TRANSIENT = '/跨月订单|前月补提供|待匹配/u';
/** 附加费按这些字和模板类目对应(账单表名「山东中通快运加收&上楼费」→ 模板「上楼费」)。 */
private const FEE_WORDS = ['上楼', '转件', '超区', '改地址', '送货', '偏远', '进仓', '入仓', '派送', '叉车', '打包', '拦截', '加收'];
private const STOP_LABELS = ['总计', '合计', '小计', '总金额', '结算金额'];
private const SCAN_ROWS = 400;
/**
* 类目名里的月份顺延 $delta 个月:「2026.8-9月记账补款」→「2026.9-10月记账补款」,「9月记账补款」→「10月记账补款」,「运费10月」→「运费11月」。
*/
public static function roll(string $label, int $delta): string
{
if ($delta === 0) {
return $label;
}
return preg_replace_callback('/(?:(\d{4})(\.|年))?(\d{1,2})(?:-(\d{1,2}))?月/u', static function (array $m) use ($delta): string {
$year = $m[1] !== '' ? (int) $m[1] : null;
[$y1, $a] = self::shift($year, (int) $m[3], $delta);
if (($m[4] ?? '') === '') {
return ($year !== null ? $y1 . $m[2] : '') . $a . '月';
}
[$y2, $b] = self::shift($year ?? $y1, (int) $m[4], $delta);
$prefix = $year !== null ? $y1 . $m[2] : '';
// 跨年:2026.12-2027.1月
$second = $year !== null && $y2 !== $y1 ? $y2 . $m[2] . $b : (string) $b;
return $prefix . $a . '-' . $second . '月';
}, $label) ?? $label;
}
/**
* 按模板排小汇总。
*
* @param list<string> $template 模板类目(已顺延月份)
* @param array<string,array{bill:?float,self:?float,kind:string}> $auto 系统生成的行,kind 见 CourierBillMatcher::refreshSummary
* @return list<array{label:string,bill:?float,self:?float,fee:bool,blank:bool}> 模板行在前(顺序不变),模板里没有的系统行排在后面
*/
public static function apply(array $template, array $auto, int $month): array
{
$rows = [];
$index = [];
foreach ($template as $label) {
$key = self::normalize($label);
if ($key === '') {
continue;
}
// 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行
$index[$key] ??= count($rows);
$rows[] = ['label' => $label, 'bill' => null, 'self' => null, 'fee' => false, 'blank' => true];
}
$extras = [];
foreach ($auto as $label => $item) {
$slot = self::slotFor((string) $label, $item['kind'], $index, $month);
if ($slot === null) {
$extras[] = ['label' => (string) $label, 'bill' => $item['bill'], 'self' => $item['self'], 'fee' => $item['kind'] === 'fee', 'blank' => false];
continue;
}
$row = &$rows[$slot];
$row['bill'] = $item['bill'] === null && $row['bill'] === null ? null : (float) $row['bill'] + (float) $item['bill'];
$row['self'] = $item['self'] === null && $row['self'] === null ? null : (float) $row['self'] + (float) $item['self'];
$row['fee'] = $row['fee'] || $item['kind'] === 'fee';
$row['blank'] = false;
unset($row);
}
return [...$rows, ...$extras];
}
/** 模板里属于附加费的那几行(自算先放 0,可回填)。 @param list<string> $feeLabels @return list<string> */
public static function feeSlots(array $template, array $feeLabels, int $month): array
{
$auto = [];
foreach ($feeLabels as $label) {
$auto[$label] = ['bill' => 0.0, 'self' => 0.0, 'kind' => 'fee'];
}
return array_values(array_map(static fn (array $r): string => self::normalize($r['label']),
array_filter(self::apply($template, $auto, $month), static fn (array $r): bool => $r['fee'])));
}
/** 上月小汇总的类目:去掉当月临时行。 @param iterable<string> $labels @return list<string> */
public static function fromLabels(iterable $labels, int $delta): array
{
$result = [];
foreach ($labels as $label) {
$label = trim((string) $label);
if ($label !== '' && ! preg_match(self::TRANSIENT, $label)) {
$result[] = self::roll($label, $delta);
}
}
return $result;
}
/**
* 从手工发送版账单的「汇总」类表里找小汇总:表头是 标题(如「樵舍中通-上楼10月」)| 快递金额 | 自算金额 | 差异 四格,
* 下面一列是类目,读到「总计 / 合计」或空行为止。一张表里可以有几块(左右并排也行)。只读类目名,不读金额。
*
* @param iterable<string,iterable<int,array<int,mixed>>> $sheets
* @return list<array{title:string,labels:list<string>}>
*/
public static function blocks(iterable $sheets): array
{
$blocks = [];
foreach ($sheets as $rows) {
// 小汇总都在表的前面,只看前 400 行(运费明细表动辄几万行,不整表读进内存)
$grid = [];
foreach ($rows as $row) {
$grid[] = array_values($row);
if (count($grid) >= self::SCAN_ROWS) {
break;
}
}
foreach ($grid as $r => $row) {
foreach ($row as $d => $cell) {
// 表头:标题 | 快递金额(快递提供金额/原始/快递…)| 自算(自算金额/简尚/简尚核对…)| 差异
if ($d < 3 || ! in_array(self::normalize((string) $cell), ['差异', '差额'], true) || trim((string) ($row[$d - 1] ?? '')) === ''
|| trim((string) ($row[$d - 2] ?? '')) === '' || is_numeric($row[$d - 2]) || is_numeric($row[$d - 1])) {
continue;
}
$c = $d - 2;
$title = trim((string) ($row[$c - 1] ?? ''));
$labels = [];
for ($i = $r + 1; $i < count($grid); $i++) {
$label = trim((string) ($grid[$i][$c - 1] ?? ''));
if ($label === '' || in_array(self::normalize($label), self::STOP_LABELS, true)
|| in_array(self::normalize((string) ($grid[$i][$d] ?? '')), ['差异', '差额'], true)) {
break;
}
$labels[] = $label;
}
// 首重、体积这类数字表不是小汇总
$labels = array_values(array_filter($labels, static fn (string $l): bool => ! is_numeric($l)));
if ($title !== '' && ! is_numeric($title) && $labels !== []) {
$blocks[] = ['title' => $title, 'labels' => $labels];
}
}
}
}
return $blocks;
}
public static function normalize(string $label): string
{
return preg_replace('/\s+/u', '', $label) ?? '';
}
/** @param array<string,int> $index */
private static function slotFor(string $label, string $kind, array $index, int $month): ?int
{
$key = self::normalize($label);
if (isset($index[$key])) {
return $index[$key];
}
$find = static function (callable $test) use ($index): ?int {
foreach ($index as $name => $slot) {
if ($test((string) $name)) {
return $slot;
}
}
return null;
};
return match (true) {
// 本月运费(含重量差、价格差)合成手工的运费那一行:「运费-重量差」>「运费10月 / 10月运费」>「运费」
$kind === 'freight' => $find(static fn (string $n): bool => $n === '运费-重量差')
?? $find(static fn (string $n): bool => (bool) preg_match('/^(' . $month . '月)?(快递)?运费(' . $month . '月)?$/u', $n) && str_contains($n, $month . '月'))
?? $find(static fn (string $n): bool => (bool) preg_match('/^(快递)?运费$/u', $n))
?? $find(static fn (string $n): bool => str_contains($n, '运费') && ! preg_match('/\d+月|退|补|不结算|调拨|面单|抵扣|逆向|附加/u', $n)),
str_starts_with($kind, 'prior:') => $find(static fn (string $n): bool => str_contains($n, '运费')
&& (bool) preg_match('/(^|[^\d])' . substr($kind, 6) . '月/u', $n) && ! str_contains($n, '记账')),
$kind === 'duplicate' => $find(static fn (string $n): bool => (bool) preg_match('/重复|查重/u', $n)),
$kind === 'unshipped' => $find(static fn (string $n): bool => str_contains($n, '未发出') && ! str_contains($n, '实际已发出')),
$kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)),
$kind === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')),
$kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'),
$kind === 'fee' => self::feeSlot($key, $find),
default => null,
};
}
private static function feeSlot(string $label, callable $find): ?int
{
foreach (self::FEE_WORDS as $word) {
if (str_contains($label, $word)) {
$slot = $find(static fn (string $n): bool => str_contains($n, $word));
if ($slot !== null) {
return $slot;
}
}
}
return $find(static fn (string $n): bool => str_contains($n, '附加费'));
}
/** @return array{0:int,1:int} */
private static function shift(?int $year, int $month, int $delta): array
{
$index = ($year ?? 2000) * 12 + ($month - 1) + $delta;
return [intdiv($index, 12), $index % 12 + 1];
}
}