feat(快递账单): 群推送免登录上传链接

This commit is contained in:
limeng 2026-12-02 21:17:54 +08:00
parent 224f9f778e
commit 2dca095bff
11 changed files with 444 additions and 9 deletions

View File

@ -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),

View File

@ -0,0 +1,107 @@
<?php
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\CourierUploadLink;
use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBillImports;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* 推送到快递钉钉对账群的免登录上传页:下载模板、按模板上传这一家这个月的账单,上传后进入快递账单对账。
*/
final class CourierUploadShare extends Controller
{
public function __construct(
private readonly CourierBillStore $store,
private readonly CourierUploadLink $links,
private readonly FreightBillTemplate $template,
private readonly PortalFreightBillImports $imports,
) {}
public function show(Request $request, string $token): Response
{
$t = $this->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 . '月';
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* 快递上传账单的免登录链接:推送到这家快递的钉钉对账群,链接里带公司、对账分组、账单月份(加密 + Laravel 签名),
* 只能给这一家这一个月上传,不能看别家,也看不到对账结果。
*/
final class CourierUploadLink
{
public const TTL_DAYS = 30;
public function pageUrl(int $companyId, int $groupId, string $month): string
{
return $this->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)), '+/', '-_'), '=');
}
}

View File

@ -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']);

View File

@ -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);

View File

@ -101,7 +101,7 @@
<h3>对账分组({{ count($cbGroups) }})</h3>
<div class="cbr-scroll">
<table>
<thead><tr><th scope="col">分组名称</th><th scope="col">快递名称1</th><th scope="col">归到承运商</th><th scope="col">合并账单</th><th scope="col">负责人</th><th scope="col">文件名关键字</th><th scope="col">指定表头</th><th scope="col"></th></tr></thead>
<thead><tr><th scope="col">分组名称</th><th scope="col">快递名称1</th><th scope="col">归到承运商</th><th scope="col">合并账单</th><th scope="col">负责人</th><th scope="col">文件名关键字</th><th scope="col">指定表头</th><th scope="col">钉钉对账群</th><th scope="col"></th></tr></thead>
<tbody>
@forelse ($cbGroups as $group)
<tr>
@ -112,13 +112,36 @@
<td>{{ $group->owner }}</td>
<td>{{ $group->keywords }}</td>
<td>{{ collect([$group->waybill_header, $group->amount_header, $group->weight_header])->filter()->implode(' / ') ?: '自动' }}</td>
@php($robot = $cbRobots[$group->name] ?? [])
<td class="wrap">
<details>
<summary>
@if ($robot['configured'] ?? false)
<span class="cbr-chip ok">已配</span> {{ $robot['webhook_hint'] ?? '' }}
@else
<span class="cbr-chip">未配</span>
@endif
</summary>
<form method="POST" action="{{ $action('save-robot', ['group' => $group->id]) }}" class="cbr-form" style="margin-top:6px">@csrf
<input type="text" name="webhook" placeholder="机器人 Webhook(https://oapi.dingtalk.com/robot/send?access_token=…)" style="min-width:320px">
<input type="text" name="secret" placeholder="加签密钥 SEC…(留空不改)">
<button type="submit">保存</button>
</form>
</details>
@if ($robot['configured'] ?? false)
<form method="POST" action="{{ $action('push-upload-links') }}" class="cbr-form" style="margin-top:4px"
onsubmit="return confirm('往「{{ $group->name }}」钉钉对账群推送 {{ $month }} 账单上传链接?')">@csrf
<input type="hidden" name="month" value="{{ $month }}"><input type="hidden" name="group" value="{{ $group->id }}">
<button type="submit">推送 {{ $month }} 上传链接</button></form>
@endif
</td>
<td class="cbr-form">
<a data-cbr-tab href="{{ $pageUrl(['cb_view' => 'groups', 'edit' => $group->id]) }}">编辑</a>
<form method="POST" action="{{ $action('delete-group', ['group' => $group->id]) }}" onsubmit="return confirm('确定删除这个分组?')">@csrf<button type="submit" class="cbr-danger">删除</button></form>
</td>
</tr>
@empty
<tr><td colspan="8" class="cbr-empty">还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。</td></tr>
<tr><td colspan="9" class="cbr-empty">还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。</td></tr>
@endforelse
</tbody>
</table>

View File

