CaiWuXiTong/app/Http/Controllers/Business/DropshipFreightShare.php
Claude 505855da4c 代发运费对账:核对完成后推送厂家钉钉群确认,厂家免登录逐单确认或提异议
- 财务端:各厂家汇总/单家明细加「核对完成」「推送厂家确认」「重新推送」,显示厂家确认状态和异议
- 推送用供应商对账里这家的钉钉群机器人(和货款对账同一个群),附免登录签名链接(30 天)
- 厂家确认页:汇总、不结或运费有差的单逐单勾选异议并写原因,其他单号可按「单号 原因」填写;可下载厂家版 Excel
- 提交后状态实时回写,并在群里发回执;重新推送版本号加一,旧链接作废
- 状态和异议存在 supplier_payable_overrides 通用表,无数据库迁移

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UNTa9mVziToe5w52mmrrar
2026-12-02 19:38:02 +08:00

182 lines
9.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\Category;
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipReconciler;
use App\Support\DropshipFreight\DropshipShareLink;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
/**
* 钉钉群推送的代发运费确认页(免登录,同供应商对账的货款确认页):
* 厂家看本账期每一单的结算结果,没有异议点「确认无异议」,对某一单有异议就勾选那一单写原因提交。
*/
final class DropshipFreightShare extends Controller
{
/** 确认页上逐单列出的「要看的单」最多这么多行,其余可下载 Excel 后在文本框里填。 */
private const MAX_ROWS = 500;
public function __construct(
private readonly DropshipFreightStore $store,
private readonly DropshipReconciler $reconciler,
private readonly DropshipConfirmation $confirmations,
private readonly DropshipShareLink $links,
) {}
public function show(Request $request, string $token): Response
{
$t = $this->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<array>,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 . '月';
}
}