feat(代发运费): 推送厂家确认并记录逐单异议 (#1667)

This commit is contained in:
limeng 2026-12-02 19:47:28 +08:00
parent 7bb4667a47
commit c6273cb3f6
13 changed files with 935 additions and 5 deletions

View File

@ -2,16 +2,21 @@
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\Category;
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipReconciler;
use App\Support\DropshipFreight\DropshipShareLink;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Throwable;
/** 代发运费对账:代发厂家开的运费 对 系统核算运费,按我方核算结算;不进快递应付汇总。 */
final class DropshipFreightController extends Controller
@ -22,6 +27,7 @@ final class DropshipFreightController extends Controller
public function __construct(
private readonly DropshipFreightStore $store,
private readonly DropshipReconciler $reconciler,
private readonly DropshipConfirmation $confirmations,
) {}
public function page(Request $request): array
@ -62,7 +68,10 @@ final class DropshipFreightController extends Controller
}
}
return ['dfRows' => $rows, 'dfWithout' => $without, 'dfTotals' => [
$notifier = app(SupplierDingTalkNotifier::class);
return ['dfRows' => $rows, 'dfWithout' => $without, 'dfStates' => $this->confirmations->states($month, self::companyId()),
'dfRobots' => $notifier->configurationMap(array_column($rows, 'factory')), 'dfTotals' => [
'bill' => array_sum(array_column($rows, 'bill')), 'settle' => array_sum(array_column($rows, 'settle')),
'diff' => array_sum(array_column($rows, 'diff')), 'attention' => array_sum(array_column($rows, 'attention')),
]];
@ -87,7 +96,10 @@ final class DropshipFreightController extends Controller
['path' => $request->url(), 'query' => $request->query()]);
$files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get();
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files];
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files,
'dfState' => $this->confirmations->state($month, (int) $factory->id, self::companyId()),
'dfDisputes' => $this->confirmations->disputes($month, (int) $factory->id, self::companyId()),
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name)];
}
private function uploadData(string $month): array
@ -180,6 +192,66 @@ final class DropshipFreightController extends Controller
. ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。');
}
/** 财务点「核对完成」/「撤销」:核对完成的厂家才能推送给厂家确认。 */
public function check(Request $request, int $factory)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'checked' => ['required', 'boolean']]);
$f = $this->factory($factory);
$summary = $this->reconciler->factoryMonth($f, $data['month'])['summary'];
$this->guard(fn () => $this->confirmations->check($data['month'], $f, $summary, (bool) $data['checked'], self::companyId(),
user()?->id, self::user()));
return $this->back($request, [], (bool) $data['checked'] ? '「' . $f->name . '」' . $data['month'] . ' 已标记核对完成,可以推送给厂家确认。'
: '已撤销「' . $f->name . '」的核对完成。');
}
/** 推送到厂家钉钉群(和供应商货款对账同一个群机器人),附免登录确认页链接;重新推送版本号加一,旧链接作废。 */
public function push(Request $request, int $factory)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m']]);
$month = $data['month'];
$f = $this->factory($factory);
$result = $this->reconciler->factoryMonth($f, $month);
$summary = $result['summary'];
$attention = self::attention($result['rows']);
$notifier = app(SupplierDingTalkNotifier::class);
if (! $notifier->configuration((string) $f->name)['configured']) {
throw ValidationException::withMessages(['dropship' => '「' . $f->name . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']);
}
$companyId = self::companyId();
$version = $this->guard(fn () => $this->confirmations->startPush($month, $f, $summary, $attention, $companyId, user()?->id, self::user()));
$url = app(DropshipShareLink::class)->pageUrl($companyId, (int) $f->id, $month, $version);
try {
$notifier->pushDropshipFreight((string) $f->name, $month, $summary, $attention, $version, $url);
} catch (Throwable $error) {
$this->confirmations->markFailed($month, (int) $f->id, $companyId, $error->getMessage());
report($error);
throw ValidationException::withMessages(['dropship' => '推送失败:' . $error->getMessage()]);
}
$this->confirmations->markPushed($month, (int) $f->id, $companyId);
return $this->back($request, [], '已推送到「' . $f->name . '」钉钉群(第 ' . $version . ' 次),等厂家在确认页确认。');
}
/** 厂家开了运费、但不是「一致」的单:不结算或运费有差,确认页上请厂家重点看。 */
public static function attention(array $rows): int
{
return count(array_filter($rows, static fn (array $r): bool => $r['bill'] !== null && $r['status'] !== Category::MATCH));
}
private function factory(int $id): object
{
$factory = collect($this->store->factories())->firstWhere('id', $id);
abort_if($factory === null, 404);
return $factory;
}
private static function companyId(): int
{
return (int) (company_id() ?: 1);
}
public function export(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]);

View File

@ -0,0 +1,181 @@
<?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 . '月';
}
}

View File

