From 34b7c1c5e7d7fec1dee8ffaf3b97ba4223e07620 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Thu, 3 Dec 2026 12:11:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E4=BB=A3=E5=8F=91=E8=BF=90=E8=B4=B9):=20?= =?UTF-8?q?=E5=90=88=E5=85=A5=E8=A1=A5=E4=B8=81=2033=20=E5=92=8C=2034=20(#?= =?UTF-8?q?1684)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DropshipFreight/DropshipExporter.php | 104 +++++++++++++++--- app/Support/DropshipFreight/DropshipFees.php | 4 +- .../Feature/Business/DropshipFreightTest.php | 85 ++++++++++++-- 3 files changed, 162 insertions(+), 31 deletions(-) diff --git a/app/Support/DropshipFreight/DropshipExporter.php b/app/Support/DropshipFreight/DropshipExporter.php index 8fbbd5239..87322690e 100644 --- a/app/Support/DropshipFreight/DropshipExporter.php +++ b/app/Support/DropshipFreight/DropshipExporter.php @@ -21,6 +21,8 @@ use RuntimeException; */ final class DropshipExporter { + /** 小汇总里放厂家附加费表金额的那一行(手工汇总里已有带「附加费」的类目就填那一行)。 */ + public const FEE_LABEL = '厂家账单-附加费'; private const CHUNK = 500; public function __construct( @@ -77,7 +79,8 @@ final class DropshipExporter [$originals, $sources, $original] = $this->writeOriginal($book, $files, $baseFileId, $index, $baseCount); $lookup = $index->prepare('SELECT raw FROM originals WHERE file = ? AND sheet = ? AND row = ?'); $rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(StatementExporter::FRONT, static fn ($f) => $f[0] !== '_'))); - $tail = ['厂家运费(这一单合计)', '结算运费', '最终结算运费', '分类', '说明']; + $tail = ['厂家运费(这一单合计)', '结算运费', '分类', '说明']; + $front = self::frontColumns(); // 对账类:本月一致 / 运费有差 / 系统未核算,和前月补提供、跨月订单(按月份各一张) $sheets = ['对账' => static fn (array $r): bool => in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)]; @@ -91,19 +94,19 @@ final class DropshipExporter if ($picked === []) { continue; } - $book->row($name, [...$original, ...array_keys(StatementExporter::FRONT), ...array_values($rest), ...$tail], true); + $book->row($name, [...$original, ...array_keys($front), ...array_values($rest), ...$tail], true); foreach (array_chunk($picked, self::CHUNK) as $chunk) { $details = $this->shipping->details(array_map(static fn (array $r): string => (string) $r['ship_waybill'], $chunk)); foreach ($chunk as $r) { $ship = $details[strtoupper((string) $r['ship_waybill'])] ?? []; $cells = $this->originalCells($r, $sources, $original, $lookup); - foreach (StatementExporter::FRONT as $field) { + foreach ($front as $field) { $cells[] = $this->front($field, $r, $ship); } foreach (array_keys($rest) as $field) { $cells[] = self::value($field, $ship[$field] ?? null); } - $book->row($name, [...$cells, $r['bill'], $r['settle'], $r['final'] ?? $r['settle'], $r['label'], $r['note']]); + $book->row($name, [...$cells, $r['bill'], $r['settle'], $r['label'], $r['note']]); } } } @@ -139,32 +142,81 @@ final class DropshipExporter } /** - * 汇总:照这家上月手工汇总的样子(标题、表头、类目顺序),月份顺延。运费行系统填(厂家开的运费合计 / 按我方核算的结算运费), - * 货款、记账等先空着手工填;差异和合计行是公式,手工填了会跟着算。下面不再附别的(分类明细看各分类子表)。 + * 汇总:照这家上月手工汇总的样子(标题、表头、类目顺序),月份顺延。 + * - 运费行:原始 = 按我方结算的那些单(一致、运费有差、系统未核算、前月补提供)厂家开的运费,简尚核对 = 最终结算运费; + * - 厂家开了运费但这个月不付的,按分类各加一行(快递不符、重复、匹配不到、未发出、跨月订单-X月):原始 = 厂家开的运费,简尚核对 = 0; + * 这样「原始」合计 = 厂家账单运费合计。手工汇总里已有同名类目的就填在那一行,不重复加; + * - 记账等先空着手工填;差异和合计行是公式,手工填了会跟着算。下面不再附别的(分类明细看各分类子表)。 */ private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void { $template = $this->store->summaryTemplate($factory, $month); $billTotal = $settleTotal = null; + $extras = []; + foreach ([Category::MISMATCH, Category::DUPLICATE, Category::UNMATCHED, Category::UNSHIPPED] as $category) { + $extras[DropshipReconciler::LABELS[$category]] = null; + } foreach ($rows as $r) { - if ($r['bill'] !== null) { - $billTotal = (float) $billTotal + (float) $r['bill']; + if ($r['bill'] === null) { + continue; } - $final = $r['final'] ?? $r['settle']; - if ($final !== null) { - $settleTotal = (float) $settleTotal + (float) $final; + if (in_array($r['status'], DropshipReconciler::PAYABLE, true)) { + $billTotal = (float) $billTotal + (float) $r['bill']; + $final = $r['final'] ?? $r['settle']; + if ($final !== null) { + $settleTotal = (float) $settleTotal + (float) $final; + } + } elseif ($r['status'] === Category::LATER) { + $label = Category::label(Category::LATER, (string) $r['status_month']); + $extras[$label] = (float) ($extras[$label] ?? 0) + (float) $r['bill']; + } elseif (array_key_exists($label = DropshipReconciler::LABELS[$r['status']] ?? '', $extras)) { + $extras[$label] = (float) $extras[$label] + (float) $r['bill']; } } - $labels = $template['labels']; - if (($billTotal !== null || $settleTotal !== null) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) { + $extras = array_filter($extras, static fn ($v): bool => $v !== null); + // 厂家按模板填的「附加费」表:金额合计放一行(不逐单核对,简尚核对空着手工填) + $fee = 0.0; + $hasFee = false; + foreach ($this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month) + ->where('status', 'parsed')->pluck('sheets') as $sheets) { + foreach ((array) json_decode((string) $sheets, true) as $sheet) { + if (! empty($sheet['fees'])) { + $fee += array_sum(array_map('floatval', (array) $sheet['fees'])); + $hasFee = true; + } + } + } + // 上月手工汇总里的分类行(快递不符、未发出、跨月订单-X月……)这个月没有就不留空行 + $labels = array_values(array_filter($template['labels'], static fn (string $l): bool => array_key_exists(trim($l), $extras) + || ! preg_match('/^(快递不符|重复|匹配不到|未发出|跨月订单)/u', trim($l)))); + if (! $hasFee) { + $labels = array_values(array_filter($labels, static fn (string $l): bool => ! str_contains($l, '附加费'))); + } + if (($billTotal !== null || $settleTotal !== null || $extras !== []) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) { array_unshift($labels, '运费'); } + foreach (array_keys($extras) as $label) { + if (! in_array($label, array_map('trim', $labels), true)) { + $labels[] = $label; + } + } + $feeLabel = null; + if ($hasFee) { + $feeLabel = collect($labels)->first(static fn (string $l): bool => str_contains($l, '附加费')) ?? self::FEE_LABEL; + if (! in_array($feeLabel, $labels, true)) { + $labels[] = $feeLabel; + } + } $book->row('汇总', [$template['title'], ...array_slice(array_pad($template['headers'], 3, ''), 0, 3)], true); $sums = [0.0, 0.0]; - foreach ($labels as $index => $label) { + foreach (array_values($labels) as $index => $label) { $n = $index + 2; - [$bill, $settle] = DropshipSummaryTemplate::isFreight($label) - ? [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)] : [null, null]; + [$bill, $settle] = match (true) { + DropshipSummaryTemplate::isFreight($label) => [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)], + array_key_exists(trim($label), $extras) => [round($extras[trim($label)], 2), 0.0], + $label === $feeLabel => [round($fee, 2), null], + default => [null, null], + }; $sums[0] += (float) $bill; $sums[1] += (float) $settle; $book->row('汇总', [$label, $bill, $settle, self::diff($n, $bill, $settle)]); @@ -175,7 +227,6 @@ final class DropshipExporter new XlsxFormula('SUM(C2:C' . $last . ')', round($sums[1], 2)), new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', round($sums[0] - $sums[1], 2))], true); } - /** 差异 = 原始 − 简尚,两格都空就空着(公式,手工填了会跟着算)。 */ private static function diff(int $row, ?float $bill, ?float $settle): XlsxFormula { return new XlsxFormula('IF(COUNT(B' . $row . ':C' . $row . ')=0,"",N(B' . $row . ')-N(C' . $row . '))', @@ -328,13 +379,30 @@ final class DropshipExporter }, $original); } + /** 对账表前面几列:照快递对账单的,「核算运费」后面加「最终结算运费」。 @return array */ + private static function frontColumns(): array + { + $result = []; + foreach (StatementExporter::FRONT as $label => $field) { + $result[$label] = $field; + if ($field === 'qc_freight') { + $result['最终结算运费'] = '_final'; + } + } + + return $result; + } + private function front(string $field, array $r, array $ship): string|float|null { return match ($field) { '_measured' => $ship['qc_measured_weight'] ?? null, '_unshipped' => null, '_weight_diff' => null, - '_freight_diff' => $r['bill'] !== null && ($ship['qc_freight'] ?? null) !== null ? round((float) $r['bill'] - (float) $ship['qc_freight'], 2) : null, + '_final' => $r['final'] ?? $r['settle'] ?? null, + // 运费差 = 厂家运费 − 最终结算运费 + '_freight_diff' => $r['bill'] !== null && ($r['final'] ?? $r['settle'] ?? null) !== null + ? round((float) $r['bill'] - (float) ($r['final'] ?? $r['settle']), 2) : null, default => self::value($field, $ship[$field] ?? null), }; } diff --git a/app/Support/DropshipFreight/DropshipFees.php b/app/Support/DropshipFreight/DropshipFees.php index 83b351c7b..736eeca99 100644 --- a/app/Support/DropshipFreight/DropshipFees.php +++ b/app/Support/DropshipFreight/DropshipFees.php @@ -22,9 +22,9 @@ final class DropshipFees /** 财务可以改的列(快递运费取结算运费,不在这里改)。 */ public const EDITABLE = ['booking', 'extra_freight', 'extra_booking', 'returned', 'intercept', 'readdress', 'repack', 'overlength']; - /** 附加费类型里出现这些字就归到这一列,按顺序认(「补记账」先于「记账」)。 */ + /** 附加费类型里出现这些字就归到这一列,按顺序认(「补记账」先于「记账」,「拦截退回」算拦截费)。 */ private const MATCH = ['extra_booking' => ['补记账'], 'booking' => ['记账'], 'extra_freight' => ['补运费', '补运'], - 'returned' => ['退回', '退件', '退货'], 'intercept' => ['拦截'], 'readdress' => ['改地址', '改址'], 'repack' => ['翻箱'], 'overlength' => ['超长']]; + 'intercept' => ['拦截'], 'readdress' => ['改地址', '改址'], 'repack' => ['翻箱'], 'overlength' => ['超长'], 'returned' => ['退回', '退件', '退货']]; public function __construct( private readonly DropshipFreightStore $store, diff --git a/tests/Feature/Business/DropshipFreightTest.php b/tests/Feature/Business/DropshipFreightTest.php index 53a115705..a97a546be 100644 --- a/tests/Feature/Business/DropshipFreightTest.php +++ b/tests/Feature/Business/DropshipFreightTest.php @@ -150,15 +150,15 @@ final class DropshipFreightTest extends FeatureTestCase $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10']))->assertOk(); // 导入这家 10 月手工做好的账单:只读汇总的样子(标题、表头、类目),导出汇总照它排 $manual = new UploadedFile($this->xlsx(['运费+货款' => [['快递单号', '运费'], ['1', 2]], '汇总' => [ - ['10月', '厂家金额', '简尚金额', '差异'], ['运费', 37923.5, 37612.5, 311], ['货款', 151323.6, 151323.6, 0], ['记账', null, -3645.9, 3645.9], - ['汇总', 189247.1, 185290.2, 3956.9], + ['10月', '厂家金额', '简尚金额', '差异'], ['运费', 37923.5, 37612.5, 311], ['货款', 151323.6, 151323.6, 0], ['记账', null, -3645.9, 3645.9], ['未发出', 15, 0, 15], + ['汇总', 189262.1, 185290.2, 3971.9], ]]), '卿德客10月手工.xlsx', null, null, true); $this->post(route("business.$section.dropship-freight.import-summary-templates"), ['month' => '2026-10', 'files' => [$manual]]) ->assertRedirect()->assertSessionHas('dropship_message'); - $this->assertSame(['10月', '["运费","货款","记账"]', '汇总'], array_values((array) $db->table('dropship_summary_templates') + $this->assertSame(['10月', '["运费","货款","记账","未发出"]', '汇总'], array_values((array) $db->table('dropship_summary_templates') ->where('factory_id', $factory->id)->where('bill_month', '2026-10')->first(['title', 'labels', 'total_label']))); $november = app(DropshipFreightStore::class)->summaryTemplate($f, '2026-11'); - $this->assertSame(['11月', ['运费', '货款', '记账'], '2026-10'], [$november['title'], $november['labels'], $november['from']]); + $this->assertSame(['11月', ['运费', '货款', '记账', '未发出'], '2026-10'], [$november['title'], $november['labels'], $november['from']]); // 小汇总不要「代发」「退货」:默认样子没有,手工汇总里带了也去掉 $this->assertSame(['运费', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::DEFAULT['labels']); $this->assertSame(['运费', '货款', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::withoutDropped( @@ -180,19 +180,30 @@ final class DropshipFreightTest extends FeatureTestCase $this->assertSame('卿德客申通', $row[1]); $this->assertEquals(6, $row[2]); $this->assertSame('一致但运费有差', $row[count($row) - 2]); + // 核算运费后面是最终结算运费;运费差 = 厂家运费 − 最终结算运费 + $head = $recon[0]; + $at = array_search('核算运费', $head, true); + $this->assertSame('最终结算运费', $head[$at + 1]); + $under = collect($recon)->first(fn ($r) => $r[0] === '773444000003'); // 厂家 5、核算 6 → 按 5 结,运费差 0 + $this->assertEquals([6, 5], [$under[$at], $under[$at + 1]]); + $this->assertEquals(0, $under[array_search('运费差', $head, true)]); + $this->assertEquals([5, 5, 1], [$row[$at], $row[$at + 1], $row[array_search('运费差', $head, true)]]); // 厂家 6、核算 5:多开 1 $swapRow = collect($recon)->first(fn ($r) => $r[0] === 'OLD0000001'); $this->assertSame('773444000020', $swapRow[6]); $sheet = $book->getSheetByName('汇总'); $summary = $sheet->toArray(null, false, false); $this->assertSame(['10月', '厂家金额', '简尚金额', '差异'], array_slice($summary[0], 0, 4)); - $this->assertSame(['运费', '货款', '记账', '汇总'], [$summary[1][0], $summary[2][0], $summary[3][0], $summary[4][0]]); - $this->assertEquals([63, 28], [$summary[1][1], $summary[1][2]]); + // 厂家开了运费、这个月不付的按分类各加一行:原始 = 厂家开的,简尚 = 0,原始合计 = 厂家账单运费合计;上月手工汇总的「未发出」这个月没有,不留空行 + $this->assertSame(['运费', '货款', '记账', '快递不符', '匹配不到', '跨月订单-11月', '汇总'], array_column(array_slice($summary, 1, 7), 0)); + $this->assertEquals([33, 28], [$summary[1][1], $summary[1][2]]); // 运费:按我方结算的单厂家开 33,最终结算 28 $this->assertNull($summary[2][1]); // 货款先空着手工填 - $this->assertSame('=SUM(B2:B4)', $sheet->getCell('B5')->getValue()); // 合计是公式,手工填了跟着算 + $this->assertEquals([[23, 0], [3, 0], [4, 0]], [array_slice($summary[4], 1, 2), array_slice($summary[5], 1, 2), array_slice($summary[6], 1, 2)]); + $this->assertSame('=SUM(B2:B7)', $sheet->getCell('B8')->getValue()); // 合计是公式,手工填了跟着算 + $this->assertEquals(63, $sheet->getCell('B8')->getCalculatedValue()); $sheet->setCellValue('C4', -100); $this->assertEquals(100, $sheet->getCell('D4')->getCalculatedValue()); - $this->assertEquals(-72, $sheet->getCell('C5')->getCalculatedValue()); - $this->assertSame(5, $sheet->getHighestDataRow()); // 汇总块下面不再附别的 + $this->assertEquals(-72, $sheet->getCell('C8')->getCalculatedValue()); + $this->assertSame(8, $sheet->getHighestDataRow()); // 汇总块下面不再附别的 $this->assertSame([3, 1], [count($book->getSheetByName('快递不符')->toArray()) - 1, count($book->getSheetByName('匹配不到')->toArray()) - 1]); $book->disconnectWorksheets(); @unlink($out); @@ -302,8 +313,8 @@ final class DropshipFreightTest extends FeatureTestCase $data = $book->getSheetByName('对账')->toArray(null, false, false); $this->assertSame(['快递单号', '运费', '备注', '备注(2)'], array_slice($data[0], 0, 4)); $this->assertSame(['00012345678901234567', 4, ' 保留空格 ', '=1+1'], array_slice($data[1], 0, 4)); - $this->assertEquals(11, $data[1][count($data[0]) - 5]); - $this->assertSame(['厂家运费(这一单合计)', '结算运费', '最终结算运费'], array_slice($data[0], -5, 3)); + $this->assertEquals(11, $data[1][count($data[0]) - 4]); + $this->assertSame(['厂家运费(这一单合计)', '结算运费', '分类', '说明'], array_slice($data[0], -4)); $this->assertContains($book->getSheetByName('对账')->getCell('D2')->getDataType(), [ \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_INLINE, ]); @@ -410,6 +421,58 @@ final class DropshipFreightTest extends FeatureTestCase $this->post($save, ['month' => '2026-11', 'fees' => ['booking' => 'abc']])->assertSessionHasErrors('fees.booking'); // 页面上的快递运费 = 最终结算运费 $this->assertEquals(13, app(DropshipReconciler::class)->factoryMonth(collect(app(DropshipFreightStore::class)->factories())->sole(), '2026-11')['summary']['settle']); + // 「拦截退回」算拦截费 + $this->assertSame('intercept', \App\Support\DropshipFreight\DropshipFees::classify('拦截退回')); + + // 导出的小汇总:附加费表金额合计放「厂家账单-附加费」一行,简尚核对空着 + $out = tempnam(sys_get_temp_dir(), 'dropship_export_'); + $handle = fopen($out, 'wb'); + try { + app(DropshipExporter::class)->export(collect(app(DropshipFreightStore::class)->factories())->sole(), '2026-11', $handle); + } finally { + fclose($handle); + } + $book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out); + $sheet = $book->getSheetByName('汇总'); + $summary = $sheet->toArray(null, false, false); + $this->assertSame(['运费', '记账', '厂家账单-附加费', '合计'], array_column(array_slice($summary, 1, 4), 0)); + $this->assertEquals([13, 13], array_slice($summary[1], 1, 2)); + $this->assertEquals(6.5, $summary[3][1]); + $this->assertNull($summary[3][2]); + $this->assertEquals(19.5, $sheet->getCell('B5')->getCalculatedValue()); + $this->assertEquals(6.5, $sheet->getCell('D5')->getCalculatedValue()); + $book->disconnectWorksheets(); + @unlink($out); + } + + public function test_export_keeps_uncalculated_settlement_blank(): void + { + Storage::fake('local'); + $db = CourierBillMatcher::db(); + $factoryId = $db->table('dropship_factories')->insertGetId(['name' => '未核算测试厂家', 'warehouse' => self::WAREHOUSE, + 'keywords' => '测试快递', 'created_at' => now(), 'updated_at' => now()]); + $this->ship('UNCALCULATED0001', '测试快递', self::WAREHOUSE, '2026-11-03 09:00:00', 1, null); + $input = $this->xlsx(['账单' => [['快递单号', '运费'], ['UNCALCULATED0001', 6]]]); + $output = tempnam(sys_get_temp_dir(), 'uncalculated_export_'); + $book = null; + try { + $store = app(DropshipFreightStore::class); + $store->uploadFor('未核算.xlsx', $input, '2026-11', $factoryId, '测试'); + $handle = fopen($output, 'wb'); + try { + app(DropshipExporter::class)->export(collect($store->factories())->sole(), '2026-11', $handle); + } finally { + fclose($handle); + } + $book = \PhpOffice\PhpSpreadsheet\IOFactory::load($output); + $this->assertSame('运费', (string) $book->getSheetByName('汇总')->getCell('A2')->getValue()); + $this->assertEquals(6, $book->getSheetByName('汇总')->getCell('B2')->getValue()); + $this->assertNull($book->getSheetByName('汇总')->getCell('C2')->getValue()); + } finally { + $book?->disconnectWorksheets(); + @unlink($input); + @unlink($output); + } } public function test_keyword_helpers(): void