From 07b73ef2aa32e5eb552c083fd5e83fdfa3348376 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E6=9C=A8?= <594326199@qq.com> Date: Wed, 28 Oct 2026 15:31:21 +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=E8=B4=9F=E6=95=B0=E9=A2=84=E8=AD=A6=E9=92=89=E9=92=89?= =?UTF-8?q?=E5=A4=84=E7=90=86=E9=97=AD=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../SupplierNegativeAlertDingTalkActions.php | 82 ++++ .../SupplierNegativeAlertDingTalkForms.php | 84 ++++ ...upplier_negative_alert_dingtalk_tables.php | 64 +++ .../SupplierNegativeAlertDingTalkWorkflow.php | 398 +++++++++++++++++ .../View/SupplierNegativeAlertPageData.php | 356 ++++++++++----- .../dingtalk-task-unavailable.blade.php | 51 +++ .../negative-alerts/dingtalk-task.blade.php | 291 +++++++++++++ .../supplier-negative-alert.blade.php | 407 +++++++++++++++++- routes/admin.php | 9 + routes/web.php | 10 + .../Business/NegativeAlertPagesTest.php | 46 +- .../SupplierNegativeAlertDingTalkTest.php | 212 +++++++++ 12 files changed, 1897 insertions(+), 113 deletions(-) create mode 100644 app/Http/Controllers/Business/SupplierNegativeAlertDingTalkActions.php create mode 100644 app/Http/Controllers/Business/SupplierNegativeAlertDingTalkForms.php create mode 100644 database/migrations/2026_10_28_150000_create_supplier_negative_alert_dingtalk_tables.php create mode 100644 modules/EcommerceFinance/Services/SupplierNegativeAlertDingTalkWorkflow.php create mode 100644 resources/views/business/pages/negative-alerts/dingtalk-task-unavailable.blade.php create mode 100644 resources/views/business/pages/negative-alerts/dingtalk-task.blade.php create mode 100644 tests/Feature/Business/SupplierNegativeAlertDingTalkTest.php diff --git a/app/Http/Controllers/Business/SupplierNegativeAlertDingTalkActions.php b/app/Http/Controllers/Business/SupplierNegativeAlertDingTalkActions.php new file mode 100644 index 00000000..ef3ddfc5 --- /dev/null +++ b/app/Http/Controllers/Business/SupplierNegativeAlertDingTalkActions.php @@ -0,0 +1,82 @@ +middleware('auth'); + $this->middleware('company.identify'); + } + + public function saveRobot(Request $request): RedirectResponse + { + $data = $request->validate([ + 'dingtalk_webhook' => ['nullable', 'string', 'max:2048'], + 'dingtalk_secret' => ['nullable', 'string', 'max:256'], + 'dingtalk_group_name' => ['required', 'string', 'max:191'], + ]); + + $this->workflow->saveConfiguration( + (string) ($data['dingtalk_webhook'] ?? ''), + (string) ($data['dingtalk_secret'] ?? ''), + (string) $data['dingtalk_group_name'], + ); + + return back()->with('success', '供应商负数预警群机器人已保存。'); + } + + public function send(Request $request): RedirectResponse + { + $data = $request->validate([ + 'purchaser' => ['required', 'string', 'max:191'], + 'month' => ['nullable', 'string', 'regex:/^\d{4}-\d{2}$/'], + 'supplier' => ['nullable', 'string', 'max:191'], + 'checker' => ['nullable', 'string', 'max:191'], + 'settlement_method' => ['nullable', 'string', 'max:191'], + ]); + $purchaser = trim((string) $data['purchaser']); + $rows = $this->pageData->rowsForFilters([ + 'purchaser' => $purchaser, + 'month' => (string) ($data['month'] ?? ''), + 'supplier' => (string) ($data['supplier'] ?? ''), + 'checker' => (string) ($data['checker'] ?? ''), + 'settlement_method' => (string) ($data['settlement_method'] ?? ''), + ]); + if ($rows === []) { + return back()->withErrors([ + 'dingtalk_send' => '当前筛选没有可发送给该采购的供应商。', + ]); + } + + try { + $result = $this->workflow->send( + $rows, + $purchaser, + $request->only(['month', 'supplier', 'checker', 'settlement_method', 'purchaser']), + (int) (company_id() ?: 1), + user_id() ? (int) user_id() : null, + ); + } catch (Throwable $exception) { + report($exception); + + return back()->withErrors(['dingtalk_send' => '发送失败:' . $exception->getMessage()]); + } + + return back()->with( + 'success', + "已发送至{$result['group_name']}:采购 {$purchaser}," + . "{$result['supplier_count']} 家供应商、{$result['row_count']} 条预警。", + ); + } +} diff --git a/app/Http/Controllers/Business/SupplierNegativeAlertDingTalkForms.php b/app/Http/Controllers/Business/SupplierNegativeAlertDingTalkForms.php new file mode 100644 index 00000000..d2f57ecc --- /dev/null +++ b/app/Http/Controllers/Business/SupplierNegativeAlertDingTalkForms.php @@ -0,0 +1,84 @@ +resolve($token); + if ($assignment === null) { + return $this->unavailable(); + } + + $snapshot = json_decode((string) $assignment->snapshot, true); + + return view('business.pages.negative-alerts.dingtalk-task', [ + 'assignment' => $assignment, + 'suppliers' => is_array($snapshot) ? array_values($snapshot) : [], + 'supplierResults' => $this->workflow->resultsForAssignment((int) $assignment->id), + 'token' => $token, + ]); + } + + public function update(Request $request, string $token): RedirectResponse|Response + { + $assignment = $this->resolve($token); + if ($assignment === null) { + return $this->unavailable(); + } + $snapshot = json_decode((string) $assignment->snapshot, true); + $supplierCount = is_array($snapshot) ? count($snapshot) : 0; + + $data = $request->validate([ + 'results' => ['required', 'array', 'size:' . $supplierCount], + 'results.*' => ['required', 'string', 'max:2000'], + ], [ + 'results.required' => '请为每个供应商填写处理结果。', + 'results.size' => '请为每个供应商填写处理结果。', + 'results.*.required' => '请为每个供应商填写处理结果。', + 'results.*.max' => '单个供应商的处理结果不能超过 2000 个字符。', + ]); + + try { + $this->workflow->submit($token, array_values((array) $data['results'])); + } catch (ValidationException $exception) { + throw $exception; + } + + return redirect() + ->route('supplier-negative-alert.task', ['token' => $token]) + ->with('negative_alert_success', '处理结果已回传财务系统,可以继续修改并再次提交。'); + } + + private function resolve(string $token): ?object + { + $assignment = $this->workflow->findByToken($token); + if ($assignment === null) { + return null; + } + + Company::find($assignment->company_id)?->makeCurrent(); + + return $assignment; + } + + private function unavailable(): Response + { + return response()->view('business.pages.negative-alerts.dingtalk-task-unavailable', [], 404); + } +} diff --git a/database/migrations/2026_10_28_150000_create_supplier_negative_alert_dingtalk_tables.php b/database/migrations/2026_10_28_150000_create_supplier_negative_alert_dingtalk_tables.php new file mode 100644 index 00000000..25892c66 --- /dev/null +++ b/database/migrations/2026_10_28_150000_create_supplier_negative_alert_dingtalk_tables.php @@ -0,0 +1,64 @@ +bigIncrements('id'); + $table->unsignedInteger('company_id'); + $table->string('purchaser_name', 191); + $table->string('group_name', 191); + $table->text('filters')->nullable(); + $table->longText('snapshot'); + $table->unsignedInteger('supplier_count')->default(0); + $table->unsignedInteger('row_count')->default(0); + $table->char('token_hash', 64)->unique(); + $table->timestamp('token_expires_at'); + $table->string('status', 24)->default('sending'); + $table->string('error_message', 500)->nullable(); + $table->timestamp('sent_at')->nullable(); + $table->timestamp('completed_at')->nullable(); + $table->unsignedBigInteger('created_by')->nullable(); + $table->timestamps(); + + $table->index(['company_id', 'purchaser_name', 'created_at'], 'sna_assignment_company_buyer_index'); + $table->index(['company_id', 'status'], 'sna_assignment_company_status_index'); + }); + } + + if (! Schema::hasTable('supplier_negative_alert_results')) { + Schema::create('supplier_negative_alert_results', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedBigInteger('assignment_id'); + $table->unsignedInteger('company_id'); + $table->string('purchaser_name', 191); + $table->string('supplier_name', 191); + $table->text('result_text'); + $table->timestamp('submitted_at'); + $table->timestamps(); + + $table->unique(['assignment_id', 'supplier_name'], 'sna_result_assignment_supplier_unique'); + $table->index( + ['company_id', 'supplier_name', 'submitted_at'], + 'sna_result_company_supplier_submitted_index', + ); + $table->foreign('assignment_id') + ->references('id') + ->on('supplier_negative_alert_assignments') + ->cascadeOnDelete(); + }); + } + } + + public function down(): void + { + Schema::dropIfExists('supplier_negative_alert_results'); + Schema::dropIfExists('supplier_negative_alert_assignments'); + } +}; diff --git a/modules/EcommerceFinance/Services/SupplierNegativeAlertDingTalkWorkflow.php b/modules/EcommerceFinance/Services/SupplierNegativeAlertDingTalkWorkflow.php new file mode 100644 index 00000000..9e8bbb65 --- /dev/null +++ b/modules/EcommerceFinance/Services/SupplierNegativeAlertDingTalkWorkflow.php @@ -0,0 +1,398 @@ +config(); + $webhook = trim((string) ($config['webhook'] ?? '')); + + return [ + 'configured' => $webhook !== '', + 'webhook_hint' => $this->maskWebhook($webhook), + 'group_name' => trim((string) ($config['group_name'] ?? self::DEFAULT_GROUP_NAME)), + ]; + } + + public function saveConfiguration(string $webhook, string $secret, string $groupName): void + { + $config = $this->config(); + $existingWebhook = trim((string) ($config['webhook'] ?? '')); + $webhook = trim($webhook); + if ($webhook === '') { + $webhook = $existingWebhook; + } + if ($webhook === '') { + throw ValidationException::withMessages(['dingtalk_webhook' => '请填写钉钉群机器人 Webhook。']); + } + $this->assertWebhook($webhook); + + $secret = trim($secret); + if ($secret === '' && $webhook === $existingWebhook) { + $secret = trim((string) ($config['secret'] ?? '')); + } + if (mb_strlen($secret) > 256) { + throw ValidationException::withMessages(['dingtalk_secret' => '机器人加签密钥过长。']); + } + + $groupName = trim($groupName); + if ($groupName === '') { + $groupName = self::DEFAULT_GROUP_NAME; + } + if (mb_strlen($groupName) > 191) { + throw ValidationException::withMessages(['dingtalk_group_name' => '钉钉群名称不能超过 191 个字符。']); + } + + setting()->set(self::SETTING_KEY, json_encode([ + 'webhook' => Crypt::encryptString($webhook), + 'secret' => $secret !== '' ? Crypt::encryptString($secret) : '', + 'group_name' => $groupName, + ], JSON_UNESCAPED_UNICODE)); + setting()->save(); + } + + /** + * @param list> $rows 已按采购筛选的负数预警记录 + * @param array $filters + * @return array{assignment_id:int,supplier_count:int,row_count:int,group_name:string,task_url:string} + */ + public function send( + array $rows, + string $purchaser, + array $filters, + int $companyId, + ?int $userId, + ): array { + $purchaser = trim($purchaser); + $config = $this->config(); + $webhook = trim((string) ($config['webhook'] ?? '')); + if ($webhook === '') { + throw ValidationException::withMessages([ + 'dingtalk_send' => '财务&采购沟通群的机器人尚未配置。', + ]); + } + $this->assertWebhook($webhook); + if ($purchaser === '') { + throw ValidationException::withMessages(['dingtalk_send' => '请先选择采购。']); + } + + $supplierGroups = []; + foreach ($rows as $row) { + $supplier = trim((string) ($row['supplier'] ?? '')); + if ($supplier === '') { + continue; + } + if (trim((string) ($row['purchaser'] ?? '')) !== $purchaser) { + continue; + } + $supplierGroups[$supplier][] = [ + 'summary_month' => trim((string) ($row['summary_month'] ?? '')), + 'checker' => trim((string) ($row['checker'] ?? '')), + 'settlement_method' => trim((string) ($row['settlement_method'] ?? '')), + 'negative_reason' => trim((string) ($row['negative_reason'] ?? '')), + 'alert_amount' => round((float) ($row['_negative_alert_amount'] ?? 0), 2), + ]; + } + if ($supplierGroups === []) { + throw ValidationException::withMessages([ + 'dingtalk_send' => '当前筛选没有可发送给该采购的供应商。', + ]); + } + + $snapshot = []; + foreach ($supplierGroups as $supplier => $supplierRows) { + $months = array_values(array_unique(array_filter(array_column($supplierRows, 'summary_month')))); + rsort($months); + $reasons = array_values(array_unique(array_filter(array_column($supplierRows, 'negative_reason')))); + $snapshot[] = [ + 'supplier' => $supplier, + 'row_count' => count($supplierRows), + 'months' => $months, + 'negative_reasons' => $reasons, + 'alert_amount' => round(array_sum(array_column($supplierRows, 'alert_amount')), 2), + 'rows' => $supplierRows, + ]; + } + + $token = Str::random(64); + $groupName = trim((string) ($config['group_name'] ?? self::DEFAULT_GROUP_NAME)); + $now = now(); + $assignmentId = DB::table('supplier_negative_alert_assignments')->insertGetId([ + 'company_id' => $companyId, + 'purchaser_name' => $purchaser, + 'group_name' => $groupName, + 'filters' => json_encode($filters, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + 'snapshot' => json_encode($snapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + 'supplier_count' => count($snapshot), + 'row_count' => count($rows), + 'token_hash' => hash('sha256', $token), + 'token_expires_at' => $now->copy()->addDays(self::TOKEN_TTL_DAYS), + 'status' => 'sending', + 'created_by' => $userId, + 'created_at' => $now, + 'updated_at' => $now, + ]); + + $taskUrl = route('supplier-negative-alert.task', ['token' => $token]); + $month = trim((string) ($filters['month'] ?? '')); + $title = '供应商负数预警 · ' . $purchaser; + $text = implode("\n", [ + '### 供应商负数预警待处理', + '- 采购:**' . $purchaser . '**', + '- 月份:' . ($month !== '' ? $month : '全部月份'), + '- 供应商:**' . count($snapshot) . '** 家', + '- 预警记录:**' . count($rows) . '** 条', + '', + '请在钉钉内点击下方按钮,按每个供应商分别填写处理结果。', + ]); + + try { + $this->sendActionCard( + $webhook, + trim((string) ($config['secret'] ?? '')), + $title, + $text, + $taskUrl, + ); + } catch (Throwable $exception) { + DB::table('supplier_negative_alert_assignments')->where('id', $assignmentId)->update([ + 'status' => 'failed', + 'error_message' => mb_substr($exception->getMessage(), 0, 500), + 'updated_at' => now(), + ]); + throw $exception; + } + + $sentAt = now(); + DB::table('supplier_negative_alert_assignments')->where('id', $assignmentId)->update([ + 'status' => 'sent', + 'sent_at' => $sentAt, + 'error_message' => null, + 'updated_at' => $sentAt, + ]); + + return [ + 'assignment_id' => $assignmentId, + 'supplier_count' => count($snapshot), + 'row_count' => count($rows), + 'group_name' => $groupName, + 'task_url' => $taskUrl, + ]; + } + + public function findByToken(string $token): ?object + { + if ($token === '') { + return null; + } + + return DB::table('supplier_negative_alert_assignments') + ->where('token_hash', hash('sha256', $token)) + ->where('token_expires_at', '>=', now()) + ->whereIn('status', ['sent', 'completed']) + ->first(); + } + + /** @param list $results */ + public function submit(string $token, array $results): object + { + $assignment = $this->findByToken($token); + if ($assignment === null) { + throw ValidationException::withMessages(['results' => '任务链接无效或已过期,请财务重新发送。']); + } + + $snapshot = json_decode((string) $assignment->snapshot, true); + $snapshot = is_array($snapshot) ? array_values($snapshot) : []; + if ($snapshot === [] || count($results) !== count($snapshot)) { + throw ValidationException::withMessages(['results' => '请为每个供应商填写处理结果。']); + } + + $now = now(); + DB::transaction(function () use ($assignment, $snapshot, $results, $now): void { + foreach ($snapshot as $index => $supplier) { + $supplierName = trim((string) ($supplier['supplier'] ?? '')); + $resultText = trim((string) ($results[$index] ?? '')); + if ($supplierName === '' || $resultText === '') { + throw ValidationException::withMessages(['results' => '请为每个供应商填写处理结果。']); + } + + DB::table('supplier_negative_alert_results')->updateOrInsert( + [ + 'assignment_id' => (int) $assignment->id, + 'supplier_name' => $supplierName, + ], + [ + 'company_id' => (int) $assignment->company_id, + 'purchaser_name' => (string) $assignment->purchaser_name, + 'result_text' => $resultText, + 'submitted_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + ); + } + + DB::table('supplier_negative_alert_assignments')->where('id', $assignment->id)->update([ + 'status' => 'completed', + 'completed_at' => $now, + 'updated_at' => $now, + ]); + }); + + return DB::table('supplier_negative_alert_assignments')->where('id', $assignment->id)->first(); + } + + /** + * @param list $suppliers + * @return array + */ + public function latestResults(array $suppliers, int $companyId): array + { + $suppliers = array_values(array_unique(array_filter(array_map('trim', $suppliers)))); + if ($suppliers === []) { + return []; + } + + $rows = DB::table('supplier_negative_alert_results') + ->where('company_id', $companyId) + ->whereIn('supplier_name', $suppliers) + ->orderByDesc('submitted_at') + ->orderByDesc('id') + ->get(['supplier_name', 'purchaser_name', 'result_text', 'submitted_at']); + + $latest = []; + foreach ($rows as $row) { + $supplier = trim((string) $row->supplier_name); + if ($supplier !== '' && ! isset($latest[$supplier])) { + $latest[$supplier] = $row; + } + } + + return $latest; + } + + /** @return array */ + public function resultsForAssignment(int $assignmentId): array + { + return DB::table('supplier_negative_alert_results') + ->where('assignment_id', $assignmentId) + ->orderBy('id') + ->pluck('result_text', 'supplier_name') + ->map(static fn (mixed $value): string => trim((string) $value)) + ->all(); + } + + /** @return array */ + private function config(): array + { + $value = setting(self::SETTING_KEY, []); + if (is_string($value)) { + $value = json_decode($value, true) ?: []; + } + if (! is_array($value)) { + return []; + } + $value['webhook'] = $this->decryptValue($value['webhook'] ?? ''); + $value['secret'] = $this->decryptValue($value['secret'] ?? ''); + + return $value; + } + + private function sendActionCard( + string $webhook, + string $secret, + string $title, + string $text, + string $taskUrl, + ): void { + $url = $webhook; + if ($secret !== '') { + $timestamp = (string) (int) (microtime(true) * 1000); + $sign = urlencode(base64_encode(hash_hmac('sha256', $timestamp . "\n" . $secret, $secret, true))); + $url .= (str_contains($url, '?') ? '&' : '?') . 'timestamp=' . $timestamp . '&sign=' . $sign; + } + + $response = Http::timeout(15)->post($url, [ + 'msgtype' => 'actionCard', + 'actionCard' => [ + 'title' => $title, + 'text' => $text, + 'btnOrientation' => '0', + 'singleTitle' => '填写处理结果', + 'singleURL' => $taskUrl, + ], + 'at' => ['atMobiles' => [], 'isAtAll' => false], + ]); + + if (! $response->successful()) { + throw new RuntimeException('钉钉群机器人返回 HTTP ' . $response->status()); + } + $body = (array) $response->json(); + if ((int) ($body['errcode'] ?? 0) !== 0) { + throw new RuntimeException( + '钉钉群机器人发送失败:' . (string) ($body['errcode'] ?? '?') + . ' ' . (string) ($body['errmsg'] ?? ''), + ); + } + } + + private function assertWebhook(string $webhook): void + { + $parts = parse_url($webhook); + parse_str((string) ($parts['query'] ?? ''), $query); + $host = strtolower((string) ($parts['host'] ?? '')); + + if (($parts['scheme'] ?? '') !== 'https' + || ! in_array($host, ['oapi.dingtalk.com', 'api.dingtalk.com'], true) + || ($parts['path'] ?? '') !== '/robot/send' + || trim((string) ($query['access_token'] ?? '')) === '') { + throw ValidationException::withMessages([ + 'dingtalk_webhook' => '请填写有效的钉钉群机器人 Webhook。', + ]); + } + } + + private function maskWebhook(string $webhook): string + { + if ($webhook === '') { + return ''; + } + $host = (string) (parse_url($webhook, PHP_URL_HOST) ?? ''); + + return $host !== '' ? 'https://' . $host . '/robot/send?access_token=••••••' : '已配置'; + } + + private function decryptValue(mixed $value): string + { + $value = trim((string) $value); + if ($value === '') { + return ''; + } + + try { + return Crypt::decryptString($value); + } catch (Throwable) { + return $value; + } + } +} diff --git a/modules/EcommerceFinance/View/SupplierNegativeAlertPageData.php b/modules/EcommerceFinance/View/SupplierNegativeAlertPageData.php index bfdf447a..fddbb148 100644 --- a/modules/EcommerceFinance/View/SupplierNegativeAlertPageData.php +++ b/modules/EcommerceFinance/View/SupplierNegativeAlertPageData.php @@ -6,6 +6,7 @@ use App\Http\Controllers\Business\PayablesFinalActions; use Illuminate\Pagination\LengthAwarePaginator; use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository; use Modules\EcommerceFinance\Services\PayablesFinalRegistry; +use Modules\EcommerceFinance\Services\SupplierNegativeAlertDingTalkWorkflow; use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; use Throwable; @@ -23,11 +24,147 @@ class SupplierNegativeAlertPageData private readonly SupplierPayableOverrideStore $store, private readonly PayablesFinalRegistry $registry, private readonly SupplierManagementMirrorRepository $supplierManagement, + private readonly SupplierNegativeAlertDingTalkWorkflow $dingTalkWorkflow, ) { } /** @return array */ public function page(): array + { + $allRows = $this->decoratedRows(); + $months = $this->monthOptions($allRows); + $supplierNames = $this->supplierOptions($allRows); + $purchaserNames = $this->purchaserOptions($allRows); + $filters = $this->filters(request()->query(), $months, $purchaserNames); + $negativeRows = $this->filterRows($allRows, $filters); + $filteredSupplierNames = array_values(array_unique(array_filter(array_map( + static fn (array $row): string => trim((string) ($row['supplier'] ?? '')), + $negativeRows, + )))); + $latestResults = $this->dingTalkWorkflow->latestResults( + $filteredSupplierNames, + (int) (company_id() ?: 1), + ); + + $total = count($negativeRows); + $pages = max((int) ceil($total / self::PER_PAGE), 1); + $page = min(max((int) request()->query('page', 1), 1), $pages); + $pageRows = array_slice($negativeRows, ($page - 1) * self::PER_PAGE, self::PER_PAGE); + $items = array_map( + static function (array $row) use ($latestResults): object { + $supplier = trim((string) ($row['supplier'] ?? '')); + $result = $latestResults[$supplier] ?? null; + $row['handling_result'] = $result ? trim((string) $result->result_text) : ''; + $row['handling_result_meta'] = $result + ? '采购 ' . trim((string) $result->purchaser_name) + . ' · ' . mb_substr((string) $result->submitted_at, 0, 16) + : ''; + + return (object) $row; + }, + $pageRows, + ); + + $negativeAlertFields = []; + $fields = collect($this->registry->fields( + PayablesFinalRegistry::SECTION_SUPPLIER, + self::DATASET, + ))->map( + static fn (array $definition, string $name): array => ['name' => $name] + $definition, + )->values()->all(); + foreach ($fields as $field) { + $negativeAlertFields[] = $field; + if (($field['name'] ?? '') === 'negative_reason') { + $negativeAlertFields[] = ['name' => 'purchaser', 'label' => '采购', 'type' => 'text']; + $negativeAlertFields[] = ['name' => 'handling_result', 'label' => '处理结果', 'type' => 'text']; + } + } + + return [ + 'view' => 'business.pages.negative-alerts.supplier-negative-alert', + 'negativeAlertFields' => $negativeAlertFields, + 'negativeAlertRows' => new LengthAwarePaginator( + $items, + $total, + self::PER_PAGE, + $page, + [ + 'path' => request()->url(), + 'query' => request()->except('page'), + ], + ), + 'negativeAlertMonths' => $months, + 'negativeAlertMonth' => $filters['month'], + 'negativeAlertSupplier' => $filters['supplier'], + 'negativeAlertSupplierNames' => $supplierNames, + 'negativeAlertChecker' => $filters['checker'], + 'negativeAlertCheckerNames' => $this->textOptions($allRows, 'checker'), + 'negativeAlertSettlementMethod' => $filters['settlement_method'], + 'negativeAlertSettlementMethods' => $this->textOptions($allRows, 'settlement_method'), + 'negativeAlertPurchaser' => $filters['purchaser'], + 'negativeAlertPurchaserNames' => $purchaserNames, + 'negativeAlertSupplierCount' => count($filteredSupplierNames), + 'negativeAlertTotal' => $total, + 'negativeAlertRobot' => $this->dingTalkWorkflow->configuration(), + 'negativeAlertSourceUrl' => route('business.pages.show', [ + 'section' => 'supplier-payables-final', + 'page' => 'supplier-payables-report', + ]), + ]; + } + + /** @param array $filters + * @return list> + */ + public function rowsForFilters(array $filters): array + { + $allRows = $this->decoratedRows(); + + return $this->filterRows($allRows, $this->filters( + $filters, + $this->monthOptions($allRows), + $this->purchaserOptions($allRows), + )); + } + + /** @return list> */ + private function decoratedRows(): array + { + $rows = $this->negativeRows(); + $supplierNames = array_values(array_unique(array_filter(array_map( + static fn (array $row): string => trim((string) ($row['supplier'] ?? '')), + $rows, + )))); + $purchasersBySupplier = []; + if ($supplierNames !== []) { + try { + foreach ($this->supplierManagement->suppliersByNames($supplierNames) as $supplier) { + $name = trim((string) ($supplier->scmname ?? '')); + $buyer = trim((string) ($supplier->buyer ?? '')); + if ($name !== '' && $buyer !== '') { + $purchasersBySupplier[$name][$buyer] = true; + } + } + } catch (Throwable $exception) { + report($exception); + } + } + $purchasersBySupplier = array_map( + static fn (array $buyers): string => implode('、', array_keys($buyers)), + $purchasersBySupplier, + ); + + foreach ($rows as &$row) { + $supplier = trim((string) ($row['supplier'] ?? '')); + $row['purchaser'] = $purchasersBySupplier[$supplier] ?? ''; + } + unset($row); + + return $rows; + } + + /** @return list> */ + private function negativeRows(): array { $rows = $this->store->listRows( PayablesFinalActions::DATASET_PREFIX . 'supplier:' . self::DATASET, @@ -59,8 +196,16 @@ class SupplierNegativeAlertPageData ); }); + return $negativeRows; + } + + /** @param list> $rows + * @return list + */ + private function monthOptions(array $rows): array + { $months = []; - foreach ($negativeRows as $row) { + foreach ($rows as $row) { $month = trim((string) ($row['summary_month'] ?? '')); if (preg_match('/^\d{4}-\d{2}$/', $month) === 1) { $months[$month] = true; @@ -69,124 +214,115 @@ class SupplierNegativeAlertPageData $months = array_keys($months); rsort($months); - $requestedMonth = trim((string) request()->query('month', '')); - $month = in_array($requestedMonth, $months, true) ? $requestedMonth : ''; - if ($month !== '') { - $negativeRows = array_values(array_filter( - $negativeRows, - static fn (array $row): bool => (string) ($row['summary_month'] ?? '') === $month, - )); - } + return $months; + } - $supplierNames = []; - foreach ($negativeRows as $row) { - $supplier = trim((string) ($row['supplier'] ?? '')); - if ($supplier !== '') { - $supplierNames[$supplier] = true; - } - } - $supplierNames = array_keys($supplierNames); - sort($supplierNames, SORT_NATURAL | SORT_FLAG_CASE); + /** @param list> $rows + * @return list + */ + private function supplierOptions(array $rows): array + { + $names = array_values(array_unique(array_filter(array_map( + static fn (array $row): string => trim((string) ($row['supplier'] ?? '')), + $rows, + )))); + sort($names, SORT_NATURAL | SORT_FLAG_CASE); - $supplierQuery = mb_substr(trim((string) request()->query('supplier', '')), 0, 191); - if ($supplierQuery !== '') { - $needle = mb_strtolower($supplierQuery); - $negativeRows = array_values(array_filter( - $negativeRows, - static function (array $row) use ($needle): bool { - $haystack = mb_strtolower(implode("\n", [ + return $names; + } + + /** @param list> $rows + * @return list + */ + private function purchaserOptions(array $rows): array + { + $names = array_values(array_unique(array_filter(array_map( + static fn (array $row): string => trim((string) ($row['purchaser'] ?? '')), + $rows, + )))); + sort($names, SORT_NATURAL | SORT_FLAG_CASE); + + return $names; + } + + /** @param list> $rows + * @return list + */ + private function textOptions(array $rows, string $field): array + { + $values = array_values(array_unique(array_filter(array_map( + static fn (array $row): string => trim((string) ($row[$field] ?? '')), + $rows, + )))); + sort($values, SORT_NATURAL | SORT_FLAG_CASE); + + return $values; + } + + /** @param array $input + * @param list $months + * @param list $purchasers + * @return array{month:string,supplier:string,checker:string,settlement_method:string,purchaser:string} + */ + private function filters(array $input, array $months, array $purchasers): array + { + $text = static fn (string $key): string => mb_substr( + trim(is_scalar($input[$key] ?? '') ? (string) ($input[$key] ?? '') : ''), + 0, + 191, + ); + $month = $text('month'); + $purchaser = $text('purchaser'); + + return [ + 'month' => in_array($month, $months, true) ? $month : '', + 'supplier' => $text('supplier'), + 'checker' => $text('checker'), + 'settlement_method' => $text('settlement_method'), + 'purchaser' => in_array($purchaser, $purchasers, true) ? $purchaser : '', + ]; + } + + /** @param list> $rows + * @param array{month:string,supplier:string,checker:string,settlement_method:string,purchaser:string} $filters + * @return list> + */ + private function filterRows(array $rows, array $filters): array + { + return array_values(array_filter( + $rows, + static function (array $row) use ($filters): bool { + if ($filters['month'] !== '' && (string) ($row['summary_month'] ?? '') !== $filters['month']) { + return false; + } + + if ($filters['supplier'] !== '') { + $supplierNeedle = mb_strtolower($filters['supplier']); + $supplierHaystack = mb_strtolower(implode("\n", [ (string) ($row['supplier'] ?? ''), (string) ($row['company'] ?? ''), ])); - - return str_contains($haystack, $needle); - }, - )); - } - - $supplierCounts = []; - foreach ($negativeRows as $row) { - $key = trim((string) ($row['company'] ?? '')) . "\0" . trim((string) ($row['supplier'] ?? '')); - $supplierCounts[$key] = true; - } - - $total = count($negativeRows); - $pages = max((int) ceil($total / self::PER_PAGE), 1); - $page = min(max((int) request()->query('page', 1), 1), $pages); - $pageRows = array_slice($negativeRows, ($page - 1) * self::PER_PAGE, self::PER_PAGE); - $pageSupplierNames = array_values(array_unique(array_filter( - array_map( - static fn (array $row): string => trim((string) ($row['supplier'] ?? '')), - $pageRows, - ), - static fn (string $name): bool => $name !== '', - ))); - $purchasersBySupplier = []; - if ($pageSupplierNames !== []) { - try { - foreach ($this->supplierManagement->suppliersByNames($pageSupplierNames) as $supplier) { - $name = trim((string) ($supplier->scmname ?? '')); - $buyer = trim((string) ($supplier->buyer ?? '')); - if ($name !== '' && $buyer !== '') { - $purchasersBySupplier[$name][$buyer] = true; + if (! str_contains($supplierHaystack, $supplierNeedle)) { + return false; } } - } catch (Throwable $exception) { - report($exception); - } - } - $purchasersBySupplier = array_map( - static fn (array $buyers): string => implode('、', array_keys($buyers)), - $purchasersBySupplier, - ); - $items = array_map( - static function (array $row) use ($purchasersBySupplier): object { - $supplier = trim((string) ($row['supplier'] ?? '')); - $row['purchaser'] = $purchasersBySupplier[$supplier] ?? ''; - return (object) $row; + foreach (['checker', 'settlement_method'] as $field) { + if ($filters[$field] === '') { + continue; + } + if (! str_contains( + mb_strtolower((string) ($row[$field] ?? '')), + mb_strtolower($filters[$field]), + )) { + return false; + } + } + + return $filters['purchaser'] === '' + || trim((string) ($row['purchaser'] ?? '')) === $filters['purchaser']; }, - $pageRows, - ); - - $negativeAlertFields = []; - $fields = collect($this->registry->fields( - PayablesFinalRegistry::SECTION_SUPPLIER, - self::DATASET, - ))->map( - static fn (array $definition, string $name): array => ['name' => $name] + $definition, - )->values()->all(); - foreach ($fields as $field) { - $negativeAlertFields[] = $field; - if (($field['name'] ?? '') === 'negative_reason') { - $negativeAlertFields[] = ['name' => 'purchaser', 'label' => '采购', 'type' => 'text']; - } - } - - return [ - 'view' => 'business.pages.negative-alerts.supplier-negative-alert', - 'negativeAlertFields' => $negativeAlertFields, - 'negativeAlertRows' => new LengthAwarePaginator( - $items, - $total, - self::PER_PAGE, - $page, - [ - 'path' => request()->url(), - 'query' => request()->except('page'), - ], - ), - 'negativeAlertMonths' => $months, - 'negativeAlertMonth' => $month, - 'negativeAlertSupplier' => $supplierQuery, - 'negativeAlertSupplierNames' => $supplierNames, - 'negativeAlertSupplierCount' => count($supplierCounts), - 'negativeAlertTotal' => $total, - 'negativeAlertSourceUrl' => route('business.pages.show', [ - 'section' => 'supplier-payables-final', - 'page' => 'supplier-payables-report', - ]), - ]; + )); } private function number(mixed $value): ?float diff --git a/resources/views/business/pages/negative-alerts/dingtalk-task-unavailable.blade.php b/resources/views/business/pages/negative-alerts/dingtalk-task-unavailable.blade.php new file mode 100644 index 00000000..57f2485c --- /dev/null +++ b/resources/views/business/pages/negative-alerts/dingtalk-task-unavailable.blade.php @@ -0,0 +1,51 @@ + + + + + + + 任务链接不可用 + + + + + + diff --git a/resources/views/business/pages/negative-alerts/dingtalk-task.blade.php b/resources/views/business/pages/negative-alerts/dingtalk-task.blade.php new file mode 100644 index 00000000..e636dc9a --- /dev/null +++ b/resources/views/business/pages/negative-alerts/dingtalk-task.blade.php @@ -0,0 +1,291 @@ +@php + $assignment = $assignment ?? null; + $suppliers = $suppliers ?? []; + $supplierResults = $supplierResults ?? []; + $completed = ($assignment->status ?? '') === 'completed'; + $filledCount = collect($suppliers)->filter( + static fn (array $supplier): bool => filled($supplierResults[$supplier['supplier'] ?? ''] ?? null) + )->count(); +@endphp + + + + + + + + 供应商负数预警处理 + + + +
+
+

{{ $assignment->group_name }}

+

供应商负数预警处理

+
+ 采购:{{ $assignment->purchaser_name }} + 发送时间:{{ mb_substr((string) $assignment->sent_at, 0, 16) }} + 状态:{{ $completed ? '已回传,可继续修改' : '待填写' }} +
+
+
+ +
+ @if (session('negative_alert_success')) +
{{ session('negative_alert_success') }}
+ @endif + @if ($errors->any()) + + @endif + +
+
+ 供应商 + {{ number_format(count($suppliers)) }} 家 +
+
+ 预警记录 + {{ number_format((int) $assignment->row_count) }} 条 +
+
+ 已填写 + {{ number_format($filledCount) }} 家 +
+
+ +
+ @csrf + @foreach ($suppliers as $index => $supplier) + @php + $supplierName = (string) ($supplier['supplier'] ?? ''); + $months = implode('、', (array) ($supplier['months'] ?? [])); + $reasons = implode(';', (array) ($supplier['negative_reasons'] ?? [])); + $value = old('results.' . $index, $supplierResults[$supplierName] ?? ''); + @endphp +
+
+
+ {{ $index + 1 }} +

{{ $supplierName }}

+
+

+ {{ number_format((int) ($supplier['row_count'] ?? 0)) }} 条预警 + @if ($months !== '') · 月份 {{ $months }} @endif +

+
+
+
+
+ 负数金额 + ¥{{ number_format((float) ($supplier['alert_amount'] ?? 0), 2) }} +
+ @if ($reasons !== '') +
+ 负数原因 + {{ $reasons }} +
+ @endif +
+
+ + + @if ($errors->has('results.' . $index)) +

{{ $errors->first('results.' . $index) }}

+ @endif +
+
+
+ @endforeach + +
+
+ 已填写 {{ $filledCount }} / {{ count($suppliers) }} 家 + +
+
+
+
+ + + + diff --git a/resources/views/business/pages/negative-alerts/supplier-negative-alert.blade.php b/resources/views/business/pages/negative-alerts/supplier-negative-alert.blade.php index dfbdacb8..10179d36 100644 --- a/resources/views/business/pages/negative-alerts/supplier-negative-alert.blade.php +++ b/resources/views/business/pages/negative-alerts/supplier-negative-alert.blade.php @@ -9,8 +9,17 @@ $month = $negativeAlertMonth ?? ''; $supplierQuery = $negativeAlertSupplier ?? ''; $supplierNames = $negativeAlertSupplierNames ?? []; + $checker = $negativeAlertChecker ?? ''; + $checkerNames = $negativeAlertCheckerNames ?? []; + $settlementMethod = $negativeAlertSettlementMethod ?? ''; + $settlementMethods = $negativeAlertSettlementMethods ?? []; + $purchaser = $negativeAlertPurchaser ?? ''; + $purchaserNames = $negativeAlertPurchaserNames ?? []; + $robot = $negativeAlertRobot ?? ['configured' => false, 'webhook_hint' => '', 'group_name' => '财务&采购沟通群']; + $robotConfigured = (bool) ($robot['configured'] ?? false); $supplierCount = (int) ($negativeAlertSupplierCount ?? 0); $total = (int) ($negativeAlertTotal ?? 0); + $canSend = $purchaser !== '' && $total > 0 && $robotConfigured; $sourceUrl = $negativeAlertSourceUrl ?? '#'; @endphp @@ -336,6 +345,197 @@ text-decoration: none; } + .supplier-negative-alert-data-page [hidden] { + display: none !important; + } + + .supplier-negative-alert-data-page .sna-workflow { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px 16px; + border: 1px solid var(--sna-border); + border-radius: 8px; + background: #FFFDF8; + } + + .supplier-negative-alert-data-page .sna-workflow-copy { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 10px; + color: var(--sna-muted); + font-size: 0.75rem; + } + + .supplier-negative-alert-data-page .sna-workflow-copy strong { + color: var(--vip-content-ink, #171717); + font-size: 0.8125rem; + } + + .supplier-negative-alert-data-page .sna-robot-state { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 3px 8px; + border-radius: 999px; + background: #F1F7EC; + color: var(--vip-success, #53793E); + } + + .supplier-negative-alert-data-page .sna-robot-state.is-missing { + background: #FFF3E1; + color: var(--sna-warning); + } + + .supplier-negative-alert-data-page .sna-robot-state::before { + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; + content: ""; + } + + .supplier-negative-alert-data-page .sna-workflow-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + } + + .supplier-negative-alert-data-page .sna-workflow-actions form { + margin: 0; + } + + .supplier-negative-alert-data-page .sna-button:disabled { + cursor: not-allowed; + opacity: 0.55; + } + + .supplier-negative-alert-data-page .sna-handling-result { + width: 17rem; + max-width: 17rem; + white-space: normal; + overflow-wrap: anywhere; + } + + .supplier-negative-alert-data-page .sna-handling-result strong { + display: -webkit-box; + overflow: hidden; + font-weight: 500; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + } + + .supplier-negative-alert-data-page .sna-handling-result small { + display: block; + margin-top: 3px; + color: var(--sna-muted); + font-size: 0.6875rem; + white-space: nowrap; + } + + .supplier-negative-alert-data-page .sna-workflow-feedback { + margin: 0; + padding: 10px 12px; + border: 1px solid #B7CDA8; + border-radius: 8px; + background: #F1F7EC; + color: #2F4A22; + font-size: 0.75rem; + } + + .supplier-negative-alert-data-page .sna-workflow-feedback.is-error { + border-color: #E3B0B0; + background: #FDF1F1; + color: var(--sna-danger); + } + + .supplier-negative-alert-data-page .sna-modal { + position: fixed; + inset: 0; + z-index: 1080; + display: grid; + place-items: center; + padding: 16px; + } + + .supplier-negative-alert-data-page .sna-modal__backdrop { + position: absolute; + inset: 0; + background: rgba(5, 5, 6, 0.58); + } + + .supplier-negative-alert-data-page .sna-modal__dialog { + position: relative; + width: min(560px, 94vw); + overflow: hidden; + border: 1px solid var(--sna-border); + border-radius: 12px; + background: var(--vip-surface, #FFFFFF); + box-shadow: 0 4px 8px rgba(23, 23, 23, 0.10); + } + + .supplier-negative-alert-data-page .sna-modal__dialog header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px; + border-bottom: 1px solid var(--sna-border); + } + + .supplier-negative-alert-data-page .sna-modal__dialog h2 { + margin: 0; + font-size: 0.875rem; + } + + .supplier-negative-alert-data-page .sna-modal__dialog header button { + border: 0; + background: transparent; + color: var(--sna-muted); + cursor: pointer; + } + + .supplier-negative-alert-data-page .sna-modal__body { + display: grid; + gap: 12px; + padding: 16px; + } + + .supplier-negative-alert-data-page .sna-modal__body label { + display: grid; + gap: 5px; + color: var(--vip-content-ink, #171717); + font-size: 0.75rem; + font-weight: 600; + } + + .supplier-negative-alert-data-page .sna-modal__body input { + width: 100%; + height: 36px; + padding: 0 10px; + border: 1px solid var(--sna-border); + border-radius: 8px; + color: var(--vip-content-ink, #171717); + font: inherit; + font-weight: 400; + } + + .supplier-negative-alert-data-page .sna-modal__hint { + margin: 0; + color: var(--sna-muted); + font-size: 0.75rem; + line-height: 1.6; + } + + .supplier-negative-alert-data-page .sna-modal__dialog footer { + display: flex; + justify-content: flex-end; + gap: 8px; + padding: 12px 16px 16px; + } + @media (max-width: 900px) { .supplier-negative-alert-data-page .sna-summary { grid-template-columns: minmax(0, 1fr); @@ -345,6 +545,10 @@ width: 100%; margin-left: 0; } + + .supplier-negative-alert-data-page .sna-workflow-actions { + width: 100%; + } } @@ -375,6 +579,13 @@ + @if (session('success')) +

{{ session('success') }}

+ @endif + @if ($errors->has('dingtalk_send')) + + @endif +
+ + +
+
+
+ !$robotConfigured])> + {{ $robotConfigured ? '群机器人已配置' : '群机器人未配置' }} + + {{ $robot['group_name'] ?? '财务&采购沟通群' }} + + @if ($purchaser === '') + 选择采购后可发送当前筛选结果 + @else + 当前采购:{{ $purchaser }} · {{ number_format($supplierCount) }} 家供应商 + @endif + +
+
+ +
+ @csrf + + + + + + +
+
+
+
@if ($rows && $rows->isNotEmpty())
@@ -456,7 +746,18 @@ 'is-negative' => $isNegativeBalance, ]) > - @if ($value === null || $value === '') + @if ($field['name'] === 'handling_result') +
+ @if ($value !== null && $value !== '') + {{ $value }} + @if (($row->handling_result_meta ?? '') !== '') + {{ $row->handling_result_meta }} + @endif + @else + 待采购处理 + @endif +
+ @elseif ($value === null || $value === '') - @elseif ($isNumber && is_numeric($value)) {{ number_format((float) $value, 2) }} @@ -492,4 +793,108 @@
@endif
+ + @php + $robotFormHasErrors = $errors->has('dingtalk_webhook') + || $errors->has('dingtalk_secret') + || $errors->has('dingtalk_group_name'); + @endphp + + + diff --git a/routes/admin.php b/routes/admin.php index 59e6d352..22ca39f2 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -12,6 +12,7 @@ use App\Http\Controllers\Business\CourierSurchargeQuotes; use App\Http\Controllers\Business\CourierSurchargeTypes; use App\Http\Controllers\Business\ProductPrices; use App\Http\Controllers\Business\SupplierPayableActions; +use App\Http\Controllers\Business\SupplierNegativeAlertDingTalkActions; use App\Http\Controllers\Business\PayablesFinalActions; use App\Http\Controllers\Business\SupplierReconciliation as SupplierReconciliationActions; use App\Http\Controllers\Business\SystemizationTodos; @@ -462,6 +463,14 @@ 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-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'); + +Route::post('workspace/supplier-negative-alerts/send-dingtalk', [SupplierNegativeAlertDingTalkActions::class, 'send']) + ->middleware(['business.page:negative-alerts,supplier-negative-alert', 'throttle:10,1']) + ->name('business.supplier-negative-alerts.send-dingtalk'); + Route::get('workspace/refunds/non-jingxi-refund-data/export', 'Business\Pages@exportNonJingxiRefunds') ->middleware('business.page:refunds,non-jingxi-refund-data') ->name('business.refunds.non-jingxi-refund-data.export'); diff --git a/routes/web.php b/routes/web.php index 14e78d5b..ae8b21e4 100644 --- a/routes/web.php +++ b/routes/web.php @@ -2,6 +2,7 @@ use App\Http\Controllers\Integrations\EsignCallbacks; use App\Http\Controllers\Onboarding\CourierOnboardingForms; +use App\Http\Controllers\Business\SupplierNegativeAlertDingTalkForms; use Illuminate\Support\Facades\Route; use Livewire\Livewire; @@ -25,6 +26,15 @@ Route::post('onboarding/courier/{token}', [CourierOnboardingForms::class, 'updat ->where('token', '[A-Za-z0-9]{32,64}') ->name('courier-onboarding.update'); +Route::get('supplier-negative-alert/task/{token}', [SupplierNegativeAlertDingTalkForms::class, 'show']) + ->middleware('throttle:60,1') + ->where('token', '[A-Za-z0-9]{64}') + ->name('supplier-negative-alert.task'); +Route::post('supplier-negative-alert/task/{token}', [SupplierNegativeAlertDingTalkForms::class, 'update']) + ->middleware('throttle:20,1') + ->where('token', '[A-Za-z0-9]{64}') + ->name('supplier-negative-alert.task.update'); + Livewire::setScriptRoute(function ($handle) { $base = request()->getBasePath(); diff --git a/tests/Feature/Business/NegativeAlertPagesTest.php b/tests/Feature/Business/NegativeAlertPagesTest.php index f86856dd..0a19d060 100644 --- a/tests/Feature/Business/NegativeAlertPagesTest.php +++ b/tests/Feature/Business/NegativeAlertPagesTest.php @@ -8,6 +8,7 @@ use App\Models\Auth\Permission; use App\Utilities\BusinessNavigation; use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository; use Modules\EcommerceFinance\Services\PayablesFinalRegistry; +use Modules\EcommerceFinance\Services\SupplierNegativeAlertDingTalkWorkflow; use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; use Tests\Feature\FeatureTestCase; @@ -95,8 +96,8 @@ class NegativeAlertPagesTest extends FeatureTestCase ); $html = (string) $response->getContent(); preg_match_all('/)/', $html, $headers); - // 序号 + 隐藏主体名称后的原字段 + 动态匹配的采购。 - $this->assertCount(count($fields) + 1, $headers[0]); + // 序号 + 隐藏主体名称后的原字段 + 动态匹配的采购 + 处理结果。 + $this->assertCount(count($fields) + 2, $headers[0]); preg_match_all('/]*>(.*?)<\/th>/s', $html, $headerMatches); $labels = array_map( static fn (string $label): string => trim(html_entity_decode(strip_tags($label), ENT_QUOTES | ENT_HTML5, 'UTF-8')), @@ -105,6 +106,8 @@ class NegativeAlertPagesTest extends FeatureTestCase $negativeReasonIndex = array_search('负数原因', $labels, true); $this->assertNotFalse($negativeReasonIndex); $this->assertSame('采购', $labels[$negativeReasonIndex + 1]); + $this->assertSame('处理结果', $labels[$negativeReasonIndex + 2]); + $this->assertStringContainsString('待采购处理', $html); $this->assertStringNotContainsString('供应商公司主体名称', $html); $this->assertStringNotContainsString('测试供应商有限公司', $html); @@ -144,6 +147,45 @@ class NegativeAlertPagesTest extends FeatureTestCase ->assertDontSeeText('九月负余额供应商'); } + public function test_supplier_negative_alert_filters_by_checker_settlement_and_purchaser(): void + { + $this->saveSupplierPayable('filter:target', '目标供应商', '-50.00', '2026-09', [ + 'checker' => '李萌', + 'settlement_method' => '订单合同', + ]); + $this->saveSupplierPayable('filter:other', '其他供应商', '-60.00', '2026-09', [ + 'checker' => '陈亲园', + 'settlement_method' => '终止合作', + ]); + $supplierManagement = \Mockery::mock(SupplierManagementMirrorRepository::class); + $supplierManagement->shouldReceive('suppliersByNames') + ->once() + ->andReturn([ + (object) ['scmname' => '目标供应商', 'buyer' => '采购甲'], + (object) ['scmname' => '其他供应商', 'buyer' => '采购乙'], + ]); + $this->app->instance(SupplierManagementMirrorRepository::class, $supplierManagement); + app(SupplierNegativeAlertDingTalkWorkflow::class)->saveConfiguration( + 'https://oapi.dingtalk.com/robot/send?access_token=test-token', + 'SEC-test', + '财务&采购沟通群', + ); + + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'negative-alerts', + 'page' => 'supplier-negative-alert', + 'checker' => '李萌', + 'settlement_method' => '订单合同', + 'purchaser' => '采购甲', + ])) + ->assertOk() + ->assertSeeText('目标供应商') + ->assertSeeText('采购甲') + ->assertSeeText('发送至钉钉(1 家)') + ->assertDontSeeText('其他供应商'); + } + public function test_supplier_negative_alert_route_no_longer_renders_under_supplier_reconciliation(): void { $this->withExceptionHandling() diff --git a/tests/Feature/Business/SupplierNegativeAlertDingTalkTest.php b/tests/Feature/Business/SupplierNegativeAlertDingTalkTest.php new file mode 100644 index 00000000..55dfcabb --- /dev/null +++ b/tests/Feature/Business/SupplierNegativeAlertDingTalkTest.php @@ -0,0 +1,212 @@ +user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + } + + public function test_group_robot_configuration_is_encrypted_and_rendered_without_secrets(): void + { + $this->loginAs() + ->post(route('business.supplier-negative-alerts.dingtalk-group.save'), [ + 'dingtalk_webhook' => self::WEBHOOK, + 'dingtalk_secret' => self::SECRET, + 'dingtalk_group_name' => '财务&采购沟通群', + ]) + ->assertStatus(302) + ->assertSessionHas('success', '供应商负数预警群机器人已保存。'); + + $stored = (string) setting(SupplierNegativeAlertDingTalkWorkflow::SETTING_KEY); + $this->assertStringNotContainsString('sna-test-token', $stored); + $this->assertStringNotContainsString(self::SECRET, $stored); + + $this->loginAs() + ->get($this->pageUrl()) + ->assertOk() + ->assertSeeText('群机器人已配置') + ->assertSeeText('财务&采购沟通群') + ->assertDontSeeText('sna-test-token') + ->assertDontSeeText(self::SECRET); + } + + public function test_group_robot_rejects_untrusted_webhook(): void + { + $this->withExceptionHandling(); + + $this->loginAs() + ->post(route('business.supplier-negative-alerts.dingtalk-group.save'), [ + 'dingtalk_webhook' => 'https://example.com/robot/send?access_token=unsafe', + 'dingtalk_secret' => self::SECRET, + 'dingtalk_group_name' => '财务&采购沟通群', + ]) + ->assertStatus(302) + ->assertSessionHasErrors('dingtalk_webhook'); + } + + public function test_send_to_dingtalk_group_and_public_supplier_form_returns_results_to_page(): void + { + $this->seedRows(); + $this->bindSupplierManagement(); + app(SupplierNegativeAlertDingTalkWorkflow::class)->saveConfiguration( + self::WEBHOOK, + self::SECRET, + '财务&采购沟通群', + ); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + + $this->loginAs() + ->post(route('business.supplier-negative-alerts.send-dingtalk'), [ + 'purchaser' => '采购甲', + 'month' => '2026-09', + ]) + ->assertStatus(302) + ->assertSessionHas('success', '已发送至财务&采购沟通群:采购 采购甲,2 家供应商、3 条预警。'); + + $assignment = DB::table('supplier_negative_alert_assignments')->first(); + $this->assertNotNull($assignment); + $this->assertSame('sent', $assignment->status); + $this->assertSame(2, (int) $assignment->supplier_count); + $this->assertSame(3, (int) $assignment->row_count); + + $taskUrl = null; + Http::assertSent(function ($request) use (&$taskUrl): bool { + $taskUrl = (string) ($request['actionCard']['singleURL'] ?? ''); + + return str_contains($request->url(), 'robot/send') + && str_contains($request->url(), 'timestamp=') + && str_contains($request->url(), 'sign=') + && ($request['msgtype'] ?? '') === 'actionCard' + && str_contains((string) ($request['actionCard']['text'] ?? ''), '采购:**采购甲**') + && str_contains($taskUrl, '/supplier-negative-alert/task/'); + }); + preg_match('/\/supplier-negative-alert\/task\/([A-Za-z0-9]{64})$/', (string) $taskUrl, $matches); + $this->assertNotEmpty($matches[1] ?? null); + $token = $matches[1]; + + $response = $this->get(route('supplier-negative-alert.task', ['token' => $token])) + ->assertOk() + ->assertSeeText('供应商负数预警处理') + ->assertSeeText('三洋木业') + ->assertSeeText('久柯家具') + ->assertSee('placeholder="请填写该供应商的核对、沟通或处理结果"', false) + ->assertSeeText('处理结果'); + $this->assertSame(2, substr_count((string) $response->getContent(), 'name="results[]"')); + + $this->post(route('supplier-negative-alert.task.update', ['token' => $token]), [ + 'results' => [ + '三洋木业:已核对,等待供应商补货。', + '久柯家具:已确认负数由历史退款导致。', + ], + ]) + ->assertRedirect(route('supplier-negative-alert.task', ['token' => $token])) + ->assertSessionHas('negative_alert_success'); + + $assignment = DB::table('supplier_negative_alert_assignments')->first(); + $this->assertSame('completed', $assignment->status); + $this->assertEqualsCanonicalizing( + ['久柯家具', '三洋木业'], + DB::table('supplier_negative_alert_results')->orderBy('supplier_name')->pluck('supplier_name')->all(), + ); + + $this->loginAs() + ->get($this->pageUrl(['month' => '2026-09', 'purchaser' => '采购甲'])) + ->assertOk() + ->assertSeeText('三洋木业:已核对,等待供应商补货。') + ->assertSeeText('久柯家具:已确认负数由历史退款导致。') + ->assertDontSeeText('待采购处理'); + } + + public function test_expired_task_link_is_unavailable(): void + { + $this->seedRows(); + $this->bindSupplierManagement(); + app(SupplierNegativeAlertDingTalkWorkflow::class)->saveConfiguration( + self::WEBHOOK, + self::SECRET, + '财务&采购沟通群', + ); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + $this->loginAs()->post(route('business.supplier-negative-alerts.send-dingtalk'), [ + 'purchaser' => '采购甲', + 'month' => '2026-09', + ]); + + $taskUrl = ''; + Http::assertSent(function ($request) use (&$taskUrl): bool { + $taskUrl = (string) ($request['actionCard']['singleURL'] ?? ''); + + return $taskUrl !== ''; + }); + preg_match('/\/([A-Za-z0-9]{64})$/', $taskUrl, $matches); + DB::table('supplier_negative_alert_assignments')->update([ + 'token_expires_at' => now()->subMinute(), + ]); + + $this->get(route('supplier-negative-alert.task', ['token' => $matches[1]])) + ->assertNotFound() + ->assertSeeText('任务链接无效或已过期'); + } + + private function seedRows(): void + { + $store = app(SupplierPayableOverrideStore::class); + $dataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:supplier-payables-report'; + foreach ([ + 'sanyang:1' => ['supplier' => '三洋木业', 'supplier_balance' => '-100.00'], + 'sanyang:2' => ['supplier' => '三洋木业', 'supplier_balance' => '-50.00'], + 'jiuke:1' => ['supplier' => '久柯家具', 'supplier_balance' => '-80.00'], + ] as $key => $row) { + $store->save($dataset, $key, $row + [ + 'summary_month' => '2026-09', + 'checker' => '李萌', + 'settlement_method' => '订单合同', + 'should_pay' => '0.00', + 'estimated_price' => '0.00', + 'negative_reason' => '历史差异待核对', + ], (int) $this->company->id, (int) $this->user->id); + } + } + + private function bindSupplierManagement(): void + { + $supplierManagement = \Mockery::mock(SupplierManagementMirrorRepository::class); + $supplierManagement->shouldReceive('suppliersByNames') + ->andReturnUsing(static function (array $names): array { + return array_map( + static fn (string $name): object => (object) ['scmname' => $name, 'buyer' => '采购甲'], + $names, + ); + }); + $this->app->instance(SupplierManagementMirrorRepository::class, $supplierManagement); + } + + /** @param array $query */ + private function pageUrl(array $query = []): string + { + return route('business.pages.show', array_merge([ + 'section' => 'negative-alerts', + 'page' => 'supplier-negative-alert', + ], $query)); + } +} -- 2.47.2