From e53fb8bfe579ecc2d8aff9c06746fe9f47821979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=9C=A8?= <594326199@qq.com> Date: Thu, 26 Nov 2026 11:42:01 +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=E5=A2=9E=E5=8A=A0=E6=9C=88=E5=BA=A6=E6=9C=AA?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E5=82=AC=E5=8A=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SendSupplierStatementReminders.php | 100 +++++++++ .../SetSupplierStatementReminderTargets.php | 96 +++++++++ app/Console/Kernel.php | 8 + config/supplier_reconciliation.php | 15 ++ .../Services/SupplierDingTalkNotifier.php | 77 +++++++ .../Services/SupplierStatementReminder.php | 156 ++++++++++++++ .../SupplierStatementReminderTargets.php | 59 +++++ .../Services/SupplierStatementStore.php | 16 ++ .../View/SupplierReconciliationPageData.php | 6 +- .../SupplierStatementReminderTest.php | 201 ++++++++++++++++++ 10 files changed, 732 insertions(+), 2 deletions(-) create mode 100644 app/Console/Commands/SendSupplierStatementReminders.php create mode 100644 app/Console/Commands/SetSupplierStatementReminderTargets.php create mode 100644 config/supplier_reconciliation.php create mode 100644 modules/EcommerceFinance/Services/SupplierStatementReminder.php create mode 100644 modules/EcommerceFinance/Services/SupplierStatementReminderTargets.php create mode 100644 tests/Feature/Business/SupplierStatementReminderTest.php diff --git a/app/Console/Commands/SendSupplierStatementReminders.php b/app/Console/Commands/SendSupplierStatementReminders.php new file mode 100644 index 000000000..acea3333a --- /dev/null +++ b/app/Console/Commands/SendSupplierStatementReminders.php @@ -0,0 +1,100 @@ +option('date')) ?: now($timezone)->toDateString(); + try { + $date = Carbon::createFromFormat('!Y-m-d', $dateValue, $timezone)->startOfDay(); + } catch (Throwable) { + $this->error('执行日期格式无效。'); + + return self::FAILURE; + } + if ($date->format('Y-m-d') !== $dateValue) { + $this->error('执行日期格式无效。'); + + return self::FAILURE; + } + + $failed = false; + $dryRun = (bool) $this->option('dry-run'); + foreach (Company::enabled()->orderBy('id')->get() as $company) { + $company->makeCurrent(); + $lock = Cache::lock(sprintf( + 'supplier-statement-reminder:%d:%s', + $company->id, + $date->toDateString(), + ), 900); + if (! $dryRun && ! $lock->get()) { + $this->warn("#{$company->id} {$company->name}: 已有催办任务运行"); + continue; + } + + try { + $result = $reminder->send( + $date, + (int) $company->id, + $dryRun, + trim((string) $this->option('supplier')), + ); + if ($result['stage'] === null) { + $this->line("#{$company->id} {$company->name}: 今天不在催办阶段"); + continue; + } + if ($result['target_count'] === 0) { + $this->warn("#{$company->id} {$company->name}: 当前催办名单未配置"); + continue; + } + + $this->line(sprintf( + '#%d %s %s %s: 名单 %d 家,可提醒 %d 家,%s %d 家,已上传 %d 家,已提醒 %d 家,未配置机器人 %d 家,失败 %d 家', + $company->id, + $company->name, + $result['accounting_month'], + $result['stage'], + $result['target_count'], + $result['configured'], + $dryRun ? '将提醒' : '已发送', + count($dryRun ? $result['previewed'] : $result['sent']), + count($result['uploaded']), + count($result['already_sent']), + count($result['missing_robot']), + count($result['failed']), + )); + foreach ($result['failed'] as $supplier => $message) { + $this->error("{$supplier}: {$message}"); + $failed = true; + } + } catch (Throwable $exception) { + report($exception); + $this->error("#{$company->id} {$company->name}: 催办任务失败:" . $exception->getMessage()); + $failed = true; + } finally { + if (! $dryRun) { + $lock->release(); + } + } + } + + return $failed ? self::FAILURE : self::SUCCESS; + } +} diff --git a/app/Console/Commands/SetSupplierStatementReminderTargets.php b/app/Console/Commands/SetSupplierStatementReminderTargets.php new file mode 100644 index 000000000..2c94ae0b5 --- /dev/null +++ b/app/Console/Commands/SetSupplierStatementReminderTargets.php @@ -0,0 +1,96 @@ +option('company') ?: (company_id() ?: 1)); + $company = Company::query()->whereKey($companyId)->first(); + if (! $company) { + $this->error("公司 #{$companyId} 不存在。"); + + return self::FAILURE; + } + $company->makeCurrent(); + + $path = trim((string) $this->argument('file')) ?: '-'; + $handle = $path === '-' ? STDIN : @fopen($path, 'rb'); + if (! is_resource($handle)) { + $this->error('无法读取供应商名单文件。'); + + return self::FAILURE; + } + + $names = []; + $lineNumber = 0; + try { + while (($line = fgets($handle)) !== false) { + $lineNumber++; + if ($lineNumber === 1) { + $line = ltrim($line, "\xEF\xBB\xBF"); + } + $name = trim($line); + if ($lineNumber === 1 && in_array($name, ['供应商', '供应商名称'], true)) { + continue; + } + if ($name !== '') { + $names[] = $name; + } + } + } finally { + if ($path !== '-') { + fclose($handle); + } + } + + if ($lineNumber > 5000) { + $this->error('催办名单不能超过 5000 行。'); + + return self::FAILURE; + } + if ($names === []) { + $this->error('供应商名单为空,未修改现有名单。'); + + return self::FAILURE; + } + + try { + $saved = $targets->replace($names); + } catch (Throwable $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $missingRobots = array_values(array_diff($saved, $notifier->configuredSuppliers())); + $this->info(sprintf( + '#%d %s: 已保存 %d 家当前供应商;其中 %d 家可自动催办,%d 家未配置钉钉群机器人。', + $company->id, + $company->name, + count($saved), + count($saved) - count($missingRobots), + count($missingRobots), + )); + if ($missingRobots !== []) { + $this->warn('未配置机器人:' . implode('、', $missingRobots)); + } + + return self::SUCCESS; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 65083b24a..d89b86655 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -89,6 +89,14 @@ class Kernel extends ConsoleKernel ->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log')) ->runInBackground(); + // 厂家对账单月度催办:每日运行,按截止日前、截止日、逾期阶段各提醒一次。 + $schedule->command('supplier-statement:send-reminders') + ->dailyAt((string) config('supplier_reconciliation.reminder.run_time', '10:00')) + ->timezone('Asia/Shanghai') + ->withoutOverlapping(30) + ->appendOutputTo(storage_path('logs/supplier-statement-reminders.log')) + ->runInBackground(); + // 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。 $schedule->command('inventory:sync-warehouse-mapping-alert') ->dailyAt('10:15') diff --git a/config/supplier_reconciliation.php b/config/supplier_reconciliation.php new file mode 100644 index 000000000..4aed29427 --- /dev/null +++ b/config/supplier_reconciliation.php @@ -0,0 +1,15 @@ + max(1, min(28, (int) env('SUPPLIER_STATEMENT_UPLOAD_DEADLINE_DAY', 5))), + 'return_confirmation_deadline_day' => max(1, min(28, (int) env('SUPPLIER_RETURN_CONFIRMATION_DEADLINE_DAY', 13))), + + 'reminder' => [ + // 每天运行任务,只在对应阶段执行;3-4 日提示即将截止,5 日提示当日截止,6 日起提示逾期。 + 'due_soon_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_DUE_SOON_DAY', 3))), + 'overdue_day' => max(1, min(28, (int) env('SUPPLIER_STATEMENT_OVERDUE_DAY', 6))), + 'run_time' => env('SUPPLIER_STATEMENT_REMINDER_TIME', '10:00'), + 'contact_name' => env('SUPPLIER_STATEMENT_REMINDER_CONTACT_NAME', '苏木'), + ], +]; diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index dec48229b..303f390b7 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -2,6 +2,7 @@ namespace Modules\EcommerceFinance\Services; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Http; use Illuminate\Validation\ValidationException; @@ -72,6 +73,16 @@ class SupplierDingTalkNotifier return $result; } + /** @return list */ + public function configuredSuppliers(): array + { + return array_keys(array_filter( + $this->configs(), + static fn (mixed $config): bool => is_array($config) + && trim((string) ($config['webhook'] ?? '')) !== '', + )); + } + /** * @return array{ * configured:bool, @@ -494,6 +505,72 @@ class SupplierDingTalkNotifier return true; } + public function sendStatementReminder( + string $supplier, + string $accountingMonth, + Carbon $deadline, + Carbon $runDate, + string $stage, + int $companyId, + ): void { + if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $accountingMonth) !== 1) { + throw ValidationException::withMessages(['statement_reminder' => '对账月份格式无效。']); + } + if (! in_array($stage, ['due_soon', 'due_today', 'overdue'], true)) { + throw ValidationException::withMessages(['statement_reminder' => '催办阶段无效。']); + } + + $configs = $this->configs(); + $config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : []; + $webhook = trim((string) ($config['webhook'] ?? '')); + if ($webhook === '') { + throw ValidationException::withMessages([ + 'dingtalk_statement_reminder' => '该厂家还没有配置钉钉群机器人 Webhook。', + ]); + } + $this->assertWebhook($webhook); + + $month = Carbon::createFromFormat('!Y-m', $accountingMonth, config('app.platform_timezone', 'Asia/Shanghai')); + $deadlineLabel = $deadline->format('n月j日') . ' 24:00'; + $deadlineDays = $deadline->day - $runDate->day; + $statusLine = match ($stage) { + 'due_soon' => '距离上传截止还有 **' . max(0, $deadlineDays) . ' 天**,请尽快上传。', + 'due_today' => '**今天是上传截止日**,请于 24:00 前完成上传。', + 'overdue' => '**上传已逾期 ' . max(0, -$deadlineDays) . ' 天**,请尽快补传。', + }; + $portalUrl = route('business.supplier-portal.home', ['company_id' => $companyId]); + $contactName = trim((string) config('supplier_reconciliation.reminder.contact_name', '苏木')); + $contactLine = $contactName !== '' + ? '如无法登录或上传,请在群里反馈并艾特' . $contactName . '。' + : '如无法登录或上传,请在群里反馈并联系财务。'; + + $lines = [ + '### 供应商月度对账单催办 · ' . $supplier, + '- 对账月份:**' . $month->format('Y年n月') . '**', + '- 上传截止:**' . $deadlineLabel . '**', + '- 系统状态:**本月尚未收到对账单上传记录**', + '- ' . $statusLine, + '', + '#### [打开厂家端对账入口](' . $portalUrl . ')', + '请完成钉钉身份验证后上传对账单;同一钉钉账号对应多家供应商时,登录后可切换厂家。', + $contactLine, + '如已完成上传,可忽略本提醒。', + ]; + + $this->send( + $webhook, + trim((string) ($config['secret'] ?? '')), + (bool) ($config['at_all'] ?? false), + $supplier . ' · 供应商对账单催办', + implode("\n", $lines), + ); + + $config['last_pushed_at'] = $this->platformTimestamp(); + $config['last_push_count'] = 1; + $configs[$supplier] = $config; + $this->persist($configs); + } + /** @param list> $records */ private function statementMonths(array $records): string { diff --git a/modules/EcommerceFinance/Services/SupplierStatementReminder.php b/modules/EcommerceFinance/Services/SupplierStatementReminder.php new file mode 100644 index 000000000..27bdde34b --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierStatementReminder.php @@ -0,0 +1,156 @@ +day >= $overdueDay) { + return 'overdue'; + } + if ($date->day === $deadlineDay) { + return 'due_today'; + } + if ($date->day >= $dueSoonDay) { + return 'due_soon'; + } + + return null; + } + + /** + * @return array{ + * stage:?string, + * accounting_month:string, + * deadline:string, + * target_count:int, + * configured:int, + * missing_robot:list, + * uploaded:list, + * already_sent:list, + * sent:list, + * previewed:list, + * failed:array + * } + */ + public function send( + Carbon $date, + int $companyId, + bool $dryRun = false, + string $onlySupplier = '', + ): array { + $stage = $this->stageFor($date); + $accountingMonth = $date->copy()->startOfMonth()->subMonthNoOverflow()->format('Y-m'); + $deadline = $date->copy()->startOfMonth() + ->addDays((int) config('supplier_reconciliation.upload_deadline_day', 5) - 1) + ->setTime(23, 59, 59); + $result = [ + 'stage' => $stage, + 'accounting_month' => $accountingMonth, + 'deadline' => $deadline->toDateTimeString(), + 'target_count' => 0, + 'configured' => 0, + 'missing_robot' => [], + 'uploaded' => [], + 'already_sent' => [], + 'sent' => [], + 'previewed' => [], + 'failed' => [], + ]; + if ($stage === null) { + return $result; + } + + $targets = $this->targets->names(); + $onlySupplier = trim($onlySupplier); + if ($onlySupplier !== '') { + $targets = array_values(array_filter( + $targets, + static fn (string $supplier): bool => $supplier === $onlySupplier, + )); + } + $configured = array_fill_keys($this->notifier->configuredSuppliers(), true); + $suppliers = array_values(array_filter( + $targets, + static fn (string $supplier): bool => isset($configured[$supplier]), + )); + $result['target_count'] = count($targets); + $result['configured'] = count($suppliers); + $result['missing_robot'] = array_values(array_diff($targets, $suppliers)); + $state = $this->state(); + + foreach (array_values(array_unique($suppliers)) as $supplier) { + if ($this->statements->hasUploadInMonth($supplier, $date->format('Y-m'), $companyId)) { + $result['uploaded'][] = $supplier; + continue; + } + if (isset($state[$accountingMonth][$stage][$supplier])) { + $result['already_sent'][] = $supplier; + continue; + } + if ($dryRun) { + $result['previewed'][] = $supplier; + continue; + } + + try { + $this->notifier->sendStatementReminder( + $supplier, + $accountingMonth, + $deadline, + $date, + $stage, + $companyId, + ); + $this->recordSent($accountingMonth, $stage, $supplier, $deadline); + $result['sent'][] = $supplier; + } catch (Throwable $exception) { + report($exception); + $result['failed'][$supplier] = $exception->getMessage(); + } + } + + return $result; + } + + private function state(): array + { + $state = setting(self::SETTING_KEY, []); + if (is_string($state)) { + $state = json_decode($state, true) ?: []; + } + + return is_array($state) ? $state : []; + } + + private function recordSent(string $accountingMonth, string $stage, string $supplier, Carbon $deadline): void + { + $state = $this->state(); + $state[$accountingMonth][$stage][$supplier] = [ + 'sent_at' => now()->toDateTimeString(), + 'deadline' => $deadline->toDateTimeString(), + ]; + uksort($state, static fn (string $left, string $right): int => strcmp($right, $left)); + $state = array_slice($state, 0, 24, true); + + setting()->set(self::SETTING_KEY, json_encode($state, JSON_UNESCAPED_UNICODE)); + setting()->save(); + } +} diff --git a/modules/EcommerceFinance/Services/SupplierStatementReminderTargets.php b/modules/EcommerceFinance/Services/SupplierStatementReminderTargets.php new file mode 100644 index 000000000..83d9133bf --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierStatementReminderTargets.php @@ -0,0 +1,59 @@ + */ + public function names(): array + { + $names = setting(self::SETTING_KEY, []); + if (is_string($names)) { + $names = json_decode($names, true) ?: []; + } + if (! is_array($names)) { + return []; + } + + return $this->normalize($names); + } + + /** @return list */ + public function replace(array $names): array + { + $names = $this->normalize($names); + if (count($names) > 5000) { + throw new InvalidArgumentException('催办名单不能超过 5000 家供应商。'); + } + + setting()->set(self::SETTING_KEY, json_encode($names, JSON_UNESCAPED_UNICODE)); + setting()->save(); + + return $names; + } + + /** @return list */ + private function normalize(array $names): array + { + $normalized = []; + foreach ($names as $name) { + $name = trim((string) $name); + if ($name === '') { + continue; + } + if (mb_strlen($name) > 191) { + throw new InvalidArgumentException('供应商名称超过 191 个字符。'); + } + $normalized[$name] = true; + } + + $normalized = array_keys($normalized); + natcasesort($normalized); + + return array_values($normalized); + } +} diff --git a/modules/EcommerceFinance/Services/SupplierStatementStore.php b/modules/EcommerceFinance/Services/SupplierStatementStore.php index 6779fc162..125973dcf 100644 --- a/modules/EcommerceFinance/Services/SupplierStatementStore.php +++ b/modules/EcommerceFinance/Services/SupplierStatementStore.php @@ -50,6 +50,22 @@ class SupplierStatementStore return array_slice($uploads, 0, $limit); } + public function hasUploadInMonth(string $supplier, string $month, int $companyId): bool + { + $month = substr(trim($month), 0, 7); + if ($supplier === '' || preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { + return false; + } + + foreach ($this->store->listRows(self::LOG_PREFIX . $supplier, $companyId) as $upload) { + if (substr((string) ($upload['uploaded_at'] ?? ''), 0, 7) === $month) { + return true; + } + } + + return false; + } + /** @return list 已经上传过对账单的厂家名称 */ public function uploadedSuppliers(int $companyId): array { diff --git a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php index 513cc9dc1..09cacfd50 100644 --- a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php +++ b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php @@ -410,8 +410,10 @@ class SupplierReconciliationPageData { $now = \Illuminate\Support\Carbon::now(); $accountingMonth = $now->copy()->subMonthNoOverflow()->startOfMonth(); - $uploadDeadline = $now->copy()->startOfMonth()->addDays(4)->setTime(23, 59, 59); - $returnDeadline = $now->copy()->startOfMonth()->addDays(12)->setTime(18, 0); + $uploadDeadlineDay = (int) config('supplier_reconciliation.upload_deadline_day', 5); + $returnDeadlineDay = (int) config('supplier_reconciliation.return_confirmation_deadline_day', 13); + $uploadDeadline = $now->copy()->startOfMonth()->addDays($uploadDeadlineDay - 1)->setTime(23, 59, 59); + $returnDeadline = $now->copy()->startOfMonth()->addDays($returnDeadlineDay - 1)->setTime(18, 0); return [ 'accountingMonthKey' => $accountingMonth->format('Y-m'), diff --git a/tests/Feature/Business/SupplierStatementReminderTest.php b/tests/Feature/Business/SupplierStatementReminderTest.php new file mode 100644 index 000000000..8148e7ecd --- /dev/null +++ b/tests/Feature/Business/SupplierStatementReminderTest.php @@ -0,0 +1,201 @@ +company->makeCurrent(); + } + + protected function tearDown(): void + { + Carbon::setTestNow(); + + parent::tearDown(); + } + + public function test_due_soon_reminder_is_scoped_to_unuploaded_suppliers_and_never_duplicates(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai')); + app(SupplierStatementReminderTargets::class)->replace(['晨丰', '鸣飞家具']); + $notifier = app(SupplierDingTalkNotifier::class); + $notifier->save('晨丰', self::WEBHOOK, '', false); + $notifier->save('鸣飞家具', self::WEBHOOK . '-second', '', false); + app(SupplierStatementStore::class)->save('晨丰', [], '晨丰-202610.csv', (int) $this->company->id, null); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + + $this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03']) + ->assertSuccessful(); + $this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-04']) + ->assertSuccessful(); + + Http::assertSentCount(1); + $request = Http::recorded()->first()[0]; + $text = (string) ($request['markdown']['text'] ?? ''); + $this->assertStringContainsString('statement-reminder-test-second', $request->url()); + $this->assertStringContainsString('供应商月度对账单催办 · 鸣飞家具', $text); + $this->assertStringContainsString('对账月份:**2026年10月**', $text); + $this->assertStringContainsString('上传截止:**11月5日 24:00**', $text); + $this->assertStringContainsString('距离上传截止还有 **2 天**', $text); + $this->assertStringContainsString('/1/workspace/supplier-portal', $text); + $this->assertStringNotContainsString('晨丰', $text); + + $state = json_decode((string) setting('supplier_reconciliation.statement_reminders'), true); + $this->assertArrayHasKey('鸣飞家具', $state['2026-10']['due_soon'] ?? []); + $this->assertArrayNotHasKey('晨丰', $state['2026-10']['due_soon'] ?? []); + } + + public function test_deadline_and_overdue_stages_each_send_once(): void + { + app(SupplierStatementReminderTargets::class)->replace(['晨丰']); + app(SupplierDingTalkNotifier::class)->save('晨丰', self::WEBHOOK, '', false); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + + foreach (['2026-11-03', '2026-11-05', '2026-11-06', '2026-11-07'] as $date) { + Carbon::setTestNow(Carbon::parse($date . ' 10:00:00', 'Asia/Shanghai')); + $this->artisan('supplier-statement:send-reminders', ['--date' => $date]) + ->assertSuccessful(); + } + + Http::assertSentCount(3); + $texts = Http::recorded() + ->map(static fn (array $pair): string => (string) ($pair[0]['markdown']['text'] ?? '')) + ->implode("\n"); + $this->assertStringContainsString('今天是上传截止日', $texts); + $this->assertStringContainsString('上传已逾期 1 天', $texts); + } + + public function test_dry_run_reports_uploaded_and_pending_suppliers_without_sending(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai')); + app(SupplierStatementReminderTargets::class)->replace(['晨丰', '鸣飞家具', '未配置厂家']); + $notifier = app(SupplierDingTalkNotifier::class); + $notifier->save('晨丰', self::WEBHOOK, '', false); + $notifier->save('鸣飞家具', self::WEBHOOK . '-second', '', false); + app(SupplierStatementStore::class)->save('晨丰', [], '晨丰-202610.csv', (int) $this->company->id, null); + Http::fake(); + + $result = app(SupplierStatementReminder::class)->send( + Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'), + (int) $this->company->id, + true, + ); + + Http::assertNothingSent(); + $this->assertSame(['鸣飞家具'], $result['previewed']); + $this->assertSame(['晨丰'], $result['uploaded']); + $this->assertSame(['未配置厂家'], $result['missing_robot']); + $this->assertNull(setting('supplier_reconciliation.statement_reminders')); + } + + public function test_failed_delivery_is_not_recorded_and_can_be_retried(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai')); + app(SupplierStatementReminderTargets::class)->replace(['晨丰']); + app(SupplierDingTalkNotifier::class)->save('晨丰', self::WEBHOOK, '', false); + Http::fakeSequence() + ->push(['errcode' => 500, 'errmsg' => 'temporary failure'], 500) + ->push(['errcode' => 0, 'errmsg' => 'ok']); + + $this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03']) + ->assertFailed(); + $this->assertNull(setting('supplier_reconciliation.statement_reminders')); + + $this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03']) + ->assertSuccessful(); + Http::assertSentCount(2); + $state = json_decode((string) setting('supplier_reconciliation.statement_reminders'), true); + $this->assertArrayHasKey('晨丰', $state['2026-10']['due_soon'] ?? []); + } + + public function test_dry_run_handles_122_configured_suppliers(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai')); + $suppliers = array_map(static fn (int $index): string => '测试供应商' . str_pad( + (string) $index, + 3, + '0', + STR_PAD_LEFT, + ), range(1, 122)); + + $configs = []; + foreach ($suppliers as $supplier) { + $configs[$supplier] = [ + 'webhook' => \Illuminate\Support\Facades\Crypt::encryptString(self::WEBHOOK), + 'secret' => '', + 'at_all' => false, + 'card_conversation_id' => '', + 'card_robot_code' => '', + 'last_pushed_at' => '', + 'last_push_count' => 0, + ]; + } + setting()->set( + 'supplier_reconciliation.dingtalk_robots', + json_encode($configs, JSON_UNESCAPED_UNICODE), + ); + setting()->save(); + app(SupplierStatementReminderTargets::class)->replace($suppliers); + Http::fake(); + + $result = app(SupplierStatementReminder::class)->send( + Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai'), + (int) $this->company->id, + true, + ); + + Http::assertNothingSent(); + $this->assertCount(122, $result['previewed']); + $this->assertSame([], $result['failed']); + $this->assertNull(setting('supplier_reconciliation.statement_reminders')); + } + + public function test_reminder_requires_a_current_supplier_allowlist(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-03 10:00:00', 'Asia/Shanghai')); + app(SupplierDingTalkNotifier::class)->save('晨丰', self::WEBHOOK, '', false); + Http::fake(); + + $this->artisan('supplier-statement:send-reminders', ['--date' => '2026-11-03']) + ->expectsOutputToContain('当前催办名单未配置') + ->assertSuccessful(); + + Http::assertNothingSent(); + $this->assertNull(setting('supplier_reconciliation.statement_reminders')); + } + + public function test_supplier_allowlist_can_be_imported_from_a_text_file(): void + { + $path = tempnam(sys_get_temp_dir(), 'supplier-reminder-targets-'); + file_put_contents($path, "\xEF\xBB\xBF供应商\n 晨丰 \n鸣飞家具\n晨丰\n"); + + try { + $this->artisan('supplier-statement:targets:set', [ + 'file' => $path, + '--company' => $this->company->id, + ])->expectsOutputToContain('已保存 2 家当前供应商') + ->assertSuccessful(); + } finally { + @unlink($path); + } + + $this->assertSame( + ['晨丰', '鸣飞家具'], + app(SupplierStatementReminderTargets::class)->names(), + ); + } +} -- 2.47.2