From 801df996d476ec9de2d4fd3430e6e527fafaf7d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=9C=A8?= <594326199@qq.com> Date: Mon, 2 Nov 2026 22:02:18 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86=E6=95=B4=E6=9C=88=E9=80=80=E8=B4=A7=E9=92=89=E9=92=89?= =?UTF-8?q?=E6=8E=A8=E9=80=81=20(#833)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加供应商对账整月退货推送入口,支持全部确认状态、按消息容量自动分批、不限制退货行数;补充设置字段容量迁移。 Co-authored-by: 苏木 <594326199@qq.com> Co-committed-by: 苏木 <594326199@qq.com> --- .../Business/SupplierReconciliation.php | 27 +++ ...ngs_value_for_supplier_dingtalk_robots.php | 38 +++ .../Services/SupplierDingTalkNotifier.php | 226 +++++++++++++++++- .../View/SupplierReconciliationPageData.php | 53 +++- .../finance-data.blade.php | 38 ++- routes/admin.php | 4 + .../SupplierReconciliationDingTalkTest.php | 160 +++++++++++++ 7 files changed, 537 insertions(+), 9 deletions(-) create mode 100644 database/migrations/2026_11_02_181500_expand_settings_value_for_supplier_dingtalk_robots.php diff --git a/app/Http/Controllers/Business/SupplierReconciliation.php b/app/Http/Controllers/Business/SupplierReconciliation.php index 4d60a922..1fa85343 100644 --- a/app/Http/Controllers/Business/SupplierReconciliation.php +++ b/app/Http/Controllers/Business/SupplierReconciliation.php @@ -207,6 +207,33 @@ class SupplierReconciliation extends Controller ); } + public function pushReturns(Request $request): RedirectResponse + { + $request->validate([ + 'supplier' => ['required', 'string', 'max:191'], + 'month' => ['required', 'string', 'regex:/^\d{4}-\d{2}$/'], + ]); + [$supplier, $companyId] = $this->returnTarget($request); + $month = trim((string) $request->input('month')); + $returns = $this->pageData->returnRowsForMonth($supplier, $companyId, $month); + if ($returns === []) { + return back()->withErrors([ + 'dingtalk_return_push' => "该厂家在 {$month} 没有可推送的退货数据。", + ]); + } + + try { + $result = $this->dingTalkNotifier->pushReturns($supplier, $returns, $month); + } catch (Throwable $exception) { + return back()->withErrors(['dingtalk_return_push' => '推送失败:' . $exception->getMessage()]); + } + + return back()->with( + 'success', + "已推送 {$result['rows']} 条退货到 {$supplier} 钉钉群({$month},{$result['messages']} 条消息)。", + ); + } + private function markReturn(Request $request, string $status, string $message): RedirectResponse { $request->validate(['key' => ['required', 'string', 'max:191']]); diff --git a/database/migrations/2026_11_02_181500_expand_settings_value_for_supplier_dingtalk_robots.php b/database/migrations/2026_11_02_181500_expand_settings_value_for_supplier_dingtalk_robots.php new file mode 100644 index 00000000..7442a7ce --- /dev/null +++ b/database/migrations/2026_11_02_181500_expand_settings_value_for_supplier_dingtalk_robots.php @@ -0,0 +1,38 @@ +mediumText('value')->nullable()->change(); + }); + } + + public function down(): void + { + if (DB::getDriverName() !== 'mysql') { + return; + } + + $maxLength = (int) DB::table('settings') + ->selectRaw('MAX(CHAR_LENGTH(value)) AS max_length') + ->value('max_length'); + if ($maxLength > 65535) { + return; + } + + Schema::table('settings', function (Blueprint $table): void { + $table->text('value')->nullable()->change(); + }); + } +}; diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index d0da1b14..899280bf 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -9,7 +9,7 @@ use RuntimeException; use Throwable; /** - * 货款对账差异:按供应商保存钉钉群机器人,并推送当前比对差异。 + * 供应商对账:按供应商保存钉钉群机器人,推送货款差异或整月退货。 */ class SupplierDingTalkNotifier { @@ -19,6 +19,9 @@ class SupplierDingTalkNotifier private const MAX_MESSAGES = 20; + /** 钉钉单条内容有大小上限;这里留出 JSON 与签名参数的安全余量。 */ + private const RETURN_MESSAGE_MAX_BYTES = 18_000; + /** @return array{configured:bool,webhook_hint:string,at_all:bool,last_pushed_at:string,last_push_count:int} */ public function configuration(string $supplier): array { @@ -116,6 +119,52 @@ class SupplierDingTalkNotifier return ['messages' => count($chunks), 'rows' => count($differences)]; } + /** + * @param list> $returns + * @return array{messages:int,rows:int} + */ + public function pushReturns(string $supplier, array $returns, string $month): array + { + if ($returns === []) { + throw ValidationException::withMessages([ + 'dingtalk_return_push' => '该厂家在 ' . $month . ' 没有可推送的退货数据。', + ]); + } + + $configs = $this->configs(); + $config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : []; + $webhook = trim((string) ($config['webhook'] ?? '')); + if ($webhook === '') { + throw ValidationException::withMessages([ + 'dingtalk_return_push' => '该厂家还没有配置钉钉群机器人 Webhook。', + ]); + } + $this->assertWebhook($webhook); + + $summary = $this->summarizeReturns($returns); + $chunks = $this->returnMessageChunks($supplier, $returns, $summary, $month); + $total = count($chunks); + $rowOffset = 0; + foreach ($chunks as $index => $chunk) { + $title = $supplier . ' · 供应商退货对账 · ' . $month; + $this->send( + $webhook, + trim((string) ($config['secret'] ?? '')), + (bool) ($config['at_all'] ?? false), + $title, + $this->returnMessage($supplier, $chunk, $summary, $month, $index + 1, $total, $rowOffset), + ); + $rowOffset += count($chunk); + } + + $config['last_pushed_at'] = now()->format('Y-m-d H:i:s'); + $config['last_push_count'] = count($returns); + $configs[$supplier] = $config; + $this->persist($configs); + + return ['messages' => count($chunks), 'rows' => count($returns)]; + } + /** * @param list> $rows * @return array{count:int,extra:int,mismatch:int,missing:int,difference_amount:float} @@ -144,6 +193,162 @@ class SupplierDingTalkNotifier return $summary; } + /** + * @param list> $rows + * @return array{count:int,qty:float,amount:float,pending:int,confirmed:int,disputed:int} + */ + public function summarizeReturns(array $rows): array + { + $summary = [ + 'count' => count($rows), + 'qty' => 0.0, + 'amount' => 0.0, + 'pending' => 0, + 'confirmed' => 0, + 'disputed' => 0, + ]; + + foreach ($rows as $row) { + $summary['qty'] += (float) ($row['_supplier_qty'] ?? $row['qty'] ?? 0); + $summary['amount'] += (float) ($row['_supplier_amount'] ?? $row['amount'] ?? 0); + $status = (string) ($row['_status'] ?? ''); + if ($status === SupplierReturnConfirmation::STATUS_CONFIRMED) { + $summary['confirmed']++; + } elseif ($status === SupplierReturnConfirmation::STATUS_DISPUTED) { + $summary['disputed']++; + } else { + $summary['pending']++; + } + } + + $summary['qty'] = round($summary['qty'], 2); + $summary['amount'] = round($summary['amount'], 2); + + return $summary; + } + + /** + * 按钉钉单条消息容量装箱,不限制总行数和消息总数。 + * + * @param list> $rows + * @param array{count:int,qty:float,amount:float,pending:int,confirmed:int,disputed:int} $summary + * @return list>> + */ + private function returnMessageChunks(string $supplier, array $rows, array $summary, string $month): array + { + $chunks = []; + $current = []; + $rowOffset = 0; + + foreach (array_values($rows) as $row) { + $candidate = [...$current, $row]; + $messageSize = strlen($this->returnMessage($supplier, $candidate, $summary, $month, 1, 1, $rowOffset)); + + if ($current !== [] && $messageSize > self::RETURN_MESSAGE_MAX_BYTES) { + $chunks[] = $current; + $rowOffset += count($current); + $current = [$row]; + continue; + } + + if ($current === [] && $messageSize > self::RETURN_MESSAGE_MAX_BYTES) { + throw ValidationException::withMessages([ + 'dingtalk_return_push' => '第 ' . ($rowOffset + 1) . ' 条退货内容超过钉钉单条消息容量,无法推送。', + ]); + } + + $current = $candidate; + } + + if ($current !== []) { + $chunks[] = $current; + } + + return $chunks; + } + + /** + * @param list> $rows + * @param array{count:int,qty:float,amount:float,pending:int,confirmed:int,disputed:int} $summary + */ + private function returnMessage( + string $supplier, + array $rows, + array $summary, + string $month, + int $part, + int $parts, + int $rowOffset, + ): string { + $lines = [ + '### 供应商退货对账通知 · ' . $supplier, + '- 业务类型:货款对账 / 退货明细', + '- 对账月份:**' . $month . '**', + '- 本月全部退货:**' . $summary['count'] . '** 行(待确认 ' . $summary['pending'] + . ' / 已确认 ' . $summary['confirmed'] . ' / 异议中 ' . $summary['disputed'] . ')', + '- 厂家净扣减:**' . $this->number($summary['qty']) . '** 件,**¥' + . number_format($summary['amount'], 2) . '**', + ]; + + if ($parts > 1) { + $lines[] = '- 本条为第 ' . $part . ' / ' . $parts . ' 条。'; + } + + $lines[] = ''; + foreach ($rows as $index => $row) { + $date = $this->messageText($row['send_time'] ?? '', 64); + $barcode = $this->messageText($row['barcode'] ?? '', 128); + $skuName = $this->messageText($row['sku_name'] ?? '', 160); + $status = $this->returnStatusLabel((string) ($row['_status'] ?? '')); + $target = $this->messageText($row['_accounting_label'] ?? '厂家扣减', 40); + $qty = (float) ($row['qty'] ?? $row['_supplier_qty'] ?? 0); + $supplierQty = (float) ($row['_supplier_qty'] ?? $qty); + $unitPrice = (float) ($row['unit_price'] ?? 0); + $amount = (float) ($row['amount'] ?? 0); + $supplierAmount = (float) ($row['_supplier_amount'] ?? $amount); + + $lines[] = sprintf( + '%d. **%s**|条码:%s%s', + $rowOffset + $index + 1, + $date !== '' ? $date : '日期缺失', + $barcode !== '' ? $barcode : '—', + $skuName !== '' ? '|' . $skuName : '', + ); + $lines[] = ' 状态:' . $status . '|记账归属:' . $target + . '|数量:' . $this->number($qty) + . '|单价:¥' . number_format($unitPrice, 2) + . '|金额:¥' . number_format($amount, 2); + $lines[] = ' 厂家净扣减:' . $this->number($supplierQty) + . ' 件 / ¥' . number_format($supplierAmount, 2); + + $detail = []; + foreach ([ + '仓库' => [$row['warehouse'] ?? '', 80], + 'WMS配货单号' => [$row['wms_pick_no'] ?? '', 100], + '快递单号' => [$row['express_no'] ?? '', 100], + '备注' => [$row['remark'] ?? '', 300], + ] as $label => [$value, $maxLength]) { + $value = $this->messageText($value, $maxLength); + if ($value !== '') { + $detail[] = $label . ':' . $value; + } + } + if ($detail !== []) { + $lines[] = ' ' . implode('|', $detail); + } + + $accountingNote = $this->messageText($row['_accounting_note'] ?? '', 300); + if ($accountingNote !== '' && $accountingNote !== '按厂家退货扣减') { + $lines[] = ' ' . $accountingNote; + } + } + + $lines[] = ''; + $lines[] = '> 本条推送包含该厂家整月全部退货记录,不按确认状态筛选。请在本群核对;如有异议,请回复条目序号和原因。'; + + return implode("\n", $lines); + } + /** * @param list> $rows * @param array{count:int,extra:int,mismatch:int,missing:int,difference_amount:float} $summary @@ -323,6 +528,25 @@ class SupplierDingTalkNotifier } } + private function returnStatusLabel(string $status): string + { + return match ($status) { + SupplierReturnConfirmation::STATUS_CONFIRMED => '已确认', + SupplierReturnConfirmation::STATUS_DISPUTED => '异议中', + default => '待确认', + }; + } + + private function messageText(mixed $value, int $maxLength): string + { + $text = is_scalar($value) ? trim((string) $value) : ''; + if ($text === '' || mb_strlen($text) <= $maxLength) { + return $text; + } + + return mb_substr($text, 0, max(1, $maxLength - 1)) . '…'; + } + private function number(float $value): string { return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.'); diff --git a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php index 089eb7ac..f14be245 100644 --- a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php +++ b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php @@ -133,6 +133,7 @@ class SupplierReconciliationPageData self::COMPARISON_PER_PAGE, ); } + $returnPushMonth = $month !== '' ? $month : now()->format('Y-m'); return [ 'view' => 'business.pages.supplier-reconciliation.finance-data', @@ -149,6 +150,7 @@ class SupplierReconciliationPageData 'financeReturnPanel' => $detail !== null ? $this->financeReturnPanel($selected, $companyId, $month, $reconciler) : null, + 'returnPushMonth' => $returnPushMonth, 'robot' => $selected !== '' ? $this->dingTalkNotifier->configuration($selected) : null, 'listUrl' => route('business.pages.show', array_filter([ 'section' => 'supplier-reconciliation', @@ -307,10 +309,7 @@ class SupplierReconciliationPageData $rows = []; foreach ($allRows as $row) { - $rowMonth = substr(trim((string) ($row['send_time'] ?? '')), 0, 7); - if ($rowMonth === '') { - $rowMonth = substr(trim((string) ($row['summary_month'] ?? '')), 0, 7); - } + $rowMonth = $this->returnRowMonth($row); if ($month !== '' && $rowMonth !== $month) { continue; } @@ -472,6 +471,31 @@ class SupplierReconciliationPageData )); } + /** + * 返回指定厂家整月退货,不按确认状态或记账归属筛除。 + * + * @return list> + */ + public function returnRowsForMonth(string $supplier, int $companyId, string $month): array + { + if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { + return []; + } + + $statuses = $this->returnConfirmations->statuses($supplier, $companyId); + $rows = []; + foreach ($this->returnRows($supplier, $companyId) as $row) { + if ($this->returnRowMonth($row) !== $month) { + continue; + } + + $row['_status'] = $statuses[(string) ($row['_action_key'] ?? '')] ?? ''; + $rows[] = $this->returnAccounting->enrich($row); + } + + return $rows; + } + /** * 厂家端当前查询条件下的全部退货行(用于导出,不分页)。 * @@ -610,6 +634,27 @@ class SupplierReconciliationPageData : ''; } + /** @param array $row */ + private function returnRowMonth(array $row): string + { + $sendDate = $this->normalizeFilterDate($row['send_time'] ?? ''); + if ($sendDate !== '') { + return substr($sendDate, 0, 7); + } + + $summaryMonth = $this->filterText($row['summary_month'] ?? ''); + if (preg_match('/^(\d{4})[-\/.](\d{1,2})/', $summaryMonth, $matches) !== 1) { + return ''; + } + + $year = (int) $matches[1]; + $month = (int) $matches[2]; + + return $month >= 1 && $month <= 12 + ? sprintf('%04d-%02d', $year, $month) + : ''; + } + private function companyId(): int { return (int) (company_id() ?: 1); 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 46a07812..2e7dceac 100644 --- a/resources/views/business/pages/supplier-reconciliation/finance-data.blade.php +++ b/resources/views/business/pages/supplier-reconciliation/finance-data.blade.php @@ -43,6 +43,9 @@ .supplier-reconciliation-page .sr-robot-config summary { cursor: pointer; color: #5B5343; font-size: .8125rem; font-weight: 600; } .supplier-reconciliation-page .sr-robot-form { display: grid; grid-template-columns: minmax(260px, 2fr) minmax(180px, 1fr) auto; gap: 10px; align-items: end; margin-top: 12px; } .supplier-reconciliation-page .sr-robot-check { display: flex; align-items: center; gap: 6px; min-height: 36px; color: var(--vip-content-muted, #595959); font-size: .75rem; } + .supplier-reconciliation-page .sr-return-push { display: flex; flex-wrap: wrap; align-items: end; gap: 10px; padding: 12px; border: 1px solid #E4DCCB; border-radius: 8px; background: var(--vip-content-accent-soft, #F7F0DE); } + .supplier-reconciliation-page .sr-return-push .sr-field { min-width: 180px; margin: 0; } + .supplier-reconciliation-page .sr-return-push-note { flex: 1 1 320px; color: var(--vip-content-muted, #595959); font-size: .75rem; line-height: 1.6; } .supplier-reconciliation-page .sr-select-cell { width: 34px; text-align: center; } .supplier-reconciliation-page .sr-select-cell input { width: 15px; height: 15px; accent-color: var(--vip-content-accent-dark, #856632); } .supplier-reconciliation-page .sr-robot-form input[type="url"], @@ -59,9 +62,13 @@ @if ($errors->has('import')) @endif - @if ($errors->has('dingtalk_push') || $errors->has('dingtalk_webhook') || $errors->has('dingtalk_secret')) + @if ($errors->has('dingtalk_push') || $errors->has('dingtalk_return_push') || $errors->has('dingtalk_webhook') || $errors->has('dingtalk_secret') || $errors->has('month')) @endif @@ -181,7 +188,7 @@ @endif -
+
厂家钉钉群机器人: {{ $robot['configured'] ? '已配置' : '未配置,配置后才能推送差异' }} @@ -218,7 +225,7 @@

在厂家钉钉群的「群设置 → 智能群助手 → 添加机器人 → 自定义」中复制 Webhook;如机器人启用加签,请同时填写加签密钥。 - 如机器人使用关键词校验,请把关键词设为「货款对账」。 + 如机器人使用关键词校验,请把关键词设为「对账」,可同时匹配货款差异和退货推送。 Webhook 和密钥保存后仅用于本系统推送,页面不会再次展示完整内容。

@@ -427,6 +434,29 @@ 直接读取「应付款终版 → 退货对账」同一数据集;修改退货数量、备注、标题后,财务端和厂家门户同时更新。 +
+ @csrf + + + + + 推送该月全部退货,包含待确认、已确认和异议中记录,不按确认状态筛选。 + 不受当前对账人筛选影响,不限制退货行数,按钉钉消息容量自动分批续发。 + @if (! $robot['configured']) + 请先配置厂家钉钉群机器人。 + @endif + +
退货行数{{ number_format($returnAccounting['count']) }}
厂家净扣减¥{{ number_format($returnAccounting['supplier_amount'], 2) }}
diff --git a/routes/admin.php b/routes/admin.php index bf8f1d75..0f6a584a 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -464,6 +464,10 @@ Route::post('workspace/supplier-reconciliation/push-differences', [SupplierRecon ->middleware('business.page:supplier-reconciliation,finance-data') ->name('business.supplier-reconciliation.push-differences'); +Route::post('workspace/supplier-reconciliation/push-returns', [SupplierReconciliationActions::class, 'pushReturns']) + ->middleware('business.page:supplier-reconciliation,finance-data') + ->name('business.supplier-reconciliation.push-returns'); + Route::post('workspace/supplier-negative-alerts/dingtalk-group', [SupplierNegativeAlertDingTalkActions::class, 'saveRobot']) ->middleware(['business.page:negative-alerts,supplier-negative-alert', 'throttle:10,1']) ->name('business.supplier-negative-alerts.dingtalk-group.save'); diff --git a/tests/Feature/Business/SupplierReconciliationDingTalkTest.php b/tests/Feature/Business/SupplierReconciliationDingTalkTest.php index 061fe6da..2e49b6cb 100644 --- a/tests/Feature/Business/SupplierReconciliationDingTalkTest.php +++ b/tests/Feature/Business/SupplierReconciliationDingTalkTest.php @@ -6,6 +6,7 @@ use App\Models\Auth\Permission; use Illuminate\Support\Facades\Http; use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier; use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; +use Modules\EcommerceFinance\Services\SupplierReturnConfirmation; use Modules\EcommerceFinance\Services\SupplierStatementStore; use Tests\Feature\FeatureTestCase; @@ -229,6 +230,165 @@ class SupplierReconciliationDingTalkTest extends FeatureTestCase Http::assertSentCount(2); } + public function test_finance_page_shows_monthly_return_push_entry(): void + { + $this->seedReconciliation(); + + $this->loginAs()->get($this->pageUrl()) + ->assertOk() + ->assertSeeText('一键推送整月退货') + ->assertSeeText('推送该月全部退货,包含待确认、已确认和异议中记录,不按确认状态筛选。') + ->assertSee('name="month"', false); + } + + public function test_monthly_return_push_sends_all_statuses_and_only_the_selected_supplier_month(): void + { + $this->saveRobot(); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + + $companyId = (int) $this->company->id; + $store = app(SupplierPayableOverrideStore::class); + foreach ([ + 'return:pending' => [ + 'send_time' => '2026-09-03 10:00:00', 'barcode' => 'RETURN-PENDING', + 'sku_name' => '待确认退货', 'qty' => '1', 'unit_price' => '100', 'amount' => '100', + ], + 'return:confirmed' => [ + 'send_time' => '2026-09-12 10:00:00', 'barcode' => 'RETURN-CONFIRMED', + 'sku_name' => '已确认退货', 'qty' => '2', 'unit_price' => '50', 'amount' => '100', + ], + 'return:disputed' => [ + 'send_time' => '2026-09-22 10:00:00', 'barcode' => 'RETURN-DISPUTED', + 'sku_name' => '异议中退货', 'qty' => '3', 'unit_price' => '10', 'amount' => '30', + ], + 'return:october' => [ + 'send_time' => '2026-10-01 10:00:00', 'barcode' => 'RETURN-OCTOBER', + 'sku_name' => '其他月份退货', 'qty' => '9', 'unit_price' => '10', 'amount' => '90', + ], + 'return:foreign' => [ + 'send_time' => '2026-09-15 10:00:00', 'supplier' => '鸣飞家具', 'barcode' => 'RETURN-FOREIGN', + 'sku_name' => '其他厂家退货', 'qty' => '8', 'unit_price' => '10', 'amount' => '80', + ], + ] as $key => $row) { + $store->save('final:supplier:return-reconciliation', $key, $row + [ + 'summary_month' => '2026-09', + 'supplier' => '晨丰', + 'warehouse' => '一号仓', + 'wms_pick_no' => 'WMS-' . strtoupper(substr($key, 7)), + 'express_no' => 'SF-' . strtoupper(substr($key, 7)), + ], $companyId, null); + } + + $confirmations = app(SupplierReturnConfirmation::class); + $confirmations->mark('晨丰', 'return:confirmed', SupplierReturnConfirmation::STATUS_CONFIRMED, $companyId, null); + $confirmations->mark('晨丰', 'return:disputed', SupplierReturnConfirmation::STATUS_DISPUTED, $companyId, null); + + $this->loginAs() + ->post(route('business.supplier-reconciliation.push-returns'), [ + 'supplier' => '晨丰', + 'month' => '2026-09', + ]) + ->assertStatus(302) + ->assertSessionHas('success', '已推送 3 条退货到 晨丰 钉钉群(2026-09,1 条消息)。'); + + Http::assertSentCount(1); + Http::assertSent(function ($request): bool { + $text = (string) ($request['markdown']['text'] ?? ''); + + return str_contains($request->url(), 'oapi.dingtalk.com/robot/send') + && str_contains($text, '供应商退货对账通知 · 晨丰') + && str_contains($text, '业务类型:货款对账 / 退货明细') + && str_contains($text, '- 对账月份:**2026-09**') + && str_contains($text, '待确认 1 / 已确认 1 / 异议中 1') + && str_contains($text, 'RETURN-PENDING') + && str_contains($text, 'RETURN-CONFIRMED') + && str_contains($text, 'RETURN-DISPUTED') + && str_contains($text, '状态:已确认') + && str_contains($text, '状态:异议中') + && str_contains($text, '不按确认状态筛选') + && ! str_contains($text, 'RETURN-OCTOBER') + && ! str_contains($text, 'RETURN-FOREIGN'); + }); + } + + public function test_return_messages_are_split_by_size_instead_of_a_fixed_row_count(): void + { + $this->saveRobot(); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + + $rows = []; + for ($index = 1; $index <= 31; $index++) { + $rows[] = $this->returnNotificationRow($index); + } + + $result = app(SupplierDingTalkNotifier::class)->pushReturns('晨丰', $rows, '2026-09'); + + $this->assertSame(31, $result['rows']); + $this->assertSame(1, $result['messages']); + Http::assertSentCount(1); + Http::assertSent(function ($request): bool { + $text = (string) ($request['markdown']['text'] ?? ''); + + return str_contains($text, 'RETURN-BULK-01') + && str_contains($text, 'RETURN-BULK-31'); + }); + } + + public function test_monthly_return_push_has_no_application_row_or_message_cap(): void + { + $this->saveRobot(); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + + $rows = []; + for ($index = 1; $index <= 601; $index++) { + $rows[] = $this->returnNotificationRow($index); + } + + $result = app(SupplierDingTalkNotifier::class)->pushReturns('晨丰', $rows, '2026-09'); + + $this->assertSame(601, $result['rows']); + $this->assertGreaterThan(1, $result['messages']); + Http::assertSentCount($result['messages']); + foreach (Http::recorded() as [$request]) { + $this->assertLessThanOrEqual(20_000, strlen((string) ($request['markdown']['text'] ?? ''))); + } + } + + public function test_monthly_return_push_rejects_an_empty_month_without_http_call(): void + { + $this->saveRobot(); + Http::fake(); + + $this->loginAs() + ->post(route('business.supplier-reconciliation.push-returns'), [ + 'supplier' => '晨丰', + 'month' => '2026-08', + ]) + ->assertStatus(302) + ->assertSessionHasErrors([ + 'dingtalk_return_push' => '该厂家在 2026-08 没有可推送的退货数据。', + ]); + + Http::assertNothingSent(); + } + + private function returnNotificationRow(int $index): array + { + return [ + 'send_time' => '2026-09-' . str_pad((string) (($index - 1) % 28 + 1), 2, '0', STR_PAD_LEFT) . ' 10:00:00', + 'barcode' => sprintf('RETURN-BULK-%02d', $index), + 'sku_name' => '批量退货', + 'qty' => '1', + 'unit_price' => '10', + 'amount' => '10', + '_supplier_qty' => 1.0, + '_supplier_amount' => 10.0, + '_status' => '', + '_accounting_label' => '厂家扣减', + '_accounting_note' => '按厂家退货扣减', + ]; + } + private function seedReconciliation(): void { $companyId = (int) $this->company->id;