From 2dca095bffae1508a1cee22be603b3ed405357a0 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Wed, 2 Dec 2026 21:17:54 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=BF=AB=E9=80=92=E8=B4=A6=E5=8D=95):=20?= =?UTF-8?q?=E7=BE=A4=E6=8E=A8=E9=80=81=E5=85=8D=E7=99=BB=E5=BD=95=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Business/CourierBillController.php | 54 ++++++++- .../Business/CourierUploadShare.php | 107 ++++++++++++++++++ .../CourierBills/CourierUploadLink.php | 54 +++++++++ .../CourierBills/PortalFreightBillImports.php | 21 +++- .../Services/SupplierDingTalkNotifier.php | 20 +++- .../courier-bills/groups.blade.php | 27 ++++- .../courier-bills/upload-share.blade.php | 72 ++++++++++++ .../courier-bills/upload.blade.php | 12 ++ routes/admin.php | 2 + routes/signed.php | 12 ++ .../Business/PortalFreightBillTest.php | 72 ++++++++++++ 11 files changed, 444 insertions(+), 9 deletions(-) create mode 100644 app/Http/Controllers/Business/CourierUploadShare.php create mode 100644 app/Support/CourierBills/CourierUploadLink.php create mode 100644 resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php diff --git a/app/Http/Controllers/Business/CourierBillController.php b/app/Http/Controllers/Business/CourierBillController.php index fef9c9b34..db697a8dd 100644 --- a/app/Http/Controllers/Business/CourierBillController.php +++ b/app/Http/Controllers/Business/CourierBillController.php @@ -13,7 +13,9 @@ use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; +use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier; use RuntimeException; +use Throwable; /** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */ final class CourierBillController extends Controller @@ -35,7 +37,9 @@ final class CourierBillController extends Controller $db = $this->store->db(); $months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all(); $month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m')); - $data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $this->store->groups()]; + $groups = $this->store->groups(); + $data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $groups, + 'cbRobots' => app(SupplierDingTalkNotifier::class)->configurationMap(array_map(static fn ($g): string => (string) $g->name, $groups))]; $data += match ($view) { 'statement' => $this->statementData($request), 'details' => $this->detailsData($request, $month), @@ -479,6 +483,54 @@ final class CourierBillController extends Controller } } + /** 给对账分组配这家快递的钉钉对账群机器人(群设置 → 机器人 → 自定义,安全设置选「加签」)。 */ + public function saveRobot(Request $request, int $group) + { + $data = $request->validate(['webhook' => ['nullable', 'string', 'max:500'], 'secret' => ['nullable', 'string', 'max:256']]); + $g = collect($this->store->groups())->firstWhere('id', $group); + abort_if($g === null, 404); + app(SupplierDingTalkNotifier::class)->save((string) $g->name, (string) ($data['webhook'] ?? ''), (string) ($data['secret'] ?? ''), false); + + return $this->back($request, ['cb_view' => 'groups'], '已保存「' . $g->name . '」的钉钉对账群机器人。'); + } + + /** 往快递钉钉对账群推这个月的免登录上传链接:传 group 只推这一家,不传就推所有配了机器人的分组。 */ + public function pushUploadLinks(Request $request) + { + $data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'group' => ['nullable', 'integer']]); + $notifier = app(SupplierDingTalkNotifier::class); + $groups = collect($this->store->groups()); + if (! empty($data['group'])) { + $groups = $groups->where('id', (int) $data['group']); + abort_if($groups->isEmpty(), 404); + } + $configured = array_flip($notifier->configuredSuppliers()); + $companyId = (int) (company_id() ?: 1); + $sent = $failed = []; + $skipped = 0; + foreach ($groups as $g) { + if (! isset($configured[$g->name])) { + $skipped++; + continue; + } + try { + $notifier->pushCourierUploadLink((string) $g->name, $data['month'], + app(\App\Support\CourierBills\CourierUploadLink::class)->pageUrl($companyId, (int) $g->id, $data['month'])); + $sent[] = $g->name; + } catch (Throwable $error) { + report($error); + $failed[] = $g->name . '(发送失败,请检查群机器人配置)'; + } + } + if (! empty($data['group']) && $sent === [] && $failed === []) { + throw ValidationException::withMessages(['courier_bills' => '这家还没有配置钉钉对账群机器人,请先在「对账分组」里配置。']); + } + + return $this->back($request, [], '已推送 ' . $data['month'] . ' 上传链接 ' . count($sent) . ' 家' . ($sent !== [] ? ':' . implode('、', array_slice($sent, 0, 30)) : '') + . ($failed !== [] ? ';失败 ' . count($failed) . ' 家:' . implode('、', $failed) : '') + . ($skipped > 0 && empty($data['group']) ? ';' . $skipped . ' 家没配钉钉群机器人,没推' : '') . '。'); + } + private function back(Request $request, array $query, string $message) { $target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => self::section($request), diff --git a/app/Http/Controllers/Business/CourierUploadShare.php b/app/Http/Controllers/Business/CourierUploadShare.php new file mode 100644 index 000000000..ccc7bcf4d --- /dev/null +++ b/app/Http/Controllers/Business/CourierUploadShare.php @@ -0,0 +1,107 @@ +target($request, $token); + $expires = $this->expiresAt($request); + $files = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']) + ->orderByDesc('id')->limit(20)->get(); + $pending = array_map(static fn (array $file): object => (object) [ + 'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'], + 'status' => $file['status'], 'message' => $file['message'], 'created_at' => $file['at'], + ], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'])); + $files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values(); + + return response()->view('business.pages.courier-payables.courier-bills.upload-share', [ + 'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files, + 'expiresAt' => $expires, 'confirmed' => $t['confirmed'], + 'uploadUrl' => $this->links->signedRoute('signed.courier-bill-upload.upload', $token, $t['companyId'], $expires), + 'templateUrl' => $this->links->signedRoute('signed.courier-bill-upload.template', $token, $t['companyId'], $expires), + ])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive', + 'Referrer-Policy' => 'no-referrer']); + } + + public function template(Request $request, string $token): StreamedResponse + { + $t = $this->target($request, $token); + + return $this->template->download($t['group']->name . '_' . $t['month'] . '_账单上传模板.xlsx'); + } + + public function upload(Request $request, string $token): RedirectResponse + { + $t = $this->target($request, $token); + $back = $this->links->signedRoute('signed.courier-bill-upload.show', $token, $t['companyId'], $this->expiresAt($request)); + if ($t['confirmed']) { + throw ValidationException::withMessages(['upload' => '这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。']); + } + $request->validate(['import' => ['required', 'file', 'max:51200']], [], ['import' => '账单文件']); + $file = $request->file('import'); + $extension = strtolower($file->getClientOriginalExtension()); + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + throw ValidationException::withMessages(['upload' => '只支持 xlsx、xls、csv,请用上传模板。']); + } + $this->imports->submit($file, [ + 'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'], + 'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'], + 'source' => 'courier_upload_link', + 'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64), + ]); + + return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。'); + } + + /** @return array{companyId:int,group:object,month:string,confirmed:bool} */ + private function target(Request $request, string $token): array + { + $companyId = (int) ($request->route('company_id') ?: company_id() ?: 1); + $payload = $this->links->resolveToken($token, $companyId); + abort_if($payload === null, 404, '链接无效或已过期。'); + $group = collect($this->store->groups())->firstWhere('id', $payload['group_id']); + abort_if($group === null, 404, '链接无效或已过期。'); + $confirmed = $this->store->db()->table('courier_bill_statements')->where('group_id', $group->id) + ->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists(); + + return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed]; + } + + private function expiresAt(Request $request): CarbonImmutable + { + $expires = (int) $request->query('expires', 0); + + return $expires > 0 ? CarbonImmutable::createFromTimestamp($expires) : CarbonImmutable::now()->addDays(CourierUploadLink::TTL_DAYS); + } + + private static function monthLabel(string $month): string + { + [$y, $m] = explode('-', $month); + + return (int) $y . '年' . (int) $m . '月'; + } +} diff --git a/app/Support/CourierBills/CourierUploadLink.php b/app/Support/CourierBills/CourierUploadLink.php new file mode 100644 index 000000000..2a0a12df5 --- /dev/null +++ b/app/Support/CourierBills/CourierUploadLink.php @@ -0,0 +1,54 @@ +signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $companyId); + } + + public function signedRoute(string $routeName, string $token, int $companyId, ?\DateTimeInterface $expires = null): string + { + return URL::temporarySignedRoute($routeName, $expires ?? now()->addDays(self::TTL_DAYS), ['company_id' => $companyId, 'token' => $token]); + } + + /** @return array{group_id:int,month:string}|null */ + public function resolveToken(string $token, int $companyId): ?array + { + try { + $padding = (4 - strlen($token) % 4) % 4; + $encrypted = base64_decode(strtr($token . str_repeat('=', $padding), '-_', '+/'), true); + if ($encrypted === false) { + return null; + } + $payload = json_decode(Crypt::decryptString($encrypted), true, flags: JSON_THROW_ON_ERROR); + } catch (Throwable) { + return null; + } + if (! is_array($payload) || (int) ($payload['company_id'] ?? 0) !== $companyId || (int) ($payload['group_id'] ?? 0) <= 0 + || preg_match('/^\d{4}-\d{2}$/', (string) ($payload['month'] ?? '')) !== 1) { + return null; + } + + return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month']]; + } + + private function token(int $companyId, int $groupId, string $month): string + { + $payload = json_encode(['company_id' => $companyId, 'group_id' => $groupId, 'month' => $month], JSON_THROW_ON_ERROR); + + return rtrim(strtr(base64_encode(Crypt::encryptString($payload)), '+/', '-_'), '='); + } +} diff --git a/app/Support/CourierBills/PortalFreightBillImports.php b/app/Support/CourierBills/PortalFreightBillImports.php index 1ec472600..67aff9057 100644 --- a/app/Support/CourierBills/PortalFreightBillImports.php +++ b/app/Support/CourierBills/PortalFreightBillImports.php @@ -32,17 +32,20 @@ final class PortalFreightBillImports touch($queue . '/' . $token); } - public function recent(int $companyId, string $name): array + public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null): array { $files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: []; rsort($files); $out = []; - foreach (array_slice($files, 0, 10) as $path) { + foreach ($files as $path) { $task = json_decode((string) file_get_contents($path), true); if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue; + if ($targetId !== null && (int) $task['target_id'] !== $targetId) continue; + if ($month !== null && $task['month'] !== $month) continue; $out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'], 'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'], 'message' => $task['message'], 'at' => $task['created_at']]; + if (count($out) >= 10) break; } usort($out, static fn ($a, $b) => strcmp($b['at'], $a['at'])); return array_slice($out, 0, 10); @@ -83,10 +86,18 @@ final class PortalFreightBillImports private function process(array $task): void { - $user = User::find($task['user_id']); - if (! $user || ! $user->enabled || ! $user->companies()->where('companies.id', $task['company_id'])->exists()) throw new RuntimeException('上传账号已停用或授权已变化,请联系财务。'); \App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true); - if (SupplierPortalAccess::isSupplierUser($user) && ! in_array($task['name'], app(SupplierPortalAccess::class)->supplierNamesFor($user), true)) throw new RuntimeException('厂家授权已变化,请联系财务。'); + if (($task['source'] ?? null) === 'courier_upload_link') { + if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。'); + if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->where('group_id', $task['target_id']) + ->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) { + throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。'); + } + } else { + $user = User::find($task['user_id']); + if (! $user || ! $user->enabled || ! $user->companies()->where('companies.id', $task['company_id'])->exists()) throw new RuntimeException('上传账号已停用或授权已变化,请联系财务。'); + if (SupplierPortalAccess::isSupplierUser($user) && ! in_array($task['name'], app(SupplierPortalAccess::class)->supplierNamesFor($user), true)) throw new RuntimeException('厂家授权已变化,请联系财务。'); + } $portal = app(PortalFreightBills::class); $path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/input.' . $task['extension']); app(FreightBillTemplate::class)->validate($path, $task['extension']); diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index d4ed7f778..aff81c0e5 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -505,6 +505,24 @@ class SupplierDingTalkNotifier return true; } + /** 快递账单:往这家快递的钉钉对账群推免登录上传链接(机器人在快递账单对账 → 对账分组里配置)。 */ + public function pushCourierUploadLink(string $courier, string $month, string $url): void + { + [$webhook, $config] = $this->robotFor($courier, 'courier_upload_link'); + $this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false), + $courier . ' · 运费账单上传 · ' . $this->displayMonth($month), implode("\n", [ + '### 运费账单上传 · ' . $courier, + '- 账单月份:**' . $this->displayMonth($month) . '**', + '- 请按上传模板填写(单号、省、重量、运费、送货备注、面单、费率),单号和运费必填', + '', + '#### [打开账单上传页](' . $url . ')', + '- 页面上可下载上传模板;同一个月可以分几次上传,上传后群里会收到回执。', + '', + '> 无需登录;链接只能上传本快递本月的账单,有效期 ' . \App\Support\CourierBills\CourierUploadLink::TTL_DAYS . ' 天。', + ])); + $this->touch($courier, 1); + } + /** @param array{rows:int,waybills:int,amount:float} $summary */ public function sendFreightBillUploadReceipt(string $name, string $kind, string $month, string $fileName, array $summary): bool { @@ -658,7 +676,7 @@ class SupplierDingTalkNotifier $config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : []; $webhook = trim((string) ($config['webhook'] ?? '')); if ($webhook === '') { - throw ValidationException::withMessages([$field => '「' . $supplier . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']); + throw ValidationException::withMessages([$field => '「' . $supplier . '」还没有配置钉钉群机器人。']); } $this->assertWebhook($webhook); diff --git a/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php b/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php index 8f4d284d2..f4f296eb6 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php @@ -101,7 +101,7 @@
| 分组名称 | 快递名称1 | 归到承运商 | 合并账单 | 负责人 | 文件名关键字 | 指定表头 | ||
|---|---|---|---|---|---|---|---|---|
| 分组名称 | 快递名称1 | 归到承运商 | 合并账单 | 负责人 | 文件名关键字 | 指定表头 | 钉钉对账群 | |
| {{ $group->owner }} | {{ $group->keywords }} | {{ collect([$group->waybill_header, $group->amount_header, $group->weight_header])->filter()->implode(' / ') ?: '自动' }} | + @php($robot = $cbRobots[$group->name] ?? []) +
+
+
+ @if ($robot['configured'] ?? false)
+
+ @endif
+ + @if ($robot['configured'] ?? false) + 已配 {{ $robot['webhook_hint'] ?? '' }} + @else + 未配 + @endif ++ + |
编辑 | ||||
| 还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。 | ||||||||
| 还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。 | ||||||||
| 文件 | 行数 | 运费合计 | 状态 | 上传时间 |
|---|---|---|---|---|
| {{ $f->original_name }} | {{ number_format((int) $f->row_count) }} | +{{ number_format((float) $f->amount, 2) }} | +{{ match ($f->status) { 'parsed' => '已读入', 'failed' => '未读入:' . $f->message, 'queued' => '等待处理', 'running' => '正在校验和读入', default => '待财务处理' } }} | +{{ substr((string) $f->created_at, 0, 16) }} |
还没有上传。
+ @endif +