diff --git a/app/Support/CourierBills/BillParser.php b/app/Support/CourierBills/BillParser.php index 1bae9e328..73e70d2ed 100644 --- a/app/Support/CourierBills/BillParser.php +++ b/app/Support/CourierBills/BillParser.php @@ -21,7 +21,7 @@ final class BillParser /** 金额列名里出现这些字,整张表当附加费表,不读。 */ public const SURCHARGE_AMOUNT_WORDS = ['加收', '附加', '上楼', '转件', '派送', '派件', '超区', '偏远', '退件', '退回', '赔', '扣款', '罚款', '保价']; /** 有这一列时逐行看:费用项目不是运费的行(上楼费、转件费……)不读。 */ - public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目']; + public const ITEM_HEADERS = ['费用项目', '费用类型', '费用名称', '收费项目', '费用科目', '费用类别', '计费项目', '附加费类型']; private const HEADER_SCAN_ROWS = 15; private const SKIP_WORDS = ['合计', '总计', '小计', '汇总', '总额']; diff --git a/app/Support/CourierBills/FreightBillTemplate.php b/app/Support/CourierBills/FreightBillTemplate.php index 7c05889f8..2dd5f413a 100644 --- a/app/Support/CourierBills/FreightBillTemplate.php +++ b/app/Support/CourierBills/FreightBillTemplate.php @@ -7,12 +7,20 @@ use Symfony\Component\HttpFoundation\StreamedResponse; use Throwable; /** - * 快递 / 代发厂家自己上传运费账单用的统一模板:单号、省、重量、运费、送货备注、面单、费率。 - * 严格按模板:第一张表第一行必须就是这 7 列;单号、运费必填,重量、面单、费率填了就得是数字。 + * 快递 / 代发厂家自己上传运费账单用的统一模板,两张表: + * - 第一张「账单」:单号、省、重量、运费、快递名称、面单、费率。第一行必须就是这 7 列;单号、运费必填,重量、面单、费率填了就得是数字。 + * - 「附加费」:快递单号、附加费金额、附加费类型。没有附加费可以空着;填了就三列都要填,金额是数字。 + * 快递账单的附加费表只读金额进小汇总(不逐单核对);代发运费只核运费,附加费表随原文件保存。 */ final class FreightBillTemplate { - public const HEADERS = ['单号', '省', '重量', '运费', '送货备注', '面单', '费率']; + 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 = ['合计', '总计', '小计']; @@ -23,6 +31,7 @@ final class FreightBillTemplate 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); } @@ -30,7 +39,7 @@ final class FreightBillTemplate /** * 校验上传的文件是不是按模板填的,不对就把前几处错误一起报出来。 * - * @return array{rows:int,waybills:int,amount:float} + * @return array{rows:int,waybills:int,amount:float,surcharge_rows:int,surcharge_amount:float} */ public function validate(string $path, string $extension): array { @@ -40,12 +49,34 @@ final class FreightBillTemplate } catch (Throwable $error) { throw new RuntimeException('读不了这个文件:' . $error->getMessage()); } - if ($rows === null) { - throw new RuntimeException('文件是空的。'); - } 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; @@ -55,7 +86,7 @@ final class FreightBillTemplate $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_values(self::trimTail($cells)); + $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 !== '')) . '」。'); @@ -103,12 +134,61 @@ final class FreightBillTemplate if ($count === 0) { throw new RuntimeException('模板里还没有填账单明细。'); } - $sheets->next(); - if ($sheets->valid()) 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 $cells */ private static function trimTail(array $cells): array { diff --git a/app/Support/CourierBills/PortalFreightBillImports.php b/app/Support/CourierBills/PortalFreightBillImports.php index 67aff9057..3a2a18a82 100644 --- a/app/Support/CourierBills/PortalFreightBillImports.php +++ b/app/Support/CourierBills/PortalFreightBillImports.php @@ -100,7 +100,7 @@ final class PortalFreightBillImports } $portal = app(PortalFreightBills::class); $path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/input.' . $task['extension']); - app(FreightBillTemplate::class)->validate($path, $task['extension']); + $validated = app(FreightBillTemplate::class)->validate($path, $task['extension']); if ($task['kind'] === 'dropship') { $factory = $portal->factory($task['name']); if ($factory === null || (int) $factory->id !== $task['target_id']) throw new RuntimeException('厂家设置已变化,请联系财务。'); @@ -115,7 +115,22 @@ final class PortalFreightBillImports } if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。')); // 回执采用实际读入金额,避免重复单号等过滤后仍报上传文件总额。 - $summary = ['rows' => (int) ($row->row_count ?? $row->waybill_count), 'waybills' => (int) ($row->waybill_count ?? $row->row_count), 'amount' => (float) $row->amount]; + $surchargeRows = $validated['surcharge_rows']; + $surchargeAmount = $validated['surcharge_amount']; + if ($task['kind'] === 'courier') { + $fees = $store->db()->table('courier_bill_surcharges')->where('file_id', $id); + $surchargeRows = $fees->count(); + $surchargeAmount = round((float) $fees->sum('amount'), 2); + } + $summary = ['rows' => (int) ($row->row_count ?? $row->waybill_count), 'waybills' => (int) ($row->waybill_count ?? $row->row_count), + 'amount' => round((float) $row->amount - ($task['kind'] === 'courier' ? $surchargeAmount : 0), 2), + 'surcharge_rows' => $surchargeRows, 'surcharge_amount' => $surchargeAmount]; + if ($surchargeRows > 0) { + $message = '附加费 ' . number_format($surchargeRows) . ' 行,合计 ' . number_format($surchargeAmount, 2) . ' 元' + . ($task['kind'] === 'dropship' ? '(随原文件保存,不计入代发运费)' : '(计入小汇总)'); + $store->db()->table($task['kind'] === 'dropship' ? 'dropship_bill_files' : 'courier_bill_files')->where('id', $id) + ->update(['message' => mb_substr(implode(';', array_filter([$row->message, $message])), 0, 255)]); + } try { app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($task['name'], $task['kind'] === 'dropship' ? '代发运费账单' : '快递账单', $task['month'], $task['original_name'], $summary); } catch (Throwable $e) { report($e); } diff --git a/docs/厂家门户运费账单上传.md b/docs/厂家门户运费账单上传.md index 193564a40..6c5831d00 100644 --- a/docs/厂家门户运费账单上传.md +++ b/docs/厂家门户运费账单上传.md @@ -2,14 +2,14 @@ 厂家和快递通过原有钉钉入口进入门户,下载统一模板后提交账单。账号仅能给绑定的厂家或快递上传。财务账号沿用原页面权限,可为选定对象代传。 -模板第一行依次为:单号、省、重量、运费、送货备注、面单、费率。仅一张可见账单表,单号及运费必填;单号须完整,数字列须为有效数字。支持 XLSX、XLS、CSV,单份最多50MB、100,000行;XLS沿用现有读取器20MB限制。 +模板包含“账单”和可选的“附加费”两张表。账单第一行依次为:单号、省、重量、运费、快递名称、面单、费率;旧版第五列“送货备注”仍兼容。单号及运费必填,单号须完整,数字列须为有效数字。“附加费”表为快递单号、附加费金额、附加费类型,无附加费时可留空或不保留该表,有明细时三列必填。支持 XLSX、XLS、CSV,单份最多50MB,每张明细表最多100,000行;XLS沿用现有读取器20MB限制。CSV只包含主账单,附加费用XLSX或XLS上传。 网页只保存文件并显示等待处理。服务器每分钟通过现有独立批容器执行 `portal-freight:import-pending`,每次处理一份。使用共享同步锁,1 CPU、1GiB容器内存、PHP512MiB和一小时上限。无待办时不启动容器。校验失败在上传记录显示原因;进程中断不自动重导,下一次标记失败,财务核对已有记录后再决定重传。 -后台继续使用现有代发/快递账单读取与对账规则,重复上传、已结算月份等限制仍生效。门户快递上传不会通过文件名或合并分组设置扩大目标范围。成功回执使用实际读入行数和金额;未配置群机器人时不发送。 +后台继续使用现有代发/快递账单读取与对账规则,重复上传、已结算月份等限制仍生效。门户快递上传不会通过文件名或合并分组设置扩大目标范围。快递附加费按类型进入现有小汇总;代发附加费随原文件保存,不计入代发运费。成功回执使用实际读入行数,将运费与附加费分别显示;未配置群机器人时不发送。 不新增数据库表。任务文件沿用私有共享storage目录,原账单由现有账单存储流程留存。页面仅查当前对象的近期任务及最近10份已读入账单。 -验证需包含:两类门户上传、未授权对象拒绝、停用账号拒绝、模板错误、多表拒绝、后台隔离、重复导入和原有对账回归。性能基准以线上已有约7,500行账单为参照,使用10,000行合成账单在隔离环境测量,不向真实厂家群发送测试消息。 +验证需包含:两类门户上传、未授权对象拒绝、停用账号拒绝、模板错误、空附加费表兼容、附加费类型与金额、额外工作表拒绝、后台隔离、重复导入和原有对账回归。性能基准以线上已有约7,500行账单为参照,使用合成账单在隔离环境测量,不向真实厂家群发送测试消息。 本次隔离SQLite验证:10,000行代发账单,文件222,830字节,读入0.482秒,45次数据库查询,数据库累计44.89ms;7,500行快递账单,文件167878字节,读入1.003秒,7609次查询,数据库累计243.36ms。进程峰值分别约128.7MiB和130MiB;包含测试框架开销。未对生产执行压测。 diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index 49791461d..57b13016f 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -513,7 +513,8 @@ class SupplierDingTalkNotifier $supplier . ' · 代发运费账单上传提醒 · ' . $this->displayMonth($month), implode("\n", [ '### 代发运费账单上传提醒 · ' . $supplier, '- 请上传 **' . $this->displayMonth($month) . '** 代发运费账单', - '- 按上传模板填写(单号、省、重量、运费、送货备注、面单、费率),单号和运费必填', + '- 按上传模板填写(单号、省、重量、运费、快递名称、面单、费率),单号和运费必填', + '- 有附加费的填模板里的「附加费」表(快递单号、附加费金额、附加费类型),没有就空着', '', '#### [打开厂家对账入口](' . $portalUrl . ')', '- 钉钉登录后,在「上传运费账单」里选「代发运费账单」,可先下载上传模板。', @@ -530,7 +531,8 @@ class SupplierDingTalkNotifier $courier . ' · 运费账单上传 · ' . $this->displayMonth($month), implode("\n", [ '### 运费账单上传 · ' . $courier, '- 账单月份:**' . $this->displayMonth($month) . '**', - '- 请按上传模板填写(单号、省、重量、运费、送货备注、面单、费率),单号和运费必填', + '- 请按上传模板填写(单号、省、重量、运费、快递名称、面单、费率),单号和运费必填', + '- 有附加费的填模板里的「附加费」表(快递单号、附加费金额、附加费类型),没有就空着', '', '#### [打开账单上传页](' . $url . ')', '- 页面上可下载上传模板;同一个月可以分几次上传,上传后群里会收到回执。', @@ -540,7 +542,7 @@ class SupplierDingTalkNotifier $this->touch($courier, 1); } - /** @param array{rows:int,waybills:int,amount:float} $summary */ + /** @param array{rows:int,waybills:int,amount:float,surcharge_rows?:int,surcharge_amount?:float} $summary */ public function sendFreightBillUploadReceipt(string $name, string $kind, string $month, string $fileName, array $summary): bool { $configs = $this->configs(); @@ -557,6 +559,7 @@ class SupplierDingTalkNotifier '- 账单月份:**' . $this->displayMonth($month) . '**', '- 上传文件:' . ($fileName !== '' ? $fileName : '未命名文件'), '- 账单:**' . $summary['rows'] . '** 行,运费合计 **¥' . number_format((float) $summary['amount'], 2) . '**', + ...(($summary['surcharge_rows'] ?? 0) > 0 ? ['- 附加费:**' . $summary['surcharge_rows'] . '** 行,合计 **¥' . number_format((float) $summary['surcharge_amount'], 2) . '**'] : []), '- 上传时间:' . $this->platformTimestamp(), '- 数据状态:**已进入财务核对**', ])); diff --git a/resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php b/resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php index 95e2bab58..2796d8a7a 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php @@ -33,7 +33,7 @@