@ -0,0 +1,175 @@
<?php
namespace App\Support\DropshipFreight;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use RuntimeException;
/**
* 代发运费对账的「核对完成 → 推送厂家确认 → 厂家确认 / 逐单异议」状态。
*
* 和供应商对账一样存在通用数据表 supplier_payable_overrides 里,不加新表:
* - 数据集 dropship-freight-confirm,记录键「月份|厂家ID」:这家这个月的状态、推送版本、推送时的金额快照;
* - 数据集 dropship-freight-dispute:月份|厂家ID,记录键是快递单号:厂家对这一单的异议原因(带推送版本)。
* 每次推送版本号加一,旧链接随之作废;历史异议保留,按版本区分。
*/
final class DropshipConfirmation
{
public const DATASET = 'dropship-freight-confirm';
public const DISPUTES = 'dropship-freight-dispute:';
public const OPEN = 'open';
public const CHECKED = 'checked';
public const SENDING = 'sending';
public const PUSHED = 'pushed';
public const FAILED = 'failed';
public const CONFIRMED = 'confirmed';
public const DISPUTED = 'disputed';
public const LABELS = [
self::OPEN => '未核完', self::CHECKED => '已核完,待推送', self::SENDING => '推送中', self::PUSHED => '已推送,待厂家确认',
self::FAILED => '推送失败', self::CONFIRMED => '厂家已确认', self::DISPUTED => '厂家有异议',
];
public function __construct(private readonly SupplierPayableOverrideStore $store) {}
public static function key(string $month, int $factoryId): string
{
return $month . '|' . $factoryId;
}
public static function label(?array $state): string
{
return self::LABELS[(string) ($state['status'] ?? self::OPEN)] ?? self::LABELS[self::OPEN];
}
public function state(string $month, int $factoryId, int $companyId): ?array
{
return $this->store->findRow(self::DATASET, self::key($month, $factoryId), $companyId);
}
/** @return array<int,array<string,mixed>> 厂家ID => 状态 */
public function states(string $month, int $companyId): array
{
$out = [];
foreach ($this->store->listRows(self::DATASET, $companyId) as $row) {
if (($row['month'] ?? '') === $month) {
$out[(int) ($row['factory_id'] ?? 0)] = $row;
}
}
return $out;
}
/** 财务点「核对完成」/「撤销核对完成」。厂家已确认后不能再撤销,要改就重新推送。 */
public function check(string $month, object $factory, array $summary, bool $checked, int $companyId, ?int $userId, string $by): array
{
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
$status = (string) ($state['status'] ?? self::OPEN);
if (! $checked && in_array($status, [self::PUSHED, self::CONFIRMED, self::DISPUTED, self::SENDING], true)) {
throw new RuntimeException('已经推送给厂家,不能撤销;有改动请改完后重新推送。');
}
$values = array_merge($this->base($state, $month, $factory), [
'status' => $checked ? ($status === self::OPEN || $status === self::FAILED ? self::CHECKED : $status) : self::OPEN,
'checked_at' => $checked ? now()->toDateTimeString() : null,
'checked_by' => $checked ? $by : null,
'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'],
]);
$this->store->save(self::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_check');
return $values;
}
/** 开始一次推送:版本号加一并记下这次的金额快照,返回新版本号。 */
public function startPush(string $month, object $factory, array $summary, int $attention, int $companyId, ?int $userId, string $by): int
{
$state = $this->state($month, (int) $factory->id, $companyId) ?? [];
if (($state['status'] ?? self::OPEN) === self::OPEN) {
throw new RuntimeException('先点「核对完成」再推送给厂家。');
}
if (($state['status'] ?? '') === self::SENDING) {
throw new RuntimeException('正在推送,请稍后刷新查看结果。');
}
$version = (int) ($state['version'] ?? 0) + 1;
$values = array_merge($this->base($state, $month, $factory), [
'status' => self::SENDING, 'version' => $version, 'pushed_by' => $by, 'push_requested_at' => now()->toDateTimeString(),
'bill' => $summary['bill'], 'settle' => $summary['settle'], 'diff' => $summary['diff'], 'billed' => $summary['billed'],
'attention' => $attention, 'confirmed_at' => null, 'disputed_count' => 0, 'push_error' => null,
]);
$this->store->save(self::DATASET, self::key($month, (int) $factory->id), $values, $companyId, $userId, 'dropship_push');
return $version;
}
public function markPushed(string $month, int $factoryId, int $companyId): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::PUSHED, 'pushed_at' => now()->toDateTimeString()], 'dropship_pushed');
}
public function markFailed(string $month, int $factoryId, int $companyId, string $message): void
{
$this->merge($month, $factoryId, $companyId, ['status' => self::FAILED, 'push_error' => mb_strimwidth($message, 0, 300, '…', 'UTF-8')], 'dropship_push_failed');
}
/**
* 厂家在确认页提交:没有异议 = 确认;有异议的单逐单记原因。同一版本只能提交一次。
*
* @param array<string,string> $disputes 快递单号 => 原因
* @return array<string,mixed> 提交后的状态
*/
public function submit(string $month, int $factoryId, int $version, array $disputes, int $companyId): array
{
$state = $this->state($month, $factoryId, $companyId);
if ($state === null || (int) ($state['version'] ?? 0) !== $version) {
throw new RuntimeException('这个链接已经不是最新一次推送,请以群里最新的推送为准。');
}
if (in_array($state['status'] ?? '', [self::CONFIRMED, self::DISPUTED], true)) {
throw new RuntimeException('本次对账已经提交,请查看已提交的结果。');
}
if (($state['status'] ?? '') !== self::PUSHED) {
throw new RuntimeException('本次对账尚未推送成功,请等待财务重新推送。');
}
$now = now()->toDateTimeString();
$this->store->transaction(function () use ($month, $factoryId, $version, $disputes, $companyId, $now): void {
foreach ($disputes as $waybill => $reason) {
$this->store->save(self::DISPUTES . self::key($month, $factoryId), $version . '|' . $waybill,
['waybill' => (string) $waybill, 'reason' => $reason, 'version' => $version, 'submitted_at' => $now],
$companyId, null, 'manufacturer_link');
}
$this->merge($month, $factoryId, $companyId, [
'status' => $disputes === [] ? self::CONFIRMED : self::DISPUTED,
'confirmed_at' => $now, 'disputed_count' => count($disputes),
], 'manufacturer_link');
});
return $this->state($month, $factoryId, $companyId) ?? [];
}
/** @return list<array<string,mixed>> 这家这个月的异议,最新版本在前 */
public function disputes(string $month, int $factoryId, int $companyId, ?int $version = null): array
{
$rows = $this->store->listRows(self::DISPUTES . self::key($month, $factoryId), $companyId);
if ($version !== null) {
$rows = array_values(array_filter($rows, static fn (array $r): bool => (int) ($r['version'] ?? 0) === $version));
}
usort($rows, static fn (array $a, array $b): int => [(int) ($b['version'] ?? 0), (string) ($a['waybill'] ?? '')]
<=> [(int) ($a['version'] ?? 0), (string) ($b['waybill'] ?? '')]);
return $rows;
}
private function base(array $state, string $month, object $factory): array
{
$keep = array_diff_key($state, array_flip(['_action_key']));
return array_merge($keep, ['factory_id' => (int) $factory->id, 'factory' => (string) $factory->name,
'supplier' => (string) $factory->name, 'month' => $month]);
}
private function merge(string $month, int $factoryId, int $companyId, array $values, string $source): void
{
$state = $this->state($month, $factoryId, $companyId) ?? [];
unset($state['_action_key']);
$this->store->save(self::DATASET, self::key($month, $factoryId), array_merge($state, $values), $companyId, null, $source);
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Support\DropshipFreight;
use DateTimeInterface;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* 代发运费确认页的免登录链接(同供应商对账的货款确认页):
* 公司、厂家、月份、推送版本放进加密令牌,URL 再做 Laravel 签名,厂家只能看本厂家本次推送的账期。
*/
final class DropshipShareLink
{
public const TTL_DAYS = 30;
public function pageUrl(int $companyId, int $factoryId, string $month, int $version): string
{
return $this->signedRoute('signed.dropship-freight.show', $this->token($companyId, $factoryId, $month, $version), $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{factory_id:int,month:string,version:int}|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['factory_id'] ?? 0) <= 0
|| preg_match('/^\d{4}-\d{2}$/', (string) ($payload['month'] ?? '')) !== 1 || (int) ($payload['version'] ?? 0) <= 0) {
return null;
}
return ['factory_id' => (int) $payload['factory_id'], 'month' => (string) $payload['month'], 'version' => (int) $payload['version']];
}
private function token(int $companyId, int $factoryId, string $month, int $version): string
{
$payload = json_encode(['company_id' => $companyId, 'factory_id' => $factoryId, 'month' => $month, 'version' => $version],
JSON_THROW_ON_ERROR);
return rtrim(strtr(base64_encode(Crypt::encryptString($payload)), '+/', '-_'), '=');
}
}

