target($request, $token); $current = (int) ($t['state']['version'] ?? 0) === $t['version']; $rows = $t['rows']; $attention = array_values(array_filter($rows, static fn (array $r): bool => $r['status'] !== Category::MATCH)); $expires = $this->expiresAt($request); $submitted = in_array($t['state']['status'] ?? '', [DropshipConfirmation::CONFIRMED, DropshipConfirmation::DISPUTED], true); return response()->view('business.pages.courier-payables.dropship-freight.share', [ 'factory' => $t['factory']->name, 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'version' => $t['version'], 'current' => $current, 'state' => $t['state'], 'submitted' => $current && $submitted, 'summary' => $t['summary'], 'attention' => array_slice($attention, 0, self::MAX_ROWS), 'attentionTotal' => count($attention), 'matchCount' => count($rows) - count($attention), 'maxRows' => self::MAX_ROWS, 'disputes' => $current ? $this->confirmations->disputes($t['month'], (int) $t['factory']->id, $t['companyId'], $t['version']) : [], 'expiresAt' => $expires, 'submitUrl' => $this->links->signedRoute('signed.dropship-freight.submit', $token, $t['companyId'], $expires), 'excelUrl' => $this->links->signedRoute('signed.dropship-freight.excel', $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 submit(Request $request, string $token): RedirectResponse { $t = $this->target($request, $token); $data = $request->validate([ 'd' => ['nullable', 'array', 'max:' . self::MAX_ROWS], 'd.*' => ['string', 'max:64'], 'r' => ['nullable', 'array'], 'r.*' => ['nullable', 'string', 'max:200'], 'other' => ['nullable', 'string', 'max:20000'], ]); $billed = array_flip(array_map(static fn (array $r): string => strtoupper((string) $r['waybill']), $t['rows'])); $byUpper = []; foreach ($t['rows'] as $r) { $byUpper[strtoupper((string) $r['waybill'])] = (string) $r['waybill']; } $disputes = []; foreach ((array) ($data['d'] ?? []) as $waybill) { $reason = trim((string) (($data['r'] ?? [])[$waybill] ?? '')); if ($reason === '') { throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 勾选了有异议,请写上原因。']); } $disputes[$waybill] = $reason; } foreach (preg_split('/\R/u', (string) ($data['other'] ?? '')) ?: [] as $line) { $line = trim($line); if ($line === '') { continue; } $parts = preg_split('/[\s,,::\t]+/u', $line, 2) ?: []; $waybill = trim((string) ($parts[0] ?? ''), " \t@"); $reason = trim((string) ($parts[1] ?? '')); if ($reason === '') { throw ValidationException::withMessages(['dispute' => '「' . $line . '」:请按「单号 原因」填写,单号后面写上原因。']); } $disputes[$waybill] = mb_substr($reason, 0, 200); } $normalized = []; foreach ($disputes as $waybill => $reason) { $key = strtoupper(trim((string) $waybill)); if (! isset($billed[$key])) { throw ValidationException::withMessages(['dispute' => '单号 ' . $waybill . ' 不在本账期你们开的运费账单里,请核对单号。']); } $normalized[$byUpper[$key]] = $reason; } try { $state = $this->confirmations->submit($t['month'], (int) $t['factory']->id, $t['version'], $normalized, $t['companyId']); } catch (RuntimeException $error) { throw ValidationException::withMessages(['dispute' => $error->getMessage()]); } $message = $normalized === [] ? '已确认无异议,财务系统已实时收到。' : '已提交 ' . count($normalized) . ' 单异议,财务核实后会在群里回复。'; try { if (app(SupplierDingTalkNotifier::class)->sendDropshipFreightReceipt((string) $t['factory']->name, $t['month'], (float) ($state['settle'] ?? $t['summary']['settle']), $normalized)) { $message .= '回执已发到钉钉群。'; } } catch (Throwable $error) { report($error); } return redirect()->to($this->links->signedRoute('signed.dropship-freight.show', $token, $t['companyId'], $this->expiresAt($request))) ->with('success', $message); } /** 厂家版对账单:汇总 + 明细(每单的厂家运费、应结运费、状态和说明),不含内部核算公式。 */ public function excel(Request $request, string $token): StreamedResponse { $t = $this->target($request, $token); $s = $t['summary']; $name = str_replace(['/', '\\'], '-', (string) $t['factory']->name) . '_' . $t['month'] . '_代发运费对账单.xlsx'; return response()->streamDownload(function () use ($t, $s): void { $book = new StreamingWorkbook(); $book->row('汇总', ['厂家', '账期', '厂家开运费单数', '厂家运费', '应结运费', '差额(厂家−应结)'], true); $book->row('汇总', [$t['factory']->name, self::monthLabel($t['month']), $s['billed'], $s['bill'], $s['settle'], $s['diff']]); $book->row('汇总', []); $book->row('汇总', ['分类', '单数'], true); foreach (DropshipReconciler::LABELS as $key => $label) { if ($key !== Category::UNPROVIDED && ($s['counts'][$key] ?? 0) > 0) { $book->row('汇总', [$label, $s['counts'][$key]]); } } $book->row('明细', ['快递单号', '发货时间', '快递名称', '厂家运费', '应结运费', '差额(厂家−应结)', '状态', '说明'], true); foreach ($t['rows'] as $r) { $book->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['settle'] ?? 0, round((float) $r['bill'] - (float) ($r['settle'] ?? 0), 2), $r['label'], $r['note']]); } $book->writeTo(fopen('php://output', 'wb')); }, $name); } /** @return array{companyId:int,factory:object,month:string,version:int,state:array,rows:list,summary:array} */ 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, '链接无效或已过期。'); $factory = collect($this->store->factories())->firstWhere('id', $payload['factory_id']); abort_if($factory === null, 404, '链接无效或已过期。'); $result = $this->reconciler->factoryMonth($factory, $payload['month']); // 厂家看的是他们开了运费的单;厂家没开的单(厂家未提供)本来就不付,不放在确认页 $rows = array_values(array_filter($result['rows'], static fn (array $r): bool => $r['bill'] !== null)); return ['companyId' => $companyId, 'factory' => $factory, 'month' => $payload['month'], 'version' => $payload['version'], 'state' => $this->confirmations->state($payload['month'], (int) $factory->id, $companyId) ?? [], 'rows' => $rows, 'summary' => $result['summary']]; } private function expiresAt(Request $request): CarbonImmutable { $expires = (int) $request->query('expires', 0); return $expires > 0 ? CarbonImmutable::createFromTimestamp($expires) : CarbonImmutable::now()->addDays(DropshipShareLink::TTL_DAYS); } private static function monthLabel(string $month): string { [$y, $m] = explode('-', $month); return (int) $y . '年' . (int) $m . '月'; } }