{{ $group->name }} · {{ $monthLabel }} 运费账单上传

请先点右上角「下载上传模板」,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」; - 单号、运费必填,重量、面单、费率填数字,省、送货备注可空。不按模板的文件会被退回并提示哪里要改。 + 「账单」表:单号、运费必填,重量、面单、费率填数字,省、快递名称可空;「附加费」表:快递单号、附加费金额、附加费类型,没有附加费就空着。不按模板的文件会被退回并提示哪里要改。 同一个月可以分几次上传,每份最多 50MB、100,000 行。上传后等待校验和读入,刷新本页查看结果。 链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录,只能上传本快递本月的账单。
@@ -58,7 +58,7 @@ @foreach ($files as $f) {{ $f->original_name }}{{ number_format((int) $f->row_count) }} {{ number_format((float) $f->amount, 2) }} - {{ match ($f->status) { 'parsed' => '已读入', 'failed' => '未读入:' . $f->message, 'queued' => '等待处理', 'running' => '正在校验和读入', default => '待财务处理' } }} + {{ match ($f->status) { 'parsed' => '已读入', 'failed' => '未读入:' . $f->message, 'queued' => '等待处理', 'running' => '正在校验和读入', default => '待财务处理' } }}@if ($f->status === 'parsed' && $f->message)
{{ $f->message }}
@endif {{ substr((string) $f->created_at, 0, 16) }} @endforeach diff --git a/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php b/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php index 09730ed58..3cc34e46d 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php @@ -6,7 +6,7 @@ 每家快递的钉钉对账群配一个群机器人(在「对账分组」里配,群设置 → 机器人 → 自定义,安全设置选「加签」),这里一键往这些群推本月的免登录上传链接。 - 快递点开链接、下载模板(单号、省、重量、运费、送货备注、面单、费率)填好上传,后台校验读入后进入对账;链接只能传那一家那个月,30 天有效。已有 {{ collect($cbRobots ?? [])->where('configured', true)->count() }} 家配了机器人。 + 快递点开链接、下载模板(单号、省、重量、运费、快递名称、面单、费率)填好上传,后台校验读入后进入对账;链接只能传那一家那个月,30 天有效。已有 {{ collect($cbRobots ?? [])->where('configured', true)->count() }} 家配了机器人。 diff --git a/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php b/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php index 7849e5e08..d66235a5a 100644 --- a/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php +++ b/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php @@ -25,7 +25,7 @@

