From 08d06ab918f645566182b6926922d73cb0488226 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 19:32:44 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E5=8E=82=E5=AE=B6=E9=97=A8=E6=88=B7?= =?UTF-8?q?=EF=BC=9A=E4=BB=A3=E5=8F=91=E5=8E=82=E5=AE=B6=E3=80=81=E5=BF=AB?= =?UTF-8?q?=E9=80=92=E6=8C=89=E7=BB=9F=E4=B8=80=E6=A8=A1=E6=9D=BF=E8=87=AA?= =?UTF-8?q?=E5=B7=B1=E4=B8=8A=E4=BC=A0=E8=BF=90=E8=B4=B9=E8=B4=A6=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 统一上传模板:单号、省、重量、运费、送货备注、面单、费率;严格校验表头,单号、运费必填,重量/面单/费率须为数字 - 代发厂家用现有供应商对账钉钉登录,页面多「上传运费账单」,传入代发运费对账(按厂家名对上代发厂家设置) - 快递:钉钉组织部门名是快递对账分组名或承运商名的,也能登录厂家门户,只看到上传快递账单,传入快递账单对账 - 只能给自己绑定的那家上传;财务在同一页面可代传;上传后发钉钉群回执(配了机器人的话) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UNTa9mVziToe5w52mmrrar --- .../Business/PortalFreightBillController.php | 120 +++++++++++++ app/Services/Auth/SupplierPortalAccess.php | 14 ++ .../CourierBills/FreightBillTemplate.php | 112 +++++++++++++ .../CourierBills/PortalFreightBills.php | 92 ++++++++++ .../DropshipFreight/DropshipFreightStore.php | 15 +- .../Services/SupplierDingTalkNotifier.php | 24 +++ .../View/SupplierReconciliationPageData.php | 19 +++ .../_freight-bills.blade.php | 69 ++++++++ .../supplier-data.blade.php | 8 +- routes/admin.php | 9 + .../Business/PortalFreightBillTest.php | 158 ++++++++++++++++++ 11 files changed, 637 insertions(+), 3 deletions(-) create mode 100644 app/Http/Controllers/Business/PortalFreightBillController.php create mode 100644 app/Support/CourierBills/FreightBillTemplate.php create mode 100644 app/Support/CourierBills/PortalFreightBills.php create mode 100644 resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php create mode 100644 tests/Feature/Business/PortalFreightBillTest.php diff --git a/app/Http/Controllers/Business/PortalFreightBillController.php b/app/Http/Controllers/Business/PortalFreightBillController.php new file mode 100644 index 000000000..757627be7 --- /dev/null +++ b/app/Http/Controllers/Business/PortalFreightBillController.php @@ -0,0 +1,120 @@ + '代发运费账单', 'courier' => '快递账单']; + + public function __construct( + private readonly FreightBillTemplate $template, + private readonly PortalFreightBills $portal, + private readonly SupplierPortalAccess $access, + ) { + $this->middleware('auth'); + $this->middleware('company.identify'); + } + + public function template(): StreamedResponse + { + return $this->template->download('运费账单上传模板.xlsx'); + } + + public function upload(Request $request): RedirectResponse + { + $data = $request->validate([ + 'kind' => ['required', 'in:dropship,courier'], + 'month' => ['required', 'date_format:Y-m'], + 'group' => ['nullable', 'integer'], + 'import' => ['required', 'file', 'max:51200'], + ], [], ['import' => '账单文件', 'month' => '账单月份']); + $file = $request->file('import'); + $extension = strtolower($file->getClientOriginalExtension()); + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + throw ValidationException::withMessages(['freight_bill' => '只支持 xlsx、xls、csv,请用上传模板。']); + } + $name = $this->effectiveName($request); + $original = (string) $file->getClientOriginalName(); + try { + $summary = $this->template->validate((string) $file->getRealPath(), $extension); + } catch (RuntimeException $error) { + throw ValidationException::withMessages(['freight_bill' => $error->getMessage()]); + } + $uploader = mb_substr((string) ($request->user()?->name ?: $request->user()?->email ?: '厂家门户') . '(门户)', 0, 64); + + if ($data['kind'] === 'dropship') { + $factory = $this->portal->factory($name); + if ($factory === null) { + throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在代发厂家里,请联系财务。']); + } + $id = app(DropshipFreightStore::class)->uploadFor($original, (string) $file->getRealPath(), $data['month'], (int) $factory->id, $uploader); + $row = app(DropshipFreightStore::class)->db()->table('dropship_bill_files')->find($id); + } else { + $groups = $this->portal->groups($name); + if ($groups === []) { + throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在快递账单对账分组里,请联系财务。']); + } + $group = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0)); + if ($group === null) { + throw ValidationException::withMessages(['freight_bill' => '请选择是哪一个快递的账单。']); + } + $ids = app(CourierBillStore::class)->upload([$file], $data['month'], [(int) $group->id], $uploader); + $row = app(CourierBillStore::class)->db()->table('courier_bill_files')->find($ids[0] ?? 0); + } + if ($row === null || $row->status !== 'parsed') { + throw ValidationException::withMessages(['freight_bill' => '文件已收到,但没有读入:' . ($row->message ?? '未知原因') . '。请联系财务。']); + } + + $message = '已上传' . self::KINDS[$data['kind']] . ':' . $name . ' ' . $data['month'] . ',' . number_format($summary['rows']) . ' 行,运费合计 ' + . number_format($summary['amount'], 2) . ' 元,已进入财务核对'; + try { + if (app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($name, self::KINDS[$data['kind']], $data['month'], $original, $summary)) { + $message .= ';上传回执已发到钉钉群'; + } + } catch (Throwable $error) { + report($error); + } + + return back()->with('success', $message . '。'); + } + + /** 厂家/快递账号只能是钉钉组织绑定的那几家;财务账号按页面上选的那家。 */ + private function effectiveName(Request $request): string + { + $user = $request->user(); + $name = trim((string) $request->input('supplier', '')); + if ($user && SupplierPortalAccess::isSupplierUser($user)) { + $names = $this->access->supplierNamesFor($user); + abort_if($names === [], 403, '当前钉钉账号未绑定有效厂家,请联系财务人员。'); + if (count($names) === 1 && $name === '') { + return $names[0]; + } + abort_unless(in_array($name, $names, true), 403, '该厂家不在当前账号的授权范围内。'); + + return $name; + } + if ($name === '') { + throw ValidationException::withMessages(['freight_bill' => '请先选择厂家。']); + } + + return $name; + } +} diff --git a/app/Services/Auth/SupplierPortalAccess.php b/app/Services/Auth/SupplierPortalAccess.php index 27fdc9522..2f193ff75 100644 --- a/app/Services/Auth/SupplierPortalAccess.php +++ b/app/Services/Auth/SupplierPortalAccess.php @@ -129,6 +129,20 @@ class SupplierPortalAccess } $resolved = []; + // 快递:部门名是快递账单对账分组名或承运商名的,也能登录厂家门户上传快递账单(不在供应商主档里) + foreach (\App\Support\CourierBills\PortalFreightBills::courierNames(array_keys($groupsByName)) as $courierName) { + if (isset($matchedSupplierNames[$courierName])) { + continue; + } + usort($groupsByName[$courierName], static fn (array $left, array $right): int => + (int) ($right['depth'] ?? 0) <=> (int) ($left['depth'] ?? 0)); + $resolved[] = [ + 'supplier_name' => $courierName, + 'supplier_code' => '', + 'dingtalk_group_id' => (int) ($groupsByName[$courierName][0]['Id'] ?? 0), + 'dingtalk_group_name' => $courierName, + ]; + } foreach (array_keys($matchedSupplierNames) as $supplierName) { $matchingRows = array_values(array_filter( $supplierRows, diff --git a/app/Support/CourierBills/FreightBillTemplate.php b/app/Support/CourierBills/FreightBillTemplate.php new file mode 100644 index 000000000..3d8e2dd52 --- /dev/null +++ b/app/Support/CourierBills/FreightBillTemplate.php @@ -0,0 +1,112 @@ +streamDownload(static function (): void { + $book = new StreamingWorkbook(); + $book->row('账单', self::HEADERS, true); + $book->writeTo(fopen('php://output', 'wb')); + }, $fileName); + } + + /** + * 校验上传的文件是不是按模板填的,不对就把前几处错误一起报出来。 + * + * @return array{rows:int,waybills:int,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 ($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_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 . ' 行没有单号'; + } + $freight = BillParser::number($cells[3] ?? null); + if ($freight === null) { + $errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字'); + } + foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) { + if (($cells[$col] ?? '') !== '' && BillParser::number($cells[$col]) === null) { + $errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字'; + } + } + if (count($errors) >= self::MAX_ERRORS) { + break; + } + $count++; + $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)]; + } + + /** @param list $cells */ + private static function trimTail(array $cells): array + { + while ($cells !== [] && end($cells) === '') { + array_pop($cells); + } + + return $cells; + } +} diff --git a/app/Support/CourierBills/PortalFreightBills.php b/app/Support/CourierBills/PortalFreightBills.php new file mode 100644 index 000000000..b57a0f703 --- /dev/null +++ b/app/Support/CourierBills/PortalFreightBills.php @@ -0,0 +1,92 @@ +dropship->factories())->first(static fn (object $f): bool => trim((string) $f->name) === trim($name)); + } catch (Throwable) { + return null; + } + } + + /** @return list 这个承运商名对应的快递对账分组 */ + public function groups(string $name): array + { + $name = trim($name); + try { + return array_values(array_filter($this->courier->groups(), static fn (object $g): bool => $name !== '' + && (trim((string) $g->name) === $name || trim((string) ($g->summary_carrier ?? '')) === $name))); + } catch (Throwable) { + return []; + } + } + + /** + * 钉钉组织里能认作「快递」的部门名:快递对账分组名和小汇总承运商名。 + * + * @param list $names + * @return list + */ + public static function courierNames(array $names): array + { + $names = array_values(array_unique(array_filter(array_map('trim', $names)))); + if ($names === []) { + return []; + } + try { + $db = CourierBillMatcher::db(); + $found = $db->table('courier_bill_groups')->whereIn('name', $names)->pluck('name') + ->merge($db->table('courier_bill_groups')->whereIn('summary_carrier', $names)->pluck('summary_carrier')) + ->map(static fn ($n): string => trim((string) $n))->unique()->values()->all(); + } catch (Throwable) { + return []; + } + + return array_values(array_intersect($names, $found)); + } + + /** @return array{factory:?object,groups:list,files:list>} */ + public function panel(string $name): array + { + $factory = $this->factory($name); + $groups = $this->groups($name); + $files = []; + try { + if ($factory !== null) { + foreach ($this->dropship->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->orderByDesc('id')->limit(10) + ->get() as $f) { + $files[] = ['kind' => '代发运费', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->waybill_count, + 'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at]; + } + } + if ($groups !== []) { + $ids = array_map(static fn (object $g): int => (int) $g->id, $groups); + foreach ($this->courier->db()->table('courier_bill_files')->whereIn('group_id', $ids)->orderByDesc('id')->limit(10)->get() as $f) { + $files[] = ['kind' => '快递账单', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->row_count, + 'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at]; + } + } + } catch (Throwable) { + // 表没建好时只是不显示上传记录 + } + usort($files, static fn (array $a, array $b): int => strcmp($b['at'], $a['at'])); + + return ['factory' => $factory, 'groups' => $groups, 'files' => array_slice($files, 0, 10)]; + } +} diff --git a/app/Support/DropshipFreight/DropshipFreightStore.php b/app/Support/DropshipFreight/DropshipFreightStore.php index b741fc575..aa389fe90 100644 --- a/app/Support/DropshipFreight/DropshipFreightStore.php +++ b/app/Support/DropshipFreight/DropshipFreightStore.php @@ -174,6 +174,17 @@ final class DropshipFreightStore return $ids; } + /** 厂家自己上传(厂家门户):已经知道是哪家,不用从文件名认。 */ + public function uploadFor(string $name, string $path, string $month, int $factoryId, string $user): int + { + $factory = collect($this->factories())->firstWhere('id', $factoryId); + if ($factory === null) { + throw new RuntimeException('厂家不存在。'); + } + + return $this->register($name, $path, $month, [$factory], $user, $factory); + } + public function assign(int $fileId, int $factoryId): void { $file = $this->db()->table('dropship_bill_files')->find($fileId); @@ -287,12 +298,12 @@ final class DropshipFreightStore } /** @param list $factories */ - private function register(string $name, string $path, string $month, array $factories, string $user): int + private function register(string $name, string $path, string $month, array $factories, string $user, ?object $known = null): int { $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); $stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension; Storage::disk(self::DISK)->put($stored, fopen($path, 'rb')); - $factory = self::identify($name, $factories); + $factory = $known ?? self::identify($name, $factories); $id = (int) $this->db()->table('dropship_bill_files')->insertGetId([ 'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_factory', 'message' => $factory === null ? '文件名里没认出是哪家厂家,请选择厂家' : null, diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index e60658b03..b573c5f9a 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -505,6 +505,30 @@ class SupplierDingTalkNotifier return true; } + /** @param array{rows:int,waybills:int,amount:float} $summary */ + public function sendFreightBillUploadReceipt(string $name, string $kind, string $month, string $fileName, array $summary): bool + { + $configs = $this->configs(); + $config = is_array($configs[$name] ?? null) ? $configs[$name] : []; + $webhook = trim((string) ($config['webhook'] ?? '')); + if ($webhook === '') { + return false; + } + $this->assertWebhook($webhook); + $fileName = mb_strimwidth(trim((string) preg_replace('/[\r\n`]+/u', ' ', basename($fileName))), 0, 120, '…', 'UTF-8'); + $this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false), + $name . ' · ' . $kind . '上传回执 · ' . $this->displayMonth($month), implode("\n", [ + '### ' . $kind . '上传回执 · ' . $name, + '- 账单月份:**' . $this->displayMonth($month) . '**', + '- 上传文件:' . ($fileName !== '' ? $fileName : '未命名文件'), + '- 账单:**' . $summary['rows'] . '** 行,运费合计 **¥' . number_format((float) $summary['amount'], 2) . '**', + '- 上传时间:' . $this->platformTimestamp(), + '- 数据状态:**已进入财务核对**', + ])); + + return true; + } + public function sendStatementReminder( string $supplier, string $accountingMonth, diff --git a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php index a089a695b..955df3d18 100644 --- a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php +++ b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php @@ -350,8 +350,17 @@ class SupplierReconciliationPageData ? $this->returnPanelData($selected, $companyId, request()->query()) : ['returnPanel' => null, 'returnWarehouses' => []]; + $freightPanel = $selected !== '' ? app(\App\Support\CourierBills\PortalFreightBills::class)->panel($selected) : null; + // 只是快递(不是供应商、也不是代发厂家)的账号:不显示货款对账单和退货,只上传快递账单 + $courierOnly = $freightPanel !== null && $freightPanel['groups'] !== [] && $freightPanel['factory'] === null + && $statementPage['total'] === 0 && ! $this->isSupplier($selected); + return [ 'view' => 'business.pages.supplier-reconciliation.supplier-data', + 'freightPanel' => $freightPanel, + 'courierOnly' => $courierOnly, + 'freightTemplateUrl' => route('business.supplier-reconciliation.freight-bill.template'), + 'freightUploadUrl' => route('business.supplier-reconciliation.freight-bill.upload'), 'supplierNames' => $supplierNames, 'supplierQuery' => $supplierQuery, 'supplierNotFound' => $supplierNotFound, @@ -374,6 +383,16 @@ class SupplierReconciliationPageData ] + $this->vendorPeriodContext(); } + private function isSupplier(string $name): bool + { + try { + return app(\Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository::class)->suppliersByNames([$name]) !== []; + } catch (\Throwable) { + // 供应商主档镜像暂时读不到:名字已经对上快递分组、又没有货款对账单,按快递处理 + return false; + } + } + /** * 厂家门户只读取当前登录联系人绑定的供应商数据。 * diff --git a/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php b/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php new file mode 100644 index 000000000..1bf718fd7 --- /dev/null +++ b/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php @@ -0,0 +1,69 @@ +@php + $fp = $freightPanel; + $kinds = []; + if ($fp['factory'] !== null) { $kinds['dropship'] = '代发运费账单'; } + if ($fp['groups'] !== []) { $kinds['courier'] = '快递账单'; } + $defaultMonth = $accountingMonthKey ?? now()->subMonth()->format('Y-m'); +@endphp + +
+

