CaiWuXiTong/app/Support/CourierBills/FreightBillTemplate.php
Claude 7b8ab8f137 运费上传模板:新增「附加费」子表,送货备注列改为快递名称
- 模板两张表:账单(单号、省、重量、运费、快递名称、面单、费率)+ 附加费(快递单号、附加费金额、附加费类型)
- 附加费表可空,表头右侧注明「无附加费无需填写」;填了则三列必填、金额须为数字
- 旧模板第 5 列「送货备注」仍可上传
- 快递账单的附加费表进小汇总;代发运费只核运费,附加费随原文件保存
- 上传提示、回执、群通知带附加费行数和合计

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UNTa9mVziToe5w52mmrrar
2026-12-03 09:20:07 +08:00

202 lines
9.4 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 RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
/**
* 快递 / 代发厂家自己上传运费账单用的统一模板,两张表:
* - 第一张「账单」:单号、省、重量、运费、快递名称、面单、费率。第一行必须就是这 7 列;单号、运费必填,重量、面单、费率填了就得是数字。
* - 「附加费」:快递单号、附加费金额、附加费类型。没有附加费可以空着;填了就三列都要填,金额是数字。
* 快递账单的附加费表只读金额进小汇总(不逐单核对);代发运费只核运费,附加费表随原文件保存。
*/
final class FreightBillTemplate
{
public const HEADERS = ['单号', '省', '重量', '运费', '快递名称', '面单', '费率'];
/** 旧模板第 5 列叫「送货备注」,照样收。 */
private const LEGACY_HEADERS = ['送货备注' => '快递名称'];
public const SURCHARGE_SHEET = '附加费';
public const SURCHARGE_HEADERS = ['快递单号', '附加费金额', '附加费类型'];
/** 写在附加费表表头右边(空一列)的说明,校验时不算表头。 */
public const SURCHARGE_NOTE = '注:无附加费无需填写,这张表空着即可';
private const MAX_ERRORS = 10;
private const TOTAL_WORDS = ['合计', '总计', '小计'];
public function __construct(private readonly BillWorkbookReader $reader) {}
public function download(string $fileName): StreamedResponse
{
return response()->streamDownload(static function (): void {
$book = new StreamingWorkbook();
$book->row('账单', self::HEADERS, true);
$book->row(self::SURCHARGE_SHEET, [...self::SURCHARGE_HEADERS, '', self::SURCHARGE_NOTE], true);
$book->writeTo(fopen('php://output', 'wb'));
}, $fileName);
}
/**
* 校验上传的文件是不是按模板填的,不对就把前几处错误一起报出来。
*
* @return array{rows:int,waybills:int,amount:float,surcharge_rows:int,surcharge_amount:float}
*/
public function validate(string $path, string $extension): array
{
try {
$sheets = $this->reader->sheets($path, $extension);
$rows = $sheets->current();
} catch (Throwable $error) {
throw new RuntimeException('读不了这个文件:' . $error->getMessage());
}
if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) {
throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。');
}
$result = $this->validateBill($rows);
$surcharge = ['surcharge_rows' => 0, 'surcharge_amount' => 0.0];
try {
for ($sheets->next(); $sheets->valid(); $sheets->next()) {
if (trim((string) $sheets->key()) === self::SURCHARGE_SHEET) {
$surcharge = $this->validateSurcharge($sheets->current());
} else {
throw new RuntimeException('请只保留模板的「账单」和可选的「附加费」工作表,不要附带其他工作表。');
}
}
} catch (RuntimeException $error) {
throw $error;
} catch (Throwable $error) {
throw new RuntimeException('读不了「附加费」表:' . $error->getMessage());
}
return $result + $surcharge;
}
/** @return array{rows:int,waybills:int,amount:float} */
private function validateBill(?iterable $rows): array
{
if ($rows === null) {
throw new RuntimeException('文件是空的。');
}
$errors = [];
$header = null;
$count = 0;
$amount = 0.0;
$waybills = [];
foreach ($rows as $index => $row) {
$cells = array_map(static fn ($v): string => trim((string) $v), $row);
if ($header === null) {
$cells[0] = preg_replace('/^\x{FEFF}/u', '', $cells[0] ?? '');
$header = array_map(static fn (string $h): string => self::LEGACY_HEADERS[$h] ?? $h, array_values(self::trimTail($cells)));
if ($header !== self::HEADERS) {
throw new RuntimeException('请用上传模板:第一行必须依次是「' . implode('、', self::HEADERS) . '」,现在是「'
. implode('、', array_filter($header, static fn (string $h): bool => $h !== '')) . '」。');
}
continue;
}
if (implode('', $cells) === '') {
continue;
}
$line = (int) $index;
$waybill = $cells[0] ?? '';
if (in_array($waybill, self::TOTAL_WORDS, true)) {
continue;
}
if ($waybill === '') {
$errors[] = '第 ' . $line . ' 行没有单号';
} elseif (Waybill::normalize($waybill) === null) {
$errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本';
}
$freight = BillParser::number($cells[3] ?? null);
if ($freight === null || ! is_finite($freight)) {
$errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字');
}
foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) {
$value = BillParser::number($cells[$col] ?? null);
if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) {
$errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字';
}
}
if (count($errors) >= self::MAX_ERRORS) {
break;
}
$count++;
if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。');
$amount += (float) $freight;
$waybills[$waybill] = true;
}
if ($header === null) {
throw new RuntimeException('文件是空的。');
}
if ($errors !== []) {
throw new RuntimeException('账单有 ' . (count($errors) >= self::MAX_ERRORS ? '多处' : count($errors) . ' 处') . '要改:'
. implode(';', array_slice($errors, 0, self::MAX_ERRORS)) . '。');
}
if ($count === 0) {
throw new RuntimeException('模板里还没有填账单明细。');
}
return ['rows' => $count, 'waybills' => count($waybills), 'amount' => round($amount, 2)];
}
/** @return array{surcharge_rows:int,surcharge_amount:float} */
private function validateSurcharge(iterable $rows): array
{
$errors = [];
$header = null;
$count = 0;
$amount = 0.0;
foreach ($rows as $index => $row) {
$cells = array_map(static fn ($v): string => trim((string) $v), $row);
if ($header === null) {
if (implode('', $cells) === '') {
continue;
}
$header = array_values(self::trimTail(array_slice($cells, 0, count(self::SURCHARGE_HEADERS))));
if ($header !== self::SURCHARGE_HEADERS) {
throw new RuntimeException('「附加费」表第一行必须依次是「' . implode('、', self::SURCHARGE_HEADERS) . '」,现在是「'
. implode('、', array_filter($header, static fn (string $h): bool => $h !== '')) . '」。');
}
continue;
}
$cells = array_slice($cells, 0, count(self::SURCHARGE_HEADERS));
if (implode('', $cells) === '' || in_array($cells[0] ?? '', self::TOTAL_WORDS, true)) {
continue;
}
$line = (int) $index;
if (($cells[0] ?? '') === '') {
$errors[] = '附加费第 ' . $line . ' 行没有快递单号';
} elseif (Waybill::normalize($cells[0]) === null) {
$errors[] = '附加费第 ' . $line . ' 行单号格式不对,请使用完整单号文本';
}
$fee = BillParser::number($cells[1] ?? null);
if ($fee === null || ! is_finite($fee)) {
$errors[] = '附加费第 ' . $line . ' 行金额' . (($cells[1] ?? '') === '' ? '没填' : '「' . $cells[1] . '」不是数字');
}
if (($cells[2] ?? '') === '') {
$errors[] = '附加费第 ' . $line . ' 行没写附加费类型';
}
if (count($errors) >= self::MAX_ERRORS) {
break;
}
$count++;
if ($count > 100000) throw new RuntimeException('每份附加费表最多100,000行,请分批上传。');
$amount += (float) $fee;
}
if ($errors !== []) {
throw new RuntimeException('「附加费」表有 ' . (count($errors) >= self::MAX_ERRORS ? '多处' : count($errors) . ' 处') . '要改:'
. implode(';', array_slice($errors, 0, self::MAX_ERRORS)) . '。');
}
return ['surcharge_rows' => $count, 'surcharge_amount' => round($amount, 2)];
}
/** @param list<string> $cells */
private static function trimTail(array $cells): array
{
while ($cells !== [] && end($cells) === '') {
array_pop($cells);
}
return $cells;
}
}