View File

@ -568,6 +568,90 @@ class SupplierDingTalkNotifier
$this->persist($configs);
}
/**
* 代发运费对账:推送核对好的运费汇总和确认页链接到这家厂家的钉钉群(和货款对账同一个群机器人)。
*
* @param array{billed:int,bill:float,settle:float,diff:float} $summary
*/
public function pushDropshipFreight(string $supplier, string $month, array $summary, int $attention, int $version, string $url): void
{
[$webhook, $config] = $this->robotFor($supplier, 'dingtalk_dropship_push');
$lines = [
'### 代发运费对账确认 · ' . $supplier,
'- 账期:**' . $this->displayMonth($month) . '**',
'- 厂家开运费:**' . $summary['billed'] . '** 单,**¥' . number_format((float) $summary['bill'], 2) . '**',
'- 核对后应结运费:**¥' . number_format((float) $summary['settle'], 2) . '**',
'- 差额(厂家 − 应结):**¥' . number_format((float) $summary['diff'], 2) . '**',
'- 不结或运费有差的单:**' . $attention . '** 单,原因见确认页',
];
if ($version > 1) {
$lines[] = '- 本次为第 **' . $version . '** 次推送,以本次为准,之前的链接作废';
}
array_push($lines, '', '#### [打开运费确认页](' . $url . ')',
'- 逐单核对;对哪一单有异议,就在那一单勾选「有异议」并写原因,没有异议直接点「确认无异议」。',
'- 提交后结果实时回传财务系统,并在本群发送回执。', '',
'> 无需登录;链接仅可查看本厂家本账期,有效期 ' . \App\Support\DropshipFreight\DropshipShareLink::TTL_DAYS . ' 天。');
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$supplier . ' · 代发运费对账确认 · ' . $this->displayMonth($month), implode("\n", $lines));
$this->touch($supplier, 1);
}
/** @param array<string,string> $disputes 快递单号 => 原因 */
public function sendDropshipFreightReceipt(string $supplier, string $month, float $settle, array $disputes): bool
{
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
return false;
}
$this->assertWebhook($webhook);
$lines = [
'### 代发运费确认回执 · ' . $supplier,
'- 账期:**' . $this->displayMonth($month) . '**',
'- 应结运费:**¥' . number_format($settle, 2) . '**',
'- 结果:' . ($disputes === [] ? '**确认无异议**' : '**有异议 ' . count($disputes) . ' 单**,财务核实后回复'),
];
$n = 0;
foreach ($disputes as $waybill => $reason) {
if (++$n > 10) {
$lines[] = '- ……其余 ' . (count($disputes) - 10) . ' 单见财务系统';
break;
}
$lines[] = '- ' . $waybill . ':' . mb_strimwidth(str_replace(["\r", "\n"], ' ', $reason), 0, 60, '…', 'UTF-8');
}
array_push($lines, '- 提交时间:' . $this->platformTimestamp(), '- 系统状态:**已实时回传财务系统**');
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$supplier . ' · 代发运费确认回执 · ' . $this->displayMonth($month), implode("\n", $lines));
return true;
}
/** @return array{0:string,1:array<string,mixed>} */
private function robotFor(string $supplier, string $field): array
{
$configs = $this->configs();
$config = is_array($configs[$supplier] ?? null) ? $configs[$supplier] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
throw ValidationException::withMessages([$field => '「' . $supplier . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']);
}
$this->assertWebhook($webhook);
return [$webhook, $config];
}
private function touch(string $supplier, int $count): void
{
$configs = $this->configs();
if (! is_array($configs[$supplier] ?? null)) {
return;
}
$configs[$supplier]['last_pushed_at'] = $this->platformTimestamp();
$configs[$supplier]['last_push_count'] = $count;
$this->persist($configs);
}
/** @param list<array<string,mixed>> $records */
private function statementMonths(array $records): string
{

View File

@ -0,0 +1,26 @@
@php
use App\Support\DropshipFreight\DropshipConfirmation as DC;
$st = (string) ($state['status'] ?? DC::OPEN);
$chip = match ($st) { DC::CONFIRMED => 'ok', DC::DISPUTED, DC::FAILED => 'bad', DC::PUSHED, DC::SENDING => 'warn', default => '' };
$robotOk = (bool) ($robot['configured'] ?? false);
@endphp
<span class="cbr-chip {{ $chip }}" title="{{ $state['push_error'] ?? '' }}">{{ DC::label($state) }}@if (in_array($st, [DC::PUSHED, DC::CONFIRMED, DC::DISPUTED], true)) · 第{{ (int) ($state['version'] ?? 1) }}次@endif @if ($st === DC::DISPUTED) · {{ (int) ($state['disputed_count'] ?? 0) }} 单@endif</span>
@if ($st === DC::OPEN)
<form method="POST" action="{{ $action('check', ['factory' => $fid]) }}" style="display:inline">@csrf
<input type="hidden" name="month" value="{{ $month }}"><input type="hidden" name="checked" value="1">
<button type="submit">核对完成</button></form>
@else
@if (in_array($st, [DC::CHECKED, DC::FAILED], true))
<form method="POST" action="{{ $action('check', ['factory' => $fid]) }}" style="display:inline">@csrf
<input type="hidden" name="month" value="{{ $month }}"><input type="hidden" name="checked" value="0">
<button type="submit">撤销</button></form>
@endif
@if ($st !== DC::SENDING)
<form method="POST" action="{{ $action('push', ['factory' => $fid]) }}" style="display:inline"
data-confirm="推送「{{ $fname }}」{{ $month }} 代发运费到厂家钉钉群,请厂家确认?{{ in_array($st, [DC::PUSHED, DC::DISPUTED, DC::CONFIRMED], true) ? '重新推送后,之前的链接作废。' : '' }}"
onsubmit="return confirm(this.dataset.confirm)">@csrf
<input type="hidden" name="month" value="{{ $month }}">
<button type="submit" class="cbr-primary" @disabled(! $robotOk) title="{{ $robotOk ? '推送到这家的钉钉对账群' : '这家还没配钉钉群机器人:在供应商对账里配置(和货款对账同一个群)' }}">{{ in_array($st, [DC::PUSHED, DC::DISPUTED, DC::CONFIRMED], true) ? '重新推送' : '推送厂家确认' }}</button></form>
@endif
@endif
@if (! $robotOk)<div class="cbr-muted">未配钉钉群机器人</div>@endif

View File

@ -19,6 +19,27 @@
<div><span>差额(厂家 − 结算)</span><strong class="cbr-diff">{{ $money($s['diff']) }}</strong></div>
</div>
<section class="cbr-panel" aria-label="厂家确认">
<div class="cbr-panel-body cbr-form">
<strong>厂家确认:</strong>
@include('business.pages.courier-payables.dropship-freight._confirm', ['fid' => $dfFactory->id, 'fname' => $dfFactory->name, 'state' => $dfState, 'robot' => $dfRobot])
@if (! empty($dfState['pushed_at']))<span class="cbr-muted">推送:{{ $dfState['pushed_at'] }}({{ $dfState['pushed_by'] ?? '' }})</span>@endif
@if (! empty($dfState['confirmed_at']))<span class="cbr-muted">厂家提交:{{ $dfState['confirmed_at'] }}</span>@endif
</div>
@if ($dfDisputes !== [])
<div class="cbr-scroll">
<table>
<thead><tr><th scope="col">推送</th><th scope="col">快递单号</th><th scope="col">厂家异议原因</th><th scope="col">提交时间</th></tr></thead>
<tbody>
@foreach ($dfDisputes as $d)
<tr><td>第{{ (int) ($d['version'] ?? 0) }}次</td><td>{{ $d['waybill'] ?? '' }}</td><td class="wrap">{{ $d['reason'] ?? '' }}</td><td>{{ $d['submitted_at'] ?? '' }}</td></tr>
@endforeach
</tbody>
</table>
</div>
@endif
</section>
<nav class="cbr-tabs" aria-label="按状态看">
<a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $dfFactory->id, 'month' => $month]) }}" class="{{ $dfStatus === '' ? 'is-active' : '' }}">全部<span>{{ array_sum($s['counts']) }}</span></a>
<a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $dfFactory->id, 'month' => $month, 'status' => 'attention']) }}" class="{{ $dfStatus === 'attention' ? 'is-active' : '' }}">要看的<span>{{ $s['attention'] }}</span></a>

