feat(快递账单): 樵舍与圆通联合上传链接 (#1721)

This commit is contained in:
limeng 2026-12-04 10:21:19 +08:00
parent aea68c2d2d
commit 398cf9690c
12 changed files with 477 additions and 27 deletions

View File

@ -209,10 +209,28 @@ final class CourierBillController extends Controller
private function uploadData(string $month): array
{
return ['cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
$jointUploads = [];
foreach (\App\Support\CourierBills\CourierJointUploads::SETS as $key => $set) {
try {
app(\App\Support\CourierBills\CourierJointUploads::class)->resolve($key);
$jointUploads[$key] = $set;
} catch (RuntimeException) { /* 分组未配置的环境不显示入口。 */ }
}
return ['cbJointUploads' => $jointUploads, 'cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
}
public function jointUploadLink(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'],
'joint' => ['required', Rule::in(array_keys(\App\Support\CourierBills\CourierJointUploads::SETS))]]);
$url = $this->guard(fn () => app(\App\Support\CourierBills\CourierUploadLink::class)
->jointPageUrl((int) (company_id() ?: 1), $data['joint'], $data['month']));
return redirect()->away($url);
}
private function ledgerData(Request $request): array
{
$db = $this->store->db();

View File

@ -3,6 +3,7 @@
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\CourierJointUploads;
use App\Support\CourierBills\CourierUploadLink;
use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBillImports;
@ -30,17 +31,20 @@ final class CourierUploadShare extends Controller
{
$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();
$query = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']);
if ($t['joint'] !== null) $query->where('extra_group_ids', json_encode(['joint_upload' => $t['payload']['joint']]));
else $query->where(fn ($q) => $q->whereNull('extra_group_ids')->orWhere('extra_group_ids', 'not like', '%"joint_upload"%'));
$files = $query->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']));
], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'], $t['joint']['key'] ?? null));
$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'],
'joint' => $t['joint'], 'uploadLabel' => $t['joint']['label'] ?? $t['group']->name,
'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',
@ -51,7 +55,7 @@ final class CourierUploadShare extends Controller
{
$t = $this->target($request, $token);
return $this->template->download($t['group']->name . '_' . $t['month'] . '_账单上传模板.xlsx');
return $this->template->download(($t['joint']['label'] ?? $t['group']->name) . '_' . $t['month'] . '_账单上传模板.xlsx');
}
public function upload(Request $request, string $token): RedirectResponse
@ -71,13 +75,14 @@ final class CourierUploadShare extends Controller
'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'],
'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'],
'source' => 'courier_upload_link',
'joint' => $t['payload']['joint'],
'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64),
]);
return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。');
}
/** @return array{companyId:int,group:object,month:string,confirmed:bool} */
/** @return array{companyId:int,group:object,month:string,confirmed:bool,joint:?array,payload:array} */
private function target(Request $request, string $token): array
{
$companyId = (int) ($request->route('company_id') ?: company_id() ?: 1);
@ -85,10 +90,15 @@ final class CourierUploadShare extends Controller
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)
$joint = null;
if ($payload['joint'] !== null) {
try { $joint = app(CourierJointUploads::class)->verify($payload['joint']); }
catch (\RuntimeException $e) { abort(410, $e->getMessage()); }
}
$confirmed = $this->store->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$group->id])
->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists();
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed];
return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed, 'joint' => $joint, 'payload' => $payload];
}
private function expiresAt(Request $request): CarbonImmutable

View File

