From b439dfda0ac09e8c7c6434e240cf8667deb3f8ad Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Mon, 30 Nov 2026 14:02:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E5=8F=91=E8=BF=90=E8=B4=B9=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6=E4=B8=8E=E5=BF=AB=E9=80=92=E5=B0=8F=E6=B1=87=E6=80=BB?= =?UTF-8?q?=E7=B1=BB=E7=9B=AE=E6=A8=A1=E6=9D=BF=20(#1560)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ImportCourierSummaryTemplates.php | 44 +++ .../Business/CourierBillController.php | 28 +- .../Business/DropshipFreightController.php | 230 +++++++++++ app/Http/Controllers/Business/Pages.php | 5 +- .../CourierBills/CourierBillMatcher.php | 94 ++++- app/Support/CourierBills/CourierBillStore.php | 80 +++- app/Support/CourierBills/SummaryTemplate.php | 216 +++++++++++ .../DropshipFreight/DropshipFreightStore.php | 359 ++++++++++++++++++ .../DropshipFreight/DropshipReconciler.php | 292 ++++++++++++++ .../DropshipFreight/FactoryBillParser.php | 186 +++++++++ config/business_navigation.php | 2 + ..._100000_create_dropship_freight_tables.php | 61 +++ ...e_courier_bill_summary_templates_table.php | 28 ++ .../courier-bills/statement.blade.php | 15 +- .../courier-bills/upload.blade.php | 11 + .../dropship-freight/factories.blade.php | 46 +++ .../dropship-freight/factory.blade.php | 65 ++++ .../dropship-freight/overview.blade.php | 51 +++ .../dropship-freight/page.blade.php | 88 +++++ .../dropship-freight/upload.blade.php | 53 +++ routes/admin.php | 15 + .../Feature/Business/CourierBillPagesTest.php | 8 + .../CourierBillReconciliationTest.php | 105 +++++ .../Feature/Business/DropshipFreightTest.php | 250 ++++++++++++ 24 files changed, 2311 insertions(+), 21 deletions(-) create mode 100644 app/Console/Commands/ImportCourierSummaryTemplates.php create mode 100644 app/Http/Controllers/Business/DropshipFreightController.php create mode 100644 app/Support/CourierBills/SummaryTemplate.php create mode 100644 app/Support/DropshipFreight/DropshipFreightStore.php create mode 100644 app/Support/DropshipFreight/DropshipReconciler.php create mode 100644 app/Support/DropshipFreight/FactoryBillParser.php create mode 100644 database/migrations/2026_11_30_100000_create_dropship_freight_tables.php create mode 100644 database/migrations/2026_11_30_110000_create_courier_bill_summary_templates_table.php create mode 100644 resources/views/business/pages/courier-payables/dropship-freight/factories.blade.php create mode 100644 resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php create mode 100644 resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php create mode 100644 resources/views/business/pages/courier-payables/dropship-freight/page.blade.php create mode 100644 resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php create mode 100644 tests/Feature/Business/DropshipFreightTest.php diff --git a/app/Console/Commands/ImportCourierSummaryTemplates.php b/app/Console/Commands/ImportCourierSummaryTemplates.php new file mode 100644 index 00000000..8252d2b1 --- /dev/null +++ b/app/Console/Commands/ImportCourierSummaryTemplates.php @@ -0,0 +1,44 @@ +option('month'); + if (! preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $month)) { + $this->error('--month 要写成 2026-10 这样'); + + return self::FAILURE; + } + $blocks = json_decode((string) @file_get_contents((string) $this->argument('file')), true); + if (! is_array($blocks)) { + $this->error('读不了 JSON 文件'); + + return self::FAILURE; + } + $blocks = array_values(array_filter(array_map(static fn ($b): ?array => is_array($b) && isset($b['title'], $b['labels']) && is_array($b['labels']) + ? ['title' => (string) $b['title'], 'labels' => array_map('strval', $b['labels']), 'group' => isset($b['group']) ? (string) $b['group'] : null, + 'source' => isset($b['source']) ? (string) $b['source'] : null] + : null, $blocks))); + $result = $store->saveSummaryTemplates($blocks, $month); + $this->info('读到 ' . $result['blocks'] . ' 块,记下 ' . count($result['saved']) . ' 家 ' . $month . ' 的类目:' . implode('、', $result['saved'])); + if ($result['unknown'] !== []) { + $this->warn('没找到分组:' . implode('、', $result['unknown'])); + } + + return self::SUCCESS; + } +} diff --git a/app/Http/Controllers/Business/CourierBillController.php b/app/Http/Controllers/Business/CourierBillController.php index 8371ea67..fef9c9b3 100644 --- a/app/Http/Controllers/Business/CourierBillController.php +++ b/app/Http/Controllers/Business/CourierBillController.php @@ -347,10 +347,32 @@ final class CourierBillController extends Controller public function fillItem(Request $request, int $statement, int $item) { - $data = $request->validate(['self' => ['nullable', 'numeric']], [], ['self' => '自算金额']); - $this->guard(fn () => $this->store->fillSummaryItem($statement, $item, isset($data['self']) ? (float) $data['self'] : null)); + $data = $request->validate(['self' => ['nullable', 'numeric'], 'bill' => ['nullable', 'numeric']], [], ['self' => '自算金额', 'bill' => '快递提供金额']); + $this->guard(fn () => $this->store->fillSummaryItem($statement, $item, isset($data['self']) ? (float) $data['self'] : null, + isset($data['bill']) ? (float) $data['bill'] : null, $request->has('bill'))); - return $this->back($request, [], '已回填自算金额。'); + return $this->back($request, [], '已回填。'); + } + + public function importSummaryTemplates(Request $request) + { + $data = $request->validate([ + 'month' => ['required', 'date_format:Y-m'], + 'files' => ['required', 'array', 'max:80'], 'files.*' => ['file', 'max:51200'], + ], [], ['files' => '手工小汇总', 'files.*' => '手工小汇总']); + $files = []; + foreach ($data['files'] as $file) { + if (! in_array(strtolower($file->getClientOriginalExtension()), ['xlsx', 'xls'], true)) { + throw ValidationException::withMessages(['templates' => '只支持 xlsx、xls:' . $file->getClientOriginalName()]); + } + $files[] = [$file->getClientOriginalName(), (string) $file->getRealPath()]; + } + $result = $this->guard(fn () => $this->store->importSummaryTemplates($files, $data['month'])); + $message = '读到 ' . $result['blocks'] . ' 块小汇总,记下 ' . count($result['saved']) . ' 家 ' . $data['month'] . ' 的类目' + . ($result['saved'] !== [] ? ':' . implode('、', $result['saved']) : '') + . ($result['unknown'] !== [] ? '。认不出是哪家的:' . implode('、', array_slice($result['unknown'], 0, 20)) . '(标题里要有分组名)' : ''); + + return $this->back($request, ['cb_view' => 'upload', 'month' => $data['month']], $message . '。'); } public function deleteItem(Request $request, int $statement, int $item) diff --git a/app/Http/Controllers/Business/DropshipFreightController.php b/app/Http/Controllers/Business/DropshipFreightController.php new file mode 100644 index 00000000..7890dd44 --- /dev/null +++ b/app/Http/Controllers/Business/DropshipFreightController.php @@ -0,0 +1,230 @@ + '各厂家汇总', 'factory' => '单家明细', 'upload' => '上传厂家账单', 'factories' => '代发厂家设置']; + + public function __construct( + private readonly DropshipFreightStore $store, + private readonly DropshipReconciler $reconciler, + ) {} + + public function page(Request $request): array + { + $view = array_key_exists((string) $request->query('df_view'), self::VIEWS) ? (string) $request->query('df_view') : 'overview'; + $data = ['view' => 'business.pages.courier-payables.dropship-freight.page', 'dfView' => $view, 'dfViews' => self::VIEWS, + 'dfSection' => CourierBillController::section($request), 'dfUnavailable' => false]; + try { + $months = $this->store->db()->table('dropship_bill_files')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all(); + $month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m')); + $data += ['dfMonth' => $month, 'dfFactories' => $this->store->factories()]; + $data += match ($view) { + 'factory' => $this->factoryData($request, $month), + 'upload' => $this->uploadData($month), + 'factories' => [], + default => $this->overviewData($month), + }; + } catch (QueryException $error) { + report($error); + $data['dfUnavailable'] = true; + } + + return $data; + } + + private function overviewData(string $month): array + { + $billed = $this->store->db()->table('dropship_bill_lines')->where('bill_month', $month)->distinct()->pluck('factory_id') + ->map(static fn ($id): int => (int) $id)->all(); + $own = $this->store->ownExpressNames(); + $rows = []; + $without = []; + foreach ($this->store->factories() as $factory) { + if (in_array((int) $factory->id, $billed, true)) { + $rows[] = $this->reconciler->factoryMonth($factory, $month, $own)['summary']; + } else { + $without[] = $factory->name; + } + } + + return ['dfRows' => $rows, 'dfWithout' => $without, 'dfTotals' => [ + 'bill' => array_sum(array_column($rows, 'bill')), 'settle' => array_sum(array_column($rows, 'settle')), + 'diff' => array_sum(array_column($rows, 'diff')), 'attention' => array_sum(array_column($rows, 'attention')), + ]]; + } + + private function factoryData(Request $request, string $month): array + { + $factory = collect($this->store->factories())->firstWhere('id', (int) $request->query('factory')); + if ($factory === null) { + return ['dfFactory' => null]; + } + $result = $this->reconciler->factoryMonth($factory, $month); + $status = (string) $request->query('status', ''); + $rows = $result['rows']; + if ($status === 'attention') { + $rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true))); + } elseif (array_key_exists($status, DropshipReconciler::LABELS)) { + $rows = array_values(array_filter($rows, static fn (array $r): bool => $r['status'] === $status)); + } + $page = max(1, (int) $request->query('page', 1)); + $paginator = new LengthAwarePaginator(array_slice($rows, ($page - 1) * 100, 100), count($rows), 100, $page, + ['path' => $request->url(), 'query' => $request->query()]); + $files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get(); + + return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files]; + } + + private function uploadData(string $month): array + { + $files = $this->store->db()->table('dropship_bill_files as f')->leftJoin('dropship_factories as d', 'd.id', '=', 'f.factory_id') + ->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'd.name as factory_name']); + + return ['dfFiles' => $files]; + } + + public function upload(Request $request) + { + $data = $request->validate([ + 'month' => ['required', 'date_format:Y-m'], + 'files' => ['required', 'array', 'max:80'], 'files.*' => ['file', 'max:51200'], + ], [], ['files' => '厂家账单', 'files.*' => '厂家账单']); + foreach ($data['files'] as $file) { + if (! in_array(strtolower($file->getClientOriginalExtension()), DropshipFreightStore::EXTENSIONS, true)) { + throw ValidationException::withMessages(['dropship' => '只支持 xlsx、xls、csv、zip:' . $file->getClientOriginalName()]); + } + } + $ids = $this->guard(fn () => $this->store->upload($data['files'], $data['month'], self::user())); + $files = $this->store->db()->table('dropship_bill_files')->whereIn('id', $ids)->get(); + + return $this->back($request, ['df_view' => 'upload', 'month' => $data['month']], '已上传 ' . count($ids) . ' 个文件:已读入 ' + . $files->where('status', 'parsed')->count() . ' 个,待选厂家 ' . $files->where('status', 'pending_factory')->count() + . ' 个,失败 ' . $files->where('status', 'failed')->count() . ' 个。'); + } + + public function assign(Request $request, int $file) + { + $data = $request->validate(['factory_id' => ['required', 'integer']]); + $this->guard(fn () => $this->store->assign($file, (int) $data['factory_id'])); + + return $this->back($request, [], '已读入。'); + } + + public function deleteFile(Request $request, int $file) + { + $this->guard(fn () => $this->store->deleteFile($file)); + + return $this->back($request, [], '已删除文件。'); + } + + public function saveFactory(Request $request) + { + $data = $request->validate([ + 'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'warehouse' => ['required', 'string', 'max:128'], + 'keywords' => ['required', 'string', 'max:255'], 'note' => ['nullable', 'string', 'max:255'], + ], [], ['name' => '厂家', 'warehouse' => '代发仓', 'keywords' => '代发快递关键字']); + $this->guard(fn () => $this->store->saveFactory(isset($data['id']) ? (int) $data['id'] : null, $data)); + + return $this->back($request, ['df_view' => 'factories'], '已保存厂家「' . trim($data['name']) . '」。'); + } + + public function deleteFactory(Request $request, int $factory) + { + $this->guard(fn () => $this->store->deleteFactory($factory)); + + return $this->back($request, ['df_view' => 'factories'], '已删除厂家。'); + } + + public function generate(Request $request) + { + $data = $request->validate(['month' => ['required', 'date_format:Y-m']]); + $result = $this->guard(fn () => $this->store->generate($data['month'])); + + return $this->back($request, ['df_view' => 'factories'], '按 ' . $data['month'] . ' 发货数据新增 ' . count($result['created']) . ' 家' + . ($result['created'] !== [] ? ':' . implode('、', $result['created']) : '') + . ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。'); + } + + public function export(Request $request) + { + $data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]); + $month = $data['month']; + $factories = collect($this->store->factories()); + if (! empty($data['factory'])) { + $factories = $factories->where('id', (int) $data['factory'])->values(); + abort_if($factories->isEmpty(), 404); + } else { + $billed = $this->store->db()->table('dropship_bill_lines')->where('bill_month', $month)->distinct()->pluck('factory_id')->map('intval')->all(); + $factories = $factories->filter(fn ($f) => in_array((int) $f->id, $billed, true))->values(); + } + $own = $this->store->ownExpressNames(); + $name = ($factories->count() === 1 ? $factories->first()->name : '代发厂家') . $month . '代发运费对账.xlsx'; + + return response()->streamDownload(function () use ($factories, $month, $own): void { + $book = new StreamingWorkbook(); + $book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '结算运费(按我方核算)', + '差额(厂家−结算)', ...array_values(DropshipReconciler::LABELS)], true); + $details = []; + foreach ($factories as $factory) { + $result = $this->reconciler->factoryMonth($factory, $month, $own); + $s = $result['summary']; + $book->row('汇总', [$s['factory'], $s['warehouse'], $s['keywords'], $month, $s['billed'], $s['bill'], $s['settle'], $s['diff'], + ...array_values($s['counts'])]); + $details[] = [$factory, $result['rows']]; + } + foreach ($details as [$factory, $rows]) { + $sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28); + $book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true); + foreach ($rows as $r) { + $book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settle'], + $r['diff'], $r['label'], $r['note'], $r['formula']]); + } + } + $book->writeTo(fopen('php://output', 'wb')); + }, $name); + } + + /** @template T @param callable():T $action @return T */ + private function guard(callable $action): mixed + { + try { + return $action(); + } catch (RuntimeException $error) { + throw ValidationException::withMessages(['dropship' => $error->getMessage()]); + } + } + + private function back(Request $request, array $query, string $message) + { + $target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => CourierBillController::section($request), + 'page' => self::PAGE, ...$query]); + + return redirect()->to($target)->with('dropship_message', $message); + } + + private static function monthParam(mixed $value): ?string + { + return is_string($value) && preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $value) ? $value : null; + } + + private static function user(): string + { + $user = user(); + + return (string) ($user?->name ?? $user?->email ?? 'system'); + } +} diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 45311f75..b1d71042 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -5661,8 +5661,8 @@ class Pages extends Controller protected function resolveContentForSection(string $section, string $page, ?string $tab): ?array { if (in_array($section, self::PAYABLES_FINAL_SECTIONS, true)) { - // 终版目录目前只有快递账单对账和快递应付汇总接了数据,其余页面仍是占位。 - return $section === 'courier-payables-final' && in_array($page, ['courier-bill-reconciliation', 'courier-payable-summary'], true) + // 终版目录目前只有快递账单对账、代发运费对账和快递应付汇总接了数据,其余页面仍是占位。 + return $section === 'courier-payables-final' && in_array($page, ['courier-bill-reconciliation', 'courier-payable-summary', 'dropship-freight-reconciliation'], true) ? $this->resolveContent($page, $tab) : null; } @@ -5729,6 +5729,7 @@ class Pages extends Controller 'accessory-reship-deductions' => app(\Modules\EcommerceFinance\View\AccessoryReshipPageData::class)->page(), 'unshipped-waybills' => app(\App\Http\Controllers\Business\UnshippedWaybillController::class)->page(request()), 'courier-bill-reconciliation' => app(\App\Http\Controllers\Business\CourierBillController::class)->page(request()), + 'dropship-freight-reconciliation' => app(\App\Http\Controllers\Business\DropshipFreightController::class)->page(request()), 'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()), 'shipping-data' => $this->contentForShippingData(), 'return-pickup-management' => $this->contentForReturnPickupManagement(), diff --git a/app/Support/CourierBills/CourierBillMatcher.php b/app/Support/CourierBills/CourierBillMatcher.php index 5df71ea6..8c828693 100644 --- a/app/Support/CourierBills/CourierBillMatcher.php +++ b/app/Support/CourierBills/CourierBillMatcher.php @@ -213,9 +213,16 @@ final class CourierBillMatcher }; $order = [Category::MATCH => 1, Category::DIFF => 1, Category::UNCALCULATED => 1, Category::PRIOR => 2, Category::LATER => 3, Category::DUPLICATE => 4, Category::UNSHIPPED => 5, Category::UNMATCHED => 6, Category::MISMATCH => 7]; + $kinds = []; foreach ($rows as $row) { $category = (string) ($row->category ?? ''); $name = $label($category, $row->category === Category::DUPLICATE ? null : $row->category_month); + $kinds[$name] = match ($category) { + Category::MATCH, Category::DIFF, Category::UNCALCULATED => 'freight', + Category::PRIOR => 'prior:' . (int) substr((string) $row->category_month, 5, 2), + Category::LATER => 'later', Category::DUPLICATE => 'duplicate', Category::UNSHIPPED => 'unshipped', + Category::UNMATCHED => 'unmatched', Category::MISMATCH => 'mismatch', default => 'other', + }; $items[$name] ??= ['bill' => 0.0, 'self' => 0.0, 'sort' => ($order[$category] ?? 9) * 100 + (int) substr((string) $row->category_month, 5, 2)]; $items[$name]['bill'] += (float) $row->bill; $items[$name]['self'] += (float) $row->self; @@ -228,6 +235,7 @@ final class CourierBillMatcher if ((int) $weight->n > 0 && isset($items[$priceLabel])) { $weightLabel = (int) substr($month, 5, 2) . '月运费-重量差'; $items[$weightLabel] = ['bill' => (float) $weight->bill, 'self' => (float) $weight->self, 'sort' => $items[$priceLabel]['sort']]; + $kinds[$weightLabel] = 'freight'; $items[$priceLabel]['bill'] -= (float) $weight->bill; $items[$priceLabel]['self'] -= (float) $weight->self; if ((int) $weight->n === (int) $db->table('courier_bill_lines')->where('statement_id', $statementId)->where('category', Category::DIFF)->count()) { @@ -244,21 +252,48 @@ final class CourierBillMatcher $this->addAccessoryDeduction($statementId, $month, $items); $manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label') ->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip(); + $kinds['配件补发扣款'] = 'accessory'; $fees = $this->surchargeItems($statementId); + $template = $this->templateFor($statementId); $sort = 8000; foreach ($fees as $item => $sum) { - if (! isset($manualLabels[$item]) && ! isset($items[$item])) { + if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) { // 附加费不逐单核对:自算先放 0,手工核对后在小汇总里回填 $items[$item] = ['bill' => $sum, 'self' => 0.0, 'sort' => $sort++]; + $kinds[$item] = 'fee'; } } $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->delete(); - $sort = 0; - foreach ($items as $name => $item) { - $db->table('courier_bill_summary_items')->insert([ - 'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4), - 'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort, - ]); + if ($template !== null) { + // 照上月小汇总的类目排:算得出的填进对应类目,算不出的空着;手工回填过的类目保留手工行,挪到模板位置 + $auto = []; + foreach ($items as $name => $item) { + $auto[$name] = ['bill' => $item['bill'], 'self' => $item['self'], 'kind' => $kinds[$name] ?? 'other']; + } + $manualIds = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->get(['id', 'label']) + ->mapWithKeys(static fn ($row): array => [SummaryTemplate::normalize((string) $row->label) => (int) $row->id])->all(); + $sort = 0; + foreach (SummaryTemplate::apply($template, $auto, (int) substr($month, 5, 2)) as $row) { + $sort++; + $key = SummaryTemplate::normalize($row['label']); + if (isset($manualIds[$key])) { + $db->table('courier_bill_summary_items')->where('id', $manualIds[$key])->update(['sort' => $sort]); + unset($manualIds[$key]); // 同名第二行仍按模板留空行 + continue; + } + $db->table('courier_bill_summary_items')->insert([ + 'statement_id' => $statementId, 'label' => $row['label'], 'bill_amount' => $row['bill'] === null ? null : round($row['bill'], 4), + 'self_amount' => $row['self'] === null ? null : round($row['self'], 2), 'manual' => false, 'sort' => $sort, + ]); + } + } else { + $sort = 0; + foreach ($items as $name => $item) { + $db->table('courier_bill_summary_items')->insert([ + 'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4), + 'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort, + ]); + } } $totals = $db->table('courier_bill_lines')->where('statement_id', $statementId) ->selectRaw('COUNT(*) as line_count, COALESCE(SUM(bill_amount),0) as bill')->first(); @@ -296,7 +331,50 @@ final class CourierBillMatcher /** 小汇总里哪些行是账单读出来的附加费(可以回填自算金额)。 @return list */ public function feeLabels(int $statementId): array { - return array_map('strval', array_keys($this->surchargeItems($statementId))); + $labels = array_map('strval', array_keys($this->surchargeItems($statementId))); + $template = $labels === [] ? null : $this->templateFor($statementId); + if ($template === null) { + return $labels; + } + $month = (int) substr((string) self::db()->table('courier_bill_statements')->where('id', $statementId)->value('bill_month'), 5, 2); + + return SummaryTemplate::feeSlots($template, $labels, $month); + } + + /** + * 这张对账单的小汇总类目模板(已顺延月份),没有就 null(按系统默认排): + * 先用同一分组上月的对账单小汇总;系统里没有上月的,用导入的上月手工小汇总;再没有,用导入的本月手工小汇总。 + * + * @return list|null + */ + public function templateFor(int $statementId): ?array + { + $db = self::db(); + $statement = $db->table('courier_bill_statements')->where('id', $statementId)->first(['group_id', 'bill_month']); + if ($statement === null) { + return null; + } + $previous = \Carbon\CarbonImmutable::createFromFormat('Y-m-d', $statement->bill_month . '-01')->subMonth()->format('Y-m'); + $previousId = $db->table('courier_bill_statements')->where('group_id', $statement->group_id)->where('bill_month', $previous)->value('id'); + if ($previousId !== null) { + $labels = $db->table('courier_bill_summary_items')->where('statement_id', $previousId)->orderBy('sort')->orderBy('id')->pluck('label')->all(); + if ($labels !== []) { + return SummaryTemplate::fromLabels($labels, 1); + } + } + try { + $imported = $db->table('courier_bill_summary_templates')->where('group_id', $statement->group_id) + ->whereIn('bill_month', [$previous, $statement->bill_month])->pluck('labels', 'bill_month')->all(); + } catch (\Illuminate\Database\QueryException) { + return null; // 还没建模板表 + } + foreach ([$previous => 1, $statement->bill_month => 0] as $month => $delta) { + if (isset($imported[$month])) { + return SummaryTemplate::fromLabels((array) json_decode((string) $imported[$month], true), $delta); + } + } + + return null; } /** diff --git a/app/Support/CourierBills/CourierBillStore.php b/app/Support/CourierBills/CourierBillStore.php index ea7cdfa6..b88c9e4e 100644 --- a/app/Support/CourierBills/CourierBillStore.php +++ b/app/Support/CourierBills/CourierBillStore.php @@ -879,7 +879,7 @@ final class CourierBillStore } /** @return list [文件名, 临时路径] */ - private function unzip(string $path): array + public function unzip(string $path): array { $zip = new ZipArchive(); if ($zip->open($path) !== true) { @@ -987,10 +987,11 @@ final class CourierBillStore } /** - * 回填附加费行的自算金额:回填后变成手工行(以后重新匹配不再覆盖;删掉手工行就恢复成账单金额、自算 0)。 - * 手工行直接改;系统按明细算的运费类行不能改,要改请处理明细。 + * 回填小汇总:附加费行回填自算金额;照上月类目排出来、系统没数的空行可以同时回填快递金额和自算金额。 + * 回填后变成手工行(以后重新匹配不再覆盖;删掉手工行就恢复成系统的样子)。手工行直接改。 + * 系统按明细算的运费类行不能改,要改请处理明细。 */ - public function fillSummaryItem(int $statementId, int $itemId, ?float $self): void + public function fillSummaryItem(int $statementId, int $itemId, ?float $self, ?float $bill = null, bool $withBill = false): void { $this->assertOpen($statementId); $db = $this->db(); @@ -998,10 +999,77 @@ final class CourierBillStore if ($item === null) { throw new RuntimeException('小汇总这一行不存在,请刷新。'); } - if (! $item->manual && ! in_array(preg_replace('/\s+/u', '', (string) $item->label), $this->matcher->feeLabels($statementId), true)) { + $blank = ! $item->manual && $item->bill_amount === null && $item->self_amount === null; + $fee = in_array(SummaryTemplate::normalize((string) $item->label), $this->matcher->feeLabels($statementId), true); + if (! $item->manual && ! $blank && ! $fee) { throw new RuntimeException('「' . $item->label . '」是系统按明细算的,不能直接改,请在明细里处理。'); } - $db->table('courier_bill_summary_items')->where('id', $itemId)->update(['self_amount' => $self, 'manual' => true]); + $values = ['self_amount' => $self, 'manual' => true]; + if ($withBill && ($item->manual || $blank)) { + $values['bill_amount'] = $bill; + } + $db->table('courier_bill_summary_items')->where('id', $itemId)->update($values); + } + + /** + * 导入手工小汇总的类目(发送版账单里的「汇总」表),当作 $month 的类目模板;只读类目名,不读金额。 + * 导入后重新排本月和下月还没确认的对账单的小汇总。 + * + * @param list $files [原文件名, 路径] + * @return array{blocks:int,saved:list,unknown:list} + */ + public function importSummaryTemplates(array $files, string $month): array + { + $reader = new BillWorkbookReader(); + $blocks = []; + foreach ($files as [$name, $path]) { + $found = SummaryTemplate::blocks($reader->sheets($path, strtolower(pathinfo($name, PATHINFO_EXTENSION)))); + foreach ($found as $block) { + // 标题认不出分组时(如「10月份账单」),一个文件只有一块就按文件名认 + $blocks[] = $block + ['source' => $name, 'fallback' => count($found) === 1 ? $name : null]; + } + } + + return $this->saveSummaryTemplates($blocks, $month); + } + + /** + * @param list,group?:?string,source?:?string,fallback?:?string}> $blocks group = 分组名(有就按它认) + * @return array{blocks:int,saved:list,unknown:list} + */ + public function saveSummaryTemplates(array $blocks, string $month): array + { + $groups = $this->groups(); + $byName = collect($groups)->keyBy(static fn ($g): string => (string) $g->name); + $saved = []; + $unknown = []; + foreach ($blocks as $block) { + $title = trim(preg_replace('/(\d{4}[.年])?\d{1,2}月(份)?/u', '', $block['title']) ?? $block['title']); + $group = ($block['group'] ?? null) !== null ? $byName->get((string) $block['group']) : null; + $group ??= self::identify($title, $groups); + if ($group === null && ($block['fallback'] ?? null) !== null) { + $group = self::identify((string) $block['fallback'], $groups); + } + if ($group === null) { + $unknown[] = ($block['group'] ?? null) ?: $block['title']; + continue; + } + $this->db()->table('courier_bill_summary_templates')->updateOrInsert( + ['group_id' => $group->id, 'bill_month' => $month], + ['labels' => json_encode(array_values($block['labels']), JSON_UNESCAPED_UNICODE), + 'source' => mb_substr(trim(($block['source'] ?? '') . ' · ' . $block['title'], ' ·'), 0, 255), + 'created_at' => now(), 'updated_at' => now()], + ); + $saved[(int) $group->id] = $group->name; + } + $next = \Carbon\CarbonImmutable::createFromFormat('Y-m-d', $month . '-01')->addMonth()->format('Y-m'); + $statements = $this->db()->table('courier_bill_statements')->whereIn('group_id', array_keys($saved)) + ->whereIn('bill_month', [$month, $next])->where('status', 'open')->pluck('id'); + foreach ($statements as $id) { + $this->matcher->refreshSummary((int) $id); + } + + return ['blocks' => count($blocks), 'saved' => array_values($saved), 'unknown' => array_values(array_unique($unknown))]; } public function deleteSummaryItem(int $statementId, int $itemId): void diff --git a/app/Support/CourierBills/SummaryTemplate.php b/app/Support/CourierBills/SummaryTemplate.php new file mode 100644 index 00000000..b4cbbee9 --- /dev/null +++ b/app/Support/CourierBills/SummaryTemplate.php @@ -0,0 +1,216 @@ + $template 模板类目(已顺延月份) + * @param array $auto 系统生成的行,kind 见 CourierBillMatcher::refreshSummary + * @return list 模板行在前(顺序不变),模板里没有的系统行排在后面 + */ + public static function apply(array $template, array $auto, int $month): array + { + $rows = []; + $index = []; + foreach ($template as $label) { + $key = self::normalize($label); + if ($key === '') { + continue; + } + // 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行 + $index[$key] ??= count($rows); + $rows[] = ['label' => $label, 'bill' => null, 'self' => null, 'fee' => false, 'blank' => true]; + } + $extras = []; + foreach ($auto as $label => $item) { + $slot = self::slotFor((string) $label, $item['kind'], $index, $month); + if ($slot === null) { + $extras[] = ['label' => (string) $label, 'bill' => $item['bill'], 'self' => $item['self'], 'fee' => $item['kind'] === 'fee', 'blank' => false]; + continue; + } + $row = &$rows[$slot]; + $row['bill'] = $item['bill'] === null && $row['bill'] === null ? null : (float) $row['bill'] + (float) $item['bill']; + $row['self'] = $item['self'] === null && $row['self'] === null ? null : (float) $row['self'] + (float) $item['self']; + $row['fee'] = $row['fee'] || $item['kind'] === 'fee'; + $row['blank'] = false; + unset($row); + } + + return [...$rows, ...$extras]; + } + + /** 模板里属于附加费的那几行(自算先放 0,可回填)。 @param list $feeLabels @return list */ + public static function feeSlots(array $template, array $feeLabels, int $month): array + { + $auto = []; + foreach ($feeLabels as $label) { + $auto[$label] = ['bill' => 0.0, 'self' => 0.0, 'kind' => 'fee']; + } + + return array_values(array_map(static fn (array $r): string => self::normalize($r['label']), + array_filter(self::apply($template, $auto, $month), static fn (array $r): bool => $r['fee']))); + } + + /** 上月小汇总的类目:去掉当月临时行。 @param iterable $labels @return list */ + public static function fromLabels(iterable $labels, int $delta): array + { + $result = []; + foreach ($labels as $label) { + $label = trim((string) $label); + if ($label !== '' && ! preg_match(self::TRANSIENT, $label)) { + $result[] = self::roll($label, $delta); + } + } + + return $result; + } + + /** + * 从手工发送版账单的「汇总」类表里找小汇总:表头是 标题(如「樵舍中通-上楼10月」)| 快递金额 | 自算金额 | 差异 四格, + * 下面一列是类目,读到「总计 / 合计」或空行为止。一张表里可以有几块(左右并排也行)。只读类目名,不读金额。 + * + * @param iterable>> $sheets + * @return list}> + */ + public static function blocks(iterable $sheets): array + { + $blocks = []; + foreach ($sheets as $rows) { + // 小汇总都在表的前面,只看前 400 行(运费明细表动辄几万行,不整表读进内存) + $grid = []; + foreach ($rows as $row) { + $grid[] = array_values($row); + if (count($grid) >= self::SCAN_ROWS) { + break; + } + } + foreach ($grid as $r => $row) { + foreach ($row as $d => $cell) { + // 表头:标题 | 快递金额(快递提供金额/原始/快递…)| 自算(自算金额/简尚/简尚核对…)| 差异 + if ($d < 3 || ! in_array(self::normalize((string) $cell), ['差异', '差额'], true) || trim((string) ($row[$d - 1] ?? '')) === '' + || trim((string) ($row[$d - 2] ?? '')) === '' || is_numeric($row[$d - 2]) || is_numeric($row[$d - 1])) { + continue; + } + $c = $d - 2; + $title = trim((string) ($row[$c - 1] ?? '')); + $labels = []; + for ($i = $r + 1; $i < count($grid); $i++) { + $label = trim((string) ($grid[$i][$c - 1] ?? '')); + if ($label === '' || in_array(self::normalize($label), self::STOP_LABELS, true) + || in_array(self::normalize((string) ($grid[$i][$d] ?? '')), ['差异', '差额'], true)) { + break; + } + $labels[] = $label; + } + // 首重、体积这类数字表不是小汇总 + $labels = array_values(array_filter($labels, static fn (string $l): bool => ! is_numeric($l))); + if ($title !== '' && ! is_numeric($title) && $labels !== []) { + $blocks[] = ['title' => $title, 'labels' => $labels]; + } + } + } + } + + return $blocks; + } + + public static function normalize(string $label): string + { + return preg_replace('/\s+/u', '', $label) ?? ''; + } + + /** @param array $index */ + private static function slotFor(string $label, string $kind, array $index, int $month): ?int + { + $key = self::normalize($label); + if (isset($index[$key])) { + return $index[$key]; + } + $find = static function (callable $test) use ($index): ?int { + foreach ($index as $name => $slot) { + if ($test((string) $name)) { + return $slot; + } + } + + return null; + }; + + return match (true) { + // 本月运费(含重量差、价格差)合成手工的运费那一行:「运费-重量差」>「运费10月 / 10月运费」>「运费」 + $kind === 'freight' => $find(static fn (string $n): bool => $n === '运费-重量差') + ?? $find(static fn (string $n): bool => (bool) preg_match('/^(' . $month . '月)?(快递)?运费(' . $month . '月)?$/u', $n) && str_contains($n, $month . '月')) + ?? $find(static fn (string $n): bool => (bool) preg_match('/^(快递)?运费$/u', $n)) + ?? $find(static fn (string $n): bool => str_contains($n, '运费') && ! preg_match('/\d+月|退|补|不结算|调拨|面单|抵扣|逆向|附加/u', $n)), + str_starts_with($kind, 'prior:') => $find(static fn (string $n): bool => str_contains($n, '运费') + && (bool) preg_match('/(^|[^\d])' . substr($kind, 6) . '月/u', $n) && ! str_contains($n, '记账')), + $kind === 'duplicate' => $find(static fn (string $n): bool => (bool) preg_match('/重复|查重/u', $n)), + $kind === 'unshipped' => $find(static fn (string $n): bool => str_contains($n, '未发出') && ! str_contains($n, '实际已发出')), + $kind === 'unmatched' => $find(static fn (string $n): bool => (bool) preg_match('/匹配不到|查不到|未匹配|无发货数据|匹配失败/u', $n)), + $kind === 'mismatch' => $find(static fn (string $n): bool => str_contains($n, '不符')), + $kind === 'accessory' => $find(static fn (string $n): bool => SummaryMapper::classify($n) === 'AL'), + $kind === 'fee' => self::feeSlot($key, $find), + default => null, + }; + } + + private static function feeSlot(string $label, callable $find): ?int + { + foreach (self::FEE_WORDS as $word) { + if (str_contains($label, $word)) { + $slot = $find(static fn (string $n): bool => str_contains($n, $word)); + if ($slot !== null) { + return $slot; + } + } + } + + return $find(static fn (string $n): bool => str_contains($n, '附加费')); + } + + /** @return array{0:int,1:int} */ + private static function shift(?int $year, int $month, int $delta): array + { + $index = ($year ?? 2000) * 12 + ($month - 1) + $delta; + + return [intdiv($index, 12), $index % 12 + 1]; + } +} diff --git a/app/Support/DropshipFreight/DropshipFreightStore.php b/app/Support/DropshipFreight/DropshipFreightStore.php new file mode 100644 index 00000000..043e95d1 --- /dev/null +++ b/app/Support/DropshipFreight/DropshipFreightStore.php @@ -0,0 +1,359 @@ + 厂家,keyword_list 已拆成数组 */ + public function factories(): array + { + return $this->db()->table('dropship_factories')->orderBy('name')->get()->map(static function ($factory) { + $factory->keyword_list = self::splitKeywords((string) $factory->keywords); + + return $factory; + })->all(); + } + + /** @param array{name:string,warehouse:string,keywords:string,note?:?string} $data */ + public function saveFactory(?int $id, array $data): int + { + $keywords = self::splitKeywords($data['keywords']); + if ($keywords === []) { + throw new RuntimeException('至少填一个代发快递关键字。'); + } + $values = ['name' => trim($data['name']), 'warehouse' => trim($data['warehouse']), 'keywords' => implode(',', $keywords), + 'note' => self::blank($data['note'] ?? null), 'updated_at' => now()]; + $same = $this->db()->table('dropship_factories')->where('name', $values['name'])->value('id'); + if ($same !== null && (int) $same !== $id) { + throw new RuntimeException('厂家「' . $values['name'] . '」已经有了。'); + } + if ($id === null) { + return (int) $this->db()->table('dropship_factories')->insertGetId($values + ['created_at' => now()]); + } + $this->db()->table('dropship_factories')->where('id', $id)->update($values); + + return $id; + } + + public function deleteFactory(int $id): void + { + if ($this->db()->table('dropship_bill_files')->where('factory_id', $id)->exists()) { + throw new RuntimeException('这家厂家已有上传的账单,先删掉账单文件再删厂家。'); + } + $this->db()->table('dropship_factories')->where('id', $id)->delete(); + } + + /** 自有快递:快递账单对账分组里的全部快递名称1。自有快递不给代发仓结算运费。 */ + public function ownExpressNames(): array + { + try { + return collect($this->courierBills->groups())->flatMap(static fn ($group): array => $group->express_names) + ->map(static fn ($name): string => trim((string) $name))->filter()->unique()->values()->all(); + } catch (Throwable) { + return []; + } + } + + /** + * 按某月发货数据生成厂家清单(只补还没有的代发仓): + * 「工厂-…代发仓」发出的快递名称1,去掉自有快递和通用快递后剩下的就是这家的代发快递,关键字取它们共同的部分。 + * + * @return array{created:list,skipped:list} + */ + public function generate(string $month): array + { + [$from, $to] = self::monthRange($month); + $rows = $this->shipping->connection()->table('jst_oms_shipping') + ->where('ship_time', '>=', $from)->where('ship_time', '<', $to) + ->groupBy('warehouse_name', 'express_name1', 'supplier_name') + ->selectRaw('warehouse_name, express_name1, supplier_name, COUNT(DISTINCT express_no) as n')->get(); + $own = array_flip($this->ownExpressNames()); + $warehousesOf = []; + $byWarehouse = []; + $suppliers = []; + foreach ($rows as $row) { + $warehouse = trim((string) $row->warehouse_name); + $express = trim((string) $row->express_name1); + if ($warehouse === '' || $express === '') { + continue; + } + $warehousesOf[$express][$warehouse] = true; + if (str_starts_with($warehouse, '工厂-') && str_ends_with($warehouse, '代发仓')) { + $byWarehouse[$warehouse][$express] = ($byWarehouse[$warehouse][$express] ?? 0) + (int) $row->n; + foreach (preg_split('/[,,、]/u', (string) $row->supplier_name) ?: [] as $supplier) { + if (($supplier = trim($supplier)) !== '') { + $suppliers[$warehouse][$supplier] = ($suppliers[$warehouse][$supplier] ?? 0) + (int) $row->n; + } + } + } + } + $existing = collect($this->factories()); + $created = []; + $skipped = []; + ksort($byWarehouse); + foreach ($byWarehouse as $warehouse => $expresses) { + if ($existing->contains('warehouse', $warehouse)) { + continue; + } + $candidates = array_values(array_filter(array_keys($expresses), + static fn (string $e): bool => ! isset($own[$e]) && count($warehousesOf[$e] ?? []) < self::GENERIC_WAREHOUSES)); + if ($candidates === []) { + $skipped[] = $warehouse . '(只有自有快递或通用快递)'; + continue; + } + $core = self::warehouseCore($warehouse); + $named = array_values(array_filter($candidates, static fn (string $e): bool => self::commonPart([$e, $core]) !== '')); + // 关键字尽量取厂家名(代发仓核心名)里的字,口径同手工:「卿德客申通」「卿德客极兔」→「卿德客」 + $shared = $named !== [] ? self::commonPart([...$named, $core]) : ''; + $keywords = $shared !== '' ? [$shared] : self::keywordsFor($named !== [] ? $named : $candidates); + $names = $suppliers[$warehouse] ?? []; + arsort($names); + $name = (string) (array_key_first($names) ?? $core); + if ($existing->contains('name', $name)) { + $name .= '(' . $core . ')'; + } + $this->saveFactory(null, ['name' => $name, 'warehouse' => $warehouse, 'keywords' => implode(',', $keywords), + 'note' => '按 ' . $month . ' 发货数据生成:' . implode('、', $named !== [] ? $named : $candidates)]); + $existing->push((object) ['name' => $name, 'warehouse' => $warehouse]); + $created[] = $name; + } + + return ['created' => $created, 'skipped' => $skipped]; + } + + /** + * @param list $files + * @return list 文件 id + */ + public function upload(array $files, string $month, string $user): array + { + $factories = $this->factories(); + $ids = []; + foreach ($files as $file) { + if (strtolower($file->getClientOriginalExtension()) === 'zip') { + foreach ($this->courierBills->unzip((string) $file->getRealPath()) as [$name, $path]) { + $ids[] = $this->register($name, $path, $month, $factories, $user); + } + continue; + } + $ids[] = $this->register($file->getClientOriginalName(), (string) $file->getRealPath(), $month, $factories, $user); + } + + return $ids; + } + + public function assign(int $fileId, int $factoryId): void + { + $file = $this->db()->table('dropship_bill_files')->find($fileId); + if ($file === null || $file->status !== 'pending_factory') { + throw new RuntimeException('这个文件不是待选厂家状态。'); + } + if (! $this->db()->table('dropship_factories')->where('id', $factoryId)->exists()) { + throw new RuntimeException('厂家不存在。'); + } + $this->ingest($fileId, $factoryId); + } + + public function deleteFile(int $fileId): void + { + $file = $this->db()->table('dropship_bill_files')->find($fileId); + if ($file === null) { + return; + } + $this->db()->transaction(function () use ($file): void { + $this->db()->table('dropship_bill_lines')->where('file_id', $file->id)->delete(); + $this->db()->table('dropship_bill_files')->where('id', $file->id)->delete(); + }); + Storage::disk(self::DISK)->delete($file->stored_path); + } + + /** @param list $factories */ + private function register(string $name, string $path, string $month, array $factories, string $user): 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); + $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, + 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(), + ]); + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + $this->db()->table('dropship_bill_files')->where('id', $id)->update(['status' => 'failed', 'message' => '不支持的文件类型']); + } elseif ($factory !== null) { + $this->ingest($id, (int) $factory->id); + } + + return $id; + } + + private function ingest(int $fileId, int $factoryId): void + { + $db = $this->db(); + $file = $db->table('dropship_bill_files')->find($fileId); + try { + $result = $this->parser->parse(Storage::disk(self::DISK)->path($file->stored_path), pathinfo($file->stored_path, PATHINFO_EXTENSION)); + } catch (Throwable $error) { + $db->table('dropship_bill_files')->where('id', $fileId)->update(['factory_id' => $factoryId, 'status' => 'failed', + 'message' => mb_substr('读取失败:' . $error->getMessage(), 0, 500), 'updated_at' => now()]); + + return; + } + $lines = $result['lines']; + $notes = []; + if ($lines === []) { + $notes[] = '没读到厂家运费:要有一张表同时有单号列(快递单号/运单号/单号…)和运费列(快递运费/运费/快递费…),且运费不为空'; + } + $others = []; + foreach (array_chunk(array_map('strval', array_keys($lines)), 1000) as $chunk) { + array_push($others, ...$db->table('dropship_bill_lines')->where('factory_id', $factoryId)->where('bill_month', $file->bill_month) + ->where('file_id', '!=', $fileId)->whereIn('waybill_no', $chunk)->distinct()->pluck('waybill_no')->map('strval')->all()); + } + if ($others !== [] && count($others) * 2 >= count($lines)) { + $db->table('dropship_bill_files')->where('id', $fileId)->update(['factory_id' => $factoryId, 'status' => 'failed', + 'message' => '重复导入:这家本月已上传的账单里已有 ' . count($others) . '/' . count($lines) . ' 个相同单号,这份没读入。要换新版本先删掉旧文件。', + 'sheets' => json_encode($result['sheets'], JSON_UNESCAPED_UNICODE), 'updated_at' => now()]); + + return; + } + if ($others !== []) { + $notes[] = count($others) . ' 个单号本月别的账单文件里也有,对账时只算一次'; + $lines = array_diff_key($lines, array_flip($others)); + } + $db->transaction(function () use ($db, $fileId, $factoryId, $file, $lines, $result, $notes): void { + $db->table('dropship_bill_lines')->where('file_id', $fileId)->delete(); + foreach (array_chunk($lines, 500, true) as $chunk) { + $insert = []; + foreach ($chunk as $waybill => $line) { + $insert[] = ['file_id' => $fileId, 'factory_id' => $factoryId, 'bill_month' => $file->bill_month, 'waybill_no' => (string) $waybill, + 'amount' => $line['amount'], 'sheet' => mb_substr($line['sheet'], 0, 64), 'row_no' => $line['row']]; + } + $db->table('dropship_bill_lines')->insert($insert); + } + $read = array_values(array_filter($result['sheets'], static fn (array $s): bool => $s['read'])); + $db->table('dropship_bill_files')->where('id', $fileId)->update([ + 'factory_id' => $factoryId, 'status' => 'parsed', 'waybill_count' => count($lines), + 'amount' => round(array_sum(array_column($lines, 'amount')), 2), + 'sheets' => json_encode($result['sheets'], JSON_UNESCAPED_UNICODE), + 'message' => mb_substr(implode(';', [...array_map(static fn (array $s): string => '「' . $s['sheet'] . '」' . $s['note'], $read), ...$notes]), 0, 500), + 'updated_at' => now(), + ]); + }); + } + + /** 文件名里出现厂家名、关键字或代发仓核心名,取最长命中的那家。 */ + public static function identify(string $fileName, array $factories): ?object + { + $best = null; + $bestLength = 0; + foreach ($factories as $factory) { + foreach ([$factory->name, ...$factory->keyword_list, self::warehouseCore((string) $factory->warehouse)] as $word) { + $word = trim((string) $word); + if (mb_strlen($word) >= 2 && mb_strlen($word) > $bestLength && str_contains($fileName, $word)) { + $best = $factory; + $bestLength = mb_strlen($word); + } + } + } + + return $best; + } + + /** 「工厂-山东卿德客代发仓」→「卿德客」 */ + public static function warehouseCore(string $warehouse): string + { + $core = preg_replace('/^工厂-|代发仓$/u', '', trim($warehouse)) ?? ''; + $core = preg_replace('/^(山东|河北|浙江|江苏|福建|河南|江西|安徽|广东|湖北|湖南|四川|天津|北京|上海)/u', '', $core) ?? $core; + + return preg_replace('/^(菏泽|霸州|临沂|常州|徐州|曹县|郯城|洛阳)/u', '', $core) ?? $core; + } + + /** @return list */ + public static function splitKeywords(string $value): array + { + return array_values(array_unique(array_filter(array_map('trim', preg_split('/[,,、\s]+/u', $value) ?: []), + static fn (string $k): bool => $k !== ''))); + } + + /** + * 代发快递的关键字:几个快递名称共同的部分(如「卿德客申通」「卿德客极兔」→「卿德客」);没有共同部分就各用全名。 + * + * @param list $expresses + * @return list + */ + public static function keywordsFor(array $expresses): array + { + $common = self::commonPart($expresses); + + return $common !== '' ? [$common] : array_values($expresses); + } + + /** 几个字符串共同的最长子串(至少 2 个字)。 */ + public static function commonPart(array $values): string + { + $values = array_values(array_filter(array_map('strval', $values), static fn (string $v): bool => $v !== '')); + if ($values === []) { + return ''; + } + usort($values, static fn (string $a, string $b): int => mb_strlen($a) <=> mb_strlen($b)); + $shortest = $values[0]; + $length = mb_strlen($shortest); + for ($size = $length; $size >= 2; $size--) { + for ($start = 0; $start + $size <= $length; $start++) { + $part = mb_substr($shortest, $start, $size); + if (array_reduce($values, static fn (bool $ok, string $v): bool => $ok && str_contains($v, $part), true)) { + return $part; + } + } + } + + return ''; + } + + /** @return array{0:string,1:string} */ + public static function monthRange(string $month): array + { + $start = \Carbon\CarbonImmutable::createFromFormat('Y-m-d', $month . '-01')->startOfDay(); + + return [$start->format('Y-m-d H:i:s'), $start->addMonth()->format('Y-m-d H:i:s')]; + } + + private static function blank(?string $value): ?string + { + $value = trim((string) $value); + + return $value === '' ? null : mb_substr($value, 0, 255); + } +} diff --git a/app/Support/DropshipFreight/DropshipReconciler.php b/app/Support/DropshipFreight/DropshipReconciler.php new file mode 100644 index 00000000..032eac29 --- /dev/null +++ b/app/Support/DropshipFreight/DropshipReconciler.php @@ -0,0 +1,292 @@ + '一致', Category::DIFF => '一致但运费有差', Category::UNCALCULATED => '一致(系统未核算)', + Category::PRIOR => '前月补提供', Category::LATER => '跨月订单', Category::DUPLICATE => '重复', Category::UNSHIPPED => '未发出', + Category::UNMATCHED => '匹配不到', Category::MISMATCH => '快递不符', Category::UNPROVIDED => '厂家未提供(不付)', + ]; + /** 按我方核算运费结算的分类。 */ + public const PAYABLE = [Category::MATCH, Category::DIFF, Category::UNCALCULATED, Category::PRIOR]; + /** 需要人工看一眼的分类。 */ + public const ATTENTION = [Category::DIFF, Category::UNCALCULATED, Category::PRIOR, Category::LATER, Category::DUPLICATE, + Category::UNSHIPPED, Category::UNMATCHED, Category::MISMATCH]; + + private const CHUNK = 500; + + public function __construct( + private readonly DropshipFreightStore $store, + private readonly ShippingLookup $shipping, + private readonly UnshippedWaybills $unshipped, + ) {} + + /** + * @return array{rows:list>,summary:array} + */ + public function factoryMonth(object $factory, string $month, ?array $own = null): array + { + $own = array_flip($own ?? $this->store->ownExpressNames()); + $keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords); + $bill = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month) + ->get(['waybill_no', 'amount'])->groupBy('waybill_no') + ->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all(); + // 数字单号做数组键会变成整数,查库前转回字符串(整数和 varchar 比较会用不上索引) + $billed = array_map('strval', array_keys($bill)); + $system = array_values(array_diff($this->dropshipWaybills($factory, $keywords, $own, $month), $billed)); + $info = $this->shippingInfo([...$billed, ...$system]); + $unshipped = array_change_key_case($this->unshipped->unshippedSources($billed), CASE_UPPER); + // 换单:账单开的是旧单号、发货数据里是新单号。货实际发了,运费看新单号是不是这家代发单(代发仓 + 关键字 + 非自有快递) + $missing = array_values(array_filter($billed, static fn (string $w): bool => ! isset($info[$w]))); + $replaced = $missing === [] ? [] : $this->shipping->replacedBy($missing); + $newInfo = $this->shippingInfo(array_values(array_diff(array_map(static fn (array $r): string => $r[0], $replaced), array_keys($info)))); + // 同一个包裹的所有单号(换单前后):以前月份的账单开过其中任何一个,都算重复,免得旧单号、新单号各付一次 + $aliases = []; + foreach ($billed as $waybill) { + $aliases[$waybill] = array_values(array_unique(array_filter([...($info[$waybill]['fronts'] ?? []), + $replaced[$waybill][0] ?? null, ...($info[$replaced[$waybill][0] ?? '']['fronts'] ?? [])], + static fn ($w): bool => $w !== null && $w !== '' && $w !== $waybill))); + } + $earliest = $this->earlierBills((int) $factory->id, $month, array_values(array_unique([...$billed, ...array_merge(...array_values($aliases ?: [[]]))]))); + $earlier = []; + foreach ($billed as $waybill) { + $months = array_values(array_filter(array_map(static fn (string $w): ?string => $earliest[$w] ?? null, [$waybill, ...$aliases[$waybill]]))); + if ($months !== []) { + $earlier[$waybill] = min($months); + } + } + $billedSet = array_flip($billed); + $isDropship = static fn (array $i): bool => $i['warehouse'] === $factory->warehouse && $i['express'] !== null + && ! isset($own[$i['express']]) && self::matches($i['express'], $keywords); + + $rows = []; + $covered = []; + foreach ($billed as $waybill) { + $i = $info[$waybill] ?? null; + $swap = null; + if ($i === null && isset($replaced[$waybill])) { + $swap = $replaced[$waybill][0]; + $i = $info[$swap] ?? $newInfo[$swap] ?? null; + $covered[$swap] = true; + } + $ship = $i === null ? null : ['ship_time' => $i['ship_time'], 'express_name' => $i['express'], 'calc_freight' => $i['calc']]; + // 是这家代发单就让「快递不符」那一步通过,不是就不通过 + $names = $i !== null && $isDropship($i) ? [(string) $i['express'] => 0] : []; + $duplicateMonth = $earlier[$waybill] ?? ($swap !== null && isset($billedSet[$swap]) ? $month : null); + [$category, $categoryMonth] = CourierBillMatcher::categorize(false, $duplicateMonth, + $swap === null && isset($unshipped[$waybill]), $ship, $names, $month, $bill[$waybill]); + $note = match ($category) { + Category::DUPLICATE => $swap !== null && $duplicateMonth === $month ? '换单后的新单号 ' . $swap . ' 账单里也开了,只算新单号' + : $categoryMonth . ' 的账单已开过这个包裹' . ($aliases[$waybill] !== [] ? '(换单前后单号:' . implode('、', $aliases[$waybill]) . ')' : ''), + Category::UNSHIPPED => implode('、', $unshipped[$waybill]), + Category::UNMATCHED => '发货数据里哪个月都查不到这个单号', + Category::MISMATCH => isset($own[(string) $i['express']]) ? '自有快递「' . $i['express'] . '」,不给代发仓结算运费' + : '发货数据:' . ($i['warehouse'] ?: '无仓库') . ' / ' . ($i['express'] ?: '无快递名称1'), + Category::PRIOR, Category::LATER => $categoryMonth . ' 发货', + Category::UNCALCULATED => $i['calc_status'], + default => null, + }; + if ($swap !== null && $category !== Category::DUPLICATE) { + $note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '') + . ($i === null ? ';新单号发货数据里也查不到' : ''); + } + $rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note); + } + $system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w]))); + foreach ($system as $waybill) { + $rows[] = self::row($waybill, $info[$waybill] ?? null, null, Category::UNPROVIDED, null, '厂家账单里没有,不付'); + } + $order = array_flip(array_keys(self::LABELS)); + usort($rows, static fn (array $a, array $b): int => [$order[$a['status']], (string) $a['ship_time']] <=> [$order[$b['status']], (string) $b['ship_time']]); + + return ['rows' => $rows, 'summary' => self::summarize($factory, $month, $rows)]; + } + + public static function label(string $status, ?string $month = null): string + { + return in_array($status, [Category::PRIOR, Category::LATER], true) && $month !== null + ? Category::label($status, $month) : (self::LABELS[$status] ?? $status); + } + + private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array + { + $calc = $i['calc'] ?? null; + + return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null, + 'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc, + 'settle' => in_array($status, self::PAYABLE, true) ? $calc : null, + 'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null, + 'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth), + 'note' => $note, 'formula' => $i['formula'] ?? null]; + } + + /** @param list> $rows */ + public static function summarize(object $factory, string $month, array $rows): array + { + $counts = array_fill_keys(array_keys(self::LABELS), 0); + $bill = $settle = 0.0; + $billedCount = $over = $under = 0; + foreach ($rows as $row) { + $counts[$row['status']]++; + if ($row['bill'] !== null) { + $billedCount++; + $bill += $row['bill']; + } + $settle += (float) $row['settle']; + if ($row['status'] === Category::DIFF) { + $row['diff'] > 0 ? $over++ : $under++; + } + } + + return ['factory_id' => (int) $factory->id, 'factory' => $factory->name, 'warehouse' => $factory->warehouse, 'month' => $month, + 'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2), + 'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under, + 'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))]; + } + + public static function matches(string $express, array $keywords): bool + { + foreach ($keywords as $keyword) { + if ($keyword !== '' && str_contains($express, $keyword)) { + return true; + } + } + + return false; + } + + /** 系统认出的这家本月代发单号:代发仓发出、快递名称1 含关键字、不是自有快递。 @return list */ + private function dropshipWaybills(object $factory, array $keywords, array $own, string $month): array + { + if ($keywords === []) { + return []; + } + [$from, $to] = DropshipFreightStore::monthRange($month); + $rows = $this->shipping->connection()->table('jst_oms_shipping')->where('warehouse_name', $factory->warehouse) + ->where('ship_time', '>=', $from)->where('ship_time', '<', $to) + ->where(function ($query) use ($keywords): void { + foreach ($keywords as $keyword) { + $query->orWhere('express_name1', 'like', '%' . $keyword . '%'); + } + }) + ->distinct()->get(['express_no', 'express_name1']); + $result = []; + foreach ($rows as $row) { + $express = trim((string) $row->express_name1); + $waybill = strtoupper(trim((string) $row->express_no)); + if ($waybill !== '' && ! isset($own[$express])) { + $result[$waybill] = true; + } + } + + return array_map('strval', array_keys($result)); + } + + /** + * 单号的发货信息和核算运费(一个单号几个包裹时运费相加,任一包裹没核算成功就算未核算)。 + * + * @param list $waybills + * @return array + */ + private function shippingInfo(array $waybills): array + { + $result = []; + $connection = $this->shipping->connection(); + foreach (array_chunk($waybills, self::CHUNK) as $chunk) { + $rows = $connection->table('jst_oms_shipping')->whereIn('express_no', $chunk)->orderBy('id') + ->get(['express_no', 'express_name1', 'warehouse_name', 'ship_time', 'source_id', 'front_no']); + $sources = []; + foreach ($rows as $row) { + $key = strtoupper(trim((string) $row->express_no)); + $item = $result[$key] ?? ['ship_time' => null, 'month' => null, 'express' => null, 'warehouse' => null, + 'calc' => null, 'calc_status' => null, 'formula' => null, 'fronts' => []]; + if ($row->ship_time !== null && ($item['ship_time'] === null || (string) $row->ship_time < $item['ship_time'])) { + $item['ship_time'] = (string) $row->ship_time; + $item['month'] = substr((string) $row->ship_time, 0, 7); + } + $item['express'] ??= self::blank($row->express_name1); + $item['warehouse'] ??= self::blank($row->warehouse_name); + $front = strtoupper(trim((string) ($row->front_no ?? ''))); + if ($front !== '' && $front !== $key && ! in_array($front, $item['fronts'], true)) { + $item['fronts'][] = $front; + } + if ($row->source_id !== null) { + $sources[$key][(int) $row->source_id] = true; + } + $result[$key] = $item; + } + $ids = array_merge(...array_values(array_map('array_keys', $sources ?: [[]]))); + $freights = []; + foreach (array_chunk(array_values(array_unique($ids)), self::CHUNK) as $part) { + foreach ($connection->table('jst_oms_shipping_freight')->whereIn('source_id', $part)->get() as $row) { + $freights[(int) $row->source_id] = $row; + } + } + foreach ($sources as $key => $set) { + $total = 0.0; + $ok = true; + $status = null; + $formulas = []; + foreach (array_keys($set) as $source) { + $freight = $freights[$source] ?? null; + if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) { + $ok = false; + $status = $freight === null ? '还没核算(等运费核算跑完)' : (string) ($freight->status ?: '没核算出运费'); + break; + } + $total += (float) $freight->freight; + if (($freight->formula ?? null) !== null && $freight->formula !== '') { + $formulas[] = (string) $freight->formula; + } + } + $result[$key]['calc'] = $ok ? round($total, 2) : null; + $result[$key]['calc_status'] = $ok ? null : $status; + $result[$key]['formula'] = $formulas === [] ? null : implode(';', $formulas); + } + } + + return $result; + } + + /** @return array 单号 => 以前最早哪个月的账单开过 */ + private function earlierBills(int $factoryId, string $month, array $waybills): array + { + $result = []; + foreach (array_chunk($waybills, self::CHUNK) as $chunk) { + foreach ($this->store->db()->table('dropship_bill_lines')->where('factory_id', $factoryId)->where('bill_month', '<', $month) + ->whereIn('waybill_no', $chunk)->distinct()->get(['waybill_no', 'bill_month']) as $row) { + $key = (string) $row->waybill_no; + $result[$key] = isset($result[$key]) ? min($result[$key], (string) $row->bill_month) : (string) $row->bill_month; + } + } + + return $result; + } + + private static function blank(mixed $value): ?string + { + $value = trim((string) $value); + + return $value === '' ? null : $value; + } +} diff --git a/app/Support/DropshipFreight/FactoryBillParser.php b/app/Support/DropshipFreight/FactoryBillParser.php new file mode 100644 index 00000000..30faa6ed --- /dev/null +++ b/app/Support/DropshipFreight/FactoryBillParser.php @@ -0,0 +1,186 @@ + 厂家开的运费」。 + * + * 厂家账单格式各不相同(运费+货款、送货单、账单、Sheet1……),逐表在前 15 行找表头: + * 要同时有单号列和厂家运费列才读;货款、记账、退货、拦截、附加费、我方对账等表不读。 + * 一个单号在一张表里有几行(一单多件),运费相加;几张表都有同一单号时,只取第一张表的。 + * 运费为空或 0 的单号不算厂家开了运费(包邮、京东快递等)。 + */ +final class FactoryBillParser +{ + /** 单号列:按顺序先全等、再包含(不认订单号、交易单号、条码拼接列)。 */ + public const WAYBILL_HEADERS = ['快递单号', '运单号', '运单号码', '运单编号', '物流单号', '母单号', '面单号', '单号']; + /** 厂家运费列:按顺序全等匹配;「快递」只在全等时当金额(卿德客账单的运费列就叫「快递」)。 */ + public const AMOUNT_HEADERS = ['快递运费', '运费', '快递费', '运费金额', '快递费用', '邮费', '快递']; + /** 偏远地区单独一列的运费(浩浦等),和运费列相加。 */ + public const EXTRA_AMOUNT_HEADERS = ['偏远', '偏远费', '偏远运费', '偏远加收']; + /** 表名含这些字的不读:货款/记账/退货/拦截/附加费,以及我方自己做的对账表。 */ + public const SKIP_SHEET_WORDS = ['记账', '退货', '退回', '拦截', '附加', '违约', '汇总', '入库', '入仓', '报价', '对账', + '我代', '我入', '我退', '少算', '未发出', '补款', '补件', '赔']; + + private const HEADER_SCAN_ROWS = 15; + private const TOTAL_WORDS = ['合计', '总计', '小计', '汇总', '总额']; + + public function __construct(private readonly BillWorkbookReader $reader) {} + + /** + * @return array{lines:array,sheets:list} + */ + public function parse(string $path, string $extension): array + { + $lines = []; + $sheets = []; + foreach ($this->reader->sheets($path, $extension) as $sheet => $rows) { + $sheet = (string) $sheet; + $word = self::skipWord($sheet); + if ($word !== null) { + $sheets[] = ['sheet' => $sheet, 'read' => false, 'note' => '表名含「' . $word . '」,不是运费表']; + continue; + } + $columns = null; + $scanned = 0; + $mine = []; + foreach ($rows as $rowNumber => $row) { + if ($columns === null) { + if (++$scanned > self::HEADER_SCAN_ROWS) { + break; + } + $columns = self::findColumns($row); + continue; + } + $raw = trim((string) ($row[$columns['waybill']] ?? '')); + if ($raw === '' || self::isTotalRow($row)) { + continue; + } + $waybill = Waybill::parse($raw)['waybill']; + $amount = BillParser::number($row[$columns['amount']] ?? null); + foreach ($columns['extra'] as $extra) { + $value = BillParser::number($row[$extra] ?? null); + if ($value !== null) { + $amount = ($amount ?? 0.0) + $value; + } + } + if ($waybill === null || $amount === null) { + continue; + } + $mine[$waybill] ??= ['amount' => 0.0, 'sheet' => $sheet, 'row' => (int) $rowNumber]; + $mine[$waybill]['amount'] += $amount; + } + if ($columns === null) { + $sheets[] = ['sheet' => $sheet, 'read' => false, 'note' => '没有同时找到单号列和运费列']; + continue; + } + $count = 0; + $total = 0.0; + $repeated = 0; + foreach ($mine as $waybill => $line) { + $line['amount'] = round($line['amount'], 2); + if (abs($line['amount']) < 0.005) { + continue; + } + if (isset($lines[$waybill])) { + $repeated++; + continue; + } + $lines[$waybill] = $line; + $count++; + $total += $line['amount']; + } + $sheets[] = ['sheet' => $sheet, 'read' => true, 'rows' => $count, 'amount' => round($total, 2), + 'note' => '单号列「' . $columns['waybill_header'] . '」、运费列「' . $columns['amount_header'] . '」' + . ($columns['extra'] !== [] ? '(加上「' . implode('」「', array_map(static fn (int $i): string => $columns['headers'][$i], $columns['extra'])) . '」)' : '') + . ($repeated > 0 ? ';' . $repeated . ' 个单号前面的表已有,没重复算' : '')]; + } + + return ['lines' => $lines, 'sheets' => $sheets]; + } + + public static function skipWord(string $sheet): ?string + { + foreach (self::SKIP_SHEET_WORDS as $word) { + if (str_contains($sheet, $word)) { + return $word; + } + } + + return null; + } + + /** + * @param array $row + * @return array{waybill:int,amount:int,extra:list,headers:list,waybill_header:string,amount_header:string}|null + */ + public static function findColumns(array $row): ?array + { + $headers = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row); + $waybill = null; + foreach (self::WAYBILL_HEADERS as $candidate) { + $index = array_search($candidate, $headers, true); + if ($index !== false) { + $waybill = (int) $index; + break; + } + } + if ($waybill === null) { + foreach (self::WAYBILL_HEADERS as $candidate) { + foreach ($headers as $index => $header) { + if ($header !== '' && str_contains($header, $candidate) && ! preg_match('/订单|交易|条码|退回|原单|换单|入库|业务|采购/u', $header)) { + $waybill = (int) $index; + break 2; + } + } + } + } + if ($waybill === null) { + return null; + } + $amount = null; + foreach (self::AMOUNT_HEADERS as $candidate) { + $index = array_search($candidate, $headers, true); + if ($index !== false && $index !== $waybill) { + $amount = (int) $index; + break; + } + } + if ($amount === null) { + foreach ($headers as $index => $header) { + if ($header !== '' && str_contains($header, '运费') && ! preg_match('/结算|提供|成本|差|率|首重|续重|面单|附加|退回|拦截|合计|货款|发货数据/u', $header)) { + $amount = (int) $index; + break; + } + } + } + if ($amount === null) { + return null; + } + + $extra = []; + foreach ($headers as $index => $header) { + if ($index !== $amount && in_array($header, self::EXTRA_AMOUNT_HEADERS, true)) { + $extra[] = (int) $index; + } + } + + return ['waybill' => $waybill, 'amount' => $amount, 'extra' => $extra, 'headers' => array_values($headers), + 'waybill_header' => $headers[$waybill], 'amount_header' => $headers[$amount]]; + } + + private static function isTotalRow(array $row): bool + { + foreach (array_slice($row, 0, 3) as $cell) { + if (in_array(preg_replace('/\s+/u', '', (string) $cell) ?? '', self::TOTAL_WORDS, true)) { + return true; + } + } + + return false; + } +} diff --git a/config/business_navigation.php b/config/business_navigation.php index 4e251aa6..e3d3d3fc 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -837,6 +837,7 @@ $navigation = [ ['slug' => 'courier-surcharge', 'title' => '附加费报价维护'], ['slug' => 'payable-cloud-warehouse-vehicle-fee', 'title' => '应付云仓车费'], ['slug' => 'courier-bill-reconciliation', 'title' => '快递账单对账'], + ['slug' => 'dropship-freight-reconciliation', 'title' => '代发运费对账'], ['slug' => 'courier-payables-report', 'title' => '快递应付表'], ['slug' => 'freight-difference', 'title' => '运费差'], ['slug' => 'other-surcharge-summary', 'title' => '其他附加费汇总'], @@ -907,6 +908,7 @@ $navigation = [ ['slug' => 'other-adjustments', 'title' => '其他扣款补款'], ['slug' => 'payable-cloud-warehouse-vehicle-fee', 'title' => '应付云仓车费'], ['slug' => 'courier-bill-reconciliation', 'title' => '快递账单对账'], + ['slug' => 'dropship-freight-reconciliation', 'title' => '代发运费对账'], ['slug' => 'courier-payables-report', 'title' => '快递应付表'], ['slug' => 'freight-difference', 'title' => '运费差'], ['slug' => 'other-surcharge-summary', 'title' => '其他附加费汇总'], diff --git a/database/migrations/2026_11_30_100000_create_dropship_freight_tables.php b/database/migrations/2026_11_30_100000_create_dropship_freight_tables.php new file mode 100644 index 00000000..c486fbe8 --- /dev/null +++ b/database/migrations/2026_11_30_100000_create_dropship_freight_tables.php @@ -0,0 +1,61 @@ +create('dropship_factories', function (Blueprint $table): void { + $table->id(); + $table->string('name', 128)->unique()->comment('厂家(发货数据供应商名称)'); + $table->string('warehouse', 128)->comment('代发仓(发货数据仓库)'); + $table->string('keywords', 255)->comment('代发快递关键字:快递名称1 含其一即算,逗号分隔'); + $table->string('note', 255)->nullable(); + $table->timestamps(); + }); + + $schema->create('dropship_bill_files', function (Blueprint $table): void { + $table->id(); + $table->char('bill_month', 7)->index()->comment('账单月份 YYYY-MM'); + $table->unsignedBigInteger('factory_id')->nullable()->index(); + $table->string('original_name', 255); + $table->string('stored_path', 255); + $table->string('status', 16)->comment('pending_factory 待选厂家 / parsed 已读入 / failed 读取失败'); + $table->text('sheets')->nullable()->comment('JSON:各工作表读取情况'); + $table->unsignedInteger('waybill_count')->default(0); + $table->decimal('amount', 16, 2)->default(0); + $table->string('message', 500)->nullable(); + $table->string('uploaded_by', 64)->nullable(); + $table->timestamps(); + }); + + $schema->create('dropship_bill_lines', function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('file_id')->index(); + $table->unsignedBigInteger('factory_id'); + $table->char('bill_month', 7); + $table->string('waybill_no', 96)->index(); + $table->decimal('amount', 14, 2)->comment('厂家开的运费(同一单号多行已相加)'); + $table->string('sheet', 64); + $table->unsignedInteger('row_no'); + $table->index(['factory_id', 'bill_month'], 'dropship_bill_lines_factory_month'); + }); + } + + public function down(): void + { + $schema = Schema::connection('business_mirror'); + foreach (['dropship_bill_lines', 'dropship_bill_files', 'dropship_factories'] as $name) { + $schema->dropIfExists($name); + } + } +}; diff --git a/database/migrations/2026_11_30_110000_create_courier_bill_summary_templates_table.php b/database/migrations/2026_11_30_110000_create_courier_bill_summary_templates_table.php new file mode 100644 index 00000000..9d641942 --- /dev/null +++ b/database/migrations/2026_11_30_110000_create_courier_bill_summary_templates_table.php @@ -0,0 +1,28 @@ +create('courier_bill_summary_templates', function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('group_id'); + $table->char('bill_month', 7)->comment('这份手工小汇总是哪个月的账单'); + $table->text('labels')->comment('JSON:类目名,按手工小汇总的顺序'); + $table->string('source', 255)->nullable()->comment('从哪个文件、哪一块读的'); + $table->timestamps(); + $table->unique(['group_id', 'bill_month'], 'courier_bill_summary_template_group_month'); + }); + } + + public function down(): void + { + Schema::connection('business_mirror')->dropIfExists('courier_bill_summary_templates'); + } +}; diff --git a/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php b/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php index b788e4b8..aa799a5d 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php @@ -44,9 +44,19 @@ @php($target = \App\Support\CourierBills\SummaryMapper::classify($item->label)) {{ $item->label }} @if ($item->manual)手工@endif + @php($blankRow = ! $item->manual && $item->bill_amount === null && $item->self_amount === null) + @if ($open && $blankRow) + +
@csrf + + + +
+ + @else {{ $billMoney($item->bill_amount) }} - @if ($open && ($item->manual || in_array(preg_replace('/\s+/u', '', $item->label), $cbFeeLabels ?? [], true)) && $item->bill_amount !== null) + @if ($open && ($item->manual || (in_array(preg_replace('/\s+/u', '', $item->label), $cbFeeLabels ?? [], true) && $item->bill_amount !== null)))
@csrf @@ -55,7 +65,8 @@ {{ $money($item->self_amount) }} @endif - {{ $money((float) $item->bill_amount - (float) $item->self_amount) }} + @endif + {{ $item->bill_amount === null && $item->self_amount === null ? '' : $money((float) $item->bill_amount - (float) $item->self_amount) }} {{ ['supplement' => '补给快递', 'waybill' => '面单'][$target] ?? \App\Support\CourierBills\SummaryMapper::DIFF_COLUMNS[$target] }} @if ($item->manual && $open) 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 de90633a..8ee8c4d2 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 @@ -17,6 +17,17 @@
+
+

导入手工小汇总(只读类目)

+
+ @csrf + + + + 小汇总的类目照同一家上月的排(顺序不变,类目名里的月份自动顺延,如 2026.8-9月记账补款 → 2026.9-10月记账补款),系统算得出的金额填进去,算不出的空着手工回填,新类目排在后面。系统里还没有上月对账单时,在这里传手工做好的发送版账单(带「汇总」表,表头写「快递提供金额 / 自算金额」,左边一格是标题如「樵舍中通-上楼10月」):只读类目名,不读金额。传上月的就从上月顺延;传本月的就直接用。 +
+
+

{{ $month }} 已上传文件

diff --git a/resources/views/business/pages/courier-payables/dropship-freight/factories.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/factories.blade.php new file mode 100644 index 00000000..3fac89da --- /dev/null +++ b/resources/views/business/pages/courier-payables/dropship-freight/factories.blade.php @@ -0,0 +1,46 @@ +
+

新增 / 修改代发厂家

+
+ @csrf + + + + + + +
+

从代发仓发出、快递名称1 含任一关键字的包裹算这家代发单;自有快递(快递账单对账分组里的快递名称1,如曹县韵达、北京韵达-乐鑫达)不算,也不给代发仓结算运费。

+
+ +
+

按发货数据生成厂家清单

+
+ @csrf + + + 「工厂-…代发仓」发出的快递名称1,去掉自有快递和京喜京东快递、线下快递等通用快递,剩下的算这家的代发快递;关键字取它们和厂家名共同的字。生成后请逐家核对。 +
+
+ +
+

代发厂家({{ count($dfFactories) }})

+
+ + + + @forelse ($dfFactories as $f) + + + + + @empty + + @endforelse + +
厂家代发仓关键字备注操作
{{ $f->name }}{{ $f->warehouse }}{{ $f->keywords }}{{ $f->note }} + @php $editData = json_encode(['id' => $f->id, 'name' => $f->name, 'warehouse' => $f->warehouse, 'keywords' => $f->keywords, 'note' => $f->note], JSON_UNESCAPED_UNICODE); @endphp + +
@csrf
+
还没有代发厂家。可以先用上面的「按发货数据生成」。
+
+
diff --git a/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php new file mode 100644 index 00000000..b7c9d114 --- /dev/null +++ b/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php @@ -0,0 +1,65 @@ +@if ($dfFactory === null) + +@else +@php $s = $dfSummary; @endphp +
+
+ + + + +
+ 导出这家 +
+ +
+
{{ $dfFactory->name }} · {{ $dfFactory->warehouse }}关键字:{{ $dfFactory->keywords }}
+
厂家开运费 {{ number_format($s['billed']) }} 单{{ $money($s['bill']) }}
+
结算运费(按我方核算){{ $money($s['settle']) }}
+
差额(厂家 − 结算){{ $money($s['diff']) }}
+
+ + +
+
+ + + + @forelse ($dfLines as $r) + + + + + + + + + + + + @empty + + @endforelse + +
快递单号发货时间快递名称1厂家运费我方核算结算运费差额状态说明
{{ $r['waybill'] }}{{ $r['ship_time'] ? substr($r['ship_time'], 0, 16) : '—' }}{{ $r['express'] ?? '—' }}{{ $money($r['bill']) }}{{ $money($r['calc']) }}{{ $money($r['settle']) }}{{ $money($r['diff']) }}@php $st = $r['status']; @endphp{{ $r['label'] }}{{ $r['note'] }}
没有明细。
+
+ +
+
+

{{ $month }} 账单文件

+
+ @forelse ($dfFiles as $file) +
{{ $file->original_name }}:{{ number_format($file->waybill_count) }} 单,{{ $money($file->amount) }} 元。{{ $file->message }}
+ @empty +
还没有上传这家本月的账单。
+ @endforelse +
+
+@endif diff --git a/resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php new file mode 100644 index 00000000..56e424de --- /dev/null +++ b/resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php @@ -0,0 +1,51 @@ +
+ + + + 导出全部厂家 +
+ +
+
本月有账单的厂家{{ number_format(count($dfRows)) }}
+
厂家运费合计{{ $money($dfTotals['bill']) }}
+
结算运费(按我方核算){{ $money($dfTotals['settle']) }}
+
差额(厂家 − 结算){{ $money($dfTotals['diff']) }}
+
要看一眼的单{{ number_format($dfTotals['attention']) }}
+
+ +
+
+ + + + + + + + @forelse ($dfRows as $row) + @php $other = $row['attention'] - $row['counts']['diff']; @endphp + + + + + + + + + + + + + + + @empty + + @endforelse + +
厂家代发仓关键字厂家开运费单数厂家运费结算运费差额运费有差·厂家多开运费有差·厂家少开厂家未提供(不付)其他要看的操作
{{ $row['factory'] }}{{ $row['warehouse'] }}{{ $row['keywords'] }}{{ number_format($row['billed']) }}{{ $money($row['bill']) }}{{ $money($row['settle']) }}{{ $money($row['diff']) }}{{ number_format($row['over']) }}{{ number_format($row['under']) }}{{ number_format($row['counts']['unprovided']) }}@if ($other > 0){{ number_format($other) }}@else 0 @endif打开明细
{{ $month }} 还没有上传厂家账单。先在「代发厂家设置」里建好厂家,再到「上传厂家账单」批量上传。
+
+ @if ($dfWithout !== []) + + @endif +
+

差额 = 厂家运费 − 结算运费;正数是厂家多开、按我方核算扣掉的。分类和自有快递对账一样:重复 → 未发出 → 匹配不到(发货数据哪个月都查不到)→ 快递不符(不是这家代发仓发的、不是这家代发快递或是自有快递)→ 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算)。一致类和前月补提供按我方核算结算;换单的旧单号按实际发出的新单号判断(新单号是这家代发单就照付,否则算快递不符);其他要看的 = 除运费有差外需要人工看的单。