View File

@ -19,7 +19,7 @@
<thead><tr>
<th scope="col">厂家</th><th scope="col">代发仓</th><th scope="col">关键字</th>
<th scope="col" class="num">厂家开运费单数</th><th scope="col" class="num">厂家运费</th><th scope="col" class="num">结算运费</th><th scope="col" class="num">差额</th>
<th scope="col" class="num">运费有差·厂家多开</th><th scope="col" class="num">运费有差·厂家少开</th><th scope="col" class="num">厂家未提供(不付)</th><th scope="col" class="num">其他要看的</th><th scope="col">操作</th>
<th scope="col" class="num">运费有差·厂家多开</th><th scope="col" class="num">运费有差·厂家少开</th><th scope="col" class="num">厂家未提供(不付)</th><th scope="col" class="num">其他要看的</th><th scope="col">厂家确认</th><th scope="col">操作</th>
</tr></thead>
<tbody>
@forelse ($dfRows as $row)
@ -36,10 +36,12 @@
<td class="num">{{ number_format($row['under']) }}</td>
<td class="num">{{ number_format($row['counts']['unprovided']) }}</td>
<td class="num">@if ($other > 0)<span class="cbr-chip warn">{{ number_format($other) }}</span>@else 0 @endif</td>
<td class="wrap">@include('business.pages.courier-payables.dropship-freight._confirm', ['fid' => $row['factory_id'], 'fname' => $row['factory'],
'state' => $dfStates[$row['factory_id']] ?? null, 'robot' => $dfRobots[$row['factory']] ?? []])</td>
<td><a data-cbr-tab href="{{ $pageUrl(['df_view' => 'factory', 'factory' => $row['factory_id'], 'month' => $month]) }}">打开明细</a></td>
</tr>
@empty
<tr><td colspan="12" class="cbr-empty">{{ $month }} 还没有上传厂家账单。先在「代发厂家设置」里建好厂家,再到「上传厂家账单」批量上传。</td></tr>
<tr><td colspan="13" class="cbr-empty">{{ $month }} 还没有上传厂家账单。先在「代发厂家设置」里建好厂家,再到「上传厂家账单」批量上传。</td></tr>
@endforelse
</tbody>
</table>
@ -48,4 +50,4 @@
<div class="cbr-footer">本月没收到账单的厂家({{ count($dfWithout) }},没账单就不付运费):{{ implode('、', $dfWithout) }}</div>
@endif
</section>
<p class="cbr-muted">差额 = 厂家运费 − 结算运费;正数是厂家多开、按我方核算扣掉的。分类和自有快递对账一样:重复 → 未发出 → 匹配不到(发货数据哪个月都查不到)→ 快递不符(不是这家代发仓发的、不是这家代发快递或是自有快递)→ 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算)。一致类和前月补提供按我方核算结算;换单的旧单号按实际发出的新单号判断(新单号是这家代发单就照付,否则算快递不符);其他要看的 = 除运费有差外需要人工看的单。</p>
<p class="cbr-muted">差额 = 厂家运费 − 结算运费;正数是厂家多开、按我方核算扣掉的。分类和自有快递对账一样:重复 → 未发出 → 匹配不到(发货数据哪个月都查不到)→ 快递不符(不是这家代发仓发的、不是这家代发快递或是自有快递)→ 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算)。一致类和前月补提供按我方核算结算;换单的旧单号按实际发出的新单号判断(新单号是这家代发单就照付,否则算快递不符);其他要看的 = 除运费有差外需要人工看的单。厂家确认:核对完成后点「推送厂家确认」,推送到这家的钉钉对账群(和货款对账同一个群机器人),厂家在免登录确认页逐单确认,对某一单有异议可写原因,结果实时回到这里。</p>