@ -426,9 +426,11 @@ final class CourierBillMatcher
return [];
}
$result = [];
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
foreach ($primaryIds as $fileId => $primaryId) {
$primary = (int) $primaryId;
$files = $db->table('courier_bill_files')->whereIn('id', $fileIds)->get(['id', 'statement_id', 'extra_group_ids']);
foreach ($files as $file) {
$fileId = (int) $file->id;
$primary = (int) $file->statement_id;
$joint = isset(json_decode((string) $file->extra_group_ids, true)['joint_upload']);
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
if (! (clone $rows)->exists()) {
continue;
@ -446,11 +448,14 @@ final class CourierBillMatcher
}
}
}
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, &$result): void {
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, $joint, $fileId, &$result): void {
$assigned = $joint ? self::db()->table('courier_bill_lines')->where('file_id', $fileId)
->whereIn('waybill_no', $chunk->pluck('waybill_no'))->pluck('statement_id', 'waybill_no')->all() : [];
$shipping = $joint || $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
foreach ($chunk as $row) {
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
if (($names[$express] ?? $primary) !== $statementId) {
$owner = $joint ? (int) ($assigned[$row->waybill_no] ?? 0) : ($names[$express] ?? $primary);
if ($owner !== $statementId) {
continue;
}
$label = isset($freightSheets[(string) $row->sheet]) || trim((string) $row->sheet) === '' ? (string) $row->item : (string) $row->sheet;

View File

@ -366,6 +366,31 @@ final class CourierBillStore
return $id;
}
public function uploadJoint(UploadedFile $file, string $month, array $scope, string $user): int
{
return $this->db()->transaction(function () use ($file, $month, $scope, $user): int {
$set = app(CourierJointUploads::class)->verify($scope);
$this->lockJointTargets($set['group_ids'], $month);
$id = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month,
$set['group_ids'], $set['groups'], $user, true, $scope);
if ($this->db()->table('courier_bill_files')->where('id', $id)->value('status') === 'parsed') {
foreach ($this->statementsOfFiles([$id]) as $statementId) $this->matcher->match($statementId);
}
return $id;
});
}
private function lockJointTargets(array $ids, string $month): void
{
$db = $this->db();
$db->table('courier_bill_groups')->whereIn('id', $ids)->orderBy('id')->lockForUpdate()->get();
if ($db->table('courier_bill_statements')->whereIn('group_id', $ids)->where('bill_month', $month)
->orderBy('id')->lockForUpdate()->get()->contains('status', 'confirmed')) {
throw new RuntimeException('联合上传范围中有分组本月已确认结算,请联系财务。');
}
}
/** 给待选分组的文件指定分组,读入并对账。 */
public function assign(int $fileId, int $groupId): void
{
@ -427,7 +452,7 @@ final class CourierBillStore
* @param list<int> $groupIds
* @param list<object> $groups
*/
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false): int
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false, ?array $joint = null): int
{
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
@ -440,7 +465,7 @@ final class CourierBillStore
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
'extra_group_ids' => $extra === [] ? null : json_encode($extra),
'extra_group_ids' => $joint !== null ? json_encode(['joint_upload' => $joint]) : ($extra === [] ? null : json_encode($extra)),
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
]);
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
@ -460,6 +485,12 @@ final class CourierBillStore
{
$db = $this->db();
$file = $db->table('courier_bill_files')->find($fileId);
$joint = json_decode((string) $file->extra_group_ids, true)['joint_upload'] ?? null;
if ($joint !== null) {
$set = app(CourierJointUploads::class)->verify($joint);
$this->lockJointTargets($set['group_ids'], (string) $file->bill_month);
$portal = true;
}
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
if ($statement !== null && $statement->status === 'confirmed') {
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
@ -485,7 +516,7 @@ final class CourierBillStore
$feeCount = 0;
$overlap = null;
try {
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, $joint, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
}
@ -566,7 +597,7 @@ final class CourierBillStore
$db->table('courier_bill_surcharges')->insert($fees);
}
return $portal ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
return $portal && $joint === null ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
});
} catch (Throwable $error) {
if ($reread) {
@ -645,6 +676,8 @@ final class CourierBillStore
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
{
$db = $this->db();
$metadata = json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true);
if (isset($metadata['joint_upload'])) return $this->splitJoint($fileId, $month, $metadata['joint_upload']);
$groups = collect($this->groups());
$extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true));
$bundle = trim((string) ($primary->bundle ?? ''));
@ -725,6 +758,56 @@ final class CourierBillStore
return implode(';', $parts);
}
/** 只在签名授权范围内逐批归组;任何无法归属的行整份退回,避免留在错误的主分组。 */
private function splitJoint(int $fileId, string $month, array $scope): string
{
$db = $this->db();
$set = app(CourierJointUploads::class)->verify($scope);
$this->lockJointTargets($set['group_ids'], $month);
$owners = [];
$statements = [];
foreach ($set['groups'] as $g) {
foreach (array_unique([$g->name, ...$g->express_names]) as $name) {
if (isset($owners[$name]) && $owners[$name] !== (int) $g->id) throw new RuntimeException('联合上传快递名称重复,请联系财务。');
$owners[$name] = (int) $g->id;
}
$statement = $db->table('courier_bill_statements')->where('group_id', $g->id)->where('bill_month', $month)->first();
if ($statement !== null) $statements[(int) $g->id] = (int) $statement->id;
}
$counts = [];
$db->table('courier_bill_lines')->where('file_id', $fileId)->orderBy('id')->chunkById(500, function ($lines) use ($db, $owners, $month, &$statements, &$counts): void {
$shipping = $this->shipping->summaries($lines->pluck('waybill_no')->all());
$moves = [];
foreach ($lines as $line) {
$raw = json_decode((string) $line->raw, true);
$declared = trim((string) ($raw[4] ?? ''));
if ($declared !== '' && ! isset($owners[$declared])) throw new RuntimeException('第 ' . $line->row_no . ' 行快递名称不在本链接范围内。整份文件未读入。');
$name = trim((string) ($shipping[strtoupper($line->waybill_no)]['express_name'] ?? ''));
if ($name === '') $name = $declared;
$groupId = $owners[$name] ?? null;
if ($groupId === null) throw new RuntimeException('第 ' . $line->row_no . ' 行单号 ' . $line->waybill_no . ' 无法归到本链接范围;系统查不到时请填写范围内的快递名称。整份文件未读入。');
$statements[$groupId] ??= (int) $db->table('courier_bill_statements')->insertGetId([
'group_id' => $groupId, 'bill_month' => $month, 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]);
$moves[$statements[$groupId]][] = (int) $line->id;
$counts[$groupId] = ($counts[$groupId] ?? 0) + 1;
}
foreach ($moves as $statementId => $ids) $db->table('courier_bill_lines')->whereIn('id', $ids)->update(['statement_id' => $statementId]);
});
// 附加费沿用同单号的运费归属,不把找不到归属的费用默认塞给主分组。
$missingFee = $db->table('courier_bill_surcharges as fee')->where('fee.file_id', $fileId)
->whereNotExists(fn ($q) => $q->selectRaw('1')->from('courier_bill_lines as line')
->whereColumn('line.file_id', 'fee.file_id')->whereColumn('line.waybill_no', 'fee.waybill_no'))->first();
if ($missingFee !== null) throw new RuntimeException('附加费单号 ' . $missingFee->waybill_no . ' 缺少对应运费明细,无法确定分组。整份文件未读入。');
$ambiguous = $db->table('courier_bill_lines')->where('file_id', $fileId)->groupBy('waybill_no')
->havingRaw('COUNT(DISTINCT statement_id) > 1')->first(['waybill_no']);
if ($ambiguous !== null) throw new RuntimeException('单号 ' . $ambiguous->waybill_no . ' 填写了不同快递名称,请核对。整份文件未读入。');
$notes = [];
foreach ($set['groups'] as $g) if (isset($counts[$g->id])) $notes[] = $g->name . ' ' . $counts[$g->id] . ' 行';
return '联合上传已归组:' . implode('、', $notes);
}
/**
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
* 涉及的对账单有已确认结算的就不动。

View File

@ -0,0 +1,56 @@
<?php
namespace App\Support\CourierBills;
use RuntimeException;
/** 明确授权的联合上传范围,不从机器人、文件名或合并账单配置推断。 */
final class CourierJointUploads
{
public const SETS = [
'qiaoshe' => ['label' => '樵舍联合上传', 'names' => ['江西新建中通', '江西中通快运', '樵舍中通', '樵舍中通-上楼', '山东中通快运', '西安圆通', '西安中通快运']],
'yuantong' => ['label' => '圆通联合上传', 'names' => ['常州圆通其他', '常州圆通-上楼', '小件宿迁圆通', '睢宁宿迁圆通', '苏北宿迁圆通']],
];
public function resolve(string $key): array
{
$set = self::SETS[$key] ?? throw new RuntimeException('联合上传范围不存在。');
$groups = app(CourierBillStore::class)->groups();
$selected = [];
foreach ($set['names'] as $name) {
$matches = array_values(array_filter($groups, static fn ($g) => $g->name === $name || in_array($name, $g->express_names, true)));
if (count($matches) !== 1) throw new RuntimeException('联合上传分组「' . $name . '」未配置或存在重名,请联系财务。');
$g = $matches[0];
// 一个分组可以有多个业务名称,但不得借此授权集合之外的快递。
if (array_diff($g->express_names, $set['names']) !== []) throw new RuntimeException('联合上传分组范围已变化,请联系财务。');
$selected[(int) $g->id] = $g;
}
ksort($selected);
$fingerprint = [];
foreach ($selected as $id => $group) {
$names = $group->express_names;
sort($names);
$fingerprint[] = [$id, $group->name, $names];
}
return $set + ['key' => $key, 'groups' => array_values($selected), 'group_ids' => array_keys($selected),
'fingerprint' => hash('sha256', json_encode($fingerprint, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))];
}
public function snapshot(string $key): array
{
$set = $this->resolve($key);
return array_intersect_key($set, array_flip(['key', 'group_ids', 'fingerprint']));
}
public function verify(array $snapshot): array
{
$set = $this->resolve((string) ($snapshot['key'] ?? ''));
if ($set['group_ids'] !== ($snapshot['group_ids'] ?? null) || $set['fingerprint'] !== ($snapshot['fingerprint'] ?? null)) {
throw new RuntimeException('联合上传分组设置已变化,请联系财务重新生成链接。');
}
return $set;
}
}