上传运费账单

+

+ 请先下载上传模板,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」; + 单号、运费必填,重量、面单、费率填数字,省、送货备注可空。不按模板的文件会被退回并提示哪里要改。 + 同一个月可以分几次上传,上传后进入财务核对。 +

+ @if ($errors->has('freight_bill')) + + @endif +
+ @csrf + + + @if (count($fp['groups']) > 1) + + @endif + + + + 下载上传模板 +
+ @if ($fp['files'] !== []) + + + + @foreach ($fp['files'] as $f) + + + + + + + @endforeach + +
类型月份文件行数运费合计状态上传时间
{{ $f['kind'] }}{{ $f['month'] }}{{ $f['name'] }}{{ number_format($f['count']) }}{{ number_format($f['amount'], 2) }}{{ $f['status'] === 'parsed' ? '已读入' : ($f['status'] === 'failed' ? '失败:' . $f['message'] : '待财务处理') }}{{ substr($f['at'], 0, 16) }}
+ @endif +
diff --git a/resources/views/business/pages/supplier-reconciliation/supplier-data.blade.php b/resources/views/business/pages/supplier-reconciliation/supplier-data.blade.php index ef1304e5a..20b41e7f3 100644 --- a/resources/views/business/pages/supplier-reconciliation/supplier-data.blade.php +++ b/resources/views/business/pages/supplier-reconciliation/supplier-data.blade.php @@ -270,7 +270,7 @@
@if ($supplierLocked)
- 当前厂家(由钉钉组织自动确定) + {{ ($courierOnly ?? false) ? '当前快递(由钉钉组织自动确定)' : '当前厂家(由钉钉组织自动确定)' }} {{ $selectedSupplier }} @if (($supplierCount ?? 1) > 1) 切换厂家 @@ -306,6 +306,11 @@ @endif
+ @if (! empty($freightPanel) && ($freightPanel['factory'] !== null || $freightPanel['groups'] !== [])) + @include('business.pages.supplier-reconciliation._freight-bills', ['name' => $selectedSupplier]) + @endif + + @unless ($courierOnly ?? false) @include('portal.supplier-reconciliation.workspace', [ 'supplier' => $selectedSupplier, 'workspaceIndexUrl' => route('business.pages.show', [ @@ -318,5 +323,6 @@ ]), 'workspaceFilterSupplier' => $selectedSupplier, ]) + @endunless @endif
diff --git a/routes/admin.php b/routes/admin.php index 9ea0a7de4..4a10e7e05 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -586,6 +586,15 @@ Route::get('workspace/supplier-portal', [\App\Http\Controllers\Business\Supplier ->middleware('business.page:supplier-reconciliation,supplier-data') ->name('business.supplier-portal.home'); +// 厂家门户:代发厂家 / 快递按统一模板上传运费账单 +Route::get('workspace/supplier-reconciliation/freight-bill-template', [\App\Http\Controllers\Business\PortalFreightBillController::class, 'template']) + ->middleware('business.page:supplier-reconciliation,supplier-data') + ->name('business.supplier-reconciliation.freight-bill.template'); + +Route::post('workspace/supplier-reconciliation/freight-bill', [\App\Http\Controllers\Business\PortalFreightBillController::class, 'upload']) + ->middleware(['business.page:supplier-reconciliation,supplier-data', 'throttle:import-upload']) + ->name('business.supplier-reconciliation.freight-bill.upload'); + Route::get('workspace/supplier-reconciliation/statement-template', [SupplierReconciliationActions::class, 'template']) ->middleware('business.page:supplier-reconciliation,supplier-data') ->name('business.supplier-reconciliation.template'); diff --git a/tests/Feature/Business/PortalFreightBillTest.php b/tests/Feature/Business/PortalFreightBillTest.php new file mode 100644 index 000000000..b076c7efb --- /dev/null +++ b/tests/Feature/Business/PortalFreightBillTest.php @@ -0,0 +1,158 @@ +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); + + foreach ([ + [[['快递单号', '运费'], ['1', 2]], '第一行必须依次是'], + [[self::H, ['773444000001', '江苏', 3, null]], '第 2 行运费没填'], + [[self::H, [null, '江苏', 3, 5]], '第 2 行没有单号'], + [[self::H, ['773444000001', '江苏', '三公斤', 5]], '重量「三公斤」不是数字'], + [[self::H], '还没有填账单明细'], + ] as [$rows, $message]) { + try { + $t->validate($this->xlsx($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'); + $this->company->makeCurrent(true); + $db = CourierBillMatcher::db(); + $db->table('dropship_factories')->insert(['name' => '临沂卿德客', 'warehouse' => '工厂-山东卿德客代发仓', 'keywords' => '卿德客', + '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()]); + $this->assertSame(['曹县韵达'], PortalFreightBills::courierNames(['曹县韵达', '财务中心', '临沂卿德客'])); + + \Illuminate\Support\Facades\URL::defaults(['company_id' => $this->company->id]); + $page = route('business.pages.show', ['section' => 'supplier-reconciliation', 'page' => 'supplier-data']); + $upload = route('business.supplier-reconciliation.freight-bill.upload'); + $file = fn (array $rows, string $name = '账单.xlsx') => new UploadedFile($this->xlsx($rows), $name, null, null, true); + + // 代发厂家:厂家门户里多了「上传运费账单」,传代发运费账单 + $factoryUser = $this->portalUser('临沂卿德客'); + $this->actingAsPortal($factoryUser)->get($page)->assertOk()->assertSeeText('上传运费账单')->assertSeeText('代发运费账单'); + $this->get(route('business.supplier-reconciliation.freight-bill.template'))->assertOk(); + $this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([['快递单号', '运费'], ['773444000001', 8]])]) + ->assertSessionHasErrors('freight_bill'); + $this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([self::H, ['773444000001', '江苏', 3, 8], ['773444000002', '', '', 6]])]) + ->assertSessionHas('success'); + $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('(门户)', (string) $f->uploaded_by); + // 不能替别的厂家传 + $this->post($upload, ['kind' => 'dropship', 'supplier' => '别家', 'month' => '2026-11', 'import' => $file([self::H, ['1', '', '', 1]])]) + ->assertForbidden(); + + // 快递:钉钉部门名是承运商名,只看得到上传快递账单,看不到货款对账 + $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]])]) + ->assertSessionHas('success'); + $c = $db->table('courier_bill_files')->sole(); + $this->assertSame('parsed', $c->status); + $this->assertEquals(4.5, (float) $c->amount); + $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]])]) + ->assertSessionHasErrors('freight_bill'); + } + + public function test_courier_department_in_dingtalk_resolves_to_a_portal_binding(): void + { + CourierBillMatcher::db()->table('courier_bill_groups')->insert(['name' => '曹县韵达小件', 'summary_carrier' => '曹县韵达', + 'express_names' => '[]', 'created_at' => now(), 'updated_at' => now()]); + $query = \Mockery::mock(\Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery::class); + $query->shouldReceive('select')->andReturnUsing(static fn (string $sql): array => str_contains($sql, 'hr_employee') + ? [['userid' => 'ding-c', 'unionid' => 'union-c', 'active' => 1, 'dept_id_list' => '77']] + : [['Id' => 77, 'parent_id' => 70, 'name' => '曹县韵达', 'depth' => 0], ['Id' => 70, 'parent_id' => 1, 'name' => '快递', 'depth' => 1]]); + $factory = \Mockery::mock(\Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory::class); + $factory->shouldReceive('forSource')->andReturn($query); + $suppliers = \Mockery::mock(\Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository::class); + $suppliers->shouldReceive('suppliersByNames')->andReturn([]); + + $resolved = (new SupplierPortalAccess($factory, $suppliers))->resolveAll('ding-c', 'union-c'); + + $this->assertSame([['supplier_name' => '曹县韵达', 'supplier_code' => '', 'dingtalk_group_id' => 77, 'dingtalk_group_name' => '曹县韵达']], $resolved); + } + + private function portalUser(string $name): User + { + $user = User::create(['name' => $name . '对账员', 'email' => Str::lower(Str::random(12)) . '@portal.test', 'password' => Str::random(32), + 'locale' => 'zh-CN', 'enabled' => true, 'created_from' => SupplierPortalAccess::CREATED_FROM, + 'landing_page' => 'business.supplier-portal.home', 'created_by' => 0]); + $user->roles()->attach(Role::where('name', 'user')->firstOrFail()->id); + $user->permissions()->attach(Permission::where('name', 'read-admin-panel')->firstOrFail()->id); + $user->companies()->attach($this->company->id); + DingTalkIdentity::create(['user_id' => $user->id, 'union_id' => 'union-' . $user->id, 'dingtalk_user_id' => 'ding-' . $user->id]); + SupplierPortalIdentity::create(['company_id' => $this->company->id, 'user_id' => $user->id, 'supplier_code' => null, + 'supplier_name' => $name, 'dingtalk_group_id' => 1, 'dingtalk_group_name' => $name, 'last_verified_at' => now()]); + SupplierPortalSupplier::create(['company_id' => $this->company->id, 'user_id' => $user->id, 'supplier_code' => null, + 'supplier_name' => $name, 'dingtalk_group_id' => 1, 'dingtalk_group_name' => $name, 'last_verified_at' => now()]); + + return $user; + } + + private function actingAsPortal(User $user): self + { + $identity = DingTalkIdentity::query()->where('user_id', $user->id)->firstOrFail(); + + return $this->withExceptionHandling()->loginAs($user)->withSession(['dingtalk_identity_id' => $identity->id, 'dingtalk_roster_checked_at' => now()->timestamp]); + } + + /** @param list> $rows */ + private function xlsx(array $rows): string + { + $book = new Spreadsheet(); + $sheet = $book->getActiveSheet(); + foreach ($rows as $r => $row) { + foreach ($row as $c => $value) { + if ($value !== null && $value !== '') { + $sheet->setCellValueExplicit([$c + 1, $r + 1], $value, is_string($value) + ? \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING : \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC); + } + } + } + $path = tempnam(sys_get_temp_dir(), 'pfb_') . '.xlsx'; + (new Xlsx($book))->save($path); + + return $path; + } +} -- 2.47.2 From a9f34b93cf46ec69b7d21fcd0f3622520016bd0f Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Wed, 2 Dec 2026 20:00:53 +0800 Subject: [PATCH 2/5] =?UTF-8?q?fix:=20=E9=9A=94=E7=A6=BB=E9=97=A8=E6=88=B7?= =?UTF-8?q?=E8=B4=A6=E5=8D=95=E5=AF=BC=E5=85=A5=E5=B9=B6=E4=B8=A5=E6=A0=BC?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E6=8E=88=E6=9D=83=E4=B8=8E=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Commands/ImportPortalFreightBills.php | 18 +++ .../Business/PortalFreightBillController.php | 52 ++------ app/Support/CourierBills/CourierBillStore.php | 22 ++- .../CourierBills/FreightBillTemplate.php | 13 +- .../CourierBills/PortalFreightBillImports.php | 126 ++++++++++++++++++ .../CourierBills/PortalFreightBills.php | 2 +- deploy/activate-incremental-release.sh | 1 + deploy/activate-release.sh | 1 + deploy/finance-batch-imports.json | 1 + deploy/run-finance-batch.sh | 7 + .../_freight-bills.blade.php | 12 +- .../Business/PortalFreightBillTest.php | 57 +++++++- .../Deployment/FinanceBatchIsolationTest.php | 20 +++ 13 files changed, 275 insertions(+), 57 deletions(-) create mode 100644 app/Console/Commands/ImportPortalFreightBills.php create mode 100644 app/Support/CourierBills/PortalFreightBillImports.php diff --git a/app/Console/Commands/ImportPortalFreightBills.php b/app/Console/Commands/ImportPortalFreightBills.php new file mode 100644 index 000000000..0d32e613a --- /dev/null +++ b/app/Console/Commands/ImportPortalFreightBills.php @@ -0,0 +1,18 @@ +processNext(); + return self::SUCCESS; + } +} diff --git a/app/Http/Controllers/Business/PortalFreightBillController.php b/app/Http/Controllers/Business/PortalFreightBillController.php index 757627be7..6cfd40b99 100644 --- a/app/Http/Controllers/Business/PortalFreightBillController.php +++ b/app/Http/Controllers/Business/PortalFreightBillController.php @@ -3,18 +3,14 @@ namespace App\Http\Controllers\Business; use App\Services\Auth\SupplierPortalAccess; -use App\Support\CourierBills\CourierBillStore; use App\Support\CourierBills\FreightBillTemplate; use App\Support\CourierBills\PortalFreightBills; -use App\Support\DropshipFreight\DropshipFreightStore; +use App\Support\CourierBills\PortalFreightBillImports; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Validation\ValidationException; -use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier; -use RuntimeException; use Symfony\Component\HttpFoundation\StreamedResponse; -use Throwable; /** * 厂家门户(钉钉登录的供应商对账入口)上传运费账单:代发厂家传代发运费账单,快递传快递账单,统一模板、严格校验。 @@ -52,48 +48,22 @@ final class PortalFreightBillController extends Controller throw ValidationException::withMessages(['freight_bill' => '只支持 xlsx、xls、csv,请用上传模板。']); } $name = $this->effectiveName($request); - $original = (string) $file->getClientOriginalName(); - try { - $summary = $this->template->validate((string) $file->getRealPath(), $extension); - } catch (RuntimeException $error) { - throw ValidationException::withMessages(['freight_bill' => $error->getMessage()]); - } - $uploader = mb_substr((string) ($request->user()?->name ?: $request->user()?->email ?: '厂家门户') . '(门户)', 0, 64); - if ($data['kind'] === 'dropship') { - $factory = $this->portal->factory($name); - if ($factory === null) { - throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在代发厂家里,请联系财务。']); - } - $id = app(DropshipFreightStore::class)->uploadFor($original, (string) $file->getRealPath(), $data['month'], (int) $factory->id, $uploader); - $row = app(DropshipFreightStore::class)->db()->table('dropship_bill_files')->find($id); + $target = $this->portal->factory($name); } else { $groups = $this->portal->groups($name); - if ($groups === []) { - throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在快递账单对账分组里,请联系财务。']); - } - $group = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0)); - if ($group === null) { - throw ValidationException::withMessages(['freight_bill' => '请选择是哪一个快递的账单。']); - } - $ids = app(CourierBillStore::class)->upload([$file], $data['month'], [(int) $group->id], $uploader); - $row = app(CourierBillStore::class)->db()->table('courier_bill_files')->find($ids[0] ?? 0); + $target = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0)); } - if ($row === null || $row->status !== 'parsed') { - throw ValidationException::withMessages(['freight_bill' => '文件已收到,但没有读入:' . ($row->message ?? '未知原因') . '。请联系财务。']); + if ($target === null) { + throw ValidationException::withMessages(['freight_bill' => '当前厂家或快递分组不匹配,请联系财务。']); } + app(PortalFreightBillImports::class)->submit($file, [ + 'name' => $name, 'kind' => $data['kind'], 'month' => $data['month'], 'target_id' => (int) $target->id, + 'company_id' => (int) company_id(), 'user_id' => (int) $request->user()->id, + 'uploader' => mb_substr((string) ($request->user()->name ?: $request->user()->email) . '(门户)', 0, 64), + ]); - $message = '已上传' . self::KINDS[$data['kind']] . ':' . $name . ' ' . $data['month'] . ',' . number_format($summary['rows']) . ' 行,运费合计 ' - . number_format($summary['amount'], 2) . ' 元,已进入财务核对'; - try { - if (app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($name, self::KINDS[$data['kind']], $data['month'], $original, $summary)) { - $message .= ';上传回执已发到钉钉群'; - } - } catch (Throwable $error) { - report($error); - } - - return back()->with('success', $message . '。'); + return back()->with('success', '文件已收到,正在等待校验和读入。处理结果请在下方上传记录查看。'); } /** 厂家/快递账号只能是钉钉组织绑定的那几家;财务账号按页面上选的那家。 */ diff --git a/app/Support/CourierBills/CourierBillStore.php b/app/Support/CourierBills/CourierBillStore.php index b88c9e4e6..38ebf5175 100644 --- a/app/Support/CourierBills/CourierBillStore.php +++ b/app/Support/CourierBills/CourierBillStore.php @@ -352,6 +352,16 @@ final class CourierBillStore return $ids; } + /** 门户上传仅写入已授权分组;不从可控文件名或合并账单配置扩展到其他分组。 */ + public function uploadFor(\Illuminate\Http\UploadedFile $file, string $month, int $groupId, string $user): int + { + $groups = $this->groups(); + if (! collect($groups)->contains('id', $groupId)) throw new RuntimeException('快递分组不存在。'); + $id = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month, [$groupId], $groups, $user, true); + foreach ($this->statementsOfFiles([$id]) as $statementId) $this->matcher->match($statementId); + return $id; + } + /** 给待选分组的文件指定分组,读入并对账。 */ public function assign(int $fileId, int $groupId): void { @@ -413,7 +423,7 @@ final class CourierBillStore * @param list $groupIds * @param list $groups */ - private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user): int + private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false): int { $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); $stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension; @@ -422,7 +432,7 @@ final class CourierBillStore $group = $groupIds !== [] ? collect($groups)->firstWhere('id', $groupIds[0]) : self::identify($name, $groups); - $extra = array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)])); + $extra = $portal ? [] : array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)])); $id = (int) $this->db()->table('courier_bill_files')->insertGetId([ 'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(), @@ -435,14 +445,14 @@ final class CourierBillStore return $id; } if ($group !== null) { - $this->ingest($id, $group); + $this->ingest($id, $group, false, $portal); } return $id; } /** 读文件、写账单行到主分组的对账单,再按快递名称1 拆到同一合并账单等可拆入的分组。 */ - private function ingest(int $fileId, object $group, bool $reread = false): void + private function ingest(int $fileId, object $group, bool $reread = false, bool $portal = false): void { $db = $this->db(); $file = $db->table('courier_bill_files')->find($fileId); @@ -471,7 +481,7 @@ final class CourierBillStore $feeCount = 0; $overlap = null; try { - $split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string { + $split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string { if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') { throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。'); } @@ -550,7 +560,7 @@ final class CourierBillStore $db->table('courier_bill_surcharges')->insert($fees); } - return $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread); + return $portal ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread); }); } catch (Throwable $error) { if ($reread) { diff --git a/app/Support/CourierBills/FreightBillTemplate.php b/app/Support/CourierBills/FreightBillTemplate.php index 3d8e2dd52..7c05889f8 100644 --- a/app/Support/CourierBills/FreightBillTemplate.php +++ b/app/Support/CourierBills/FreightBillTemplate.php @@ -43,6 +43,9 @@ final class FreightBillTemplate if ($rows === null) { throw new RuntimeException('文件是空的。'); } + if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) { + throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。'); + } $errors = []; $header = null; $count = 0; @@ -69,13 +72,16 @@ final class FreightBillTemplate } if ($waybill === '') { $errors[] = '第 ' . $line . ' 行没有单号'; + } elseif (Waybill::normalize($waybill) === null) { + $errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本'; } $freight = BillParser::number($cells[3] ?? null); - if ($freight === null) { + if ($freight === null || ! is_finite($freight)) { $errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字'); } foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) { - if (($cells[$col] ?? '') !== '' && BillParser::number($cells[$col]) === null) { + $value = BillParser::number($cells[$col] ?? null); + if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) { $errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字'; } } @@ -83,6 +89,7 @@ final class FreightBillTemplate break; } $count++; + if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。'); $amount += (float) $freight; $waybills[$waybill] = true; } @@ -96,6 +103,8 @@ 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)]; } diff --git a/app/Support/CourierBills/PortalFreightBillImports.php b/app/Support/CourierBills/PortalFreightBillImports.php new file mode 100644 index 000000000..1ec472600 --- /dev/null +++ b/app/Support/CourierBills/PortalFreightBillImports.php @@ -0,0 +1,126 @@ +path(self::ROOT . '/tasks/' . $token); + if (! mkdir($dir, 0700, true)) throw new RuntimeException('无法保存账单,请稍后重试。'); + $extension = strtolower($file->getClientOriginalExtension()); + $file->move($dir, 'input.' . $extension); + $task = $details + ['token' => $token, 'extension' => $extension, + 'original_name' => mb_substr($file->getClientOriginalName(), 0, 255), + 'status' => 'queued', 'created_at' => now('Asia/Shanghai')->toDateTimeString(), 'message' => null]; + $this->write($task); + $queue = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending'); + if (! is_dir($queue)) mkdir($queue, 0700, true); + touch($queue . '/' . $token); + } + + public function recent(int $companyId, string $name): array + { + $files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: []; + rsort($files); + $out = []; + foreach (array_slice($files, 0, 10) as $path) { + $task = json_decode((string) file_get_contents($path), true); + if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue; + $out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'], + 'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'], + 'message' => $task['message'], 'at' => $task['created_at']]; + } + usort($out, static fn ($a, $b) => strcmp($b['at'], $a['at'])); + return array_slice($out, 0, 10); + } + + public function processNext(): bool + { + $pending = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending/*')) ?: []; + sort($pending); + foreach ($pending as $marker) { + $token = basename($marker); + if (! Str::isUuid($token)) continue; + $path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $token . '/task.json'); + $task = json_decode((string) file_get_contents($path), true, 32, JSON_THROW_ON_ERROR); + if ($task['status'] !== 'queued') { + // 上次进程中断后不重导,保留现场供财务核对。 + if ($task['status'] === 'running') $this->write(array_replace($task, ['status' => 'failed', 'message' => '处理曾中断,请联系财务核对后重新上传。'])); + unlink($marker); + return true; + } + $task['status'] = 'running'; + $this->write($task); + try { + $this->process($task); + $task['status'] = 'completed'; + } catch (Throwable $e) { + $task['status'] = 'failed'; + $task['message'] = $e instanceof RuntimeException && ! $e instanceof \Illuminate\Database\QueryException + ? mb_substr($e->getMessage(), 0, 500) : '账单处理失败,请联系财务核对。'; + report($e); + } + $this->write($task); + unlink($marker); + return true; + } + return false; + } + + private function process(array $task): void + { + $user = User::find($task['user_id']); + if (! $user || ! $user->enabled || ! $user->companies()->where('companies.id', $task['company_id'])->exists()) throw new RuntimeException('上传账号已停用或授权已变化,请联系财务。'); + \App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true); + if (SupplierPortalAccess::isSupplierUser($user) && ! in_array($task['name'], app(SupplierPortalAccess::class)->supplierNamesFor($user), true)) throw new RuntimeException('厂家授权已变化,请联系财务。'); + $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']); + if ($task['kind'] === 'dropship') { + $factory = $portal->factory($task['name']); + if ($factory === null || (int) $factory->id !== $task['target_id']) throw new RuntimeException('厂家设置已变化,请联系财务。'); + $store = app(DropshipFreightStore::class); + $id = $store->uploadFor($task['original_name'], $path, $task['month'], $task['target_id'], $task['uploader']); + $row = $store->db()->table('dropship_bill_files')->find($id); + } else { + if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。'); + $store = app(CourierBillStore::class); + $id = $store->uploadFor(new UploadedFile($path, $task['original_name'], null, null, true), $task['month'], $task['target_id'], $task['uploader']); + $row = $store->db()->table('courier_bill_files')->find($id); + } + 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]; + try { + app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($task['name'], $task['kind'] === 'dropship' ? '代发运费账单' : '快递账单', $task['month'], $task['original_name'], $summary); + } catch (Throwable $e) { report($e); } + } + + private function write(array $task): void + { + $path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/task.json'); + if (file_put_contents($path . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX) === false) throw new RuntimeException('账单状态保存失败。'); + chmod($path . '.tmp', 0600); + rename($path . '.tmp', $path); + $index = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $task['company_id'] . '/' . hash('sha256', $task['name'])); + if (! is_dir($index)) mkdir($index, 0700, true); + $indexPath = $index . '/' . str_replace([' ', ':', '-'], '', $task['created_at']) . '-' . $task['token'] . '.json'; + file_put_contents($indexPath . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX); + chmod($indexPath . '.tmp', 0600); + rename($indexPath . '.tmp', $indexPath); + } +} diff --git a/app/Support/CourierBills/PortalFreightBills.php b/app/Support/CourierBills/PortalFreightBills.php index b57a0f703..e54959c93 100644 --- a/app/Support/CourierBills/PortalFreightBills.php +++ b/app/Support/CourierBills/PortalFreightBills.php @@ -66,7 +66,7 @@ final class PortalFreightBills { $factory = $this->factory($name); $groups = $this->groups($name); - $files = []; + $files = app(PortalFreightBillImports::class)->recent((int) company_id(), $name); try { if ($factory !== null) { foreach ($this->dropship->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->orderByDesc('id')->limit(10) diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 4df7df62a..b2218f4ea 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -264,6 +264,7 @@ CRON_TZ=Asia/Shanghai # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 +* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 # 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。 28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1 # 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 9be94d000..4b380ebb4 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -268,6 +268,7 @@ CRON_TZ=Asia/Shanghai # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 +* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 # 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。 28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1 # 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。 diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index b511c81d3..a58a4d647 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -1,4 +1,5 @@ [ + "portal-freight:import-pending", "planting-reimbursement:auto-confirm", "jushuitan:apply-shipping-corrections", "actual-tax:import", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 72b7d251e..d2b81db3c 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -8,6 +8,7 @@ is_import=0 CAIWU_BATCH_CALLER_DIR="$PWD" export CAIWU_BATCH_CALLER_DIR case "${1:-}" in + portal-freight:import-pending) is_import=1 ;; planting-reimbursement:auto-confirm) is_import=1 ;; jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;; @@ -26,6 +27,12 @@ case "${1:-}" in ;; esac cd "$REMOTE_DIR" +if [ "$1" = 'portal-freight:import-pending' ]; then + storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" + [ -n "$storage_root" ] && [ -d "$storage_root/app/private/portal-freight-bills/pending" ] || exit 0 + pending="$(find "$storage_root/app/private/portal-freight-bills/pending" -maxdepth 1 -type f -print -quit)" + [ -n "$pending" ] || exit 0 +fi if [ "$1" = 'account-bills:exports:run' ]; then storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" [ -n "$storage_root" ] && [ -d "$storage_root" ] || exit 65 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 1bf718fd7..725e6d38f 100644 --- a/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php +++ b/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php @@ -3,7 +3,7 @@ $kinds = []; if ($fp['factory'] !== null) { $kinds['dropship'] = '代发运费账单'; } if ($fp['groups'] !== []) { $kinds['courier'] = '快递账单'; } - $defaultMonth = $accountingMonthKey ?? now()->subMonth()->format('Y-m'); + $defaultMonth = $accountingMonthKey ?? now()->startOfMonth()->subMonth()->format('Y-m'); @endphp