diff --git a/resources/views/business/pages/courier-payables/dropship-freight/page.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/page.blade.php new file mode 100644 index 00000000..0c67a668 --- /dev/null +++ b/resources/views/business/pages/courier-payables/dropship-freight/page.blade.php @@ -0,0 +1,88 @@ +@php + $pageUrl = fn (array $query = []) => route('business.pages.show', ['section' => $dfSection, 'page' => 'dropship-freight-reconciliation', ...$query]); + $action = fn (string $name, array $params = []) => route('business.' . $dfSection . '.dropship-freight.' . $name, $params); + $money = fn ($value) => $value === null ? '' : number_format((float) $value, 2); + $month = $dfMonth ?? null; +@endphp +
+ @include('business.pages.courier-payables.courier-bills.style') +
+
+

代发运费对账

+

代发厂家开的运费 对 系统核算运费。代发单 = 从厂家代发仓发出、快递名称1 含厂家关键字、且不是自有快递(快递账单对账分组里的快递)。分类和快递账单对账一致;一致类和前月补提供按我方核算运费结算,厂家没开的单不付。代发运费不进快递应付汇总。

+
+ +
+ + + + @if (session('dropship_message')) +

{{ session('dropship_message') }}

+ @endif + @if (isset($errors) && $errors->any()) + + @endif + + @if ($dfUnavailable) + + @else + @include('business.pages.courier-payables.dropship-freight.' . $dfView) + @endif +
+@push('body_end') + +@endpush diff --git a/resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php new file mode 100644 index 00000000..7b3ddaa3 --- /dev/null +++ b/resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php @@ -0,0 +1,53 @@ +
+

