From b8aeea3e313b8a1f2679b6697447bba79ab1bfef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=9C=A8?= <594326199@qq.com> Date: Thu, 3 Dec 2026 18:04:32 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E4=BE=9B=E5=BA=94=E5=95=86=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6):=20=E9=9B=B6=E5=B7=AE=E5=BC=82=E4=B8=8A=E4=BC=A0?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=8E=A8=E9=80=81=E7=A1=AE=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ushSupplierZeroDifferenceConfirmations.php | 107 +++++++ .../Business/SupplierReconciliation.php | 35 ++- .../Portal/SupplierReconciliation.php | 35 ++- .../SupplierZeroDifferenceConfirmation.php | 288 ++++++++++++++++++ .../Business/SupplierReconciliationTest.php | 123 ++++++++ ...upplierZeroDifferenceConfirmationsTest.php | 82 +++++ 6 files changed, 656 insertions(+), 14 deletions(-) create mode 100644 app/Console/Commands/PushSupplierZeroDifferenceConfirmations.php create mode 100644 modules/EcommerceFinance/Services/SupplierZeroDifferenceConfirmation.php create mode 100644 tests/Feature/Console/PushSupplierZeroDifferenceConfirmationsTest.php diff --git a/app/Console/Commands/PushSupplierZeroDifferenceConfirmations.php b/app/Console/Commands/PushSupplierZeroDifferenceConfirmations.php new file mode 100644 index 000000000..7324ada5b --- /dev/null +++ b/app/Console/Commands/PushSupplierZeroDifferenceConfirmations.php @@ -0,0 +1,107 @@ +option('company')); + $month = trim((string) $this->option('month')); + if ($month === '') { + $month = now('Asia/Shanghai')->subMonthNoOverflow()->format('Y-m'); + } + if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) { + $this->error('账期格式必须为 YYYY-MM。'); + + return self::FAILURE; + } + + $suppliers = array_values(array_filter(array_map( + static fn (mixed $supplier): string => trim((string) $supplier), + (array) $this->option('supplier'), + ))); + if ($suppliers === []) { + $suppliers = $statements->uploadedSuppliers($companyId); + } + $suppliers = array_values(array_unique($suppliers)); + sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE); + if ($suppliers === []) { + $this->info('没有找到已上传对账单的厂家。'); + + return self::SUCCESS; + } + + $dryRun = (bool) $this->option('dry-run'); + $force = (bool) $this->option('force'); + $rows = []; + $pushed = 0; + $failed = 0; + $skipped = 0; + + foreach ($suppliers as $supplier) { + if ($dryRun) { + $assessment = $zeroDifferenceConfirmations->assess($supplier, $companyId, $month); + $status = $assessment['eligible'] ? '可推送' : '不推送'; + $reason = $assessment['reason']; + $qty = $assessment['qty']; + $amount = $assessment['amount']; + } else { + $result = $zeroDifferenceConfirmations->pushMonth( + $supplier, + $companyId, + $month, + null, + ! $force, + ); + $status = match ($result['status']) { + 'pushed' => '已推送', + 'failed' => '失败', + default => '跳过', + }; + $reason = $result['reason']; + $qty = $result['qty']; + $amount = $result['amount']; + if ($result['status'] === 'pushed') { + $pushed++; + } elseif ($result['status'] === 'failed') { + $failed++; + } else { + $skipped++; + } + } + + $rows[] = [ + $supplier, + $status, + rtrim(rtrim(number_format($qty, 2, '.', ''), '0'), '.'), + rtrim(rtrim(number_format($amount, 2, '.', ''), '0'), '.'), + $reason, + ]; + } + + $this->table(['厂家', '状态', '件数', '货款金额', '说明'], $rows); + if ($dryRun) { + $this->info("{$month} 检查完成,共 " . count($suppliers) . ' 家;未发送任何消息。'); + } else { + $this->info("{$month} 处理完成:已推送 {$pushed} 家,跳过 {$skipped} 家,失败 {$failed} 家。"); + } + + return $failed > 0 ? self::FAILURE : self::SUCCESS; + } +} diff --git a/app/Http/Controllers/Business/SupplierReconciliation.php b/app/Http/Controllers/Business/SupplierReconciliation.php index 0417ab82d..3bda4f2ac 100644 --- a/app/Http/Controllers/Business/SupplierReconciliation.php +++ b/app/Http/Controllers/Business/SupplierReconciliation.php @@ -16,6 +16,7 @@ use Modules\EcommerceFinance\Services\SupplierStatementMatcher; use Modules\EcommerceFinance\Services\SupplierStatementStore; use Modules\EcommerceFinance\Services\SupplierStatementTemplate; use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation; +use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation; use Modules\EcommerceFinance\View\SupplierReconciliationPageData; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\StreamedResponse; @@ -36,6 +37,7 @@ class SupplierReconciliation extends Controller private readonly SupplierComparisonCsvExporter $comparisonCsvExporter, private readonly SupplierPortalAccess $supplierPortalAccess, private readonly SupplierSummaryConfirmation $summaryConfirmations, + private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations, ) { $this->middleware('auth'); $this->middleware('company.identify'); @@ -69,23 +71,42 @@ class SupplierReconciliation extends Controller ); $message = "对账单已保存:{$supplier} 共 {$rows} 行"; - $receiptNotice = ''; + $notices = []; + $autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []]; if ($supplierPortalUpload) { try { - $receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt( + $autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload( $supplier, - (string) $request->file('import')->getClientOriginalName(), + (int) (company_id() ?: 1), $records, + user_id() ? (int) user_id() : null, ); - if ($receiptSent) { - $receiptNotice = ';上传回执已发送到该厂家钉钉群。'; + $autoPushNotice = $this->zeroDifferenceConfirmations->uploadNotice($autoPush); + if ($autoPushNotice !== '') { + $notices[] = $autoPushNotice; } } catch (Throwable $exception) { report($exception); - $receiptNotice = ';上传回执发送失败,对账单已正常保存。'; + $notices[] = '零差异对账确认自动推送失败,对账单已正常保存'; + } + + if (($autoPush['pushed'] ?? []) === []) { + try { + $receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt( + $supplier, + (string) $request->file('import')->getClientOriginalName(), + $records, + ); + if ($receiptSent) { + $notices[] = '上传回执已发送到该厂家钉钉群'; + } + } catch (Throwable $exception) { + report($exception); + $notices[] = '上传回执发送失败,对账单已正常保存'; + } } } - $message .= $receiptNotice !== '' ? $receiptNotice : '。'; + $message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。'; return $request->expectsJson() ? response()->json(['message' => $message, 'rows' => $rows]) diff --git a/app/Http/Controllers/Portal/SupplierReconciliation.php b/app/Http/Controllers/Portal/SupplierReconciliation.php index 72dfd758f..acb66ac75 100644 --- a/app/Http/Controllers/Portal/SupplierReconciliation.php +++ b/app/Http/Controllers/Portal/SupplierReconciliation.php @@ -13,6 +13,7 @@ use Modules\EcommerceFinance\Services\SupplierReturnCsvExporter; use Modules\EcommerceFinance\Services\SupplierReturnConfirmation; use Modules\EcommerceFinance\Services\SupplierStatementStore; use Modules\EcommerceFinance\Services\SupplierStatementTemplate; +use Modules\EcommerceFinance\Services\SupplierZeroDifferenceConfirmation; use Modules\EcommerceFinance\View\SupplierReconciliationPageData; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\StreamedResponse; @@ -30,6 +31,7 @@ class SupplierReconciliation extends Controller private readonly SupplierReconciliationPageData $pageData, private readonly SupplierReturnCsvExporter $returnCsvExporter, private readonly SupplierDingTalkNotifier $dingTalkNotifier, + private readonly SupplierZeroDifferenceConfirmation $zeroDifferenceConfirmations, ) { } @@ -74,21 +76,40 @@ class SupplierReconciliation extends Controller user_id() ? (int) user_id() : null, ); $message = "对账单已保存:{$supplier} 共 {$rows} 行"; - $receiptNotice = ''; + $notices = []; + $autoPush = ['pushed' => [], 'skipped' => [], 'failed' => []]; try { - $receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt( + $autoPush = $this->zeroDifferenceConfirmations->afterStatementUpload( $supplier, - (string) $request->file('import')->getClientOriginalName(), + $companyId, $records, + user_id() ? (int) user_id() : null, ); - if ($receiptSent) { - $receiptNotice = ';上传回执已发送到该厂家钉钉群。'; + $autoPushNotice = $this->zeroDifferenceConfirmations->uploadNotice($autoPush); + if ($autoPushNotice !== '') { + $notices[] = $autoPushNotice; } } catch (Throwable $exception) { report($exception); - $receiptNotice = ';上传回执发送失败,对账单已正常保存。'; + $notices[] = '零差异对账确认自动推送失败,对账单已正常保存'; } - $message .= $receiptNotice !== '' ? $receiptNotice : '。'; + + if (($autoPush['pushed'] ?? []) === []) { + try { + $receiptSent = $this->dingTalkNotifier->sendStatementUploadReceipt( + $supplier, + (string) $request->file('import')->getClientOriginalName(), + $records, + ); + if ($receiptSent) { + $notices[] = '上传回执已发送到该厂家钉钉群'; + } + } catch (Throwable $exception) { + report($exception); + $notices[] = '上传回执发送失败,对账单已正常保存'; + } + } + $message .= $notices === [] ? '。' : ';' . implode(';', $notices) . '。'; return $request->expectsJson() ? response()->json(['message' => $message, 'rows' => $rows]) diff --git a/modules/EcommerceFinance/Services/SupplierZeroDifferenceConfirmation.php b/modules/EcommerceFinance/Services/SupplierZeroDifferenceConfirmation.php new file mode 100644 index 000000000..7175f3361 --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierZeroDifferenceConfirmation.php @@ -0,0 +1,288 @@ +> $records + * @return list + */ + public function statementMonths(array $records): array + { + $months = []; + foreach ($records as $record) { + $date = trim((string) ($record['createdAt'] ?? $record['summary_month'] ?? '')); + if (preg_match('/^(\d{4})[-\/.](\d{1,2})/', $date, $matches) !== 1) { + continue; + } + + $month = (int) $matches[2]; + if ($month >= 1 && $month <= 12) { + $months[sprintf('%04d-%02d', (int) $matches[1], $month)] = true; + } + } + + $months = array_keys($months); + sort($months); + + return $months; + } + + /** + * @return array{ + * eligible:bool, + * month:string, + * reason:string, + * qty:float, + * amount:float, + * difference_count:int + * } + */ + public function assess(string $supplier, int $companyId, string $month): array + { + if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) { + return $this->assessment(false, $month, '账期格式无效'); + } + + $detail = $this->pageData->financeDetailForFilters($supplier, $companyId, [ + 'month' => $month, + ]); + if (($detail['awaitingUpload'] ?? false) === true) { + return $this->assessment(false, $month, '厂家尚未上传该账期对账单'); + } + + $rows = (array) ($detail['rows'] ?? []); + $differenceCount = (int) ($detail['difference_count'] ?? 0); + if ($rows === []) { + return $this->assessment(false, $month, '该账期没有可比对数据', 0, 0, $differenceCount); + } + if ($differenceCount > 0) { + return $this->assessment( + false, + $month, + "仍有 {$differenceCount} 条差异或未定价记录", + 0, + 0, + $differenceCount, + ); + } + + $summary = (array) ($detail['summary'] ?? []); + $sourceTotals = (array) ($detail['sourceTotals'] ?? []); + $differenceRows = (int) ($summary['supplierExtra'] ?? 0) + + (int) ($summary['mismatch'] ?? 0) + + (int) ($summary['supplierMissing'] ?? 0) + + (int) ($summary['unpriced'] ?? 0); + $mineQty = (float) ($sourceTotals['mineQty'] ?? 0); + $mineAmount = (float) ($sourceTotals['mineAmount'] ?? 0); + $theirsQty = (float) ($sourceTotals['theirsQty'] ?? 0); + $theirsAmount = (float) ($sourceTotals['theirsAmount'] ?? 0); + + if ( + $differenceRows > 0 + || abs($mineQty - $theirsQty) >= 0.005 + || abs($mineAmount - $theirsAmount) >= 0.005 + ) { + return $this->assessment( + false, + $month, + '双方件数或货款金额仍不一致', + 0, + 0, + max($differenceCount, $differenceRows), + ); + } + + $qty = (float) ($summary['settleQty'] ?? $theirsQty); + $amount = (float) ($summary['settleAmount'] ?? $theirsAmount); + if (abs($qty) < 0.00005 && abs($amount) < 0.005) { + return $this->assessment(false, $month, '该账期没有可确认的货款数据', 0, 0, 0); + } + + return [ + 'eligible' => true, + 'month' => $month, + 'reason' => '双方数据完全一致', + 'qty' => round($qty, 4), + 'amount' => round($amount, 2), + 'difference_count' => 0, + ]; + } + + /** + * @return array{ + * status:'pushed'|'skipped'|'failed', + * month:string, + * reason:string, + * qty:float, + * amount:float, + * difference_count:int + * } + */ + public function pushMonth( + string $supplier, + int $companyId, + string $month, + ?int $userId = null, + bool $skipExistingConfirmation = true, + ): array { + $assessment = $this->assess($supplier, $companyId, $month); + if ($assessment['eligible'] !== true) { + return ['status' => 'skipped'] + $assessment; + } + + if ($skipExistingConfirmation) { + $existing = $this->summaryConfirmations->latest( + $supplier, + $month, + 'settlement', + $companyId, + ); + $existingStatus = trim((string) ($existing['status'] ?? '')); + if (in_array($existingStatus, [ + SupplierSummaryConfirmation::STATUS_SENDING, + SupplierSummaryConfirmation::STATUS_PENDING, + SupplierSummaryConfirmation::STATUS_CONFIRMED, + ], true)) { + return [ + 'status' => 'skipped', + 'month' => $month, + 'reason' => $existingStatus === SupplierSummaryConfirmation::STATUS_CONFIRMED + ? '厂家已确认,默认不重复推送' + : '该账期已有待确认推送,默认不重复推送', + 'qty' => $assessment['qty'], + 'amount' => $assessment['amount'], + 'difference_count' => 0, + ]; + } + } + + try { + $result = $this->dingTalkNotifier->pushReconciliationSummary( + $supplier, + $month, + $assessment['qty'], + $assessment['amount'], + $companyId, + 'settlement', + $userId, + ); + } catch (Throwable $exception) { + return [ + 'status' => 'failed', + 'month' => $month, + 'reason' => $exception->getMessage(), + 'qty' => $assessment['qty'], + 'amount' => $assessment['amount'], + 'difference_count' => 0, + ]; + } + + return [ + 'status' => 'pushed', + 'month' => $month, + 'reason' => '已发送货款确认', + 'qty' => (float) ($result['qty'] ?? $assessment['qty']), + 'amount' => (float) ($result['amount'] ?? $assessment['amount']), + 'difference_count' => 0, + ]; + } + + /** + * @param list> $records + * @return array{ + * pushed:list>, + * skipped:list>, + * failed:list> + * } + */ + public function afterStatementUpload( + string $supplier, + int $companyId, + array $records, + ?int $userId = null, + ): array { + $result = ['pushed' => [], 'skipped' => [], 'failed' => []]; + foreach ($this->statementMonths($records) as $month) { + $push = $this->pushMonth( + $supplier, + $companyId, + $month, + $userId, + false, + ); + $result[$push['status']][] = $push; + } + + return $result; + } + + /** @param array{pushed:list>,failed:list>} $result */ + public function uploadNotice(array $result): string + { + $notices = []; + $pushed = (array) ($result['pushed'] ?? []); + if ($pushed !== []) { + $notices[] = '零差异对账确认已自动推送到该厂家钉钉群(' + . implode('、', array_map( + fn (array $row): string => $this->displayMonth((string) $row['month']), + $pushed, + )) + . ')'; + } + + $failed = (array) ($result['failed'] ?? []); + if ($failed !== []) { + $notices[] = '零差异对账确认自动推送失败(' + . implode('、', array_map( + fn (array $row): string => $this->displayMonth((string) $row['month']) + . ':' . (string) ($row['reason'] ?? '未知错误'), + $failed, + )) + . ')'; + } + + return implode(';', array_filter($notices)); + } + + private function assessment( + bool $eligible, + string $month, + string $reason, + float $qty = 0, + float $amount = 0, + int $differenceCount = 0, + ): array { + return [ + 'eligible' => $eligible, + 'month' => $month, + 'reason' => $reason, + 'qty' => $qty, + 'amount' => $amount, + 'difference_count' => $differenceCount, + ]; + } + + private function displayMonth(string $month): string + { + if (preg_match('/^(\d{4})-(\d{1,2})$/', $month, $matches) !== 1) { + return $month; + } + + return (int) $matches[1] . '年' . (int) $matches[2] . '月'; + } +} diff --git a/tests/Feature/Business/SupplierReconciliationTest.php b/tests/Feature/Business/SupplierReconciliationTest.php index d59b547fc..75949dac8 100644 --- a/tests/Feature/Business/SupplierReconciliationTest.php +++ b/tests/Feature/Business/SupplierReconciliationTest.php @@ -22,6 +22,7 @@ use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; use Modules\EcommerceFinance\Services\SupplierStatementMatcher; use Modules\EcommerceFinance\Services\SupplierStatementStore; use Modules\EcommerceFinance\Services\SupplierStatementTemplate; +use Modules\EcommerceFinance\Services\SupplierSummaryConfirmation; use Modules\EcommerceFinance\View\SupplierReconciliationPageData; use Tests\Feature\FeatureTestCase; @@ -1533,6 +1534,128 @@ class SupplierReconciliationTest extends FeatureTestCase Carbon::setTestNow(); } + public function test_supplier_portal_upload_with_zero_difference_automatically_pushes_summary_confirmation(): void + { + $companyId = (int) $this->company->id; + $supplierUser = $this->createSupplierPortalUser('晨丰'); + app(SupplierDingTalkNotifier::class)->save( + '晨丰', + 'https://oapi.dingtalk.com/robot/send?access_token=statement-zero-diff-test', + '', + false, + ); + app(SupplierPayableOverrideStore::class)->save( + 'final:supplier:payment-reconciliation', + 'mine:zero-difference-upload', + [ + 'summary_month' => '2026-09', + 'purchaseNo' => 'PO-ZERO-DIFF', + 'date' => '2026-09-30', + 'supplier' => '晨丰', + 'skuCode' => 'ZSJ-ZERO', + 'productCode' => 'ZSJ-ZERO', + 'qty' => '2', + 'unitPrice' => '128', + 'amount' => '256', + ], + $companyId, + null, + ); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + $file = UploadedFile::fake()->createWithContent( + 'zero_difference_202609.csv', + "\xEF\xBB\xBF" . self::HEADER . "\n" + . ",,PO-ZERO-DIFF,2026-09-30,晨丰,ZSJ-ZERO,规格甲,2,128.00,256.00\n", + ); + + $this->actingAsSupplierPortal($supplierUser) + ->post(route('business.supplier-reconciliation.statement.upload', ['company_id' => $companyId]), [ + 'supplier' => '晨丰', + 'import' => $file, + ]) + ->assertStatus(302) + ->assertSessionHas( + 'success', + '对账单已保存:晨丰 共 1 行;零差异对账确认已自动推送到该厂家钉钉群(2026年9月)。', + ); + + Http::assertSentCount(1); + Http::assertSent(fn ($request): bool => str_contains( + (string) ($request['markdown']['text'] ?? ''), + '供应商货款对账确认 · 晨丰', + ) && str_contains( + (string) ($request['markdown']['text'] ?? ''), + '件数:**2** 件', + ) && str_contains( + (string) ($request['markdown']['text'] ?? ''), + '货款:**¥256.00**', + )); + $confirmation = app(SupplierSummaryConfirmation::class)->latest( + '晨丰', + '2026-09', + 'settlement', + $companyId, + ); + $this->assertSame(SupplierSummaryConfirmation::STATUS_PENDING, $confirmation['status'] ?? null); + } + + public function test_vendor_portal_upload_with_zero_difference_automatically_pushes_summary_confirmation(): void + { + $companyId = (int) $this->company->id; + $vendor = $this->createVendorPortalUser('晨丰'); + app(SupplierDingTalkNotifier::class)->save( + '晨丰', + 'https://oapi.dingtalk.com/robot/send?access_token=vendor-zero-diff-test', + '', + false, + ); + app(SupplierPayableOverrideStore::class)->save( + 'final:supplier:payment-reconciliation', + 'mine:vendor-zero-difference-upload', + [ + 'summary_month' => '2026-09', + 'purchaseNo' => 'PO-VENDOR-ZERO', + 'date' => '2026-09-30', + 'supplier' => '晨丰', + 'skuCode' => 'ZSJ-VENDOR-ZERO', + 'productCode' => 'ZSJ-VENDOR-ZERO', + 'qty' => '1', + 'unitPrice' => '100', + 'amount' => '100', + ], + $companyId, + null, + ); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + $file = UploadedFile::fake()->createWithContent( + 'vendor_zero_difference_202609.csv', + "\xEF\xBB\xBF" . self::HEADER . "\n" + . ",,PO-VENDOR-ZERO,2026-09-30,晨丰,ZSJ-VENDOR-ZERO,规格甲,1,100.00,100.00\n", + ); + + $this->loginAs($vendor) + ->post(route('portal.supplier-reconciliation.statement.upload', ['company_id' => $companyId]), [ + 'import' => $file, + ]) + ->assertStatus(302) + ->assertSessionHas( + 'success', + '对账单已保存:晨丰 共 1 行;零差异对账确认已自动推送到该厂家钉钉群(2026年9月)。', + ); + + Http::assertSentCount(1); + Http::assertSent(fn ($request): bool => str_contains( + (string) ($request['markdown']['text'] ?? ''), + '供应商货款对账确认 · 晨丰', + ) && str_contains( + (string) ($request['markdown']['text'] ?? ''), + '件数:**1** 件', + ) && str_contains( + (string) ($request['markdown']['text'] ?? ''), + '货款:**¥100.00**', + )); + } + public function test_supplier_statement_upload_sends_a_dingtalk_receipt(): void { $supplierUser = $this->createSupplierPortalUser('晨丰'); diff --git a/tests/Feature/Console/PushSupplierZeroDifferenceConfirmationsTest.php b/tests/Feature/Console/PushSupplierZeroDifferenceConfirmationsTest.php new file mode 100644 index 000000000..bfdc3358c --- /dev/null +++ b/tests/Feature/Console/PushSupplierZeroDifferenceConfirmationsTest.php @@ -0,0 +1,82 @@ +shouldReceive('uploadedSuppliers')->once()->with(1)->andReturn(['零差异厂家', '有差异厂家']); + $this->app->instance(SupplierStatementStore::class, $statements); + + $confirmation = Mockery::mock(SupplierZeroDifferenceConfirmation::class); + $confirmation->shouldReceive('assess') + ->once() + ->with('零差异厂家', 1, '2026-11') + ->andReturn($this->assessment(true, '零差异厂家', 12, 1200)); + $confirmation->shouldReceive('assess') + ->once() + ->with('有差异厂家', 1, '2026-11') + ->andReturn($this->assessment(false, '仍有 2 条差异', 10, 1000, 2)); + $confirmation->shouldNotReceive('pushMonth'); + $this->app->instance(SupplierZeroDifferenceConfirmation::class, $confirmation); + + $this->artisan('supplier-reconciliation:push-zero-difference-confirmations', [ + '--month' => '2026-11', + '--company' => 1, + '--dry-run' => true, + ])->expectsOutputToContain('未发送任何消息') + ->assertSuccessful(); + } + + public function test_real_run_pushes_eligible_suppliers_and_skips_existing_confirmations(): void + { + $statements = Mockery::mock(SupplierStatementStore::class); + $statements->shouldReceive('uploadedSuppliers')->once()->with(1)->andReturn(['零差异厂家']); + $this->app->instance(SupplierStatementStore::class, $statements); + + $confirmation = Mockery::mock(SupplierZeroDifferenceConfirmation::class); + $confirmation->shouldReceive('pushMonth') + ->once() + ->with('零差异厂家', 1, '2026-11', null, true) + ->andReturn([ + 'status' => 'skipped', + 'month' => '2026-11', + 'reason' => '该账期已有待确认推送,默认不重复推送', + 'qty' => 12, + 'amount' => 1200, + 'difference_count' => 0, + ]); + $this->app->instance(SupplierZeroDifferenceConfirmation::class, $confirmation); + + $this->artisan('supplier-reconciliation:push-zero-difference-confirmations', [ + '--month' => '2026-11', + '--company' => 1, + ])->expectsOutputToContain('已推送 0 家,跳过 1 家,失败 0 家') + ->assertSuccessful(); + } + + /** @return array */ + private function assessment( + bool $eligible, + string $reason, + float $qty, + float $amount, + int $differenceCount = 0, + ): array { + return [ + 'eligible' => $eligible, + 'month' => '2026-11', + 'reason' => $reason, + 'qty' => $qty, + 'amount' => $amount, + 'difference_count' => $differenceCount, + ]; + } +}