View File

@ -19,12 +19,21 @@ final class CourierUploadLink
return $this->signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $companyId);
}
public function jointPageUrl(int $companyId, string $key, string $month): string
{
$joint = app(CourierJointUploads::class)->snapshot($key);
$payload = ['company_id' => $companyId, 'group_id' => $joint['group_ids'][0], 'month' => $month, 'joint' => $joint];
$token = rtrim(strtr(base64_encode(Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR))), '+/', '-_'), '=');
return $this->signedRoute('signed.courier-bill-upload.show', $token, $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 */
/** @return array{group_id:int,month:string,joint:?array}|null */
public function resolveToken(string $token, int $companyId): ?array
{
try {
@ -42,7 +51,7 @@ final class CourierUploadLink
return null;
}
return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month']];
return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month'], 'joint' => $payload['joint'] ?? null];
}
private function token(int $companyId, int $groupId, string $month): string

View File

@ -32,7 +32,7 @@ final class PortalFreightBillImports
touch($queue . '/' . $token);
}
public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null): array
public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null, ?string $jointKey = null): array
{
$files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: [];
rsort($files);
@ -42,6 +42,7 @@ final class PortalFreightBillImports
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;
if (($task['joint']['key'] ?? null) !== $jointKey) 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']];
@ -89,7 +90,8 @@ final class PortalFreightBillImports
\App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true);
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'])
$joint = isset($task['joint']) ? app(CourierJointUploads::class)->verify($task['joint']) : null;
if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->whereIn('group_id', $joint['group_ids'] ?? [$task['target_id']])
->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) {
throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。');
}
@ -110,7 +112,9 @@ final class PortalFreightBillImports
} else {
if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。');
$store = app(CourierBillStore::class);
$id = $store->uploadFor(new UploadedFile($path, $task['original_name'], null, null, true), $task['month'], $task['target_id'], $task['uploader']);
$file = new UploadedFile($path, $task['original_name'], null, null, true);
$id = isset($joint) ? $store->uploadJoint($file, $task['month'], $task['joint'], $task['uploader'])
: $store->uploadFor($file, $task['month'], $task['target_id'], $task['uploader']);
$row = $store->db()->table('courier_bill_files')->find($id);
}
if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。'));

