CaiWuXiTong/app/Support/CourierBills/FreightBillTemplate.php

264 lines
12 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<string,float> 附加费类型 => 金额
*/
public function surchargesByType(string $path, string $extension): array
{
$result = [];
try {
foreach ($this->reader->sheets($path, $extension) as $name => $rows) {
if (! str_contains(trim((string) $name), self::SURCHARGE_SHEET)) { // 「附加费」「厂家账单-附加费」都认
continue;
}
$header = null;
foreach ($rows as $row) {
$cells = array_slice(array_map(static fn ($v): string => trim((string) $v), $row), 0, count(self::SURCHARGE_HEADERS));
if (implode('', $cells) === '') {
continue;
}
if ($header === null) {
$header = array_values(self::trimTail($cells));
if ($header !== self::SURCHARGE_HEADERS) {
return [];
}
continue;
}
$fee = BillParser::number($cells[1] ?? null);
$type = $cells[2] ?? '';
if ($fee === null || $type === '' || ($cells[0] ?? '') === '' || in_array($cells[0], self::TOTAL_WORDS, true)) {
continue;
}
$result[$type] = round(($result[$type] ?? 0) + $fee, 2);
}
}
} catch (Throwable) {
return [];
}
return $result;
}
/** 逐行保留单号与类型,不能只汇总账单金额后丢失匹配依据。 */
public function surchargeRows(string $path,string $extension): \Generator
{
foreach($this->reader->sheets($path,$extension) as $name=>$rows){
if(!str_contains(trim((string)$name),self::SURCHARGE_SHEET))continue;
$header=false;
foreach($rows as $number=>$row){
$cells=array_slice(array_map(static fn($v):string=>trim((string)$v),$row),0,3);
if(implode('',$cells)==='')continue;
if(!$header){
if(array_values(self::trimTail($cells))!==self::SURCHARGE_HEADERS)throw new RuntimeException('附加费表头不符合模板,无法逐单核对。');
$header=true;continue;
}
if(in_array($cells[0]??'',self::TOTAL_WORDS,true))continue;
$waybill=Waybill::normalize($cells[0]??'');$amount=BillParser::number($cells[1]??null);$type=$cells[2]??'';
if($waybill===null||$amount===null||$type==='')throw new RuntimeException('附加费第 '.$number.' 行缺少完整单号、金额或类型。');
yield ['sheet'=>(string)$name,'row_no'=>(int)$number,'waybill_no'=>$waybill,'item'=>$type,'amount'=>$amount];
}
}
}
/** @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;
}
}