上传厂家账单 · {{ $month }}

+
+ @csrf +
+ +
+
+
+ +
+

{{ $month }} 已上传文件

+
+ + + + @forelse ($dfFiles as $file) + + + + + + + + + + + @empty + + @endforelse + +
文件厂家状态单号数厂家运费说明上传操作
{{ $file->original_name }}{{ $file->factory_name ?? '—' }} + @if ($file->status === 'parsed')已读入 + @elseif ($file->status === 'pending_factory')待选厂家 + @else失败@endif + {{ number_format($file->waybill_count) }}{{ $money($file->amount) }}{{ $file->message }}{{ $file->uploaded_by }} {{ substr((string) $file->created_at, 5, 11) }} + @if ($file->status === 'pending_factory') +
+ @csrf + + +
+ @elseif ($file->factory_id) + 明细 + @endif +
@csrf
+
{{ $month }} 还没有上传厂家账单。
+
+
diff --git a/routes/admin.php b/routes/admin.php index 1f5e177c..cf323658 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -740,6 +740,21 @@ foreach (['courier-payables', 'courier-payables-final'] as $courierBillSection) Route::post('groups/{group}/delete', [$controller, 'deleteGroup'])->whereNumber('group')->name('delete-group')->defaults('section', $courierBillSection); Route::post('groups/{group}/express-names', [$controller, 'addExpressName'])->whereNumber('group')->name('add-express-name')->defaults('section', $courierBillSection); Route::post('ledger/import', [$controller, 'importLedger'])->name('import-ledger')->defaults('section', $courierBillSection); + Route::post('summary-templates/import', [$controller, 'importSummaryTemplates'])->name('import-summary-templates')->defaults('section', $courierBillSection); + }); + + Route::prefix('workspace/'.$courierBillSection.'/dropship-freight-reconciliation') + ->middleware('business.page:'.$courierBillSection.',dropship-freight-reconciliation') + ->name('business.'.$courierBillSection.'.dropship-freight.') + ->group(function () use ($courierBillSection) { + $controller = \App\Http\Controllers\Business\DropshipFreightController::class; + Route::post('upload', [$controller, 'upload'])->name('upload')->defaults('section', $courierBillSection); + Route::post('files/{file}/assign', [$controller, 'assign'])->whereNumber('file')->name('assign')->defaults('section', $courierBillSection); + Route::post('files/{file}/delete', [$controller, 'deleteFile'])->whereNumber('file')->name('delete-file')->defaults('section', $courierBillSection); + Route::post('factories', [$controller, 'saveFactory'])->name('save-factory')->defaults('section', $courierBillSection); + Route::post('factories/generate', [$controller, 'generate'])->name('generate')->defaults('section', $courierBillSection); + Route::post('factories/{factory}/delete', [$controller, 'deleteFactory'])->whereNumber('factory')->name('delete-factory')->defaults('section', $courierBillSection); + Route::get('export', [$controller, 'export'])->name('export')->defaults('section', $courierBillSection); }); Route::prefix('workspace/'.$courierBillSection.'/courier-payable-summary') diff --git a/tests/Feature/Business/CourierBillPagesTest.php b/tests/Feature/Business/CourierBillPagesTest.php index 1f951f80..9e0adff8 100644 --- a/tests/Feature/Business/CourierBillPagesTest.php +++ b/tests/Feature/Business/CourierBillPagesTest.php @@ -52,6 +52,14 @@ final class CourierBillPagesTest extends FeatureTestCase $this->get($statementUrl)->assertOk()->assertSee('回填'); $this->from($statementUrl)->post(route("business.$section.courier-bills.fill-item", ['statement' => $statement->id, 'item' => $manual]), ['self' => 15]) ->assertRedirect($statementUrl)->assertSessionHas('courier_bills_message'); + // 导入手工小汇总类目:本月小汇总照它排,空行能回填快递金额和自算金额 + $template = new UploadedFile($this->xlsx(['汇总' => [['河北中通-江三/小件10月', '快递提供金额', '自算金额', '差异'], + ['运费10月', 1, 1, 0], ['快递记账', null, -3, 3], ['匹配不到', 1, null, 1], ['总计', 2, -2, 4]]]), '河北中通10月发送版.xlsx', null, null, true); + $this->post(route("business.$section.courier-bills.import-summary-templates"), ['month' => '2026-10', 'files' => [$template]]) + ->assertRedirect()->assertSessionHas('courier_bills_message', fn ($m) => str_contains($m, '记下 1 家')); + $this->get($statementUrl)->assertOk()->assertSeeText('运费10月')->assertSeeText('快递记账')->assertSee('placeholder="快递提供"', false); + $this->get(route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'upload', 'month' => '2026-10'])) + ->assertOk()->assertSeeText('导入手工小汇总'); $line = $db->table('courier_bill_lines')->where('waybill_no', 'ZT999')->first(); $this->from($statementUrl)->post(route("business.$section.courier-bills.resolve"), ['lines' => [$line->id], 'resolution' => 'exclude'])->assertRedirect($statementUrl); $this->get(route("business.$section.courier-bills.export-statement", ['statement' => $statement->id]))->assertOk(); diff --git a/tests/Feature/Business/CourierBillReconciliationTest.php b/tests/Feature/Business/CourierBillReconciliationTest.php index e95f8c71..c62d4cc7 100644 --- a/tests/Feature/Business/CourierBillReconciliationTest.php +++ b/tests/Feature/Business/CourierBillReconciliationTest.php @@ -11,6 +11,7 @@ use App\Support\CourierBills\CourierBillStore; use App\Support\CourierBills\PayableSummary; use App\Support\CourierBills\StatementExporter; use App\Support\CourierBills\SummaryMapper; +use App\Support\CourierBills\SummaryTemplate; use App\Support\CourierBills\Waybill; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; @@ -899,6 +900,110 @@ final class CourierBillReconciliationTest extends FeatureTestCase } } + public function test_summary_template_rolls_months_and_reads_manual_blocks(): void + { + $this->assertSame('2026.9-10月记账补款', SummaryTemplate::roll('2026.8-9月记账补款', 1)); + $this->assertSame('10月记账补款', SummaryTemplate::roll('9月记账补款', 1)); + $this->assertSame('运费11月', SummaryTemplate::roll('运费10月', 1)); + $this->assertSame('2026.12-2027.1月记账补款', SummaryTemplate::roll('2026.11-12月记账补款', 1)); + $this->assertSame('补1月记账', SummaryTemplate::roll('补12月记账', 1)); + $this->assertSame('拉到江西云仓的车费', SummaryTemplate::roll('拉到江西云仓的车费', 1)); + $this->assertSame(['运费11月', '2026.9-10月记账补款'], SummaryTemplate::fromLabels(['运费10月', '跨月订单-11月,本月不结算', '10月运费(前月补提供)', '2026.8-9月记账补款'], 1)); + + // 两块左右并排;表头第二、三列叫法不一(快递提供金额/自算金额、对方/我方),最后一列差异或差额;首重这种数字表不算 + $blocks = SummaryTemplate::blocks(['汇总' => [ + ['樵舍中通-上楼10月', '快递提供金额', '自算金额', '差异', null, '宿迁中通快运', '对方', '我方', '差额'], + ['运费10月', 3597.97, 3598.06, -0.09, null, '运费-重量差', 76011.13, 76004.16, 6.97], + ['未发出', null, null, 0, null, '未发出', 0, null, 0], + ['2026.8-9月记账补款', null, 491.5, -491.5, null, '合计', 76011.13, 76004.16, 6.97], + ['总计', 3597.97, 1056.2, 2541.77], + ['附加费1', null, 0], + [], + ['首重', '江苏', '浙江', '差异'], + [56.3, 28.1, 44.0, 1], + ]]); + $this->assertSame([ + ['title' => '樵舍中通-上楼10月', 'labels' => ['运费10月', '未发出', '2026.8-9月记账补款']], + ['title' => '宿迁中通快运', 'labels' => ['运费-重量差', '未发出']], + ], $blocks); + + $rows = SummaryTemplate::apply(['运费10月', '快递记账', '违约金', '查不到', '配件补发扣款', '上楼费', '2026.8-9月记账补款'], [ + '10月运费' => ['bill' => 100.0, 'self' => 99.0, 'kind' => 'freight'], + '10月运费-重量差' => ['bill' => 10.0, 'self' => 9.0, 'kind' => 'freight'], + '匹配不到' => ['bill' => 3.0, 'self' => 0.0, 'kind' => 'unmatched'], + '配件补发扣款' => ['bill' => null, 'self' => -5.0, 'kind' => 'accessory'], + '山东中通快运加收&上楼费' => ['bill' => 7.0, 'self' => 0.0, 'kind' => 'fee'], + '跨月订单-11月,本月不结算' => ['bill' => 2.0, 'self' => 0.0, 'kind' => 'later'], + ], 10); + $this->assertSame([ + ['运费10月', 110.0, 108.0], ['快递记账', null, null], ['违约金', null, null], ['查不到', 3.0, 0.0], + ['配件补发扣款', null, -5.0], ['上楼费', 7.0, 0.0], ['2026.8-9月记账补款', null, null], ['跨月订单-11月,本月不结算', 2.0, 0.0], + ], array_map(fn (array $r): array => [$r['label'], $r['bill'], $r['self']], $rows)); + $this->assertSame(['上楼费'], SummaryTemplate::feeSlots(['运费10月', '上楼费'], ['山东中通快运加收&上楼费'], 10)); + } + + public function test_summary_follows_last_months_categories_and_blank_rows_can_be_filled(): void + { + $this->seedShipping(); + $store = app(CourierBillStore::class); + $matcher = app(CourierBillMatcher::class); + $store->saveGroup(null, ['name' => '河北中通-江三', 'express_names' => ['河北中通-江三']]); + $ids = $store->upload([$this->upload('河北中通-江三10月.xlsx', [['运单编号', '运费'], ['ZT001', 10], ['ZT002', 12], ['ZT003', 5], ['ZT004', 6]])], '2026-10', [], 'tester'); + $october = (int) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('statement_id'); + $labels = fn (int $id): array => $store->db()->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->orderBy('id') + ->get()->map(fn ($i) => [$i->label, $i->bill_amount === null ? null : (float) $i->bill_amount, $i->self_amount === null ? null : (float) $i->self_amount, (bool) $i->manual])->all(); + + // 系统里没有 9 月:导入 10 月手工小汇总的类目,10 月就按它排 + $result = $store->saveSummaryTemplates([['title' => '河北中通-江三10月', 'labels' => ['运费10月', '快递记账', '违约金', '未发出', '匹配不到', '2026.8-9月记账补款']]], '2026-10'); + $this->assertSame(['河北中通-江三'], $result['saved']); + $this->assertSame([ + ['运费10月', 22.0, 21.0, false], ['快递记账', null, null, false], ['违约金', null, null, false], + ['未发出', 5.0, 0.0, false], ['匹配不到', 6.0, 0.0, false], ['2026.8-9月记账补款', null, null, false], + ], $labels($october)); + + // 空行回填快递金额和自算金额 → 手工行,重新匹配不覆盖,位置不变 + $blank = (int) $store->db()->table('courier_bill_summary_items')->where('statement_id', $october)->where('label', '2026.8-9月记账补款')->value('id'); + $store->fillSummaryItem($october, $blank, 491.5, null, true); + $store->addSummaryItem($october, '拉到江西云仓的车费', 26500, 26500); + $matcher->refreshSummary($october); + $rows = $labels($october); + $this->assertSame(['2026.8-9月记账补款', null, 491.5, true], $rows[5]); + $this->assertSame(['拉到江西云仓的车费', 26500.0, 26500.0, true], $rows[6]); + $freight = (int) $store->db()->table('courier_bill_summary_items')->where('statement_id', $october)->where('label', '运费10月')->value('id'); + try { + $store->fillSummaryItem($october, $freight, 1, 1, true); + $this->fail('运费行不能回填'); + } catch (\RuntimeException $e) { + $this->assertStringContainsString('系统按明细算的', $e->getMessage()); + } + + // 11 月:类目从系统 10 月小汇总搬过来,月份顺延;系统多出来的新类目排在后面 + $ids = $store->upload([$this->upload('河北中通-江三11月.xlsx', [['运单编号', '运费'], ['ZT007', 9], ['ZT001', 10]])], '2026-11', [], 'tester'); + $november = (int) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('statement_id'); + $this->assertSame([ + ['运费11月', 9.0, 9.0, false], ['快递记账', null, null, false], ['违约金', null, null, false], ['未发出', null, null, false], + ['匹配不到', null, null, false], ['2026.9-10月记账补款', null, null, false], ['拉到江西云仓的车费', null, null, false], + ['10月运费(前月补提供)', 10.0, 10.0, false], + ], $labels($november)); + } + + public function test_summary_template_command_imports_a_label_list_by_group_name(): void + { + $store = app(CourierBillStore::class); + $store->saveGroup(null, ['name' => '好省邮快递', 'express_names' => ['好省邮']]); + $store->saveGroup(null, ['name' => '常州德邦逆向', 'express_names' => ['常州德邦逆向']]); + $path = tempnam(sys_get_temp_dir(), 'tpl'); + file_put_contents($path, json_encode([ + ['group' => '好省邮快递', 'title' => '10月份账单', 'labels' => ['运费10月', '运费10月未退回']], + ['group' => '常州德邦逆向', 'title' => '10月份账单', 'labels' => ['运费10月', '未退回扣成本价']], + ['group' => '没有这个分组', 'title' => '10月份账单', 'labels' => ['运费']], + ], JSON_UNESCAPED_UNICODE)); + $this->artisan('courier-bills:import-summary-templates', ['file' => $path, '--month' => '2026-10']) + ->expectsOutputToContain('记下 2 家 2026-10 的类目')->expectsOutputToContain('没找到分组:没有这个分组')->assertSuccessful(); + $this->assertSame(['运费10月', '未退回扣成本价'], json_decode((string) $store->db()->table('courier_bill_summary_templates as t') + ->join('courier_bill_groups as g', 'g.id', '=', 't.group_id')->where('g.name', '常州德邦逆向')->value('t.labels'), true)); + } + private function seedShipping(): void { $db = app(\App\Support\CourierBills\ShippingLookup::class)->connection(); diff --git a/tests/Feature/Business/DropshipFreightTest.php b/tests/Feature/Business/DropshipFreightTest.php new file mode 100644 index 00000000..ab0be54d --- /dev/null +++ b/tests/Feature/Business/DropshipFreightTest.php @@ -0,0 +1,250 @@ +xlsx([ + '运费+货款' => [ + ['卿德客10月对账'], + ['快递单号', '内部订单号', '快递公司', '金额', '快递', '偏远'], + ['773444000001', '1', '卿德客申通', 15.1, 4, null], + ['773444000001', '1', '卿德客申通', 11.0, 4, null], // 一单多件:运费相加 + ['773444000002', '2', '卿德客申通', 20.0, 5.5, 3], // 偏远列加进运费 + ['JDVB0001', '3', '京喜京东快递', 30.0, null, null], // 没运费:不算厂家开了运费 + ['合计', null, null, 76.1, 13.5, 3], + ], + '对账' => [['快递单号', '运费', '结算运费'], ['773444000001', 8, 8]], + '记账' => [['物流单号', '记账金额'], ['773444000009', 30]], + '送货' => [['快递单号', '金额'], ['773444000003', 11]], + ]); + $result = (new FactoryBillParser(new BillWorkbookReader()))->parse($path, 'xlsx'); + + $this->assertSame(['773444000001', '773444000002'], array_map('strval', array_keys($result['lines']))); + $this->assertEquals(8.0, $result['lines']['773444000001']['amount']); + $this->assertEquals(8.5, $result['lines']['773444000002']['amount']); + $read = array_values(array_filter($result['sheets'], static fn (array $s): bool => $s['read'])); + $this->assertCount(1, $read); + $this->assertStringContainsString('运费列「快递」(加上「偏远」)', $read[0]['note']); + $skipped = collect($result['sheets'])->where('read', false)->pluck('note', 'sheet'); + $this->assertStringContainsString('对账', $skipped['对账']); + $this->assertStringContainsString('记账', $skipped['记账']); + $this->assertStringContainsString('没有同时找到', $skipped['送货']); + } + + public function test_generate_upload_reconcile_and_pages(): void + { + Storage::fake('local'); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs()->withExceptionHandling(); + $db = CourierBillMatcher::db(); + // 自有快递:快递账单对账分组里的快递名称1 + $db->table('courier_bill_groups')->insert(['name' => '曹县韵达', 'express_names' => json_encode(['曹县韵达'], JSON_UNESCAPED_UNICODE), + 'created_at' => now(), 'updated_at' => now()]); + $this->ship('773444000001', '卿德客申通', self::WAREHOUSE, '2026-10-03 09:00:00', 1, 8); // 一致 + $this->ship('773444000002', '卿德客申通', self::WAREHOUSE, '2026-10-04 09:00:00', 2, 5); // 厂家多开 + $this->ship('773444000003', '卿德客极兔', self::WAREHOUSE, '2026-10-05 09:00:00', 3, 6); // 厂家少开 + $this->ship('773444000004', '卿德客申通', self::WAREHOUSE, '2026-10-06 09:00:00', 4, 7); // 厂家没开:不付 + $this->ship('YD0001', '曹县韵达', self::WAREHOUSE, '2026-10-06 09:00:00', 5, 9); // 自有快递 + $this->ship('773444000006', '卿德客申通', '简尚-新外贸仓主仓', '2026-10-06 09:00:00', 6, 9); // 别的仓 + $this->ship('773444000007', '卿德客申通', self::WAREHOUSE, '2026-10-07 09:00:00', 7, null); // 未核算 + $this->ship('773444000008', '卿德客申通', self::WAREHOUSE, '2026-09-30 09:00:00', 8, 4); // 前月补提供 + $this->ship('773444000010', '卿德客申通', self::WAREHOUSE, '2026-11-02 09:00:00', 12, 4); // 跨月订单 + $this->ship('JDVB0001', '京喜京东快递', self::WAREHOUSE, '2026-10-08 09:00:00', 9, 3); + $this->ship('JDVB0002', '京喜京东快递', '工厂-河北丽彪代发仓', '2026-10-08 09:00:00', 10, 3); + $this->ship('JDVB0003', '京喜京东快递', '简尚-新外贸仓主仓', '2026-10-08 09:00:00', 11, 3); + $this->ship('773444000020', '卿德客申通', self::WAREHOUSE, '2026-10-09 09:00:00', 13, 6); // 换单后的新单号:代发单 + $this->ship('YD0020', '曹县韵达', self::WAREHOUSE, '2026-10-09 09:00:00', 14, 9); // 换单后的新单号:自有快递 + $this->shipping()->table('jst_oms_shipping')->where('express_no', '773444000020')->update(['front_no' => 'OLD0000001']); + $this->shipping()->table('jst_oms_shipping')->where('express_no', 'YD0020')->update(['front_no' => 'OLD0000002']); + $this->shipping()->table('jst_oms_shipping')->where('source_id', '<=', 8)->update(['supplier_name' => '临沂卿德客']); + + $section = 'courier-payables-final'; + $page = fn (array $q = []) => route('business.pages.show', ['section' => $section, 'page' => 'dropship-freight-reconciliation', ...$q]); + $this->get(route('business.pages.show', ['section' => $section]))->assertOk()->assertSeeText('代发运费对账'); + foreach (['overview', 'upload', 'factories'] as $view) { + $this->get($page(['df_view' => $view, 'month' => '2026-10']))->assertOk()->assertSee('data-cbr-root', false); + } + + $this->post(route("business.$section.dropship-freight.generate"), ['month' => '2026-10'])->assertRedirect()->assertSessionHas('dropship_message'); + $factory = $db->table('dropship_factories')->sole(); + $this->assertSame('临沂卿德客', $factory->name); + $this->assertSame(self::WAREHOUSE, $factory->warehouse); + $this->assertSame('卿德客', $factory->keywords); + + $bill = new UploadedFile($this->xlsx(['运费+货款' => [ + ['快递单号', '快递公司', '运费'], + ['773444000001', '卿德客申通', 8], ['773444000002', '卿德客申通', 6], ['773444000003', '卿德客极兔', 5], + ['YD0001', '曹县韵达', 9], ['773444000006', '卿德客申通', 9], ['773444000007', '卿德客申通', 4], + ['773444000008', '卿德客申通', 4], ['999999999999', '卿德客申通', 3], ['773444000010', '卿德客申通', 4], + ['OLD0000001', '卿德客申通', 6], ['OLD0000002', '卿德客申通', 5], + ]]), '临沂卿德客10月.xlsx', null, null, true); + $this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-10', 'files' => [$bill]]) + ->assertRedirect()->assertSessionHas('dropship_message'); + $file = $db->table('dropship_bill_files')->sole(); + $this->assertSame('parsed', $file->status); + $this->assertSame((int) $factory->id, (int) $file->factory_id); + $this->assertSame(11, (int) $file->waybill_count); + + $f = collect(app(DropshipFreightStore::class)->factories())->sole(); + $result = app(DropshipReconciler::class)->factoryMonth($f, '2026-10'); + $status = collect($result['rows'])->pluck('status', 'waybill')->all(); + $expected = [ + '773444000001' => Category::MATCH, '773444000002' => Category::DIFF, '773444000003' => Category::DIFF, + '773444000004' => Category::UNPROVIDED, 'YD0001' => Category::MISMATCH, '773444000006' => Category::MISMATCH, + '773444000007' => Category::UNCALCULATED, '773444000008' => Category::PRIOR, '773444000010' => Category::LATER, + '999999999999' => Category::UNMATCHED, 'OLD0000001' => Category::MATCH, 'OLD0000002' => Category::MISMATCH, + ]; + ksort($status); + ksort($expected); + $this->assertSame($expected, $status); + $s = $result['summary']; + $this->assertSame(11, $s['billed']); + $this->assertEquals(63, $s['bill']); + // 按我方核算:一致、运费有差、前月补提供、换单实际发出的代发单;跨月订单留到发货月 + $this->assertEquals(8 + 5 + 6 + 4 + 6, $s['settle']); + $this->assertEquals(63 - 29, $s['diff']); + $swap = collect($result['rows'])->firstWhere('waybill', 'OLD0000001'); + $this->assertStringContainsString('换单:实际发出 773444000020(卿德客申通)', $swap['note']); + $this->assertStringContainsString('自有快递「曹县韵达」', collect($result['rows'])->firstWhere('waybill', 'OLD0000002')['note']); + $this->assertArrayNotHasKey('773444000020', $status); // 新单号不再算「厂家未提供」 + $this->assertSame([1, 1], [$s['over'], $s['under']]); + $prior = collect($result['rows'])->firstWhere('waybill', '773444000008'); + $this->assertSame('前月补提供-9月', $prior['label']); + $own = collect($result['rows'])->firstWhere('waybill', 'YD0001'); + $this->assertStringContainsString('自有快递', (string) $own['note']); + $this->assertNull($own['settle']); + + $this->get($page(['df_view' => 'overview', 'month' => '2026-10']))->assertOk()->assertSeeText('临沂卿德客')->assertSeeText('29.00'); + $this->get($page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']))->assertOk() + ->assertSeeText('一致但运费有差')->assertSeeText('773444000004')->assertSeeText('厂家未提供(不付)')->assertSeeText('匹配不到') + ->assertSeeText('自有快递「曹县韵达」'); + $this->get($page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10', 'status' => 'attention']))->assertOk() + ->assertDontSeeText('773444000004'); + $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10']))->assertOk(); + $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10', 'factory' => $factory->id]))->assertOk(); + + // 同一份账单再传:重复导入,不读入 + $again = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000001', 8], ['773444000002', 6]]]), '卿德客10月补.xlsx', null, null, true); + $this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-10', 'files' => [$again]])->assertRedirect(); + $this->assertSame('failed', $db->table('dropship_bill_files')->orderByDesc('id')->value('status')); + // 下个月的账单又开了 10 月已开过的单 + $next = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000001', 8]]]), '卿德客11月.xlsx', null, null, true); + $this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-11', 'files' => [$next]])->assertRedirect(); + $nov = app(DropshipReconciler::class)->factoryMonth($f, '2026-11'); + $this->assertSame(Category::DUPLICATE, collect($nov['rows'])->firstWhere('waybill', '773444000001')['status']); + + // 换单跨月:10 月账单开的是旧单号 OLD0000001(已换成 773444000020),11 月账单又开新单号 → 同一包裹,算重复 + $swapNov = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000020', 6]]]), '卿德客11月补.xlsx', null, null, true); + $this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-11', 'files' => [$swapNov]])->assertRedirect(); + $nov = app(DropshipReconciler::class)->factoryMonth($f, '2026-11'); + $row = collect($nov['rows'])->firstWhere('waybill', '773444000020'); + $this->assertSame(Category::DUPLICATE, $row['status']); + $this->assertStringContainsString('OLD0000001', (string) $row['note']); + $this->assertNull($row['settle']); + + // 认不出厂家的文件:待选厂家,选后读入 + $unknown = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000004', 7]]]), '某厂家12月.xlsx', null, null, true); + $this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-12', 'files' => [$unknown]])->assertRedirect(); + $pending = $db->table('dropship_bill_files')->where('bill_month', '2026-12')->sole(); + $this->assertSame('pending_factory', $pending->status); + $this->post(route("business.$section.dropship-freight.assign", ['file' => $pending->id]), ['factory_id' => $factory->id])->assertRedirect(); + $this->assertSame('parsed', $db->table('dropship_bill_files')->where('id', $pending->id)->value('status')); + + // 厂家设置:有账单不能删;删完账单再删 + $this->post(route("business.$section.dropship-freight.save-factory"), ['id' => $factory->id, 'name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE, + 'keywords' => '卿德客,卿德客申通'])->assertRedirect(); + $this->assertSame('卿德客,卿德客申通', $db->table('dropship_factories')->value('keywords')); + $this->post(route("business.$section.dropship-freight.delete-factory", ['factory' => $factory->id]))->assertSessionHasErrors('dropship'); + foreach ($db->table('dropship_bill_files')->pluck('id') as $id) { + $this->post(route("business.$section.dropship-freight.delete-file", ['file' => $id]))->assertRedirect(); + } + $this->assertSame(0, $db->table('dropship_bill_lines')->count()); + $this->post(route("business.$section.dropship-freight.delete-factory", ['factory' => $factory->id]))->assertRedirect(); + $this->assertSame(0, $db->table('dropship_factories')->count()); + } + + public function test_partial_duplicate_check_covers_every_waybill_of_a_large_bill(): void + { + Storage::fake('local'); + $store = app(DropshipFreightStore::class); + $store->saveFactory(null, ['name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']); + $first = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773449999999', 5]]]), '卿德客10月.xlsx', null, null, true); + $store->upload([$first], '2026-10', 't'); + $rows = [['快递单号', '运费']]; + for ($i = 0; $i < 5001; $i++) { + $rows[] = [(string) (773440000000 + $i), 4]; + } + $rows[] = ['773449999999', 5]; // 第 5,002 个单号和上一份重复 + $id = $store->upload([new UploadedFile($this->xlsx(['账单' => $rows]), '卿德客10月补.xlsx', null, null, true)], '2026-10', 't')[0]; + $file = $store->db()->table('dropship_bill_files')->find($id); + $this->assertSame('parsed', $file->status); + $this->assertSame(5001, (int) $file->waybill_count); + $this->assertStringContainsString('1 个单号本月别的账单文件里也有', (string) $file->message); + $this->assertSame(1, $store->db()->table('dropship_bill_lines')->where('waybill_no', '773449999999')->count()); + } + + public function test_keyword_helpers(): void + { + $this->assertSame('卿德客', DropshipFreightStore::warehouseCore('工厂-山东卿德客代发仓')); + $this->assertSame('派雅世佳', DropshipFreightStore::warehouseCore('工厂-河北霸州派雅世佳代发仓')); + $this->assertSame('四强', DropshipFreightStore::commonPart(['四强申通', '四强圆通'])); + $this->assertSame('派雅', DropshipFreightStore::commonPart(['派雅韵达', '派雅世佳'])); + $this->assertSame('', DropshipFreightStore::commonPart(['四强申通', '森卓'])); + $this->assertSame(['卿德客', '极兔'], DropshipFreightStore::splitKeywords('卿德客, 极兔、卿德客')); + } + + private function shipping() + { + return app(ShippingLookup::class)->connection(); + } + + private function ship(string $waybill, string $express, string $warehouse, string $time, int $source, ?float $freight): void + { + $this->shipping()->table('jst_oms_shipping')->insert(['express_no' => $waybill, 'express_name1' => $express, 'warehouse_name' => $warehouse, + 'ship_time' => $time, 'source_id' => $source]); + $this->shipping()->table('jst_oms_shipping_freight')->insert(['source_id' => $source, 'freight' => $freight, + 'status' => $freight === null ? '报价管理里没有「' . $express . '」的报价' : 'OK', 'charge_weight' => 1]); + } + + /** @param array>> $sheets */ + private function xlsx(array $sheets): string + { + $book = new Spreadsheet(); + $book->removeSheetByIndex(0); + foreach ($sheets as $title => $rows) { + $sheet = $book->createSheet(); + $sheet->setTitle($title); + foreach ($rows as $r => $row) { + foreach ($row as $c => $value) { + if ($value !== null) { + $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(), 'df_') . '.xlsx'; + (new Xlsx($book))->save($path); + + return $path; + } +}