View File

@ -0,0 +1,30 @@
# 快递联合上传
入口:快递应付(及终版)→ 快递账单对账 → 上传账单 → 联合上传链接。
选择月份、打开页面后复制地址给快递。仍使用统一逐单模板及 30 天签名有效期。
## 范围与归组
- 樵舍:江西新建中通、江西中通快运、樵舍中通、樵舍中通-上楼、山东中通快运、西安圆通、西安中通快运。
- 圆通:常州圆通其他、常州圆通-上楼、小件宿迁圆通、睢宁宿迁圆通、苏北宿迁圆通。
- 睢宁宿迁圆通是苏北宿迁圆通的既有快递名称,圆通共 5 个名称、4 个分组。
- 不改分组、机器人或既有单家链接。联合权限不继承文件名、机器人共用关系或合并账单配置。
- 优先按系统单号归组;系统查不到快递名称时,使用模板内明确填写的范围内名称。
- 无法归组、范围外名称、同单号不同归属、附加费缺少运费明细时,整份回滚并提示修改。
- 附加费沿用同文件同单号运费的归属。重复文件沿用既有查重规则。
- 签名和任务固定分组快照;排队后配置变化或任一分组确认结算时禁止写入。重读、重新匹配不扩大范围。
- 已存在的 `extra_group_ids` JSON 列保存带 `joint_upload` 键的授权快照;普通文件仍为原数组结构,无迁移。
## 验证
2026-12-04 本地隔离容器,PHP 8.3、SQLite 内存测试库,禁止访问生产数据。
- `CourierJointUploadTest`:签名、别名、匿名上传、排队后配置变化/确认、归组、附加费、回滚、重读、查重、页面入口。
- `PortalFreightBillTest`、`CourierBillReconciliationTest`、`CourierBillPagesTest`:原上传、金额及页面回归。
- 相关回归 47 项,596 个断言通过;容量专项默认跳过,单独运行。
- 容量专项:100,000 行 CSV,3,900,052 字节,交替两家,校验、流式读入、归组及原有完整对账均执行。
- 100,000 行与 123,000 元合计完整,102.78 秒,PHP 峰值 154.5 MiB,数据库查询事件 101,823 次(包含既有逐行匹配更新)。
- 不据此承诺生产 MySQL 耗时;未对生产执行压测或上传测试账单。生产查询时两组尚无已上传文件和当月对账单。
生产复用已登记的 `portal-freight:import-pending` 独立批处理,每次一份;现有锁、1 CPU、1 GiB 容器、PHP 512 MiB、1 小时超时继续生效。
中断任务标记失败,联系财务核对后重传,不自动重复导入。

