diff --git a/modules/EcommerceFinance/Services/SupplierStatementMatcher.php b/modules/EcommerceFinance/Services/SupplierStatementMatcher.php index ece39993..2b792b82 100644 --- a/modules/EcommerceFinance/Services/SupplierStatementMatcher.php +++ b/modules/EcommerceFinance/Services/SupplierStatementMatcher.php @@ -6,6 +6,7 @@ use Carbon\CarbonImmutable; /** * 厂家对账单 vs 我方结算数据: + * - 双方都有快递单号时,第一层按「快递单号 + 商品编码」归组并比较; * - 行键 = 采购单号 + 日期 + 我方商品编码(对应厂家条码去掉厂家编号/版本后缀); * - 同一行键的多行先合并数量与金额,再比较双方数量和金额; * - 严格行键未匹配时,采购单号+商品编码一致、数量金额一致且日期相差不超过 7 天,仍按一致处理; @@ -29,13 +30,14 @@ class SupplierStatementMatcher private const DATE_TOLERANCE_DAYS = 7; /** - * @param list> $mine 我方数据(purchaseNo/date/productCode/unitPrice/qty/amount;productCode 为空才回退货号) - * @param list> $theirs 厂家数据(purchaseNo/createdAt/barcode/unitPrice/qty/amount) + * @param list> $mine 我方数据(expressNo/purchaseNo/date/productCode/unitPrice/qty/amount;productCode 为空才回退货号) + * @param list> $theirs 厂家数据(expressNo/purchaseNo/createdAt/barcode/unitPrice/qty/amount) * @return array{rows:list>,summary:array} */ public function compare(array $mine, array $theirs): array { $mine = $this->deduplicateMineRows($mine, $theirs); + [$mine, $theirs, $mineExpress, $theirsExpress] = $this->matchExpressGroups($mine, $theirs); $mineGrouped = $this->group($mine, ['productCode', 'skuCode'], 'purchaseNo', 'date'); $theirsGrouped = $this->group($theirs, ['barcode'], 'purchaseNo', 'createdAt'); @@ -47,6 +49,8 @@ class SupplierStatementMatcher $theirsGrouped = $this->resolveMissingPurchaseNumbers($theirsGrouped, $fallbackIndex); [$mineGrouped, $theirsGrouped] = $this->matchDateToleranceGroups($mineGrouped, $theirsGrouped); [$mineGrouped, $theirsGrouped] = $this->matchUnrecognizedDateGroups($mineGrouped, $theirsGrouped); + $mineGrouped += $mineExpress; + $theirsGrouped += $theirsExpress; $rows = []; $summary = [ @@ -69,6 +73,7 @@ class SupplierStatementMatcher $date = (string) ($mineRow['date'] ?? $theirsRow['date'] ?? ''); $barcode = (string) ($mineRow['barcode'] ?? $theirsRow['barcode'] ?? ''); $supplierBarcode = (string) ($theirsRow['supplierBarcode'] ?? ''); + $expressNo = (string) ($theirsRow['expressNo'] ?? $mineRow['expressNo'] ?? ''); $mineUnitPrice = (float) ($mineRow['unitPrice'] ?? 0); $theirsUnitPrice = (float) ($theirsRow['unitPrice'] ?? 0); $unitPrice = $mineUnitPrice > 0 ? $mineUnitPrice : $theirsUnitPrice; @@ -81,7 +86,9 @@ class SupplierStatementMatcher $quantityDifference = $this->describeDifference($qtyDifference, $amountDifference); $dateToleranceDays = (int) ($theirsRow['dateToleranceDays'] ?? 0); $fallbackNote = ''; - if (($theirsRow['matchedByFallback'] ?? false) === true) { + if (($theirsRow['matchedByExpress'] ?? false) === true) { + $fallbackNote = '已优先按快递单号+商品编码匹配;'; + } elseif (($theirsRow['matchedByFallback'] ?? false) === true) { $fallbackNote = '厂家未填采购单号,已按日期+商品编码唯一匹配;'; } elseif (($theirsRow['matchedByUnrecognizedDate'] ?? false) === true) { $dateCount = (int) ($mineRow['dateCount'] ?? 0); @@ -108,7 +115,9 @@ class SupplierStatementMatcher } elseif (abs($mineAmount - $theirsAmount) < 0.005 && abs($mineQty - $theirsQty) < 0.005) { $type = self::TYPE_MATCH; $settle = $mineAmount; - if (($theirsRow['matchedByUnrecognizedDate'] ?? false) === true) { + if (($theirsRow['matchedByExpress'] ?? false) === true) { + $note = $fallbackNote . '快递单号和商品编码对应的数量、金额一致,正常结算'; + } elseif (($theirsRow['matchedByUnrecognizedDate'] ?? false) === true) { $note = $fallbackNote . '采购单号、商品编码、数量和金额一致,正常结算'; } else { $note = $fallbackNote . ($dateToleranceDays > 0 @@ -135,6 +144,7 @@ class SupplierStatementMatcher 'date' => $date, 'barcode' => $barcode, 'supplierBarcode' => $supplierBarcode !== '' && $supplierBarcode !== $barcode ? $supplierBarcode : '', + 'expressNo' => $expressNo, 'unitPrice' => $unitPrice, 'mineUnitPrice' => $mineUnitPrice, 'theirsUnitPrice' => $theirsUnitPrice, @@ -177,6 +187,133 @@ class SupplierStatementMatcher return ['rows' => $rows, 'summary' => $summary]; } + /** + * 快递单号是双方都有的强关联键,先按「快递单号 + 商品编码」汇总匹配。 + * 已进入第一层的记录不再参与采购单号、日期等后续兜底,避免同一行被重复解释。 + * + * @param list> $mine + * @param list> $theirs + * @return array{ + * 0:list>, + * 1:list>, + * 2:array>, + * 3:array> + * } + */ + private function matchExpressGroups(array $mine, array $theirs): array + { + $mineGroups = $this->groupByExpress($mine, true); + $theirsGroups = $this->groupByExpress($theirs, false); + $matchedMine = array_intersect_key($mineGroups, $theirsGroups); + if ($matchedMine === []) { + return [$mine, $theirs, [], []]; + } + + $matchedKeys = array_fill_keys(array_keys($matchedMine), true); + $withoutMatchedRows = function (array $rows, bool $mineSide) use ($matchedKeys): array { + $remaining = []; + foreach ($rows as $row) { + $key = $this->expressMatchKeyForRow($row, $mineSide); + if ($key !== null && isset($matchedKeys[$key])) { + continue; + } + $remaining[] = $row; + } + + return $remaining; + }; + + return [ + $withoutMatchedRows($mine, true), + $withoutMatchedRows($theirs, false), + $matchedMine, + array_intersect_key($theirsGroups, $matchedKeys), + ]; + } + + /** + * @param list> $rows + * @return array> + */ + private function groupByExpress(array $rows, bool $mineSide): array + { + $grouped = []; + foreach ($rows as $row) { + $barcode = $this->barcodeValue($row, $mineSide ? ['productCode', 'skuCode'] : ['barcode']); + $expressNo = $this->normalizeExpressNo($this->firstValue($row, ['expressNo', 'express_no'])); + if ($barcode === '' || $expressNo === '') { + continue; + } + + $barcodeKey = $this->normalizeBarcode($barcode); + $key = $this->expressMatchKey($expressNo, $barcodeKey); + $purchaseNo = $this->normalizePurchaseNo($row['purchaseNo'] ?? ''); + $date = $this->normalizeDate($row[$mineSide ? 'date' : 'createdAt'] ?? ''); + $unitPrice = (float) ($row['unitPrice'] ?? 0); + $grouped[$key] ??= [ + 'purchaseNo' => $purchaseNo, + 'date' => $date, + 'barcode' => $barcode, + 'barcodeKey' => $barcodeKey, + 'supplierBarcode' => $mineSide ? '' : $barcode, + 'expressNo' => trim((string) $this->firstValue($row, ['expressNo', 'express_no'])), + 'unitPrice' => $unitPrice, + 'unitPrices' => [], + 'qty' => 0.0, + 'amount' => 0.0, + 'matchedByExpress' => true, + 'matchedByFallback' => false, + 'fallbackAmbiguous' => false, + 'dates' => [], + ]; + if ($purchaseNo !== '' && $grouped[$key]['purchaseNo'] === '') { + $grouped[$key]['purchaseNo'] = $purchaseNo; + } + if ($date !== '') { + $grouped[$key]['dates'][$date] = true; + } + if ($unitPrice > 0) { + $grouped[$key]['unitPrices'][number_format($unitPrice, 4, '.', '')] = true; + } + $grouped[$key]['qty'] += (float) ($row['qty'] ?? 0); + $grouped[$key]['amount'] += (float) ($row['amount'] ?? 0); + } + + foreach ($grouped as &$group) { + $dates = array_keys((array) $group['dates']); + sort($dates); + unset($group['dates']); + $group['dateCount'] = max(count($dates), 1); + if ($dates !== []) { + $group['date'] = $dates[0]; + if (count($dates) > 1) { + $group['dateEnd'] = $dates[array_key_last($dates)]; + } + } + $group = $this->finalizeGroup($group); + } + unset($group); + + return $grouped; + } + + /** @param array $row */ + private function expressMatchKeyForRow(array $row, bool $mineSide): ?string + { + $expressNo = $this->normalizeExpressNo($this->firstValue($row, ['expressNo', 'express_no'])); + $barcode = $this->barcodeValue($row, $mineSide ? ['productCode', 'skuCode'] : ['barcode']); + if ($expressNo === '' || $barcode === '') { + return null; + } + + return $this->expressMatchKey($expressNo, $this->normalizeBarcode($barcode)); + } + + private function expressMatchKey(string $expressNo, string $barcodeKey): string + { + return "express\0" . $expressNo . "\0" . $barcodeKey; + } + /** * 同日期、条码、数量和金额一致,仅采购单号不同的我方记录属于重复来源。 * 厂家数据中有对应采购单号时保留该行;双方都没有明确采购单号时才退回首行。 @@ -303,6 +440,12 @@ class SupplierStatementMatcher /** @param array $row @param list $fields */ private function barcodeValue(array $row, array $fields): string + { + return $this->firstValue($row, $fields); + } + + /** @param array $row @param list $fields */ + private function firstValue(array $row, array $fields): string { foreach ($fields as $field) { $value = trim((string) ($row[$field] ?? '')); @@ -550,6 +693,14 @@ class SupplierStatementMatcher return preg_match('/^(\d+)\.0+$/', $purchaseNo, $matches) === 1 ? $matches[1] : $purchaseNo; } + private function normalizeExpressNo(mixed $value): string + { + $expressNo = preg_replace('/\s+/u', '', trim((string) $value)) ?? ''; + $expressNo = ltrim($expressNo, "'@"); + + return preg_match('/^(\d+)\.0+$/', $expressNo, $matches) === 1 ? $matches[1] : strtoupper($expressNo); + } + private function normalizeDate(mixed $value): string { $raw = trim((string) $value); diff --git a/resources/views/business/pages/supplier-reconciliation/finance-data.blade.php b/resources/views/business/pages/supplier-reconciliation/finance-data.blade.php index 7c4ce478..f1e2b89a 100644 --- a/resources/views/business/pages/supplier-reconciliation/finance-data.blade.php +++ b/resources/views/business/pages/supplier-reconciliation/finance-data.blade.php @@ -127,7 +127,7 @@ @endif

- 比对口径:优先按「采购单号 + 日期 + 商品编码」核对,以我方货款对账的“商品编码”匹配厂家条码;同一采购单号、日期和商品编码的多行先合并数量与金额。 + 比对口径:双方都有快递单号时,第一层优先按「快递单号 + 商品编码」汇总核对;没有快递单号或第一层无法匹配时,再按「采购单号 + 日期 + 商品编码」核对,以我方货款对账的“商品编码”匹配厂家条码;同一匹配键的多行先合并数量与金额。 日期未对上时,如采购单号+商品编码一致、数量金额一致且日期相差不超过 7 天,仍按一致处理。
数量、金额一致 → 正常结算;厂家多(我方没有)→ 不结算、退回修改; 数量或金额不一致 → 明确列出双方数量、单价、金额及厂家多算部分,取金额低的一方结算; diff --git a/tests/Feature/Business/SupplierReconciliationTest.php b/tests/Feature/Business/SupplierReconciliationTest.php index 6f1f63a9..92d101fc 100644 --- a/tests/Feature/Business/SupplierReconciliationTest.php +++ b/tests/Feature/Business/SupplierReconciliationTest.php @@ -54,12 +54,56 @@ class SupplierReconciliationTest extends FeatureTestCase ->assertSeeText('厂家端数据') ->assertSeeText('厂家多') ->assertSeeText('取金额低的一方结算') + ->assertSeeText('第一层优先按「快递单号 + 商品编码」') ->assertSeeText('采购单号 + 日期 + 商品编码') ->assertSee('list="finance-supplier-options"', false) ->assertSeeText('对账人') ->assertSeeText('下载对账单模板'); } + public function test_comparison_uses_express_number_and_barcode_before_purchase_or_date(): void + { + $companyId = (int) $this->company->id; + app(SupplierPayableOverrideStore::class)->save( + 'final:supplier:payment-reconciliation', + 'express:000001', + [ + 'summary_month' => '2026-10', + 'expressNo' => '@SF123456', + 'purchaseNo' => 'MINE-PO', + 'date' => '2026-10-01', + 'supplier' => '晨丰', + 'skuCode' => 'CZ000927', + 'productCode' => 'CZ000927N1201V02', + 'qty' => '7', + 'unitPrice' => '86', + 'amount' => '602', + ], + $companyId, + null, + ); + $this->seedStatement('晨丰', [ + array_merge($this->statementRow('CZ000927N1201V01', '86.00', '7', '602.00'), [ + 'expressNo' => 'SF123456', + 'purchaseNo' => null, + 'createdAt' => '2026-10-09', + ]), + ]); + + $detail = app(SupplierReconciliationPageData::class)->financeDetailForFilters( + '晨丰', + $companyId, + ['month' => '2026-10'], + ); + + $this->assertSame(1, $detail['summary']['match']); + $this->assertSame(0, $detail['summary']['supplierExtra']); + $this->assertSame(0, $detail['summary']['supplierMissing']); + $this->assertSame(0, $detail['summary']['mismatch']); + $this->assertSame('SF123456', $detail['rows'][0]['expressNo']); + $this->assertStringContainsString('已优先按快递单号+商品编码匹配', $detail['rows'][0]['note']); + } + public function test_finance_supplier_list_shows_return_confirmation_progress(): void { $companyId = (int) $this->company->id; diff --git a/tests/Unit/EcommerceFinance/SupplierStatementMatcherTest.php b/tests/Unit/EcommerceFinance/SupplierStatementMatcherTest.php index d7e4e335..89c804e6 100644 --- a/tests/Unit/EcommerceFinance/SupplierStatementMatcherTest.php +++ b/tests/Unit/EcommerceFinance/SupplierStatementMatcherTest.php @@ -305,4 +305,75 @@ class SupplierStatementMatcherTest extends TestCase $this->assertSame('SJ009363N160V01', $differences[0]['barcode']); $this->assertSame(20.0, $differences[0]['qtyDifference']); } + + public function test_express_number_and_barcode_are_the_primary_match_key(): void + { + $mine = [[ + 'expressNo' => '@sf123456', + 'purchaseNo' => 'MINE-PO', + 'date' => '2026-10-01', + 'skuCode' => 'CZ000927', + 'productCode' => 'CZ000927N1201V02', + 'qty' => '7', + 'amount' => '602', + ]]; + $theirs = [[ + 'expressNo' => 'SF123456', + 'purchaseNo' => '', + 'createdAt' => '2026-10-09', + 'barcode' => 'CZ000927N1201V01', + 'qty' => '7', + 'amount' => '602', + ]]; + + $result = (new SupplierStatementMatcher())->compare($mine, $theirs); + + $this->assertSame(1, $result['summary']['match']); + $this->assertSame(0, $result['summary']['supplierExtra']); + $this->assertSame(0, $result['summary']['supplierMissing']); + $this->assertSame(0, $result['summary']['mismatch']); + $this->assertSame('SF123456', $result['rows'][0]['expressNo']); + $this->assertStringContainsString('已优先按快递单号+商品编码匹配', $result['rows'][0]['note']); + } + + public function test_express_primary_match_aggregates_same_tracking_and_barcode_rows(): void + { + $mine = [ + [ + 'expressNo' => 'SF10001', + 'purchaseNo' => '', + 'date' => '2026-10-01', + 'skuCode' => 'CZ000927', + 'qty' => '2', + 'amount' => '172', + ], + [ + 'expressNo' => 'SF10001', + 'purchaseNo' => '', + 'date' => '2026-10-02', + 'skuCode' => 'CZ000927', + 'qty' => '5', + 'amount' => '430', + ], + ]; + $theirs = [[ + 'expressNo' => 'SF10001', + 'purchaseNo' => '', + 'createdAt' => '2026-10-08', + 'barcode' => 'CZ000927N1201V01', + 'qty' => '8', + 'amount' => '688', + ]]; + + $result = (new SupplierStatementMatcher())->compare($mine, $theirs); + + $this->assertSame(0, $result['summary']['match']); + $this->assertSame(1, $result['summary']['mismatch']); + $this->assertSame(0, $result['summary']['supplierExtra']); + $this->assertSame(0, $result['summary']['supplierMissing']); + $this->assertSame(7.0, $result['rows'][0]['mineQty']); + $this->assertSame(602.0, $result['rows'][0]['mineAmount']); + $this->assertSame(1.0, $result['rows'][0]['qtyDifference']); + $this->assertStringContainsString('已优先按快递单号+商品编码匹配', $result['rows'][0]['note']); + } }