feat: 供应商负数预警钉钉采购处理闭环 #737
@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Modules\EcommerceFinance\Services\SupplierNegativeAlertDingTalkWorkflow;
|
||||
use Modules\EcommerceFinance\View\SupplierNegativeAlertPageData;
|
||||
use Throwable;
|
||||
|
||||
class SupplierNegativeAlertDingTalkActions extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SupplierNegativeAlertPageData $pageData,
|
||||
private readonly SupplierNegativeAlertDingTalkWorkflow $workflow,
|
||||
) {
|
||||
$this->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']} 条预警。",
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Business;
|
||||
|
||||
use App\Models\Common\Company;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
use Modules\EcommerceFinance\Services\SupplierNegativeAlertDingTalkWorkflow;
|
||||
|
||||
class SupplierNegativeAlertDingTalkForms extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SupplierNegativeAlertDingTalkWorkflow $workflow,
|
||||
) {
|
||||
}
|
||||
|
||||
public function show(string $token): View|Response
|
||||
{
|
||||
$assignment = $this->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);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable('supplier_negative_alert_assignments')) {
|
||||
Schema::create('supplier_negative_alert_assignments', function (Blueprint $table): void {
|
||||
$table->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');
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,398 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 供应商负数预警:向财务采购群机器人发送任务,并接收采购按供应商填写的处理结果。
|
||||
*/
|
||||
class SupplierNegativeAlertDingTalkWorkflow
|
||||
{
|
||||
public const SETTING_KEY = 'supplier_negative_alerts.dingtalk_group';
|
||||
|
||||
public const DEFAULT_GROUP_NAME = '财务&采购沟通群';
|
||||
|
||||
private const TOKEN_TTL_DAYS = 30;
|
||||
|
||||
/** @return array{configured:bool,webhook_hint:string,group_name:string} */
|
||||
public function configuration(): array
|
||||
{
|
||||
$config = $this->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<array<string,mixed>> $rows 已按采购筛选的负数预警记录
|
||||
* @param array<string,mixed> $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<string> $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<string> $suppliers
|
||||
* @return array<string,object>
|
||||
*/
|
||||
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<string,string> */
|
||||
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<string,mixed> */
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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<string,mixed> */
|
||||
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<string,mixed> $filters
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function rowsForFilters(array $filters): array
|
||||
{
|
||||
$allRows = $this->decoratedRows();
|
||||
|
||||
return $this->filterRows($allRows, $this->filters(
|
||||
$filters,
|
||||
$this->monthOptions($allRows),
|
||||
$this->purchaserOptions($allRows),
|
||||
));
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
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<array<string,mixed>> */
|
||||
private function negativeRows(): array
|
||||
{
|
||||
$rows = $this->store->listRows(
|
||||
PayablesFinalActions::DATASET_PREFIX . 'supplier:' . self::DATASET,
|
||||
@ -59,8 +196,16 @@ class SupplierNegativeAlertPageData
|
||||
);
|
||||
});
|
||||
|
||||
return $negativeRows;
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $rows
|
||||
* @return list<string>
|
||||
*/
|
||||
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<array<string,mixed>> $rows
|
||||
* @return list<string>
|
||||
*/
|
||||
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<array<string,mixed>> $rows
|
||||
* @return list<string>
|
||||
*/
|
||||
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<array<string,mixed>> $rows
|
||||
* @return list<string>
|
||||
*/
|
||||
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<string,mixed> $input
|
||||
* @param list<string> $months
|
||||
* @param list<string> $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<array<string,mixed>> $rows
|
||||
* @param array{month:string,supplier:string,checker:string,settlement_method:string,purchaser:string} $filters
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
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
|
||||
|
||||
@ -0,0 +1,51 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>任务链接不可用</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px 16px;
|
||||
background: #F8F6F1;
|
||||
color: #171717;
|
||||
font: 15px/1.6 "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
|
||||
}
|
||||
.box {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
padding: 28px 22px;
|
||||
border: 1px solid #D8D2C7;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
text-align: center;
|
||||
}
|
||||
.icon {
|
||||
display: inline-grid;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
margin-bottom: 12px;
|
||||
place-items: center;
|
||||
border-radius: 50%;
|
||||
background: #F7F0DE;
|
||||
color: #856632;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
}
|
||||
h1 { margin: 0 0 8px; font-size: 19px; }
|
||||
p { margin: 0; color: #595959; font-size: 14px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="box" role="alert">
|
||||
<div class="icon" aria-hidden="true">!</div>
|
||||
<h1>任务链接无效或已过期</h1>
|
||||
<p>请联系财务重新发送供应商负数预警任务。</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@ -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
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<meta name="format-detection" content="telephone=no">
|
||||
<title>供应商负数预警处理</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #171717;
|
||||
--muted: #595959;
|
||||
--gold: #856632;
|
||||
--gold-strong: #6A5129;
|
||||
--gold-soft: #F7F0DE;
|
||||
--bg: #F8F6F1;
|
||||
--surface: #FFFFFF;
|
||||
--border: #D8D2C7;
|
||||
--danger: #B80000;
|
||||
--success: #53793E;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font: 15px/1.55 "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
|
||||
}
|
||||
.hero {
|
||||
padding: 24px 16px 22px;
|
||||
background: #050506;
|
||||
color: #F2E7C5;
|
||||
}
|
||||
.hero__inner, .main { width: min(760px, 100%); margin: 0 auto; }
|
||||
.hero__eyebrow { margin: 0 0 7px; color: #BFAF86; font-size: 12px; letter-spacing: .08em; }
|
||||
.hero h1 { margin: 0; font-size: 22px; line-height: 1.3; }
|
||||
.hero__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 16px;
|
||||
margin-top: 12px;
|
||||
color: #DDD0AA;
|
||||
font-size: 13px;
|
||||
}
|
||||
.main { padding: 14px 16px 120px; }
|
||||
.notice {
|
||||
margin-bottom: 12px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid #B7CDA8;
|
||||
border-radius: 10px;
|
||||
background: #F1F7EC;
|
||||
color: #2F4A22;
|
||||
}
|
||||
.notice.is-error {
|
||||
border-color: #E3B0B0;
|
||||
background: #FDF1F1;
|
||||
color: #7A1010;
|
||||
}
|
||||
.summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.summary__item {
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.summary__item span { display: block; color: var(--muted); font-size: 12px; }
|
||||
.summary__item strong { display: block; margin-top: 3px; font-size: 18px; font-variant-numeric: tabular-nums; }
|
||||
.task-card {
|
||||
margin-bottom: 12px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.task-card__head { padding: 14px 16px 12px; border-bottom: 1px solid #ECE8E0; }
|
||||
.task-card__title-row { display: flex; align-items: flex-start; gap: 10px; }
|
||||
.task-card__index {
|
||||
display: inline-grid;
|
||||
flex: none;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
place-items: center;
|
||||
border-radius: 50%;
|
||||
background: var(--gold-soft);
|
||||
color: var(--gold);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.task-card h2 { margin: 0; font-size: 17px; line-height: 1.4; }
|
||||
.task-card__meta { margin: 7px 0 0 36px; color: var(--muted); font-size: 12px; }
|
||||
.task-card__body { display: grid; gap: 10px; padding: 14px 16px 16px; }
|
||||
.facts { display: grid; gap: 7px; }
|
||||
.fact {
|
||||
display: grid;
|
||||
grid-template-columns: 68px minmax(0, 1fr);
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.fact span { color: var(--muted); }
|
||||
.fact strong { font-weight: 500; overflow-wrap: anywhere; }
|
||||
.fact strong.is-negative { color: var(--danger); font-variant-numeric: tabular-nums; }
|
||||
.field { display: grid; gap: 6px; }
|
||||
.field label { font-size: 14px; font-weight: 600; }
|
||||
.field .required { margin-left: 2px; color: var(--danger); }
|
||||
textarea {
|
||||
width: 100%;
|
||||
min-height: 104px;
|
||||
padding: 11px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
resize: vertical;
|
||||
}
|
||||
textarea:focus {
|
||||
border-color: var(--gold);
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(133, 102, 50, .18);
|
||||
}
|
||||
textarea.has-error { border-color: var(--danger); }
|
||||
.error { margin: 0; color: var(--danger); font-size: 13px; }
|
||||
.submit-bar {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 20;
|
||||
padding: 12px 16px calc(12px + env(safe-area-inset-bottom));
|
||||
border-top: 1px solid var(--border);
|
||||
background: rgba(255, 255, 255, .96);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
.submit-bar__inner {
|
||||
width: min(760px, 100%);
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.submit-progress { flex: 1; color: var(--muted); font-size: 12px; }
|
||||
button {
|
||||
min-height: 44px;
|
||||
padding: 0 18px;
|
||||
border: 1px solid var(--gold-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--gold-strong);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:disabled { cursor: wait; opacity: .65; }
|
||||
@media (max-width: 520px) {
|
||||
.summary { grid-template-columns: 1fr 1fr; }
|
||||
.summary__item:last-child { grid-column: 1 / -1; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="hero">
|
||||
<div class="hero__inner">
|
||||
<p class="hero__eyebrow">{{ $assignment->group_name }}</p>
|
||||
<h1>供应商负数预警处理</h1>
|
||||
<div class="hero__meta">
|
||||
<span>采购:{{ $assignment->purchaser_name }}</span>
|
||||
<span>发送时间:{{ mb_substr((string) $assignment->sent_at, 0, 16) }}</span>
|
||||
<span>状态:{{ $completed ? '已回传,可继续修改' : '待填写' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="main">
|
||||
@if (session('negative_alert_success'))
|
||||
<div class="notice" role="status">{{ session('negative_alert_success') }}</div>
|
||||
@endif
|
||||
@if ($errors->any())
|
||||
<div class="notice is-error" role="alert">{{ $errors->first() }}</div>
|
||||
@endif
|
||||
|
||||
<section class="summary" aria-label="任务汇总">
|
||||
<div class="summary__item">
|
||||
<span>供应商</span>
|
||||
<strong>{{ number_format(count($suppliers)) }} 家</strong>
|
||||
</div>
|
||||
<div class="summary__item">
|
||||
<span>预警记录</span>
|
||||
<strong>{{ number_format((int) $assignment->row_count) }} 条</strong>
|
||||
</div>
|
||||
<div class="summary__item">
|
||||
<span>已填写</span>
|
||||
<strong data-filled-count>{{ number_format($filledCount) }} 家</strong>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<form method="POST" action="{{ route('supplier-negative-alert.task.update', ['token' => $token]) }}" data-result-form>
|
||||
@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
|
||||
<article class="task-card" data-result-card>
|
||||
<div class="task-card__head">
|
||||
<div class="task-card__title-row">
|
||||
<span class="task-card__index">{{ $index + 1 }}</span>
|
||||
<h2>{{ $supplierName }}</h2>
|
||||
</div>
|
||||
<p class="task-card__meta">
|
||||
{{ number_format((int) ($supplier['row_count'] ?? 0)) }} 条预警
|
||||
@if ($months !== '') · 月份 {{ $months }} @endif
|
||||
</p>
|
||||
</div>
|
||||
<div class="task-card__body">
|
||||
<div class="facts">
|
||||
<div class="fact">
|
||||
<span>负数金额</span>
|
||||
<strong class="is-negative">¥{{ number_format((float) ($supplier['alert_amount'] ?? 0), 2) }}</strong>
|
||||
</div>
|
||||
@if ($reasons !== '')
|
||||
<div class="fact">
|
||||
<span>负数原因</span>
|
||||
<strong>{{ $reasons }}</strong>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="result-{{ $index }}">处理结果<span class="required">*</span></label>
|
||||
<textarea
|
||||
id="result-{{ $index }}"
|
||||
name="results[]"
|
||||
maxlength="2000"
|
||||
required
|
||||
data-result-input
|
||||
@class(['has-error' => $errors->has('results.' . $index)])
|
||||
placeholder="请填写该供应商的核对、沟通或处理结果">{{ $value }}</textarea>
|
||||
@if ($errors->has('results.' . $index))
|
||||
<p class="error">{{ $errors->first('results.' . $index) }}</p>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
@endforeach
|
||||
|
||||
<div class="submit-bar">
|
||||
<div class="submit-bar__inner">
|
||||
<span class="submit-progress" data-submit-progress>已填写 {{ $filledCount }} / {{ count($suppliers) }} 家</span>
|
||||
<button type="submit" data-submit-button>{{ $completed ? '更新处理结果' : '提交处理结果' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
(() => {
|
||||
const form = document.querySelector('[data-result-form]');
|
||||
if (!form) return;
|
||||
const inputs = [...form.querySelectorAll('[data-result-input]')];
|
||||
const progress = form.querySelector('[data-submit-progress]');
|
||||
const button = form.querySelector('[data-submit-button]');
|
||||
const updateProgress = () => {
|
||||
const filled = inputs.filter(input => input.value.trim() !== '').length;
|
||||
progress.textContent = `已填写 ${filled} / ${inputs.length} 家`;
|
||||
};
|
||||
inputs.forEach(input => input.addEventListener('input', updateProgress));
|
||||
form.addEventListener('submit', () => {
|
||||
button.disabled = true;
|
||||
button.textContent = '正在回传…';
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@ -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%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -375,6 +579,13 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (session('success'))
|
||||
<p class="sna-workflow-feedback" role="status">{{ session('success') }}</p>
|
||||
@endif
|
||||
@if ($errors->has('dingtalk_send'))
|
||||
<p class="sna-workflow-feedback is-error" role="alert">{{ $errors->first('dingtalk_send') }}</p>
|
||||
@endif
|
||||
|
||||
<form method="GET" class="sna-toolbar" aria-label="供应商负数预警筛选">
|
||||
<label class="sna-field">
|
||||
<span>月份</span>
|
||||
@ -399,6 +610,43 @@
|
||||
@endforeach
|
||||
</datalist>
|
||||
</label>
|
||||
<label class="sna-field">
|
||||
<span>对账人</span>
|
||||
<input type="search"
|
||||
name="checker"
|
||||
value="{{ $checker }}"
|
||||
list="negative-alert-checker-options"
|
||||
placeholder="输入对账人"
|
||||
autocomplete="off">
|
||||
<datalist id="negative-alert-checker-options">
|
||||
@foreach ($checkerNames as $checkerName)
|
||||
<option value="{{ $checkerName }}"></option>
|
||||
@endforeach
|
||||
</datalist>
|
||||
</label>
|
||||
<label class="sna-field">
|
||||
<span>结算方式</span>
|
||||
<input type="search"
|
||||
name="settlement_method"
|
||||
value="{{ $settlementMethod }}"
|
||||
list="negative-alert-settlement-options"
|
||||
placeholder="输入结算方式"
|
||||
autocomplete="off">
|
||||
<datalist id="negative-alert-settlement-options">
|
||||
@foreach ($settlementMethods as $settlementOption)
|
||||
<option value="{{ $settlementOption }}"></option>
|
||||
@endforeach
|
||||
</datalist>
|
||||
</label>
|
||||
<label class="sna-field">
|
||||
<span>采购</span>
|
||||
<select name="purchaser">
|
||||
<option value="">全部采购</option>
|
||||
@foreach ($purchaserNames as $purchaserName)
|
||||
<option value="{{ $purchaserName }}" @selected($purchaser === $purchaserName)>{{ $purchaserName }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
<div class="sna-actions">
|
||||
<button type="submit" class="sna-button is-primary">
|
||||
<span class="material-icons-outlined" aria-hidden="true">search</span>
|
||||
@ -416,6 +664,48 @@
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<section class="sna-workflow" aria-label="采购处理流程">
|
||||
<div class="sna-workflow-copy">
|
||||
<span @class(['sna-robot-state', 'is-missing' => !$robotConfigured])>
|
||||
{{ $robotConfigured ? '群机器人已配置' : '群机器人未配置' }}
|
||||
</span>
|
||||
<strong>{{ $robot['group_name'] ?? '财务&采购沟通群' }}</strong>
|
||||
<span>
|
||||
@if ($purchaser === '')
|
||||
选择采购后可发送当前筛选结果
|
||||
@else
|
||||
当前采购:{{ $purchaser }} · {{ number_format($supplierCount) }} 家供应商
|
||||
@endif
|
||||
</span>
|
||||
</div>
|
||||
<div class="sna-workflow-actions">
|
||||
<button type="button" class="sna-button" data-sna-robot-open>
|
||||
<span class="material-icons-outlined" aria-hidden="true">settings</span>
|
||||
群机器人设置
|
||||
</button>
|
||||
<form method="POST" action="{{ route('business.supplier-negative-alerts.send-dingtalk') }}">
|
||||
@csrf
|
||||
<input type="hidden" name="month" value="{{ $month }}">
|
||||
<input type="hidden" name="supplier" value="{{ $supplierQuery }}">
|
||||
<input type="hidden" name="checker" value="{{ $checker }}">
|
||||
<input type="hidden" name="settlement_method" value="{{ $settlementMethod }}">
|
||||
<input type="hidden" name="purchaser" value="{{ $purchaser }}">
|
||||
<button type="submit" class="sna-button is-primary" @disabled(!$canSend)>
|
||||
<span class="material-icons-outlined" aria-hidden="true">send</span>
|
||||
@if ($purchaser === '')
|
||||
请先选择采购
|
||||
@elseif ($total === 0)
|
||||
当前无供应商
|
||||
@elseif (!$robotConfigured)
|
||||
请先配置群机器人
|
||||
@else
|
||||
发送至钉钉({{ number_format($supplierCount) }} 家)
|
||||
@endif
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="sna-table-card" aria-label="供应商负数预警明细">
|
||||
@if ($rows && $rows->isNotEmpty())
|
||||
<div class="sna-table-scroll">
|
||||
@ -456,7 +746,18 @@
|
||||
'is-negative' => $isNegativeBalance,
|
||||
])
|
||||
>
|
||||
@if ($value === null || $value === '')
|
||||
@if ($field['name'] === 'handling_result')
|
||||
<div class="sna-handling-result">
|
||||
@if ($value !== null && $value !== '')
|
||||
<strong title="{{ $value }}">{{ $value }}</strong>
|
||||
@if (($row->handling_result_meta ?? '') !== '')
|
||||
<small>{{ $row->handling_result_meta }}</small>
|
||||
@endif
|
||||
@else
|
||||
<span>待采购处理</span>
|
||||
@endif
|
||||
</div>
|
||||
@elseif ($value === null || $value === '')
|
||||
-
|
||||
@elseif ($isNumber && is_numeric($value))
|
||||
{{ number_format((float) $value, 2) }}
|
||||
@ -492,4 +793,108 @@
|
||||
</div>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
@php
|
||||
$robotFormHasErrors = $errors->has('dingtalk_webhook')
|
||||
|| $errors->has('dingtalk_secret')
|
||||
|| $errors->has('dingtalk_group_name');
|
||||
@endphp
|
||||
<div class="sna-modal" data-sna-robot-modal @if (!$robotFormHasErrors) hidden @endif>
|
||||
<div class="sna-modal__backdrop" data-sna-robot-close></div>
|
||||
<section class="sna-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="sna-robot-title">
|
||||
<header>
|
||||
<h2 id="sna-robot-title">钉钉群机器人设置</h2>
|
||||
<button type="button" data-sna-robot-close aria-label="关闭">
|
||||
<span class="material-icons-outlined" aria-hidden="true">close</span>
|
||||
</button>
|
||||
</header>
|
||||
<form method="POST" action="{{ route('business.supplier-negative-alerts.dingtalk-group.save') }}">
|
||||
@csrf
|
||||
<div class="sna-modal__body">
|
||||
<p class="sna-modal__hint">
|
||||
在财务采购对接群中添加自定义机器人,开启加签后填写 Webhook 和加签密钥。密钥会加密保存。
|
||||
</p>
|
||||
<label>
|
||||
钉钉群名称
|
||||
<input name="dingtalk_group_name"
|
||||
value="{{ old('dingtalk_group_name', $robot['group_name'] ?? '财务&采购沟通群') }}"
|
||||
maxlength="191"
|
||||
required>
|
||||
</label>
|
||||
@if ($errors->has('dingtalk_group_name'))
|
||||
<p class="sna-workflow-feedback is-error">{{ $errors->first('dingtalk_group_name') }}</p>
|
||||
@endif
|
||||
<label>
|
||||
Webhook
|
||||
<input name="dingtalk_webhook"
|
||||
value="{{ old('dingtalk_webhook') }}"
|
||||
placeholder="{{ $robotConfigured ? '已配置,留空表示不修改' : 'https://oapi.dingtalk.com/robot/send?access_token=...' }}"
|
||||
maxlength="2048"
|
||||
autocomplete="off">
|
||||
</label>
|
||||
@if ($robotConfigured)
|
||||
<p class="sna-modal__hint">当前 Webhook:{{ $robot['webhook_hint'] }}</p>
|
||||
@endif
|
||||
@if ($errors->has('dingtalk_webhook'))
|
||||
<p class="sna-workflow-feedback is-error">{{ $errors->first('dingtalk_webhook') }}</p>
|
||||
@endif
|
||||
<label>
|
||||
加签密钥
|
||||
<input name="dingtalk_secret"
|
||||
value="{{ old('dingtalk_secret') }}"
|
||||
placeholder="{{ $robotConfigured ? '已配置,留空表示不修改' : 'SEC...' }}"
|
||||
maxlength="256"
|
||||
autocomplete="off">
|
||||
</label>
|
||||
@if ($errors->has('dingtalk_secret'))
|
||||
<p class="sna-workflow-feedback is-error">{{ $errors->first('dingtalk_secret') }}</p>
|
||||
@endif
|
||||
</div>
|
||||
<footer>
|
||||
<button type="button" class="sna-button" data-sna-robot-close>取消</button>
|
||||
<button type="submit" class="sna-button is-primary">保存配置</button>
|
||||
</footer>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script data-caiwu-replay>
|
||||
(() => {
|
||||
if (window.caiwuSupplierNegativeAlertBound) return;
|
||||
window.caiwuSupplierNegativeAlertBound = true;
|
||||
let opener = null;
|
||||
|
||||
const modal = () => document.querySelector('[data-sna-robot-modal]');
|
||||
const close = () => {
|
||||
const current = modal();
|
||||
if (!current) return;
|
||||
current.hidden = true;
|
||||
opener?.focus?.();
|
||||
opener = null;
|
||||
};
|
||||
const open = button => {
|
||||
const current = modal();
|
||||
if (!current) return;
|
||||
opener = button;
|
||||
current.hidden = false;
|
||||
current.querySelector('input[name="dingtalk_group_name"]')?.focus();
|
||||
};
|
||||
|
||||
document.addEventListener('click', event => {
|
||||
const trigger = event.target.closest('[data-sna-robot-open]');
|
||||
if (trigger) {
|
||||
event.preventDefault();
|
||||
open(trigger);
|
||||
return;
|
||||
}
|
||||
if (event.target.closest('[data-sna-robot-close]')) {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key === 'Escape' && !modal()?.hidden) close();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
@ -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');
|
||||
|
||||
@ -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();
|
||||
|
||||
|
||||
@ -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('/<th(?:\s|>)/', $html, $headers);
|
||||
// 序号 + 隐藏主体名称后的原字段 + 动态匹配的采购。
|
||||
$this->assertCount(count($fields) + 1, $headers[0]);
|
||||
// 序号 + 隐藏主体名称后的原字段 + 动态匹配的采购 + 处理结果。
|
||||
$this->assertCount(count($fields) + 2, $headers[0]);
|
||||
preg_match_all('/<th[^>]*>(.*?)<\/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()
|
||||
|
||||
212
tests/Feature/Business/SupplierNegativeAlertDingTalkTest.php
Normal file
212
tests/Feature/Business/SupplierNegativeAlertDingTalkTest.php
Normal file
@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Http\Controllers\Business\PayablesFinalActions;
|
||||
use App\Models\Auth\Permission;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository;
|
||||
use Modules\EcommerceFinance\Services\SupplierNegativeAlertDingTalkWorkflow;
|
||||
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class SupplierNegativeAlertDingTalkTest extends FeatureTestCase
|
||||
{
|
||||
private const WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=sna-test-token';
|
||||
|
||||
private const SECRET = 'SEC-sna-test-secret';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->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<string,string> $query */
|
||||
private function pageUrl(array $query = []): string
|
||||
{
|
||||
return route('business.pages.show', array_merge([
|
||||
'section' => 'negative-alerts',
|
||||
'page' => 'supplier-negative-alert',
|
||||
], $query));
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user