上传运费账单

请先下载上传模板,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」; - 单号、运费必填,重量、面单、费率填数字,省、送货备注可空。不按模板的文件会被退回并提示哪里要改。 + 「账单」表:单号、运费必填,重量、面单、费率填数字,省、快递名称可空;「附加费」表:快递单号、附加费金额、附加费类型,没有附加费就空着。不按模板的文件会被退回并提示哪里要改。 同一个月可以分几次上传。上传后由后台校验和读入,刷新本页可查看结果;读入成功后进入财务核对。每份最多50MB、100,000行。

@if (session('success')) @@ -62,7 +62,7 @@ {{ $f['kind'] }}{{ $f['month'] }}{{ $f['name'] }} {{ in_array($f['status'], ['queued','running','failed'], true) ? '—' : number_format($f['count']) }}{{ in_array($f['status'], ['queued','running','failed'], true) ? '—' : number_format($f['amount'], 2) }} - {{ ['parsed'=>'已读入','queued'=>'等待处理','running'=>'正在校验读入'][$f['status']] ?? ($f['status'] === 'failed' ? '失败:' . $f['message'] : '待财务处理') }} + {{ ['parsed'=>'已读入','queued'=>'等待处理','running'=>'正在校验读入'][$f['status']] ?? ($f['status'] === 'failed' ? '失败:' . $f['message'] : '待财务处理') }}@if ($f['status'] === 'parsed' && $f['message'])
{{ $f['message'] }}
@endif {{ substr($f['at'], 0, 16) }} @endforeach diff --git a/tests/Feature/Business/PortalFreightBillTest.php b/tests/Feature/Business/PortalFreightBillTest.php index cfe3885cd..18193fe42 100644 --- a/tests/Feature/Business/PortalFreightBillTest.php +++ b/tests/Feature/Business/PortalFreightBillTest.php @@ -25,13 +25,14 @@ use Tests\Feature\FeatureTestCase; final class PortalFreightBillTest extends FeatureTestCase { - private const H = ['单号', '省', '重量', '运费', '送货备注', '面单', '费率']; + private const H = ['单号', '省', '重量', '运费', '快递名称', '面单', '费率']; + private const S = ['快递单号', '附加费金额', '附加费类型']; public function test_template_is_strict_about_headers_and_required_columns(): void { $t = new FreightBillTemplate(new BillWorkbookReader()); $ok = $t->validate($this->xlsx([self::H, ['773444000001', '江苏', 3.2, 8, null, 1, 2.1], ['773444000002', null, null, '6.5'], ['合计', null, null, 14.5]]), 'xlsx'); - $this->assertSame(['rows' => 2, 'waybills' => 2, 'amount' => 14.5], $ok); + $this->assertSame(['rows' => 2, 'waybills' => 2, 'amount' => 14.5, 'surcharge_rows' => 0, 'surcharge_amount' => 0.0], $ok); foreach ([ [[['快递单号', '运费'], ['1', 2]], '第一行必须依次是'], @@ -50,6 +51,59 @@ final class PortalFreightBillTest extends FeatureTestCase } } + public function test_template_has_a_surcharge_sheet_that_may_stay_empty(): void + { + $t = new FreightBillTemplate(new BillWorkbookReader()); + $bill = [self::H, ['773444000001', '江苏', 3.2, 8, '曹县韵达', 1, 2.1]]; + + // 下载的模板:两张表,附加费表头右边带说明;直接填一行运费就能过 + ob_start(); + $t->download('模板.xlsx')->sendContent(); + $path = tempnam(sys_get_temp_dir(), 'pfb_') . '.xlsx'; + file_put_contents($path, ob_get_clean()); + $sheets = []; + foreach ((new BillWorkbookReader())->sheets($path, 'xlsx') as $name => $rows) { + foreach ($rows as $row) { + $sheets[$name] = array_values(array_filter(array_map(static fn ($v): string => trim((string) $v), $row), static fn (string $v): bool => $v !== '')); + break; + } + } + $this->assertSame(['账单' => self::H, '附加费' => [...self::S, FreightBillTemplate::SURCHARGE_NOTE]], $sheets); + $this->assertStringContainsString('无附加费无需填写', FreightBillTemplate::SURCHARGE_NOTE); + + // 附加费表空着、只有表头(带说明)、或者根本没有这张表,都照收 + foreach ([['账单' => $bill], ['账单' => $bill, '附加费' => []], ['账单' => $bill, '附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE]]]] as $book) { + $this->assertSame(0, $t->validate($this->xlsxBook($book), 'xlsx')['surcharge_rows']); + } + // 旧模板第 5 列「送货备注」也收 + $old = self::H; + $old[4] = '送货备注'; + $this->assertSame(1, $t->validate($this->xlsx([$old, ['773444000001', '江苏', 3, 8]]), 'xlsx')['rows']); + + $ok = $t->validate($this->xlsxBook(['账单' => $bill, '附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE], + ['773444000001', 3, '上楼费'], ['773444000009', '2.5', '偏远加收'], ['合计', 5.5]]]), 'xlsx'); + $this->assertSame(2, $ok['surcharge_rows']); + $this->assertSame(5.5, $ok['surcharge_amount']); + $this->assertSame(8.0, (float) $ok['amount']); + + foreach ([ + [[['单号', '金额', '类型'], ['1', 2, '上楼费']], '「附加费」表第一行必须依次是'], + [[self::S, ['773444000001', null, '上楼费']], '附加费第 2 行金额没填'], + [[self::S, ['773444000001', '两块', '上楼费']], '金额「两块」不是数字'], + [[self::S, ['773444000001', 2]], '附加费第 2 行没写附加费类型'], + [[self::S, [null, 2, '上楼费']], '附加费第 2 行没有快递单号'], + [[self::S, ['7.9E+13', 2, '上楼费']], '单号格式不对'], + [[self::S, ['773444000001', '1e999', '上楼费']], '不是数字'], + ] as [$rows, $message]) { + try { + $t->validate($this->xlsxBook(['账单' => $bill, '附加费' => $rows]), 'xlsx'); + $this->fail('应当拒收:' . $message); + } catch (RuntimeException $e) { + $this->assertStringContainsString($message, $e->getMessage()); + } + } + } + public function test_dropship_factory_and_courier_upload_their_own_bills_in_the_supplier_portal(): void { Storage::fake('local'); @@ -59,6 +113,10 @@ final class PortalFreightBillTest extends FeatureTestCase 'created_at' => now(), 'updated_at' => now()]); $db->table('courier_bill_groups')->insert(['name' => '曹县韵达', 'express_names' => json_encode(['曹县韵达'], JSON_UNESCAPED_UNICODE), 'summary_carrier' => '曹县韵达', 'created_at' => now(), 'updated_at' => now()]); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + foreach (['临沂卿德客', '曹县韵达'] as $name) { + app(\Modules\EcommerceFinance\Services\SupplierDingTalkNotifier::class)->save($name, 'https://oapi.dingtalk.com/robot/send?access_token=template-test', 'SEC-test', false); + } $this->assertSame(['曹县韵达'], PortalFreightBills::courierNames(['曹县韵达', '财务中心', '临沂卿德客'])); \Illuminate\Support\Facades\URL::defaults(['company_id' => $this->company->id]); @@ -76,13 +134,20 @@ final class PortalFreightBillTest extends FeatureTestCase $this->assertSame(0, $db->table('dropship_bill_files')->count()); $this->assertTrue($imports->processNext()); $this->get($page)->assertOk()->assertSeeText('第一行必须依次是'); - $this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([self::H, ['773444000001', '江苏', 3, 8], ['773444000002', '', '', 6]])]) + $dropship = new UploadedFile($this->xlsxBook(['账单' => [self::H, ['773444000001', '江苏', 3, 8], ['773444000002', '', '', 6]], + '附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE], ['773444000001', 2, '上楼费']]]), '账单.xlsx', null, null, true); + $this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $dropship]) ->assertSessionHas('success'); $this->assertTrue($imports->processNext()); $f = $db->table('dropship_bill_files')->sole(); $this->assertSame('parsed', $f->status); $this->assertSame(2, (int) $f->waybill_count); $this->assertEquals(14, (float) $f->amount); + $this->assertStringContainsString('附加费 1 行,合计 2.00 元', $f->message); + $receipt = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''); + $this->assertStringContainsString('运费合计 **¥14.00**', $receipt); + $this->assertStringContainsString('附加费:**1** 行,合计 **¥2.00**', $receipt); + $this->get($page)->assertOk()->assertSeeText('附加费 1 行,合计 2.00 元'); $this->assertStringContainsString('(门户)', (string) $f->uploaded_by); // 不能替别的厂家传 $this->post($upload, ['kind' => 'dropship', 'supplier' => '别家', 'month' => '2026-11', 'import' => $file([self::H, ['1', '', '', 1]])]) @@ -92,13 +157,23 @@ final class PortalFreightBillTest extends FeatureTestCase $courierUser = $this->portalUser('曹县韵达'); $this->actingAsPortal($courierUser)->get($page)->assertOk()->assertSeeText('快递账单')->assertSeeText('当前快递') ->assertDontSeeText('代发运费账单'); - $this->post($upload, ['kind' => 'courier', 'month' => '2026-11', 'import' => $file([self::H, ['YD0001', '山东', 1.2, 4.5, '送货上门', 1, 3]])]) + $withFees = new UploadedFile($this->xlsxBook(['账单' => [self::H, ['YD0001', '山东', 1.2, 4.5, '曹县韵达', 1, 3]], + '附加费' => [[...self::S, null, FreightBillTemplate::SURCHARGE_NOTE], ['YD0001', 2, '上楼费'], ['YD0001', 1.5, '超长费']]]), '账单.xlsx', null, null, true); + $this->post($upload, ['kind' => 'courier', 'month' => '2026-11', 'import' => $withFees]) ->assertSessionHas('success'); $this->assertSame(0, $db->table('courier_bill_files')->count()); $this->assertTrue($imports->processNext()); $c = $db->table('courier_bill_files')->sole(); $this->assertSame('parsed', $c->status); - $this->assertEquals(4.5, (float) $c->amount); + $this->assertEquals(8, (float) $c->amount); // 文件合计 = 运费 4.5 + 附加费 3.5 + // 附加费表进小汇总(附加费),不逐单核对 + $this->assertSame(2, $db->table('courier_bill_surcharges')->where('file_id', $c->id)->count()); + $this->assertEquals(3.5, (float) $db->table('courier_bill_surcharges')->where('file_id', $c->id)->sum('amount')); + $this->assertSame(['上楼费', '超长费'], $db->table('courier_bill_surcharges')->where('file_id', $c->id)->orderBy('id')->pluck('item')->all()); + $receipt = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''); + $this->assertStringContainsString('运费合计 **¥4.50**', $receipt); + $this->assertStringContainsString('附加费:**2** 行,合计 **¥3.50**', $receipt); + $this->get($page)->assertOk()->assertSeeText('附加费 2 行,合计 3.50 元'); $this->assertSame(1, $db->table('courier_bill_statements')->where('bill_month', '2026-11')->count()); // 快递账号传代发运费账单:不是代发厂家 $this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([self::H, ['YD0002', '', '', 4]])]) @@ -133,7 +208,7 @@ final class PortalFreightBillTest extends FeatureTestCase $book->createSheet()->fromArray([self::H, ['SF87654321', '', 1, 99]]); (new Xlsx($book))->save($path); $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('只保留模板的一张账单工作表'); + $this->expectExceptionMessage('只保留模板的「账单」和可选的「附加费」工作表'); app(FreightBillTemplate::class)->validate($path, 'xlsx'); } @@ -275,9 +350,29 @@ final class PortalFreightBillTest extends FeatureTestCase /** @param list> $rows */ private function xlsx(array $rows): string + { + return $this->xlsxBook(['Sheet1' => $rows]); + } + + /** @param array>> $sheets */ + private function xlsxBook(array $sheets): string { $book = new Spreadsheet(); - $sheet = $book->getActiveSheet(); + $book->removeSheetByIndex(0); + foreach ($sheets as $name => $rows) { + $sheet = $book->createSheet(); + $sheet->setTitle($name); + $this->fill($sheet, $rows); + } + $path = tempnam(sys_get_temp_dir(), 'pfb_') . '.xlsx'; + (new Xlsx($book))->save($path); + + return $path; + } + + /** @param list> $rows */ + private function fill(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, array $rows): void + { foreach ($rows as $r => $row) { foreach ($row as $c => $value) { if ($value !== null && $value !== '') { @@ -286,9 +381,5 @@ final class PortalFreightBillTest extends FeatureTestCase } } } - $path = tempnam(sys_get_temp_dir(), 'pfb_') . '.xlsx'; - (new Xlsx($book))->save($path); - - return $path; } }