View File

@ -0,0 +1,132 @@
<x-layouts.signed>
<x-slot name="title">代发运费对账确认 · {{ $factory }} · {{ $monthLabel }}</x-slot>
<x-slot name="buttons">
<a href="{{ $excelUrl }}" class="df-share-download px-3 py-1.5 mb-3 sm:mb-0 rounded-lg text-sm font-medium leading-6">下载对账单 Excel</a>
<button type="button" onclick="window.print()" class="px-3 py-1.5 mb-3 sm:mb-0 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm font-medium leading-6">打印</button>
</x-slot>
<x-slot name="content">
<style>
.df-share { display: grid; gap: 10px; margin: 10px auto 16px; max-width: 1400px; color: var(--vip-content-ink, #171717); font-size: .8125rem; }
.df-share-download, .df-share .btn { background: var(--vip-content-accent-dark, #856632); color: #fff; }
.df-share-download:hover, .df-share .btn:hover { background: #6A5129; color: #fff; }
.df-share .head { padding: 11px 14px; border: 1px solid #D8D2C7; border-radius: 8px; background: #F7F0DE; }
.df-share .head h1 { margin: 0 0 4px; font-size: .875rem; font-weight: 600; }
.df-share .muted { color: #595959; font-size: .75rem; line-height: 1.5; }
.df-share .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 8px; }
.df-share .stat { display: grid; gap: 3px; padding: 8px 11px; border: 1px solid #ded7c9; border-radius: 8px; background: #fff; }
.df-share .stat span { color: #686053; font-size: .6875rem; }
.df-share .stat strong { font-size: 1.0625rem; font-variant-numeric: tabular-nums; }
.df-share .card { overflow: hidden; border: 1px solid #ded7c9; border-radius: 10px; background: #fff; }
.df-share .card h2 { margin: 0; padding: 8px 12px; border-bottom: 1px solid #eee8dd; font-size: .875rem; font-weight: 700; }
.df-share .scroll { max-height: 62vh; overflow: auto; }
.df-share table { width: 100%; border-collapse: collapse; font-size: .75rem; }
.df-share th { position: sticky; top: 0; z-index: 1; padding: 6px; border-bottom: 1px solid #d8d2c7; background: #f7f0de; color: #5b5343; text-align: left; }
.df-share td { padding: 6px; border-bottom: 1px solid #f0ece4; vertical-align: middle; }
.df-share .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.df-share .tag { display: inline-flex; padding: 1px 5px; border-radius: 3px; background: #efebe3; color: #645d51; font-size: .6875rem; white-space: nowrap; }
.df-share input[type=text], .df-share textarea { width: 100%; padding: 4px 6px; border: 1px solid #d8d2c7; border-radius: 6px; font: inherit; }
.df-share input[type=text]:disabled { background: #f4f2ee; }
.df-share .actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 10px 12px; }
.df-share .btn { min-height: 36px; padding: 0 16px; border: 0; border-radius: 8px; font-weight: 600; cursor: pointer; }
.df-share .alert { padding: 11px 14px; border: 1px solid #b8d8bc; border-radius: 8px; background: #eef8ef; color: #285f31; }
.df-share .alert.is-error { border-color: #e2b7b2; background: #fff2f0; color: #8c2f26; }
.df-share .alert.is-warn { border-color: #e6cf9c; background: #fff8e6; color: #7a5a14; }
@media print { .df-share .actions, .df-share textarea { display: none !important; } .df-share .scroll { max-height: none; } }
</style>
<div class="df-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>{{ $factory }} · {{ $monthLabel }} 代发运费对账确认</h1>
<div class="muted">
下面是财务按发货数据逐单核对后的结果:「一致」的单按你们开的运费结算;其他的单不结算或按我方核算运费结算,原因写在「说明」里。
没有异议请点「确认无异议」;对哪一单有异议,就勾选那一单并写上原因再提交。提交结果会实时回传财务系统,并在钉钉群发回执。
链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录。
</div>
</section>
@if (! $current)
<div class="alert is-warn" role="alert">这个链接已经不是最新一次推送,请以钉钉群里最新的推送为准。</div>
@elseif ($submitted)
<div class="alert" role="status">
@if (($state['status'] ?? '') === 'confirmed')
已于 {{ $state['confirmed_at'] ?? '' }} 确认无异议,财务系统已收到。
@else
已于 {{ $state['confirmed_at'] ?? '' }} 提交 {{ count($disputes) }} 单异议,财务核实后会在群里回复;如有调整,财务会重新推送。
@endif
</div>
@endif
<section class="stats">
<div class="stat"><span>你们开运费</span><strong>{{ number_format($summary['billed']) }} 单 · ¥{{ number_format($summary['bill'], 2) }}</strong></div>
<div class="stat"><span>应结运费</span><strong>¥{{ number_format($summary['settle'], 2) }}</strong></div>
<div class="stat"><span>差额(厂家 − 应结)</span><strong>¥{{ number_format($summary['diff'], 2) }}</strong></div>
<div class="stat"><span>一致的单</span><strong>{{ number_format($matchCount) }} 单</strong></div>
<div class="stat"><span>不结或运费有差的单</span><strong>{{ number_format($attentionTotal) }} 单</strong></div>
</section>
@if ($submitted && $disputes !== [])
<section class="card">
<h2>已提交的异议({{ count($disputes) }} 单)</h2>
<div class="scroll"><table>
<thead><tr><th>快递单号</th><th>异议原因</th></tr></thead>
<tbody>@foreach ($disputes as $d)<tr><td>{{ $d['waybill'] ?? '' }}</td><td>{{ $d['reason'] ?? '' }}</td></tr>@endforeach</tbody>
</table></div>
</section>
@endif
<form method="POST" action="{{ $submitUrl }}" class="card"
onsubmit="const n=this.querySelectorAll('input[name=&quot;d[]&quot;]:checked').length+this.other.value.trim().split(/\n/).filter(x=>x.trim()).length; return confirm(n ? '提交 ' + n + ' 单异议?' : '确认本账期代发运费无异议?')">
@csrf
<h2>不结或运费有差的单({{ number_format($attentionTotal) }} 单)@if ($attentionTotal > count($attention))<span class="muted">:这里列出前 {{ $maxRows }} 单,其余在 Excel 里,有异议写在下面文本框</span>@endif</h2>
<div class="scroll"><table>
<thead><tr>
@if ($current && ! $submitted)<th>有异议</th>@endif
<th>快递单号</th><th>发货时间</th><th>快递名称</th><th class="num">你们开的运费</th><th class="num">应结运费</th><th>状态</th><th>说明</th>
@if ($current && ! $submitted)<th style="min-width:200px">异议原因</th>@endif
</tr></thead>
<tbody>
@forelse ($attention as $r)
<tr>
@if ($current && ! $submitted)
<td><input type="checkbox" name="d[]" value="{{ $r['waybill'] }}" aria-label="{{ $r['waybill'] }} 有异议" @checked(in_array($r['waybill'], (array) old('d', [])))
onchange="const i=this.closest('tr').querySelector('input[type=text]'); i.disabled=!this.checked; if(this.checked) i.focus();"></td>
@endif
<td>{{ $r['waybill'] }}</td>
<td>{{ $r['ship_time'] ? substr($r['ship_time'], 0, 16) : '—' }}</td>
<td>{{ $r['express'] ?? '—' }}</td>
<td class="num">{{ number_format((float) $r['bill'], 2) }}</td>
<td class="num">{{ number_format((float) ($r['settle'] ?? 0), 2) }}</td>
<td><span class="tag">{{ $r['label'] }}</span></td>
<td>{{ $r['note'] }}</td>
@if ($current && ! $submitted)
<td><input type="text" name="r[{{ $r['waybill'] }}]" maxlength="200" value="{{ old('r.' . $r['waybill']) }}" @disabled(! in_array($r['waybill'], (array) old('d', []))) placeholder="勾选后填写原因"></td>
@endif
</tr>
@empty
<tr><td colspan="9" class="muted" style="padding:20px;text-align:center">没有不结或运费有差的单,你们开的运费全部按账单结算。</td></tr>
@endforelse
</tbody>
</table></div>
@if ($current && ! $submitted)
<div class="actions" style="display:block">
<label class="muted" for="df-other">其他单号有异议(包括「一致」的单):每行一单,格式「单号 原因」</label>
<textarea id="df-other" name="other" rows="3" placeholder="773444000001 这单实际是偏远地区,运费应为 12 元">{{ old('other') }}</textarea>
</div>
<div class="actions">
<button type="submit" class="btn">提交(没勾选、没填写就是确认无异议)</button>
<span class="muted">一致的单 {{ number_format($matchCount) }} 单按你们开的运费结算,明细见 Excel。</span>
</div>
@endif
</form>
</div>
</x-slot>
</x-layouts.signed>

View File

@ -809,6 +809,8 @@ foreach (['courier-payables', 'courier-payables-final'] as $courierBillSection)
Route::post('factories', [$controller, 'saveFactory'])->name('save-factory')->defaults('section', $courierBillSection);
Route::post('factories/generate', [$controller, 'generate'])->name('generate')->defaults('section', $courierBillSection);
Route::post('factories/{factory}/delete', [$controller, 'deleteFactory'])->whereNumber('factory')->name('delete-factory')->defaults('section', $courierBillSection);
Route::post('factories/{factory}/check', [$controller, 'check'])->whereNumber('factory')->name('check')->defaults('section', $courierBillSection);
Route::post('factories/{factory}/push', [$controller, 'push'])->whereNumber('factory')->name('push')->defaults('section', $courierBillSection);
Route::get('export', [$controller, 'export'])->name('export')->defaults('section', $courierBillSection);
});

View File

@ -43,3 +43,15 @@ Route::get('supplier-summary-confirmations/{token}', 'Business\SupplierSummaryCo
Route::post('supplier-summary-confirmations/{token}/confirm', 'Business\SupplierSummaryConfirmationShare@confirm')
->middleware('throttle:10,1')
->name('signed.supplier-summary-confirmations.confirm');
Route::get('dropship-freight/{token}', 'Business\DropshipFreightShare@show')
->middleware('throttle:60,1')
->name('signed.dropship-freight.show');
Route::post('dropship-freight/{token}/submit', 'Business\DropshipFreightShare@submit')
->middleware('throttle:10,1')
->name('signed.dropship-freight.submit');
Route::get('dropship-freight/{token}/excel', 'Business\DropshipFreightShare@excel')
->middleware('throttle:20,1')
->name('signed.dropship-freight.excel');

View File

@ -0,0 +1,163 @@
<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\ShippingLookup;
use App\Support\DropshipFreight\DropshipConfirmation;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
final class DropshipFreightConfirmTest extends FeatureTestCase
{
private const WAREHOUSE = '工厂-山东卿德客代发仓';
private const SECTION = 'courier-payables-final';
public function test_checked_factory_is_pushed_to_its_dingtalk_group_and_the_factory_disputes_single_waybills(): void
{
$this->withoutMiddleware(\Illuminate\Routing\Middleware\ThrottleRequests::class);
Storage::fake('local');
$this->company->makeCurrent(true);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$this->ship('773444000001', '卿德客申通', '2026-10-03 09:00:00', 1, 8); // 一致
$this->ship('773444000002', '卿德客申通', '2026-10-04 09:00:00', 2, 5); // 厂家多开
$this->ship('773444000003', '卿德客申通', '2026-10-05 09:00:00', 3, 6); // 厂家没开:不在确认页
$this->shipping()->table('jst_oms_shipping')->update(['supplier_name' => '临沂卿德客']);
$this->post(route('business.' . self::SECTION . '.dropship-freight.generate'), ['month' => '2026-10'])->assertRedirect();
$factory = CourierBillMatcher::db()->table('dropship_factories')->sole();
$bill = new UploadedFile($this->xlsx([['快递单号', '快递公司', '运费'], ['773444000001', '卿德客申通', 8], ['773444000002', '卿德客申通', 6]]),
'临沂卿德客10月.xlsx', null, null, true);
$this->post(route('business.' . self::SECTION . '.dropship-freight.upload'), ['month' => '2026-10', 'files' => [$bill]])->assertRedirect();
$action = fn (string $name) => route('business.' . self::SECTION . '.dropship-freight.' . $name, ['factory' => $factory->id]);
$overview = route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'month' => '2026-10']);
// 没核对完成不能推送;没配机器人也不能推送
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHasErrors('dropship');
$this->post($action('check'), ['month' => '2026-10', 'checked' => 1])->assertSessionHas('dropship_message');
$this->get($overview)->assertOk()->assertSeeText('已核完,待推送')->assertSeeText('未配钉钉群机器人');
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHasErrors('dropship');
app(SupplierDingTalkNotifier::class)->save('临沂卿德客', 'https://oapi.dingtalk.com/robot/send?access_token=df-test', 'SEC-df', false);
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHas('dropship_message');
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('代发运费对账确认 · 临沂卿德客', $text);
$this->assertStringContainsString('厂家开运费:**2** 单,**¥14.00**', $text);
$this->assertStringContainsString('核对后应结运费:**¥13.00**', $text);
$this->assertStringContainsString('不结或运费有差的单:**1** 单', $text);
preg_match('/\[打开运费确认页\]\(([^)]+)\)/', $text, $m);
$link1 = $m[1];
$this->get($overview)->assertOk()->assertSeeText('已推送,待厂家确认');
$page = $this->get($link1)->assertOk()->assertHeader('X-Robots-Tag', 'noindex, nofollow, noarchive')
->assertSeeText('临沂卿德客 · 2026年10月 代发运费对账确认')->assertSeeText('773444000002')->assertSeeText('一致但运费有差')
->assertDontSeeText('773444000003');
preg_match('/action="([^"]*dropship-freight[^"]*\/submit[^"]*)"/', (string) $page->getContent(), $m);
$submit = html_entity_decode($m[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
// 不在账单里的单号、勾选了没写原因:都退回
$this->post($submit, ['other' => '999 不对'])->assertSessionHasErrors('dispute');
$this->post($submit, ['d' => ['773444000002']])->assertSessionHasErrors('dispute');
$this->post($submit, ['d' => ['773444000002'], 'r' => ['773444000002' => '偏远地区,应为 6 元'],
'other' => "773444000001 这单重量不对"])->assertRedirect()->assertSessionHas('success');
$c = app(DropshipConfirmation::class);
$state = $c->state('2026-10', (int) $factory->id, (int) $this->company->id);
$this->assertSame(DropshipConfirmation::DISPUTED, $state['status']);
$this->assertSame(2, $state['disputed_count']);
$this->assertSame(['773444000001' => '这单重量不对', '773444000002' => '偏远地区,应为 6 元'],
collect($c->disputes('2026-10', (int) $factory->id, (int) $this->company->id))->sortBy('waybill')->pluck('reason', 'waybill')->all());
$receipt = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('代发运费确认回执 · 临沂卿德客', $receipt);
$this->assertStringContainsString('有异议 2 单', $receipt);
$sent = count(Http::recorded());
$this->post($submit, [])->assertSessionHasErrors('dispute');
$this->assertCount($sent, Http::recorded());
$this->assertSame(DropshipConfirmation::DISPUTED, $c->state('2026-10', (int) $factory->id, (int) $this->company->id)['status']);
$this->get($link1)->assertOk()->assertSeeText('提交 2 单异议');
$detail = route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation',
'df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']);
$this->get($detail)->assertOk()->assertSeeText('厂家有异议')->assertSeeText('偏远地区,应为 6 元');
// 重新推送:第 2 次,旧链接作废;厂家这次确认无异议
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHas('dropship_message');
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('第 **2** 次推送', $text);
preg_match('/\[打开运费确认页\]\(([^)]+)\)/', $text, $m);
$this->get($link1)->assertOk()->assertSeeText('不是最新一次推送');
$page = $this->get($m[1])->assertOk();
preg_match('/action="([^"]*dropship-freight[^"]*\/submit[^"]*)"/', (string) $page->getContent(), $s);
$this->post(html_entity_decode($s[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'), [])->assertSessionHas('success', '已确认无异议,财务系统已实时收到。回执已发到钉钉群。');
$this->assertSame(DropshipConfirmation::CONFIRMED, $c->state('2026-10', (int) $factory->id, (int) $this->company->id)['status']);
$this->get($overview)->assertOk()->assertSeeText('厂家已确认')->assertSeeText('重新推送');
$this->post($action('check'), ['month' => '2026-10', 'checked' => 0])->assertSessionHasErrors('dropship');
preg_match('/href="([^"]*dropship-freight[^"]*\/excel[^"]*)"/', (string) $page->getContent(), $x);
$this->get(html_entity_decode($x[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'))->assertOk()
->assertHeader('content-disposition');
// 已确认后仍可重新推送;同一单号的新异议不能覆盖上一版本。
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHas('dropship_message');
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
preg_match('/\[打开运费确认页\]\(([^)]+)\)/', $text, $m);
$page = $this->get($m[1])->assertOk();
preg_match('/action="([^"]*dropship-freight[^"]*\/submit[^"]*)"/', (string) $page->getContent(), $s);
$this->post(html_entity_decode($s[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'), [
'other' => '773444000002 第三版核对原因',
])->assertSessionHas('success');
$this->assertCount(2, $c->disputes('2026-10', (int) $factory->id, (int) $this->company->id, 1));
$this->assertSame('第三版核对原因', $c->disputes('2026-10', (int) $factory->id, (int) $this->company->id, 3)[0]['reason']);
}
public function test_share_tokens_are_limited_to_the_company_and_expiry(): void
{
$links = app(\App\Support\DropshipFreight\DropshipShareLink::class);
$company = (int) $this->company->id;
$url = $links->pageUrl($company, 1, '2026-10', 1);
$token = basename((string) parse_url($url, PHP_URL_PATH));
$this->assertSame(['factory_id' => 1, 'month' => '2026-10', 'version' => 1], $links->resolveToken($token, $company));
$this->assertNull($links->resolveToken($token, $company + 1));
$this->assertNull($links->resolveToken('invalid-token', $company));
$this->withExceptionHandling()->get(str_replace('/' . $token . '?', '/invalid-token?', $url))->assertForbidden();
$this->travel(31)->days();
$this->withExceptionHandling()->get($url)->assertForbidden();
$this->travelBack();
}
private function shipping()
{
return app(ShippingLookup::class)->connection();
}
private function ship(string $waybill, string $express, string $time, int $source, ?float $freight): void
{
$this->shipping()->table('jst_oms_shipping')->insert(['express_no' => $waybill, 'express_name1' => $express, 'warehouse_name' => self::WAREHOUSE,
'ship_time' => $time, 'source_id' => $source]);
$this->shipping()->table('jst_oms_shipping_freight')->insert(['source_id' => $source, 'freight' => $freight, 'status' => 'OK', 'charge_weight' => 1]);
}
/** @param list<list<mixed>> $rows */
private function xlsx(array $rows): string
{
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->setTitle('运费+货款');
foreach ($rows as $r => $row) {
foreach ($row as $c => $value) {
$sheet->setCellValueExplicit([$c + 1, $r + 1], $value, is_string($value)
? \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING : \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC);
}
}
$path = tempnam(sys_get_temp_dir(), 'dfc_') . '.xlsx';
(new Xlsx($book))->save($path);
return $path;
}
}

View File

@ -2079,6 +2079,7 @@ class SupplierReconciliationTest extends FeatureTestCase
public function test_return_summary_uses_quantity_and_amount_without_row_counts(): void
{
$this->travelTo(Carbon::parse('2026-10-01 09:00:00'));
$store = app(SupplierPayableOverrideStore::class);
$companyId = (int) $this->company->id;
$rows = [
@ -2135,6 +2136,7 @@ class SupplierReconciliationTest extends FeatureTestCase
->assertSeeText('¥950.00')
->assertDontSeeText('退货合计')
->assertDontSeeText('扣减合计');
$this->travelBack();
}
public function test_confirm_all_only_applies_to_the_current_return_filter(): void