From c6273cb3f62e7e8ebe3c0a409aa11950653c1b40 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Wed, 2 Dec 2026 19:47:28 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E4=BB=A3=E5=8F=91=E8=BF=90=E8=B4=B9):=20?= =?UTF-8?q?=E6=8E=A8=E9=80=81=E5=8E=82=E5=AE=B6=E7=A1=AE=E8=AE=A4=E5=B9=B6?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E9=80=90=E5=8D=95=E5=BC=82=E8=AE=AE=20(#1667?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Business/DropshipFreightController.php | 76 +++++++- .../Business/DropshipFreightShare.php | 181 ++++++++++++++++++ .../DropshipFreight/DropshipConfirmation.php | 175 +++++++++++++++++ .../DropshipFreight/DropshipShareLink.php | 58 ++++++ .../Services/SupplierDingTalkNotifier.php | 84 ++++++++ .../dropship-freight/_confirm.blade.php | 26 +++ .../dropship-freight/factory.blade.php | 21 ++ .../dropship-freight/overview.blade.php | 8 +- .../dropship-freight/share.blade.php | 132 +++++++++++++ routes/admin.php | 2 + routes/signed.php | 12 ++ .../Business/DropshipFreightConfirmTest.php | 163 ++++++++++++++++ .../Business/SupplierReconciliationTest.php | 2 + 13 files changed, 935 insertions(+), 5 deletions(-) create mode 100644 app/Http/Controllers/Business/DropshipFreightShare.php create mode 100644 app/Support/DropshipFreight/DropshipConfirmation.php create mode 100644 app/Support/DropshipFreight/DropshipShareLink.php create mode 100644 resources/views/business/pages/courier-payables/dropship-freight/_confirm.blade.php create mode 100644 resources/views/business/pages/courier-payables/dropship-freight/share.blade.php create mode 100644 tests/Feature/Business/DropshipFreightConfirmTest.php diff --git a/app/Http/Controllers/Business/DropshipFreightController.php b/app/Http/Controllers/Business/DropshipFreightController.php index b9cfecc1b..f44c1ed3f 100644 --- a/app/Http/Controllers/Business/DropshipFreightController.php +++ b/app/Http/Controllers/Business/DropshipFreightController.php @@ -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']]); diff --git a/app/Http/Controllers/Business/DropshipFreightShare.php b/app/Http/Controllers/Business/DropshipFreightShare.php new file mode 100644 index 000000000..1b1f0b2e9 --- /dev/null +++ b/app/Http/Controllers/Business/DropshipFreightShare.php @@ -0,0 +1,181 @@ +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 . '月'; + } +} diff --git a/app/Support/DropshipFreight/DropshipConfirmation.php b/app/Support/DropshipFreight/DropshipConfirmation.php new file mode 100644 index 000000000..85701f7f7 --- /dev/null +++ b/app/Support/DropshipFreight/DropshipConfirmation.php @@ -0,0 +1,175 @@ + '未核完', 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> 厂家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 $disputes 快递单号 => 原因 + * @return array 提交后的状态 + */ + 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> 这家这个月的异议,最新版本在前 */ + 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); + } +} diff --git a/app/Support/DropshipFreight/DropshipShareLink.php b/app/Support/DropshipFreight/DropshipShareLink.php new file mode 100644 index 000000000..80760c3f7 --- /dev/null +++ b/app/Support/DropshipFreight/DropshipShareLink.php @@ -0,0 +1,58 @@ +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)), '+/', '-_'), '='); + } +} diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index e60658b03..6466e801a 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -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 $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} */ + 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> $records */ private function statementMonths(array $records): string { diff --git a/resources/views/business/pages/courier-payables/dropship-freight/_confirm.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/_confirm.blade.php new file mode 100644 index 000000000..9e9d9ffd8 --- /dev/null +++ b/resources/views/business/pages/courier-payables/dropship-freight/_confirm.blade.php @@ -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 +{{ 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 +@if ($st === DC::OPEN) +
@csrf + +
+@else + @if (in_array($st, [DC::CHECKED, DC::FAILED], true)) +
@csrf + +
+ @endif + @if ($st !== DC::SENDING) +
@csrf + +
+ @endif +@endif +@if (! $robotOk)
未配钉钉群机器人
@endif diff --git a/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php index b7c9d1141..839ac1577 100644 --- a/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php +++ b/resources/views/business/pages/courier-payables/dropship-freight/factory.blade.php @@ -19,6 +19,27 @@
差额(厂家 − 结算){{ $money($s['diff']) }}
+
+
+ 厂家确认: + @include('business.pages.courier-payables.dropship-freight._confirm', ['fid' => $dfFactory->id, 'fname' => $dfFactory->name, 'state' => $dfState, 'robot' => $dfRobot]) + @if (! empty($dfState['pushed_at']))推送:{{ $dfState['pushed_at'] }}({{ $dfState['pushed_by'] ?? '' }})@endif + @if (! empty($dfState['confirmed_at']))厂家提交:{{ $dfState['confirmed_at'] }}@endif +
+ @if ($dfDisputes !== []) +
+ + + + @foreach ($dfDisputes as $d) + + @endforeach + +
推送快递单号厂家异议原因提交时间
第{{ (int) ($d['version'] ?? 0) }}次{{ $d['waybill'] ?? '' }}{{ $d['reason'] ?? '' }}{{ $d['submitted_at'] ?? '' }}
+
+ @endif +
+