kind === 'dropship' ? DropshipConfirmation::class : FreightConfirmation::class); } protected function links(): DropshipShareLink|CourierFreightLink { return app($this->kind === 'dropship' ? DropshipShareLink::class : CourierFreightLink::class); } private function url(Request $request, string $token, int $company, string $action, array $query = []): string { return $this->links()->signedRoute('signed.' . ($this->kind === 'dropship' ? 'dropship' : 'courier') . '-freight.' . $action, $token, $company, CarbonImmutable::createFromTimestamp((int) $request->query('expires')), $query); } private function target(Request $request, string $token): array { $company = (int) (($request->route('company_id') ?: company_id()) ?: 1); $p = $this->links()->resolveToken($token, $company); abort_if(!$p, 404); $owner = $p['factory_id']; $month = $p['month']; $version = $p['version']; if ($this->kind === 'dropship') { $party = collect(app(DropshipFreightStore::class)->factories())->firstWhere('id', $owner); } else { $db = app(CourierBillStore::class)->db(); $statement = $db->table('courier_bill_statements')->where('id', $owner)->where('bill_month', $month)->first(); $party = $statement ? $db->table('courier_bill_groups')->find($statement->group_id) : null; } abort_if(!$party, 404); $c = $this->confirmations(); $state = $c->state($month, $owner, $company) ?? []; $snapshot = $c->snapshot($month, $owner, $version, $company); $legacy = []; $legacyVersion = !$snapshot; if (!$snapshot && $this->kind === 'dropship') { $result = app(DropshipReconciler::class)->factoryMonth($party, $month); $legacy = array_values(array_filter($result['rows'], fn ($r) => $r['bill'] !== null)); $snapshot = ['summary' => $result['summary'], 'fees' => [], 'rows' => count($legacy)]; } abort_if(!$snapshot, 404); return compact('company', 'owner', 'month', 'version', 'party', 'state', 'snapshot', 'legacy', 'legacyVersion'); } public function show(Request $request, string $token) { $t = $this->target($request, $token); $data = $request->validate(['q' => ['nullable', 'string', 'max:64'], 'filter' => ['nullable', 'in:all,attention'], 'page' => ['nullable', 'integer', 'min:1']]); $q = trim($data['q'] ?? ''); $filter = $data['filter'] ?? 'attention'; $page = max(1, (int) ($data['page'] ?? 1)); $c = $this->confirmations(); if ($t['legacy'] !== []) { $all = array_values(array_filter($t['legacy'], fn ($r) => ($filter === 'all' || $r['status'] !== Category::MATCH) && ($q === '' || str_contains($r['waybill'], $q)))); $rows = array_slice($all, ($page - 1) * 50, 50); $total = count($all); } else { $query = $c->snapshotQuery($t['month'], $t['owner'], $t['version'], $t['company']); if ($filter !== 'all') { $query->where('values->status', '<>', Category::MATCH); } if ($q !== '') { $query->where('values->waybill', 'like', '%' . addcslashes($q, '%_\\') . '%'); } $total = (clone $query)->count(); $rows = $query->orderBy('id')->offset(($page - 1) * 50)->limit(50)->get(['values'])->map(fn ($r) => json_decode($r->values, true))->all(); } $current = (int) ($t['state']['version'] ?? 0) === $t['version']; $disputes = $c->disputes($t['month'], $t['owner'], $t['company'], $t['version']); return response()->view('business.pages.courier-payables.confirmation.share', $t + ['kind' => $this->kind, 'q' => $q, 'filter' => $filter, 'rows' => $rows, 'total' => $total, 'page' => $page, 'current' => $current, 'submitted' => in_array($t['state']['status'] ?? '', [FreightConfirmation::CONFIRMED, FreightConfirmation::DISPUTED], true), 'disputes' => $disputes, 'summary' => $t['snapshot']['summary'], 'draftKey' => hash('sha256', $token), 'expiresAt' => CarbonImmutable::createFromTimestamp((int) $request->query('expires'))->setTimezone('Asia/Shanghai'), 'submitUrl' => $this->url($request, $token, $t['company'], 'submit'), 'viewUrl' => $this->url($request, $token, $t['company'], 'view'), 'excelUrl' => $this->url($request, $token, $t['company'], 'excel'), 'prevUrl' => $page > 1 ? $this->url($request, $token, $t['company'], 'show', ['q' => $q, 'filter' => $filter, 'page' => $page - 1]) : null, 'nextUrl' => $page * 50 < $total ? $this->url($request, $token, $t['company'], 'show', ['q' => $q, 'filter' => $filter, 'page' => $page + 1]) : null])->withHeaders(['Cache-Control' => 'private, no-store, max-age=0', 'X-Robots-Tag' => 'noindex, nofollow, noarchive', 'Referrer-Policy' => 'no-referrer']); } public function submit(Request $request, string $token) { $t = $this->target($request, $token); $data = $request->validate(['d' => ['nullable', 'array', 'max:500'], 'd.*' => ['string', 'max:64'], 'r' => ['nullable', 'array', 'max:500'], 'r.*' => ['nullable', 'string', 'max:200'], 'other' => ['nullable', 'string', 'max:20000'], 'draft' => ['nullable', 'json', 'max:200000']]); $disputes = []; if (!empty($data['draft'])) { $draft = json_decode($data['draft'], true); if (!is_array($draft) || count($draft) > 500) throw ValidationException::withMessages(['dispute' => '一次最多提交 500 单异议。']); foreach ($draft as $waybill => $reason) { if (!is_string($reason) || trim($reason) === '' || mb_strlen($reason) > 200 || strlen((string)$waybill) > 64) { throw ValidationException::withMessages(['dispute' => '请检查异议单号及原因,每单原因最多 200 字。']); } $disputes[strtoupper(trim((string)$waybill))] = trim($reason); } } foreach ($data['d'] ?? [] as $waybill) { $reason = trim($data['r'][$waybill] ?? ''); if ($reason === '') { throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 请写上异议原因。']); } $disputes[strtoupper(trim($waybill))] = $reason; } foreach (preg_split('/\R/u', $data['other'] ?? '') as $line) { if (trim($line) === '') { continue; } $parts = preg_split('/[\s,,::]+/u', trim($line), 2); if (count($parts) !== 2) { throw ValidationException::withMessages(['dispute' => '请按「单号 原因」逐行填写。']); } $disputes[strtoupper($parts[0])] = mb_substr(trim($parts[1]), 0, 200); } if ($t['legacy'] !== []) { $allowed = []; foreach ($t['legacy'] as $row) $allowed[strtoupper($row['waybill'])] = $row['waybill']; if (array_diff(array_keys($disputes), array_keys($allowed))) { throw ValidationException::withMessages(['dispute' => '单号不在本期账单中。']); } $normalized = []; foreach ($disputes as $waybill => $reason) $normalized[$allowed[$waybill]] = $reason; $disputes = $normalized; } $c = $this->confirmations(); try { $state = $c->submit($t['month'], $t['owner'], $t['version'], $disputes, $t['company']); } catch (RuntimeException $e) { throw ValidationException::withMessages(['dispute' => $e->getMessage()]); } $message = $disputes === [] ? '已确认无异议,财务系统已实时收到。' : '已提交 ' . count($disputes) . ' 单异议,财务核实后会在群里回复。'; $error = null; try { $notifier = app(SupplierDingTalkNotifier::class); $sent = $this->kind === 'dropship' ? $notifier->sendDropshipFreightReceipt($t['party']->name, $t['month'], (float) $state['settle'], $disputes) : $notifier->sendFreightConfirmationReceipt($t['party']->name, $t['month'], (float) $state['settle'], $disputes); if (!$sent) { throw new RuntimeException('未配置群机器人'); } $message .= '回执已发到钉钉群。'; } catch (Throwable $e) { report($e); $error = '群回执发送失败,请财务重发。'; $message .= $error; } $c->markReceipt($t['month'], $t['owner'], $t['version'], $t['company'], $error); return redirect()->to($this->url($request, $token, $t['company'], 'show'))->with('success', $message); } public function excel(Request $request, string $token) { $t = $this->target($request, $token); return response()->streamDownload(function () use ($t) { $book = new StreamingWorkbook(); $s = $t['snapshot']['summary']; $book->row('汇总', ['合作方', '账期', '账单金额', '应结运费', '差额', '版本'], true); $book->row('汇总', [$t['party']->name, $t['month'], $s['bill'], $s['settle'], $s['diff'], $t['version']]); $book->row('费用', ['项目', '应结金额'], true); foreach ($t['snapshot']['fees'] ?? [] as $fee) { $book->row('费用', [$fee['label'], $fee['amount']]); } $book->row('明细', ['快递单号', '发货时间', '快递名称', '账单运费', '应结运费', '差额', '状态', '说明'], true); $rows = $t['legacy'] ?: $this->confirmations()->snapshotQuery($t['month'], $t['owner'], $t['version'], $t['company'])->orderBy('id')->lazyById(500); foreach ($rows as $record) { $r = is_array($record) ? $record : json_decode($record->values, true); $book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['final'], round($r['bill'] - (float) $r['final'], 2), $r['label'], $r['note']]); } $book->row('异议处理', ['快递单号', '异议原因', '财务结果', '回复', '复核应结运费'], true); foreach ($this->confirmations()->disputes($t['month'], $t['owner'], $t['company'], $t['version']) as $d) { $book->row('异议处理', [$d['waybill'], $d['reason'], ['accept' => '采纳', 'reject' => '不采纳'][$d['decision'] ?? ''] ?? '待处理', $d['reply'] ?? '', $d['review_amount'] ?? null]); } $book->writeTo(fopen('php://output', 'wb')); }, str_replace(['/', '\\'], '-', $t['party']->name) . '_' . $t['month'] . '_对账确认V' . $t['version'] . '.xlsx', ['Cache-Control' => 'private, no-store', 'X-Robots-Tag' => 'noindex, nofollow']); } }