View File

@ -1,5 +1,5 @@
<x-layouts.signed>
<x-slot name="title">{{ $group->name }} · {{ $monthLabel }} 账单上传</x-slot>
<x-slot name="title">{{ $uploadLabel }} · {{ $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>
@ -30,12 +30,16 @@
<div class="alert is-error" role="alert">{{ $errors->first() }}</div>
@endif
<section class="head">
<h1>{{ $group->name }} · {{ $monthLabel }} 运费账单上传</h1>
<h1>{{ $uploadLabel }} · {{ $monthLabel }} 运费账单上传</h1>
@if ($joint)
<p><strong>可上传范围:</strong>{{ implode('、', $joint['names']) }}</p>
<p class="muted">这几家的逐单运费明细可以合在一份文件中。优先按系统中的单号归组;系统查不到的单号,请在「快递名称」列填写上述名称。无法归组、填入范围外的快递或附加费缺少对应运费明细时,整份文件退回,修改后重新上传。范围内任一分组已确认结算时,请先联系财务。</p>
@endif
<div class="muted">
请先点右上角「下载上传模板」,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」;
「账单」表:单号、运费必填,重量、面单、费率填数字,省、快递名称可空;「附加费」表:快递单号、附加费金额、附加费类型,没有附加费就空着。不按模板的文件会被退回并提示哪里要改。
「账单」表:单号、运费必填,重量、面单、费率填数字,省可空,快递名称{{ $joint ? '仅在系统能查到单号时可空' : '可空' }};「附加费」表:快递单号、附加费金额、附加费类型,没有附加费就空着。不按模板的文件会被退回并提示哪里要改。
同一个月可以分几次上传,每份最多 50MB、100,000 行。上传后等待校验和读入,刷新本页查看结果。
链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录,只能上传本快递本月的账单。
链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录,只能上传{{ $joint ? '上述快递' : '本快递' }}本月的账单。
</div>
</section>
<section class="card">

View File

@ -1,3 +1,20 @@
@if (! empty($cbJointUploads))
<section class="cbr-panel" aria-label="联合上传链接">
<h3>联合上传链接</h3>
<div class="cbr-panel-body">
<p class="cbr-muted">同组快递可将逐单运费明细合在一份模板中上传,系统分别归入原有对账分组。打开后复制页面地址即可发给快递,链接 30 天有效。</p>
@foreach ($cbJointUploads as $key => $set)
<form method="GET" action="{{ $action('joint-upload-link') }}" target="_blank" class="cbr-form">
<input type="hidden" name="joint" value="{{ $key }}">
<label>{{ $set['label'] }}<input type="month" name="month" value="{{ $cbPushMonth ?? $month }}" required></label>
<button type="submit" class="cbr-primary">打开联合上传页</button>
<span class="cbr-muted">{{ implode('、', $set['names']) }}</span>
</form>
@endforeach
</div>
</section>
@endif
<section class="cbr-panel" aria-label="让快递自己上传">
<h3>让快递自己上传账单</h3>
<form method="POST" action="{{ $action('push-upload-links') }}" class="cbr-panel-body cbr-form"

View File

@ -814,6 +814,7 @@ foreach (['courier-payables', 'courier-payables-final'] as $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::get('joint-upload-link', [$controller, 'jointUploadLink'])->name('joint-upload-link')->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('rebooks/import', [$controller, 'importRebooks'])->name('import-rebooks')->defaults('section', $courierBillSection);

View File

@ -0,0 +1,213 @@
<?php
namespace Tests\Feature\Business;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\CourierJointUploads;
use App\Support\CourierBills\CourierUploadLink;
use App\Support\CourierBills\PortalFreightBillImports;
use App\Support\CourierBills\ShippingLookup;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
final class CourierJointUploadTest extends FeatureTestCase
{
private array $ids = [];
private array $paths = [];
protected function setUp(): void
{
parent::setUp();
Storage::fake('local');
$this->company->makeCurrent(true);
foreach (CourierJointUploads::SETS as $set) {
foreach ($set['names'] as $name) {
if ($name === '睢宁宿迁圆通') continue;
$aliases = $name === '苏北宿迁圆通' ? [$name, '睢宁宿迁圆通'] : [$name];
$this->ids[$name] = app(CourierBillStore::class)->saveGroup(null, ['name' => $name,
'express_names' => $aliases, 'bundle' => '故意相同的合并配置']);
}
}
$this->ids['仓储费'] = app(CourierBillStore::class)->saveGroup(null, ['name' => '南昌樵舍仓仓储费',
'express_names' => ['南昌樵舍仓仓储费'], 'bundle' => '故意相同的合并配置']);
}
protected function tearDown(): void
{
foreach ($this->paths as $path) @unlink($path);
parent::tearDown();
}
public function test_explicit_sets_and_aliases_are_bound_to_the_signed_page_and_queued_task(): void
{
$this->withExceptionHandling();
$sets = app(CourierJointUploads::class);
$this->assertCount(7, $sets->resolve('qiaoshe')['groups']);
$this->assertCount(4, $sets->resolve('yuantong')['groups']);
$links = app(CourierUploadLink::class);
$url = $links->jointPageUrl((int) $this->company->id, 'yuantong', '2026-11');
$page = $this->get($url . '&group_id=' . $this->ids['仓储费'])->assertOk()
->assertSeeText('圆通联合上传')->assertSeeText('睢宁宿迁圆通')->assertDontSeeText('南昌樵舍仓仓储费');
preg_match('/action="([^"]*\/upload[^"]*)"/', $page->getContent(), $matches);
$upload = html_entity_decode($matches[1]);
$this->post($upload, ['group_id' => $this->ids['仓储费'], 'import' => $this->csv([['YT001', '', '', 10, '睢宁宿迁圆通']])])
->assertRedirect()->assertSessionHas('success');
// 队列接收后分组改变,旧授权失效,不能继续写入。
CourierBillMatcher::db()->table('courier_bill_groups')->where('id', $this->ids['苏北宿迁圆通'])
->update(['express_names' => json_encode(['苏北宿迁圆通', '睢宁宿迁圆通', '仓储费'])]);
$this->assertTrue(app(PortalFreightBillImports::class)->processNext());
$this->assertSame(0, CourierBillMatcher::db()->table('courier_bill_lines')->count());
$this->get($url)->assertStatus(410);
$this->get(preg_replace('/signature=[^&]+/', 'signature=' . str_repeat('0', 64), $url))->assertForbidden();
}
public function test_mixed_bill_uses_shipping_then_declared_name_and_preserves_fees_and_rereads(): void
{
$ship = app(ShippingLookup::class)->connection();
$ship->table('jst_oms_shipping')->insert(['express_no' => 'YT001', 'express_name1' => '常州圆通-上楼',
'ship_time' => '2026-11-05 10:00:00', 'source_id' => 100]);
$scope = app(CourierJointUploads::class)->snapshot('yuantong');
$store = app(CourierBillStore::class);
$id = $store->uploadJoint($this->book([
['YT001', '', '', 10, '苏北宿迁圆通'], // 发货数据优先
['YT002', '', '', 20, '睢宁宿迁圆通'], // 系统没有时按明确别名
['YT003', '', '', 30, '小件宿迁圆通'],
], [['YT002', 5, '上楼费']]), '2026-11', $scope, '测试');
$db = $store->db();
$this->assertSame('parsed', $db->table('courier_bill_files')->find($id)->status);
$this->assertEquals(65, $db->table('courier_bill_files')->find($id)->amount);
$this->assertOwners(['YT001' => '常州圆通-上楼', 'YT002' => '苏北宿迁圆通', 'YT003' => '小件宿迁圆通']);
$groupId = $this->ids['苏北宿迁圆通'];
$statementId = $db->table('courier_bill_statements')->where('group_id', $groupId)->value('id');
$this->assertEquals(5, $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('label', '附加费')->sum('bill_amount'));
$store->reread($id);
$store->resplit($id);
$this->assertOwners(['YT001' => '常州圆通-上楼', 'YT002' => '苏北宿迁圆通', 'YT003' => '小件宿迁圆通']);
$this->assertSame(3, $db->table('courier_bill_lines')->count());
$duplicate = $store->uploadJoint($this->csv([['YT001', '', '', 10], ['YT002', '', '', 20]]), '2026-11', $scope, '测试');
$this->assertSame('failed', $db->table('courier_bill_files')->find($duplicate)->status);
$this->assertSame(3, $db->table('courier_bill_lines')->count());
}
public function test_outside_missing_and_inconsistent_rows_are_rejected_atomically(): void
{
$store = app(CourierBillStore::class);
$scope = app(CourierJointUploads::class)->snapshot('qiaoshe');
$cases = [
[['Q001', '', '', 10, '江西中通快运'], ['Q002', '', '', 10, '南昌樵舍仓仓储费']],
[['Q001', '', '', 10, '江西中通快运'], ['Q002', '', '', 10]],
[['Q001', '', '', 10, '江西中通快运'], ['Q001', '', '', 10, '樵舍中通']],
];
foreach ($cases as $rows) {
$id = $store->uploadJoint($this->csv($rows), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $store->db()->table('courier_bill_lines')->count());
}
$id = $store->uploadJoint($this->book([['Q001', '', '', 10, '樵舍中通']], [['Q002', 5, '上楼费']]), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $store->db()->table('courier_bill_surcharges')->count());
app(ShippingLookup::class)->connection()->table('jst_oms_shipping')->insert(['express_no' => 'Q003',
'express_name1' => '南昌樵舍仓仓储费', 'source_id' => 101]);
$id = $store->uploadJoint($this->csv([['Q003', '', '', 10, '樵舍中通']]), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
}
public function test_confirmation_after_queue_prevents_all_writes(): void
{
$url = app(CourierUploadLink::class)->jointPageUrl((int) $this->company->id, 'qiaoshe', '2026-11');
$page = $this->get($url)->assertOk();
preg_match('/action="([^"]*\/upload[^"]*)"/', $page->getContent(), $matches);
$upload = html_entity_decode($matches[1]);
$this->post($upload, ['import' => $this->csv([['Q001', '', '', 10, '樵舍中通']])])->assertRedirect();
CourierBillMatcher::db()->table('courier_bill_statements')->insert(['group_id' => $this->ids['江西中通快运'],
'bill_month' => '2026-11', 'status' => 'confirmed', 'created_at' => now(), 'updated_at' => now()]);
$this->assertTrue(app(PortalFreightBillImports::class)->processNext());
$this->assertSame(0, CourierBillMatcher::db()->table('courier_bill_files')->count());
$this->get($url)->assertOk()->assertSeeText('财务已确认结算')->assertDontSee('name="import"', false);
}
public function test_finance_can_open_each_link_and_courier_can_upload_one_mixed_file(): void
{
$this->loginAs()->withExceptionHandling();
$page = route('business.pages.show', ['section' => 'courier-payables-final', 'page' => 'courier-bill-reconciliation', 'cb_view' => 'upload']);
$this->get($page)->assertOk()->assertSeeText('樵舍联合上传')->assertSeeText('圆通联合上传');
$entry = route('business.courier-payables-final.courier-bills.joint-upload-link', ['joint' => 'qiaoshe', 'month' => '2026-11']);
$response = $this->get($entry)->assertRedirect();
$url = $response->headers->get('Location');
auth()->logout();
$response = $this->get($url)->assertOk()->assertDontSeeText('南昌樵舍仓仓储费');
preg_match('/action="([^"]*\/upload[^"]*)"/', $response->getContent(), $matches);
Http::fake();
$this->post(html_entity_decode($matches[1]), ['import' => $this->csv([
['Q001', '', '', 10, '江西中通快运'], ['Q002', '', '', 20, '西安圆通'],
])])->assertRedirect();
$this->assertTrue(app(PortalFreightBillImports::class)->processNext());
$this->assertOwners(['Q001' => '江西中通快运', 'Q002' => '西安圆通']);
$this->get($url)->assertOk()->assertSeeText('已读入')->assertSeeText('30.00');
$primary = app(CourierJointUploads::class)->resolve('qiaoshe')['group_ids'][0];
$single = app(CourierUploadLink::class)->pageUrl((int) $this->company->id, $primary, '2026-11');
$this->get($single)->assertOk()->assertDontSeeText('仓储费和圆通混合.csv');
}
public function test_large_csv_keeps_all_rows_and_amounts(): void
{
if (! getenv('JOINT_UPLOAD_BENCHMARK')) $this->markTestSkipped('独立容量验收时运行');
$n = (int) getenv('JOINT_UPLOAD_BENCHMARK');
$path = tempnam(sys_get_temp_dir(), 'joint_') . '.csv';
$this->paths[] = $path;
$f = fopen($path, 'wb');
fputcsv($f, ['单号', '省', '重量', '运费', '快递名称', '面单', '费率']);
for ($i = 0; $i < $n; $i++) fputcsv($f, ['Q' . str_pad((string) $i, 12, '0', STR_PAD_LEFT), '', '', '1.23', $i % 2 ? '樵舍中通' : '江西中通快运', '', '']);
fclose($f);
$start = microtime(true);
$queries = 0;
CourierBillMatcher::db()->listen(function () use (&$queries) { $queries++; });
$validation = app(\App\Support\CourierBills\FreightBillTemplate::class)->validate($path, 'csv');
$this->assertSame($n, $validation['rows']);
$id = app(CourierBillStore::class)->uploadJoint(new UploadedFile($path, '容量.csv', null, null, true), '2026-11',
app(CourierJointUploads::class)->snapshot('qiaoshe'), '容量验收');
$file = CourierBillMatcher::db()->table('courier_bill_files')->find($id);
$this->assertSame('parsed', $file->status, $file->message ?? '');
$this->assertSame($n, CourierBillMatcher::db()->table('courier_bill_lines')->count());
$this->assertEquals(round($n * 1.23, 2), (float) $file->amount);
fwrite(STDERR, json_encode(['rows' => $n, 'bytes' => filesize($path), 'seconds' => round(microtime(true) - $start, 2),
'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 1), 'queries' => $queries]) . PHP_EOL);
}
private function assertOwners(array $expected): void
{
$actual = CourierBillMatcher::db()->table('courier_bill_lines as l')->join('courier_bill_statements as s', 's.id', '=', 'l.statement_id')
->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')->pluck('g.name', 'l.waybill_no')->all();
$this->assertEquals($expected, $actual);
}
private function csv(array $rows): UploadedFile
{
$path = tempnam(sys_get_temp_dir(), 'joint_') . '.csv';
$this->paths[] = $path;
$f = fopen($path, 'wb');
fputcsv($f, ['单号', '省', '重量', '运费', '快递名称', '面单', '费率']);
foreach ($rows as $row) fputcsv($f, array_pad($row, 7, ''));
fclose($f);
return new UploadedFile($path, '仓储费和圆通混合.csv', null, null, true);
}
private function book(array $rows, array $fees): UploadedFile
{
$path = tempnam(sys_get_temp_dir(), 'joint_') . '.xlsx';
$this->paths[] = $path;
$book = new Spreadsheet();
$book->getActiveSheet()->setTitle('账单')->fromArray([['单号', '省', '重量', '运费', '快递名称', '面单', '费率'], ...$rows]);
$book->createSheet()->setTitle('附加费')->fromArray([['快递单号', '附加费金额', '附加费类型'], ...$fees]);
(new Xlsx($book))->save($path);
$book->disconnectWorksheets();
return new UploadedFile($path, '联合账单.xlsx', null, null, true);
}
}