@ -0,0 +1,72 @@
<x-layouts.signed>
<x-slot name="title">{{ $group->name }} · {{ $monthLabel }} 账单上传</x-slot>
<x-slot name="buttons">
<a href="{{ $templateUrl }}" class="text-white px-3 py-1.5 mb-3 sm:mb-0 rounded-lg text-sm font-medium leading-6" style="background:#856632">下载上传模板</a>
</x-slot>
<x-slot name="content">
<style>
.cu-share { display: grid; gap: 10px; margin: 10px auto 16px; max-width: 1000px; color: #24211c; font-size: .8125rem; }
.cu-share .head { padding: 11px 14px; border: 1px solid #ded7c9; border-radius: 8px; background: linear-gradient(135deg, #fffdf8, #f7f0de); }
.cu-share .head h1 { margin: 0 0 4px; font-size: 1.0625rem; font-weight: 700; }
.cu-share .muted { color: #686053; font-size: .75rem; line-height: 1.6; }
.cu-share .card { padding: 12px 14px; border: 1px solid #ded7c9; border-radius: 10px; background: #fff; }
.cu-share form { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
.cu-share input[type=file] { min-height: 34px; padding: 4px; border: 1px solid #d8d2c7; border-radius: 8px; }
.cu-share .btn { min-height: 36px; padding: 0 16px; border: 0; border-radius: 8px; background: #856632; color: #fff; font-weight: 700; cursor: pointer; }
.cu-share .alert { padding: 11px 14px; border: 1px solid #b8d8bc; border-radius: 8px; background: #eef8ef; color: #285f31; }
.cu-share .alert.is-error { border-color: #e2b7b2; background: #fff2f0; color: #8c2f26; }
.cu-share table { width: 100%; border-collapse: collapse; font-size: .75rem; }
.cu-share th, .cu-share td { padding: 6px 8px; border-bottom: 1px solid #f0ece4; text-align: left; }
.cu-share th { background: #f7f0de; color: #5b5343; }
.cu-share .num { text-align: right; font-variant-numeric: tabular-nums; }
</style>
<div class="cu-share">
@if (is_string(session('success')) && session('success') !== '')
<div class="alert" role="status">{{ session('success') }}</div>
@endif
@if ($errors->any())
<div class="alert is-error" role="alert">{{ $errors->first() }}</div>
@endif
<section class="head">
<h1>{{ $group->name }} · {{ $monthLabel }} 运费账单上传</h1>
<div class="muted">
请先点右上角「下载上传模板」,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」;
单号、运费必填,重量、面单、费率填数字,省、送货备注可空。不按模板的文件会被退回并提示哪里要改。
同一个月可以分几次上传,每份最多 50MB、100,000 行。上传后等待校验和读入,刷新本页查看结果。
链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录,只能上传本快递本月的账单。
</div>
</section>
<section class="card">
@if ($confirmed)
<div class="alert">这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。</div>
@else
<form method="POST" action="{{ $uploadUrl }}" enctype="multipart/form-data">
@csrf
<input type="file" name="import" accept=".xlsx,.xls,.csv" required aria-label="账单文件">
<button type="submit" class="btn">上传账单</button>
</form>
@endif
</section>
<section class="card">
<strong>本月已上传({{ count($files) }})</strong>
@if (count($files) > 0)
<table>
<thead><tr><th>文件</th><th class="num">行数</th><th class="num">运费合计</th><th>状态</th><th>上传时间</th></tr></thead>
<tbody>
@foreach ($files as $f)
<tr><td>{{ $f->original_name }}</td><td class="num">{{ number_format((int) $f->row_count) }}</td>
<td class="num">{{ number_format((float) $f->amount, 2) }}</td>
<td>{{ match ($f->status) { 'parsed' => '已读入', 'failed' => '未读入:' . $f->message, 'queued' => '等待处理', 'running' => '正在校验和读入', default => '待财务处理' } }}</td>
<td>{{ substr((string) $f->created_at, 0, 16) }}</td></tr>
@endforeach
</tbody>
</table>
@else
<p class="muted">还没有上传。</p>
@endif
</section>
</div>
</x-slot>
</x-layouts.signed>

View File

@ -1,3 +1,15 @@
<section class="cbr-panel" aria-label="让快递自己上传">
<h3>让快递自己上传账单</h3>
<form method="POST" action="{{ $action('push-upload-links') }}" class="cbr-panel-body cbr-form"
onsubmit="return confirm('往所有配了钉钉对账群机器人的快递群推送上传链接?')">
@csrf
<label>账单月份<input type="month" name="month" value="{{ $month }}" required></label>
<button type="submit" class="cbr-primary">推送上传链接到快递群</button>
<span class="cbr-muted">每家快递的钉钉对账群配一个群机器人(在「对账分组」里配,群设置 → 机器人 → 自定义,安全设置选「加签」),这里一键往这些群推本月的免登录上传链接。
快递点开链接、下载模板(单号、省、重量、运费、送货备注、面单、费率)填好上传,后台校验读入后进入对账;链接只能传那一家那个月,30 天有效。已有 {{ collect($cbRobots ?? [])->where('configured', true)->count() }} 家配了机器人。</span>
</form>
</section>
<section class="cbr-panel" aria-label="上传账单">
<h3>上传账单 · {{ $month }}</h3>
<form method="POST" action="{{ $action('upload') }}" enctype="multipart/form-data" class="cbr-panel-body" style="display:grid;gap:12px">

View File

@ -801,6 +801,8 @@ foreach (['courier-payables', 'courier-payables-final'] as $courierBillSection)
Route::post('groups/import', [$controller, 'importGroups'])->name('import-groups')->defaults('section', $courierBillSection);
Route::get('groups/export', [$controller, 'exportGroups'])->name('export-groups')->defaults('section', $courierBillSection);
Route::post('groups/{group}/delete', [$controller, 'deleteGroup'])->whereNumber('group')->name('delete-group')->defaults('section', $courierBillSection);
Route::post('groups/{group}/robot', [$controller, 'saveRobot'])->whereNumber('group')->name('save-robot')->defaults('section', $courierBillSection);
Route::post('upload-links', [$controller, 'pushUploadLinks'])->name('push-upload-links')->defaults('section', $courierBillSection);
Route::post('groups/{group}/express-names', [$controller, 'addExpressName'])->whereNumber('group')->name('add-express-name')->defaults('section', $courierBillSection);
Route::post('ledger/import', [$controller, 'importLedger'])->name('import-ledger')->defaults('section', $courierBillSection);
Route::post('summary-templates/import', [$controller, 'importSummaryTemplates'])->name('import-summary-templates')->defaults('section', $courierBillSection);

View File

@ -55,3 +55,15 @@ Route::post('dropship-freight/{token}/submit', 'Business\DropshipFreightShare@su
Route::get('dropship-freight/{token}/excel', 'Business\DropshipFreightShare@excel')
->middleware('throttle:20,1')
->name('signed.dropship-freight.excel');
Route::get('courier-bill-upload/{token}', 'Business\CourierUploadShare@show')
->middleware('throttle:60,1')
->name('signed.courier-bill-upload.show');
Route::post('courier-bill-upload/{token}/upload', 'Business\CourierUploadShare@upload')
->middleware('throttle:20,1')
->name('signed.courier-bill-upload.upload');
Route::get('courier-bill-upload/{token}/template', 'Business\CourierUploadShare@template')
->middleware('throttle:20,1')
->name('signed.courier-bill-upload.template');

View File

@ -15,6 +15,7 @@ use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBills;
use App\Support\CourierBills\PortalFreightBillImports;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
@ -177,6 +178,77 @@ final class PortalFreightBillTest extends FeatureTestCase
$this->assertSame([['supplier_name' => '曹县韵达', 'supplier_code' => '', 'dingtalk_group_id' => 77, 'dingtalk_group_name' => '曹县韵达']], $resolved);
}
public function test_finance_pushes_a_no_login_upload_link_to_the_courier_dingtalk_group(): void
{
Storage::fake('local');
$this->company->makeCurrent(true);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$db = CourierBillMatcher::db();
$groupId = $db->table('courier_bill_groups')->insertGetId(['name' => '曹县韵达', 'express_names' => json_encode(['曹县韵达'], JSON_UNESCAPED_UNICODE),
'bundle' => '合并测试',
'created_at' => now(), 'updated_at' => now()]);
$otherGroupId = $db->table('courier_bill_groups')->insertGetId(['name' => '其他快递', 'express_names' => json_encode(['其他快递'], JSON_UNESCAPED_UNICODE),
'bundle' => '合并测试', 'keywords' => '其他快递', 'created_at' => now(), 'updated_at' => now()]);
$section = 'courier-payables-final';
$action = fn (string $name, array $p = []) => route('business.' . $section . '.courier-bills.' . $name, $p);
$groups = route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'groups', 'month' => '2026-11']);
$this->get($groups)->assertOk()->assertSeeText('钉钉对账群')->assertSeeText('未配');
$this->post($action('push-upload-links'), ['month' => '2026-11', 'group' => $groupId])->assertSessionHasErrors('courier_bills');
$this->post($action('save-robot', ['group' => $groupId]), ['webhook' => 'https://oapi.dingtalk.com/robot/send?access_token=cx', 'secret' => 'SEC-cx'])
->assertSessionHas('courier_bills_message');
$this->get($groups)->assertOk()->assertSeeText('已配')->assertSeeText('推送 2026-11 上传链接');
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$this->post($action('push-upload-links'), ['month' => '2026-11'])->assertSessionHas('courier_bills_message');
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('运费账单上传 · 曹县韵达', $text);
preg_match('/\[打开账单上传页\]\(([^)]+)\)/', $text, $m);
$link = $m[1];
auth()->logout();
$this->get($link . '&month=2026-10')->assertOk()->assertSeeText('2026年11月');
$this->get(preg_replace('/signature=[^&]+/', 'signature=' . str_repeat('0', 64), $link))->assertForbidden();
$this->get(app(\App\Support\CourierBills\CourierUploadLink::class)->signedRoute('signed.courier-bill-upload.show',
basename(parse_url($link, PHP_URL_PATH)), (int) $this->company->id, now()->subMinute()))->assertForbidden();
$page = $this->get($link)->assertOk()->assertHeader('X-Robots-Tag', 'noindex, nofollow, noarchive')
->assertSeeText('曹县韵达 · 2026年11月 运费账单上传')->assertSeeText('还没有上传');
$html = (string) $page->getContent();
preg_match('/action="([^"]*courier-bill-upload[^"]*\/upload[^"]*)"/', $html, $u);
$upload = html_entity_decode($u[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
preg_match('/href="([^"]*courier-bill-upload[^"]*\/template[^"]*)"/', $html, $tp);
$this->get(html_entity_decode($tp[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'))->assertOk();
$file = fn (array $rows) => new UploadedFile($this->xlsx($rows), '其他快递11月.xlsx', null, null, true);
$imports = app(PortalFreightBillImports::class);
$this->post($upload, ['import' => $file([['运单号', '运费'], ['YD1', 3]])])->assertSessionHas('success');
$this->assertSame(0, $db->table('courier_bill_files')->count());
$this->assertTrue($imports->processNext());
$this->get($link)->assertOk()->assertSeeText('第一行必须依次是');
$this->post($upload, ['group' => $otherGroupId, 'month' => '2026-10',
'import' => $file([self::H, ['YD0001', '山东', 1.2, 4.5], ['YD0002', '河北', 2, 5.5]])])
->assertRedirect()->assertSessionHas('success');
$this->get($link)->assertOk()->assertSeeText('等待处理');
$this->assertSame(0, $db->table('courier_bill_files')->count());
$this->assertTrue($imports->processNext());
$f = $db->table('courier_bill_files')->sole();
$this->assertSame('parsed', $f->status);
$this->assertSame($groupId, (int) $f->group_id);
$this->assertSame('2026-11', $f->bill_month);
$this->assertEquals(10, (float) $f->amount);
$this->assertStringContainsString('(快递上传链接)', (string) $f->uploaded_by);
$this->assertStringContainsString('快递账单上传回执 · 曹县韵达', (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''));
$this->get($link)->assertOk()->assertSeeText('其他快递11月.xlsx')->assertSeeText('已读入');
// 排队期间财务确认结算,也不能在后台继续写入。
$this->post($upload, ['import' => $file([self::H, ['YD0003', '', '', 1]])])->assertSessionHas('success');
$db->table('courier_bill_statements')->where('group_id', $groupId)->update(['status' => 'confirmed']);
$this->assertTrue($imports->processNext());
$this->assertSame(1, $db->table('courier_bill_files')->count());
$this->get($link)->assertOk()->assertSeeText('财务已确认结算');
$this->post($upload, ['import' => $file([self::H, ['YD0003', '', '', 1]])])->assertSessionHasErrors('upload');
}
private function portalUser(string $name): User
{
$user = User::create(['name' => $name . '对账员', 'email' => Str::lower(Str::random(12)) . '@portal.test', 'password' => Str::random(32),