diff --git a/app/Console/Commands/ImportPortalFreightBills.php b/app/Console/Commands/ImportPortalFreightBills.php new file mode 100644 index 000000000..0d32e613a --- /dev/null +++ b/app/Console/Commands/ImportPortalFreightBills.php @@ -0,0 +1,18 @@ +processNext(); + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/RefreshAccountMappingCoverage.php b/app/Console/Commands/RefreshAccountMappingCoverage.php new file mode 100644 index 000000000..6a962f539 --- /dev/null +++ b/app/Console/Commands/RefreshAccountMappingCoverage.php @@ -0,0 +1,73 @@ +argument('month')) ?: null; + if ($this->option('pending')) { + $request = $coverage->claimPendingRefresh(); + if ($request === null) { + $this->line('没有待处理的未映射清单刷新请求。'); + + return self::SUCCESS; + } + $month = $request['month']; + $runningPath = $request['path']; + } + + try { + $raw = $coverage->refreshForMonth($month); + if (($raw['status'] ?? '') === 'refreshing') { + $this->warn('已有刷新任务正在执行,本次跳过。'); + if ($runningPath !== null) { + $coverage->requeuePendingRefresh($runningPath); + } + + return self::SUCCESS; + } + + $summary = $coverage->missingForMonth($month); + $this->info(sprintf( + '%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。', + (string) $summary['month'], + (int) $summary['missing_item_count'], + (int) $summary['missing_row_count'], + (int) $summary['source_rows'], + memory_get_peak_usage(true) / 1048576, + )); + if ($runningPath !== null) { + $coverage->finishPendingRefresh($runningPath, true); + } + + return self::SUCCESS; + } catch (Throwable $exception) { + report($exception); + if ($month !== null) { + $coverage->markFailed($month, $exception->getMessage()); + } + if ($runningPath !== null) { + $coverage->finishPendingRefresh($runningPath, false, $exception->getMessage()); + } + $this->error('未映射账单项目刷新失败:' . $exception->getMessage()); + + return self::FAILURE; + } + } +} diff --git a/app/Console/Commands/RunPayablesUnpricedCycle.php b/app/Console/Commands/RunPayablesUnpricedCycle.php new file mode 100644 index 000000000..936dac15d --- /dev/null +++ b/app/Console/Commands/RunPayablesUnpricedCycle.php @@ -0,0 +1,59 @@ +option('period')) ?: $now->copy()->subMonthNoOverflow()->format('Y-m'); + $cutoff = trim((string) $this->option('cutoff')) ?: $now->copy()->startOfMonth()->toDateString(); + $companyId = max(1, (int) $this->option('company')); + $userId = $this->option('user') !== null ? (int) $this->option('user') : null; + + try { + $completed = $store->findLatestRow( + PayablesUnpricedCycleProcessor::RUN_DATASET, + ['summary_month' => $period, 'status' => 'completed'], + $companyId, + ); + if ($completed !== null) { + $this->info("账期 {$period} 已完成,本次自动任务跳过。"); + + return self::SUCCESS; + } + + $result = $processor->processFromPlatformPrices( + $period, + $cutoff, + $companyId, + $userId, + ); + $this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); + + return self::SUCCESS; + } catch (Throwable $exception) { + report($exception); + $this->error('自动定价失败:' . $exception->getMessage()); + + return self::FAILURE; + } + } +} diff --git a/app/Http/Controllers/Business/AccountMappingActions.php b/app/Http/Controllers/Business/AccountMappingActions.php index e30914462..425b713e5 100644 --- a/app/Http/Controllers/Business/AccountMappingActions.php +++ b/app/Http/Controllers/Business/AccountMappingActions.php @@ -9,12 +9,14 @@ use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Validation\ValidationException; use Modules\EcommerceFinance\Services\AccountMappingCoa; +use Modules\EcommerceFinance\Services\AccountMappingCoverage; +use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher; use Modules\EcommerceFinance\Services\AccountMappingStore; use Modules\EcommerceFinance\Services\AccountMappingValidator; use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter; -use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher; use RuntimeException; use Symfony\Component\HttpFoundation\StreamedResponse; +use Throwable; /** * 财务规则 · 科目映射表的维护接口。 @@ -56,6 +58,7 @@ class AccountMappingActions extends Controller private readonly AccountMappingValidator $validator, private readonly AccountMappingCoa $coa, private readonly AccountMappingWorkbookImporter $importer, + private readonly AccountMappingCoverage $coverage, ) { $this->middleware('auth'); $this->middleware('company.identify'); @@ -67,6 +70,32 @@ class AccountMappingActions extends Controller return response()->json($this->payload()); } + /** + * 当前账单里有、但科目映射表里没有同平台同项目的账单项目。 + */ + public function coverage(Request $request): JsonResponse + { + $data = $request->validate([ + 'month' => ['nullable', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'], + 'refresh' => ['nullable', 'boolean'], + ]); + + try { + return response()->json($this->coverage->missingForMonth( + trim((string) ($data['month'] ?? '')) ?: null, + (bool) ($data['refresh'] ?? false), + )); + } catch (\InvalidArgumentException $exception) { + throw ValidationException::withMessages(['month' => $exception->getMessage()]); + } catch (Throwable $exception) { + report($exception); + + return response()->json([ + 'message' => '未映射账单项目暂时无法读取,请稍后重试。', + ], 503); + } + } + public function store(Request $request): JsonResponse { $values = $this->payloadValues($request); diff --git a/app/Http/Controllers/Business/CourierBillController.php b/app/Http/Controllers/Business/CourierBillController.php index fef9c9b34..db697a8dd 100644 --- a/app/Http/Controllers/Business/CourierBillController.php +++ b/app/Http/Controllers/Business/CourierBillController.php @@ -13,7 +13,9 @@ use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; +use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier; use RuntimeException; +use Throwable; /** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */ final class CourierBillController extends Controller @@ -35,7 +37,9 @@ final class CourierBillController extends Controller $db = $this->store->db(); $months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all(); $month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m')); - $data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $this->store->groups()]; + $groups = $this->store->groups(); + $data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $groups, + 'cbRobots' => app(SupplierDingTalkNotifier::class)->configurationMap(array_map(static fn ($g): string => (string) $g->name, $groups))]; $data += match ($view) { 'statement' => $this->statementData($request), 'details' => $this->detailsData($request, $month), @@ -479,6 +483,54 @@ final class CourierBillController extends Controller } } + /** 给对账分组配这家快递的钉钉对账群机器人(群设置 → 机器人 → 自定义,安全设置选「加签」)。 */ + public function saveRobot(Request $request, int $group) + { + $data = $request->validate(['webhook' => ['nullable', 'string', 'max:500'], 'secret' => ['nullable', 'string', 'max:256']]); + $g = collect($this->store->groups())->firstWhere('id', $group); + abort_if($g === null, 404); + app(SupplierDingTalkNotifier::class)->save((string) $g->name, (string) ($data['webhook'] ?? ''), (string) ($data['secret'] ?? ''), false); + + return $this->back($request, ['cb_view' => 'groups'], '已保存「' . $g->name . '」的钉钉对账群机器人。'); + } + + /** 往快递钉钉对账群推这个月的免登录上传链接:传 group 只推这一家,不传就推所有配了机器人的分组。 */ + public function pushUploadLinks(Request $request) + { + $data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'group' => ['nullable', 'integer']]); + $notifier = app(SupplierDingTalkNotifier::class); + $groups = collect($this->store->groups()); + if (! empty($data['group'])) { + $groups = $groups->where('id', (int) $data['group']); + abort_if($groups->isEmpty(), 404); + } + $configured = array_flip($notifier->configuredSuppliers()); + $companyId = (int) (company_id() ?: 1); + $sent = $failed = []; + $skipped = 0; + foreach ($groups as $g) { + if (! isset($configured[$g->name])) { + $skipped++; + continue; + } + try { + $notifier->pushCourierUploadLink((string) $g->name, $data['month'], + app(\App\Support\CourierBills\CourierUploadLink::class)->pageUrl($companyId, (int) $g->id, $data['month'])); + $sent[] = $g->name; + } catch (Throwable $error) { + report($error); + $failed[] = $g->name . '(发送失败,请检查群机器人配置)'; + } + } + if (! empty($data['group']) && $sent === [] && $failed === []) { + throw ValidationException::withMessages(['courier_bills' => '这家还没有配置钉钉对账群机器人,请先在「对账分组」里配置。']); + } + + return $this->back($request, [], '已推送 ' . $data['month'] . ' 上传链接 ' . count($sent) . ' 家' . ($sent !== [] ? ':' . implode('、', array_slice($sent, 0, 30)) : '') + . ($failed !== [] ? ';失败 ' . count($failed) . ' 家:' . implode('、', $failed) : '') + . ($skipped > 0 && empty($data['group']) ? ';' . $skipped . ' 家没配钉钉群机器人,没推' : '') . '。'); + } + private function back(Request $request, array $query, string $message) { $target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => self::section($request), diff --git a/app/Http/Controllers/Business/CourierUploadShare.php b/app/Http/Controllers/Business/CourierUploadShare.php new file mode 100644 index 000000000..ccc7bcf4d --- /dev/null +++ b/app/Http/Controllers/Business/CourierUploadShare.php @@ -0,0 +1,107 @@ +target($request, $token); + $expires = $this->expiresAt($request); + $files = $this->store->db()->table('courier_bill_files')->where('group_id', $t['group']->id)->where('bill_month', $t['month']) + ->orderByDesc('id')->limit(20)->get(); + $pending = array_map(static fn (array $file): object => (object) [ + 'original_name' => $file['name'], 'row_count' => $file['count'], 'amount' => $file['amount'], + 'status' => $file['status'], 'message' => $file['message'], 'created_at' => $file['at'], + ], $this->imports->recent($t['companyId'], (string) $t['group']->name, (int) $t['group']->id, $t['month'])); + $files = $files->concat($pending)->sortByDesc('created_at')->take(20)->values(); + + return response()->view('business.pages.courier-payables.courier-bills.upload-share', [ + 'group' => $t['group'], 'month' => $t['month'], 'monthLabel' => self::monthLabel($t['month']), 'files' => $files, + 'expiresAt' => $expires, 'confirmed' => $t['confirmed'], + 'uploadUrl' => $this->links->signedRoute('signed.courier-bill-upload.upload', $token, $t['companyId'], $expires), + 'templateUrl' => $this->links->signedRoute('signed.courier-bill-upload.template', $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 template(Request $request, string $token): StreamedResponse + { + $t = $this->target($request, $token); + + return $this->template->download($t['group']->name . '_' . $t['month'] . '_账单上传模板.xlsx'); + } + + public function upload(Request $request, string $token): RedirectResponse + { + $t = $this->target($request, $token); + $back = $this->links->signedRoute('signed.courier-bill-upload.show', $token, $t['companyId'], $this->expiresAt($request)); + if ($t['confirmed']) { + throw ValidationException::withMessages(['upload' => '这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。']); + } + $request->validate(['import' => ['required', 'file', 'max:51200']], [], ['import' => '账单文件']); + $file = $request->file('import'); + $extension = strtolower($file->getClientOriginalExtension()); + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + throw ValidationException::withMessages(['upload' => '只支持 xlsx、xls、csv,请用上传模板。']); + } + $this->imports->submit($file, [ + 'name' => (string) $t['group']->name, 'kind' => 'courier', 'month' => $t['month'], + 'target_id' => (int) $t['group']->id, 'company_id' => $t['companyId'], + 'source' => 'courier_upload_link', + 'uploader' => mb_substr($t['group']->name . '(快递上传链接)', 0, 64), + ]); + + return redirect()->to($back)->with('success', '文件已收到,正在等待校验和读入。刷新本页可查看结果,读入成功后会向已配置的钉钉群发送回执。'); + } + + /** @return array{companyId:int,group:object,month:string,confirmed:bool} */ + 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, '链接无效或已过期。'); + $group = collect($this->store->groups())->firstWhere('id', $payload['group_id']); + abort_if($group === null, 404, '链接无效或已过期。'); + $confirmed = $this->store->db()->table('courier_bill_statements')->where('group_id', $group->id) + ->where('bill_month', $payload['month'])->where('status', 'confirmed')->exists(); + + return ['companyId' => $companyId, 'group' => $group, 'month' => $payload['month'], 'confirmed' => $confirmed]; + } + + private function expiresAt(Request $request): CarbonImmutable + { + $expires = (int) $request->query('expires', 0); + + return $expires > 0 ? CarbonImmutable::createFromTimestamp($expires) : CarbonImmutable::now()->addDays(CourierUploadLink::TTL_DAYS); + } + + private static function monthLabel(string $month): string + { + [$y, $m] = explode('-', $month); + + return (int) $y . '年' . (int) $m . '月'; + } +} diff --git a/app/Http/Controllers/Business/DropshipFreightController.php b/app/Http/Controllers/Business/DropshipFreightController.php index b9cfecc1b..0f3260b19 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,112 @@ 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 . ' 次),等厂家在确认页确认。'); + } + + /** + * 通知厂家上传代发运费账单:传 factory 只通知这一家;不传就通知这个月还没上传、且配了钉钉群机器人的全部厂家。 + */ + public function notifyUpload(Request $request) + { + $data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]); + $month = $data['month']; + $notifier = app(SupplierDingTalkNotifier::class); + $factories = collect($this->store->factories()); + $single = ! empty($data['factory']); + if ($single) { + $factories = $factories->where('id', (int) $data['factory'])->values(); + abort_if($factories->isEmpty(), 404); + } + $uploaded = array_flip($this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->whereNotNull('factory_id') + ->distinct()->pluck('factory_id')->map('intval')->all()); + $robots = $notifier->configurationMap($factories->pluck('name')->map('strval')->all()); + $portal = route('business.supplier-portal.home', ['company_id' => self::companyId()]); + $sent = $failed = []; + $noRobot = $done = 0; + foreach ($factories as $f) { + if (! $single && isset($uploaded[(int) $f->id])) { + $done++; + continue; + } + if (! ($robots[$f->name]['configured'] ?? false)) { + $noRobot++; + continue; + } + try { + $notifier->pushDropshipUploadReminder((string) $f->name, $month, $portal); + $sent[] = $f->name; + } catch (Throwable $error) { + report($error); + $failed[] = $f->name; + } + } + if ($single && $noRobot > 0) { + throw ValidationException::withMessages(['dropship' => '这家还没有配置钉钉群机器人(在供应商对账里配置,和货款对账同一个群)。']); + } + + return $this->back($request, [], '已通知 ' . count($sent) . ' 家上传 ' . $month . ' 代发运费账单' . ($sent !== [] ? ':' . implode('、', array_slice($sent, 0, 40)) : '') + . ($done > 0 ? ';' . $done . ' 家已经上传,没再通知' : '') . ($noRobot > 0 ? ';' . $noRobot . ' 家没配钉钉群机器人' : '') + . ($failed !== [] ? ';发送失败:' . implode('、', $failed) : '') . '。'); + } + + /** 厂家开了运费、但不是「一致」的单:不结算或运费有差,确认页上请厂家重点看。 */ + 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/Http/Controllers/Business/PortalFreightBillController.php b/app/Http/Controllers/Business/PortalFreightBillController.php new file mode 100644 index 000000000..6cfd40b99 --- /dev/null +++ b/app/Http/Controllers/Business/PortalFreightBillController.php @@ -0,0 +1,90 @@ + '代发运费账单', 'courier' => '快递账单']; + + public function __construct( + private readonly FreightBillTemplate $template, + private readonly PortalFreightBills $portal, + private readonly SupplierPortalAccess $access, + ) { + $this->middleware('auth'); + $this->middleware('company.identify'); + } + + public function template(): StreamedResponse + { + return $this->template->download('运费账单上传模板.xlsx'); + } + + public function upload(Request $request): RedirectResponse + { + $data = $request->validate([ + 'kind' => ['required', 'in:dropship,courier'], + 'month' => ['required', 'date_format:Y-m'], + 'group' => ['nullable', 'integer'], + 'import' => ['required', 'file', 'max:51200'], + ], [], ['import' => '账单文件', 'month' => '账单月份']); + $file = $request->file('import'); + $extension = strtolower($file->getClientOriginalExtension()); + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + throw ValidationException::withMessages(['freight_bill' => '只支持 xlsx、xls、csv,请用上传模板。']); + } + $name = $this->effectiveName($request); + if ($data['kind'] === 'dropship') { + $target = $this->portal->factory($name); + } else { + $groups = $this->portal->groups($name); + $target = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0)); + } + if ($target === null) { + throw ValidationException::withMessages(['freight_bill' => '当前厂家或快递分组不匹配,请联系财务。']); + } + app(PortalFreightBillImports::class)->submit($file, [ + 'name' => $name, 'kind' => $data['kind'], 'month' => $data['month'], 'target_id' => (int) $target->id, + 'company_id' => (int) company_id(), 'user_id' => (int) $request->user()->id, + 'uploader' => mb_substr((string) ($request->user()->name ?: $request->user()->email) . '(门户)', 0, 64), + ]); + + return back()->with('success', '文件已收到,正在等待校验和读入。处理结果请在下方上传记录查看。'); + } + + /** 厂家/快递账号只能是钉钉组织绑定的那几家;财务账号按页面上选的那家。 */ + private function effectiveName(Request $request): string + { + $user = $request->user(); + $name = trim((string) $request->input('supplier', '')); + if ($user && SupplierPortalAccess::isSupplierUser($user)) { + $names = $this->access->supplierNamesFor($user); + abort_if($names === [], 403, '当前钉钉账号未绑定有效厂家,请联系财务人员。'); + if (count($names) === 1 && $name === '') { + return $names[0]; + } + abort_unless(in_array($name, $names, true), 403, '该厂家不在当前账号的授权范围内。'); + + return $name; + } + if ($name === '') { + throw ValidationException::withMessages(['freight_bill' => '请先选择厂家。']); + } + + return $name; + } +} diff --git a/app/Models/Auth/SupplierPortalSupplier.php b/app/Models/Auth/SupplierPortalSupplier.php index 867b023bf..f1a2fdf42 100644 --- a/app/Models/Auth/SupplierPortalSupplier.php +++ b/app/Models/Auth/SupplierPortalSupplier.php @@ -13,11 +13,13 @@ class SupplierPortalSupplier extends Model 'supplier_name', 'dingtalk_group_id', 'dingtalk_group_name', + 'manually_bound', 'last_verified_at', ]; protected $casts = [ 'dingtalk_group_id' => 'integer', + 'manually_bound' => 'boolean', 'last_verified_at' => 'datetime', ]; diff --git a/app/Services/Auth/SupplierPortalAccess.php b/app/Services/Auth/SupplierPortalAccess.php index 27fdc9522..31d5345de 100644 --- a/app/Services/Auth/SupplierPortalAccess.php +++ b/app/Services/Auth/SupplierPortalAccess.php @@ -8,6 +8,7 @@ use App\Models\Auth\SupplierPortalSupplier; use App\Models\Auth\User; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Facades\DB; +use InvalidArgumentException; use Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory; @@ -129,6 +130,20 @@ class SupplierPortalAccess } $resolved = []; + // 快递:部门名是快递账单对账分组名或承运商名的,也能登录厂家门户上传快递账单(不在供应商主档里) + foreach (\App\Support\CourierBills\PortalFreightBills::courierNames(array_keys($groupsByName)) as $courierName) { + if (isset($matchedSupplierNames[$courierName])) { + continue; + } + usort($groupsByName[$courierName], static fn (array $left, array $right): int => + (int) ($right['depth'] ?? 0) <=> (int) ($left['depth'] ?? 0)); + $resolved[] = [ + 'supplier_name' => $courierName, + 'supplier_code' => '', + 'dingtalk_group_id' => (int) ($groupsByName[$courierName][0]['Id'] ?? 0), + 'dingtalk_group_name' => $courierName, + ]; + } foreach (array_keys($matchedSupplierNames) as $supplierName) { $matchingRows = array_values(array_filter( $supplierRows, @@ -209,24 +224,27 @@ class SupplierPortalAccess ); foreach ($suppliers as $resolvedSupplier) { - SupplierPortalSupplier::query()->updateOrCreate( - [ - 'company_id' => $companyId, - 'user_id' => $user->id, - 'supplier_name' => $resolvedSupplier['supplier_name'], - ], - [ - 'supplier_code' => $resolvedSupplier['supplier_code'] ?? null, - 'dingtalk_group_id' => (int) $resolvedSupplier['dingtalk_group_id'], - 'dingtalk_group_name' => $resolvedSupplier['dingtalk_group_name'], - 'last_verified_at' => now(), - ], - ); + $binding = SupplierPortalSupplier::query()->firstOrNew([ + 'company_id' => $companyId, + 'user_id' => $user->id, + 'supplier_name' => $resolvedSupplier['supplier_name'], + ]); + $binding->fill([ + 'supplier_code' => $resolvedSupplier['supplier_code'] ?? null, + 'dingtalk_group_id' => (int) $resolvedSupplier['dingtalk_group_id'], + 'dingtalk_group_name' => $resolvedSupplier['dingtalk_group_name'], + 'last_verified_at' => now(), + ]); + if (! $binding->exists) { + $binding->manually_bound = false; + } + $binding->save(); } SupplierPortalSupplier::query() ->where('company_id', $companyId) ->where('user_id', $user->id) + ->where('manually_bound', false) ->whereNotIn('supplier_name', $suppliers->pluck('supplier_name')->all()) ->delete(); @@ -238,6 +256,41 @@ class SupplierPortalAccess }); } + public function bindManualSupplier( + User $user, + int $companyId, + string $supplierName, + ): SupplierPortalSupplier { + $supplierName = trim($supplierName); + if ($supplierName === '') { + throw new InvalidArgumentException('供应商名称不能为空。'); + } + + $matches = array_values(array_filter( + $this->suppliers->suppliersByNames([$supplierName]), + static fn (object $supplier): bool => + trim((string) ($supplier->scmname ?? '')) === $supplierName, + )); + if (count($matches) !== 1) { + throw new InvalidArgumentException('供应商主档中必须存在唯一同名厂家。'); + } + + return SupplierPortalSupplier::query()->updateOrCreate( + [ + 'company_id' => $companyId, + 'user_id' => $user->id, + 'supplier_name' => $supplierName, + ], + [ + 'supplier_code' => trim((string) ($matches[0]->scmcode ?? '')), + 'dingtalk_group_id' => 0, + 'dingtalk_group_name' => $supplierName, + 'manually_bound' => true, + 'last_verified_at' => now(), + ], + ); + } + public function mappingFor(User $user): ?SupplierPortalIdentity { if (! self::isSupplierUser($user)) { diff --git a/app/Support/CourierBills/CourierBillStore.php b/app/Support/CourierBills/CourierBillStore.php index b88c9e4e6..2447cc377 100644 --- a/app/Support/CourierBills/CourierBillStore.php +++ b/app/Support/CourierBills/CourierBillStore.php @@ -352,6 +352,16 @@ final class CourierBillStore return $ids; } + /** 门户上传仅写入已授权分组;不从可控文件名或合并账单配置扩展到其他分组。 */ + public function uploadFor(\Illuminate\Http\UploadedFile $file, string $month, int $groupId, string $user): int + { + $groups = $this->groups(); + if (! collect($groups)->contains('id', $groupId)) throw new RuntimeException('快递分组不存在。'); + $id = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month, [$groupId], $groups, $user, true); + foreach ($this->statementsOfFiles([$id]) as $statementId) $this->matcher->match($statementId); + return $id; + } + /** 给待选分组的文件指定分组,读入并对账。 */ public function assign(int $fileId, int $groupId): void { @@ -413,7 +423,7 @@ final class CourierBillStore * @param list $groupIds * @param list $groups */ - private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user): int + private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false): int { $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); $stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension; @@ -422,7 +432,7 @@ final class CourierBillStore $group = $groupIds !== [] ? collect($groups)->firstWhere('id', $groupIds[0]) : self::identify($name, $groups); - $extra = array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)])); + $extra = $portal ? [] : array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)])); $id = (int) $this->db()->table('courier_bill_files')->insertGetId([ 'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(), @@ -435,14 +445,14 @@ final class CourierBillStore return $id; } if ($group !== null) { - $this->ingest($id, $group); + $this->ingest($id, $group, false, $portal); } return $id; } /** 读文件、写账单行到主分组的对账单,再按快递名称1 拆到同一合并账单等可拆入的分组。 */ - private function ingest(int $fileId, object $group, bool $reread = false): void + private function ingest(int $fileId, object $group, bool $reread = false, bool $portal = false): void { $db = $this->db(); $file = $db->table('courier_bill_files')->find($fileId); @@ -471,7 +481,7 @@ final class CourierBillStore $feeCount = 0; $overlap = null; try { - $split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string { + $split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string { if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') { throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。'); } @@ -480,7 +490,9 @@ final class CourierBillStore $db->table('courier_bill_lines')->where('file_id', $fileId)->delete(); } $db->table('courier_bill_surcharges')->where('file_id', $fileId)->delete(); - $overrides = ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header]; + $overrides = $portal + ? ['waybill_header' => '单号', 'amount_header' => '运费', 'weight_header' => '重量'] + : ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header]; foreach ($this->parser->parse($path, $extension, $overrides) as $item) { if ($item['type'] === 'sheet') { $sheets[] = isset($item['skipped']) @@ -550,7 +562,7 @@ final class CourierBillStore $db->table('courier_bill_surcharges')->insert($fees); } - return $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread); + return $portal ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread); }); } catch (Throwable $error) { if ($reread) { diff --git a/app/Support/CourierBills/CourierUploadLink.php b/app/Support/CourierBills/CourierUploadLink.php new file mode 100644 index 000000000..2a0a12df5 --- /dev/null +++ b/app/Support/CourierBills/CourierUploadLink.php @@ -0,0 +1,54 @@ +signedRoute('signed.courier-bill-upload.show', $this->token($companyId, $groupId, $month), $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{group_id:int,month:string}|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['group_id'] ?? 0) <= 0 + || preg_match('/^\d{4}-\d{2}$/', (string) ($payload['month'] ?? '')) !== 1) { + return null; + } + + return ['group_id' => (int) $payload['group_id'], 'month' => (string) $payload['month']]; + } + + private function token(int $companyId, int $groupId, string $month): string + { + $payload = json_encode(['company_id' => $companyId, 'group_id' => $groupId, 'month' => $month], JSON_THROW_ON_ERROR); + + return rtrim(strtr(base64_encode(Crypt::encryptString($payload)), '+/', '-_'), '='); + } +} diff --git a/app/Support/CourierBills/FreightBillTemplate.php b/app/Support/CourierBills/FreightBillTemplate.php new file mode 100644 index 000000000..7c05889f8 --- /dev/null +++ b/app/Support/CourierBills/FreightBillTemplate.php @@ -0,0 +1,121 @@ +streamDownload(static function (): void { + $book = new StreamingWorkbook(); + $book->row('账单', self::HEADERS, true); + $book->writeTo(fopen('php://output', 'wb')); + }, $fileName); + } + + /** + * 校验上传的文件是不是按模板填的,不对就把前几处错误一起报出来。 + * + * @return array{rows:int,waybills:int,amount:float} + */ + public function validate(string $path, string $extension): array + { + try { + $sheets = $this->reader->sheets($path, $extension); + $rows = $sheets->current(); + } catch (Throwable $error) { + throw new RuntimeException('读不了这个文件:' . $error->getMessage()); + } + if ($rows === null) { + throw new RuntimeException('文件是空的。'); + } + if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) { + throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。'); + } + $errors = []; + $header = null; + $count = 0; + $amount = 0.0; + $waybills = []; + foreach ($rows as $index => $row) { + $cells = array_map(static fn ($v): string => trim((string) $v), $row); + if ($header === null) { + $cells[0] = preg_replace('/^\x{FEFF}/u', '', $cells[0] ?? ''); + $header = array_values(self::trimTail($cells)); + if ($header !== self::HEADERS) { + throw new RuntimeException('请用上传模板:第一行必须依次是「' . implode('、', self::HEADERS) . '」,现在是「' + . implode('、', array_filter($header, static fn (string $h): bool => $h !== '')) . '」。'); + } + continue; + } + if (implode('', $cells) === '') { + continue; + } + $line = (int) $index; + $waybill = $cells[0] ?? ''; + if (in_array($waybill, self::TOTAL_WORDS, true)) { + continue; + } + if ($waybill === '') { + $errors[] = '第 ' . $line . ' 行没有单号'; + } elseif (Waybill::normalize($waybill) === null) { + $errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本'; + } + $freight = BillParser::number($cells[3] ?? null); + if ($freight === null || ! is_finite($freight)) { + $errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字'); + } + foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) { + $value = BillParser::number($cells[$col] ?? null); + if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) { + $errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字'; + } + } + if (count($errors) >= self::MAX_ERRORS) { + break; + } + $count++; + if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。'); + $amount += (float) $freight; + $waybills[$waybill] = true; + } + if ($header === null) { + throw new RuntimeException('文件是空的。'); + } + if ($errors !== []) { + throw new RuntimeException('账单有 ' . (count($errors) >= self::MAX_ERRORS ? '多处' : count($errors) . ' 处') . '要改:' + . implode(';', array_slice($errors, 0, self::MAX_ERRORS)) . '。'); + } + if ($count === 0) { + throw new RuntimeException('模板里还没有填账单明细。'); + } + $sheets->next(); + if ($sheets->valid()) throw new RuntimeException('请只保留模板的一张账单工作表,不要附带其他工作表。'); + + return ['rows' => $count, 'waybills' => count($waybills), 'amount' => round($amount, 2)]; + } + + /** @param list $cells */ + private static function trimTail(array $cells): array + { + while ($cells !== [] && end($cells) === '') { + array_pop($cells); + } + + return $cells; + } +} diff --git a/app/Support/CourierBills/PortalFreightBillImports.php b/app/Support/CourierBills/PortalFreightBillImports.php new file mode 100644 index 000000000..67aff9057 --- /dev/null +++ b/app/Support/CourierBills/PortalFreightBillImports.php @@ -0,0 +1,137 @@ +path(self::ROOT . '/tasks/' . $token); + if (! mkdir($dir, 0700, true)) throw new RuntimeException('无法保存账单,请稍后重试。'); + $extension = strtolower($file->getClientOriginalExtension()); + $file->move($dir, 'input.' . $extension); + $task = $details + ['token' => $token, 'extension' => $extension, + 'original_name' => mb_substr($file->getClientOriginalName(), 0, 255), + 'status' => 'queued', 'created_at' => now('Asia/Shanghai')->toDateTimeString(), 'message' => null]; + $this->write($task); + $queue = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending'); + if (! is_dir($queue)) mkdir($queue, 0700, true); + touch($queue . '/' . $token); + } + + public function recent(int $companyId, string $name, ?int $targetId = null, ?string $month = null): array + { + $files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: []; + rsort($files); + $out = []; + foreach ($files as $path) { + $task = json_decode((string) file_get_contents($path), true); + if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue; + if ($targetId !== null && (int) $task['target_id'] !== $targetId) continue; + if ($month !== null && $task['month'] !== $month) continue; + $out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'], + 'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'], + 'message' => $task['message'], 'at' => $task['created_at']]; + if (count($out) >= 10) break; + } + usort($out, static fn ($a, $b) => strcmp($b['at'], $a['at'])); + return array_slice($out, 0, 10); + } + + public function processNext(): bool + { + $pending = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending/*')) ?: []; + sort($pending); + foreach ($pending as $marker) { + $token = basename($marker); + if (! Str::isUuid($token)) continue; + $path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $token . '/task.json'); + $task = json_decode((string) file_get_contents($path), true, 32, JSON_THROW_ON_ERROR); + if ($task['status'] !== 'queued') { + // 上次进程中断后不重导,保留现场供财务核对。 + if ($task['status'] === 'running') $this->write(array_replace($task, ['status' => 'failed', 'message' => '处理曾中断,请联系财务核对后重新上传。'])); + unlink($marker); + return true; + } + $task['status'] = 'running'; + $this->write($task); + try { + $this->process($task); + $task['status'] = 'completed'; + } catch (Throwable $e) { + $task['status'] = 'failed'; + $task['message'] = $e instanceof RuntimeException && ! $e instanceof \Illuminate\Database\QueryException + ? mb_substr($e->getMessage(), 0, 500) : '账单处理失败,请联系财务核对。'; + report($e); + } + $this->write($task); + unlink($marker); + return true; + } + return false; + } + + private function process(array $task): void + { + \App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true); + if (($task['source'] ?? null) === 'courier_upload_link') { + if ($task['kind'] !== 'courier') throw new RuntimeException('上传链接只能上传快递账单。'); + if (app(CourierBillStore::class)->db()->table('courier_bill_statements')->where('group_id', $task['target_id']) + ->where('bill_month', $task['month'])->where('status', 'confirmed')->exists()) { + throw new RuntimeException('这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。'); + } + } else { + $user = User::find($task['user_id']); + if (! $user || ! $user->enabled || ! $user->companies()->where('companies.id', $task['company_id'])->exists()) throw new RuntimeException('上传账号已停用或授权已变化,请联系财务。'); + if (SupplierPortalAccess::isSupplierUser($user) && ! in_array($task['name'], app(SupplierPortalAccess::class)->supplierNamesFor($user), true)) throw new RuntimeException('厂家授权已变化,请联系财务。'); + } + $portal = app(PortalFreightBills::class); + $path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/input.' . $task['extension']); + app(FreightBillTemplate::class)->validate($path, $task['extension']); + if ($task['kind'] === 'dropship') { + $factory = $portal->factory($task['name']); + if ($factory === null || (int) $factory->id !== $task['target_id']) throw new RuntimeException('厂家设置已变化,请联系财务。'); + $store = app(DropshipFreightStore::class); + $id = $store->uploadFor($task['original_name'], $path, $task['month'], $task['target_id'], $task['uploader']); + $row = $store->db()->table('dropship_bill_files')->find($id); + } else { + if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。'); + $store = app(CourierBillStore::class); + $id = $store->uploadFor(new UploadedFile($path, $task['original_name'], null, null, true), $task['month'], $task['target_id'], $task['uploader']); + $row = $store->db()->table('courier_bill_files')->find($id); + } + if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。')); + // 回执采用实际读入金额,避免重复单号等过滤后仍报上传文件总额。 + $summary = ['rows' => (int) ($row->row_count ?? $row->waybill_count), 'waybills' => (int) ($row->waybill_count ?? $row->row_count), 'amount' => (float) $row->amount]; + try { + app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($task['name'], $task['kind'] === 'dropship' ? '代发运费账单' : '快递账单', $task['month'], $task['original_name'], $summary); + } catch (Throwable $e) { report($e); } + } + + private function write(array $task): void + { + $path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/task.json'); + if (file_put_contents($path . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX) === false) throw new RuntimeException('账单状态保存失败。'); + chmod($path . '.tmp', 0600); + rename($path . '.tmp', $path); + $index = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $task['company_id'] . '/' . hash('sha256', $task['name'])); + if (! is_dir($index)) mkdir($index, 0700, true); + $indexPath = $index . '/' . str_replace([' ', ':', '-'], '', $task['created_at']) . '-' . $task['token'] . '.json'; + file_put_contents($indexPath . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX); + chmod($indexPath . '.tmp', 0600); + rename($indexPath . '.tmp', $indexPath); + } +} diff --git a/app/Support/CourierBills/PortalFreightBills.php b/app/Support/CourierBills/PortalFreightBills.php new file mode 100644 index 000000000..55948a3ab --- /dev/null +++ b/app/Support/CourierBills/PortalFreightBills.php @@ -0,0 +1,105 @@ +dropship->factories())->first(static fn (object $f): bool => trim((string) $f->name) === trim($name)); + } catch (Throwable) { + return null; + } + } + + /** @return list 这个承运商名对应的快递对账分组 */ + public function groups(string $name): array + { + $name = trim($name); + try { + return array_values(array_filter($this->courier->groups(), static fn (object $g): bool => $name !== '' + && (trim((string) $g->name) === $name || trim((string) ($g->summary_carrier ?? '')) === $name))); + } catch (Throwable) { + return []; + } + } + + /** 财务代传入口包含尚未上传货款对账单的代发厂家与快递。 */ + public function names(): array + { + try { + return array_values(array_unique([ + ...array_map(static fn ($f) => (string) $f->name, $this->dropship->factories()), + ...array_map(static fn ($g) => (string) $g->name, $this->courier->groups()), + ])); + } catch (Throwable) { + return []; + } + } + + /** + * 钉钉组织里能认作「快递」的部门名:快递对账分组名和小汇总承运商名。 + * + * @param list $names + * @return list + */ + public static function courierNames(array $names): array + { + $names = array_values(array_unique(array_filter(array_map('trim', $names)))); + if ($names === []) { + return []; + } + try { + $db = CourierBillMatcher::db(); + $found = $db->table('courier_bill_groups')->whereIn('name', $names)->pluck('name') + ->merge($db->table('courier_bill_groups')->whereIn('summary_carrier', $names)->pluck('summary_carrier')) + ->map(static fn ($n): string => trim((string) $n))->unique()->values()->all(); + } catch (Throwable) { + return []; + } + + return array_values(array_intersect($names, $found)); + } + + /** @return array{factory:?object,groups:list,files:list>} */ + public function panel(string $name): array + { + $factory = $this->factory($name); + $groups = $this->groups($name); + $files = app(PortalFreightBillImports::class)->recent((int) company_id(), $name); + try { + if ($factory !== null) { + foreach ($this->dropship->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->orderByDesc('id')->limit(10) + ->get() as $f) { + $files[] = ['kind' => '代发运费', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->waybill_count, + 'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at]; + } + } + if ($groups !== []) { + $ids = array_map(static fn (object $g): int => (int) $g->id, $groups); + foreach ($this->courier->db()->table('courier_bill_files')->whereIn('group_id', $ids)->orderByDesc('id')->limit(10)->get() as $f) { + $files[] = ['kind' => '快递账单', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->row_count, + 'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at]; + } + } + } catch (Throwable) { + // 表没建好时只是不显示上传记录 + } + usort($files, static fn (array $a, array $b): int => strcmp($b['at'], $a['at'])); + + return ['factory' => $factory, 'groups' => $groups, 'files' => array_slice($files, 0, 10)]; + } +} 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/DropshipFreightStore.php b/app/Support/DropshipFreight/DropshipFreightStore.php index b741fc575..aa389fe90 100644 --- a/app/Support/DropshipFreight/DropshipFreightStore.php +++ b/app/Support/DropshipFreight/DropshipFreightStore.php @@ -174,6 +174,17 @@ final class DropshipFreightStore return $ids; } + /** 厂家自己上传(厂家门户):已经知道是哪家,不用从文件名认。 */ + public function uploadFor(string $name, string $path, string $month, int $factoryId, string $user): int + { + $factory = collect($this->factories())->firstWhere('id', $factoryId); + if ($factory === null) { + throw new RuntimeException('厂家不存在。'); + } + + return $this->register($name, $path, $month, [$factory], $user, $factory); + } + public function assign(int $fileId, int $factoryId): void { $file = $this->db()->table('dropship_bill_files')->find($fileId); @@ -287,12 +298,12 @@ final class DropshipFreightStore } /** @param list $factories */ - private function register(string $name, string $path, string $month, array $factories, string $user): int + private function register(string $name, string $path, string $month, array $factories, string $user, ?object $known = null): int { $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); $stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension; Storage::disk(self::DISK)->put($stored, fopen($path, 'rb')); - $factory = self::identify($name, $factories); + $factory = $known ?? self::identify($name, $factories); $id = (int) $this->db()->table('dropship_bill_files')->insertGetId([ 'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_factory', 'message' => $factory === null ? '文件名里没认出是哪家厂家,请选择厂家' : null, 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/database/migrations/2026_12_02_200000_add_manual_binding_to_supplier_portal_suppliers.php b/database/migrations/2026_12_02_200000_add_manual_binding_to_supplier_portal_suppliers.php new file mode 100644 index 000000000..056d4a415 --- /dev/null +++ b/database/migrations/2026_12_02_200000_add_manual_binding_to_supplier_portal_suppliers.php @@ -0,0 +1,34 @@ +boolean('manually_bound') + ->default(false) + ->after('dingtalk_group_name'); + }); + } + + public function down(): void + { + if (! Schema::hasTable('supplier_portal_suppliers') + || ! Schema::hasColumn('supplier_portal_suppliers', 'manually_bound')) { + return; + } + + Schema::table('supplier_portal_suppliers', function (Blueprint $table): void { + $table->dropColumn('manually_bound'); + }); + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 153f0f246..6be7d2e0f 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -213,6 +213,8 @@ CRON_TZ=Asia/Shanghai # 供应商货款预估:每天 07:00 日结前一天;每月 1 日 07:10 重跑上月并记录差异。 0 7 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1 10 7 1 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --monthly --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1 +# 之前月未定价-本月定价:每月 2 日使用工作平台价格镜像自动生成上月数据;后两次仅在未完成时重试。 +30 8,12,16 2 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh payables:unpriced-cycle:auto --company=1 --quiet >> /opt/caiwuxitong/runtime/sync-logs/payables-unpriced-cycle.log 2>&1 0 0 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:warm-report-caches --quiet' >/dev/null 2>&1 0 0 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --quiet >/dev/null 2>&1 # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 @@ -261,7 +263,10 @@ CRON_TZ=Asia/Shanghai */15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 +# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。 +* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 +* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 # 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。 28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1 # 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index dfa21c717..70c3dd9ba 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -217,6 +217,8 @@ CRON_TZ=Asia/Shanghai # 供应商货款预估:每天 07:00 日结前一天;每月 1 日 07:10 重跑上月并记录差异。 0 7 * * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1 10 7 1 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh supplier-payable-forecast:sync --monthly --quiet >> /opt/caiwuxitong/runtime/sync-logs/supplier-payable-forecast.log 2>&1 +# 之前月未定价-本月定价:每月 2 日使用工作平台价格镜像自动生成上月数据;后两次仅在未完成时重试。 +30 8,12,16 2 * * root CAIWU_BATCH_LOCK_WAIT=10800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh payables:unpriced-cycle:auto --company=1 --quiet >> /opt/caiwuxitong/runtime/sync-logs/payables-unpriced-cycle.log 2>&1 0 0 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:warm-report-caches --quiet' >/dev/null 2>&1 0 0 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --quiet >/dev/null 2>&1 # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 @@ -265,7 +267,10 @@ CRON_TZ=Asia/Shanghai */15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 +# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。 +* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 +* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 # 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。 28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1 # 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。 diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index b90678361..a58a4d647 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -1,4 +1,5 @@ [ + "portal-freight:import-pending", "planting-reimbursement:auto-confirm", "jushuitan:apply-shipping-corrections", "actual-tax:import", @@ -53,6 +54,7 @@ "planting-details:sync-work-orders", "planting-details:import", "payables:unpriced-cycle", + "payables:unpriced-cycle:auto", "payables:final-import", "product-catalog:import-authoritative-export", "product:monthly-weighted-average:base", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 5f8330899..f13d5a3b5 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -8,10 +8,11 @@ is_import=0 CAIWU_BATCH_CALLER_DIR="$PWD" export CAIWU_BATCH_CALLER_DIR case "${1:-}" in + portal-freight:import-pending) is_import=1 ;; planting-reimbursement:auto-confirm) is_import=1 ;; - jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; + jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;; - jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; + jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;; esac case "${1:-}" in @@ -26,6 +27,12 @@ case "${1:-}" in ;; esac cd "$REMOTE_DIR" +if [ "$1" = 'portal-freight:import-pending' ]; then + storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" + [ -n "$storage_root" ] && [ -d "$storage_root/app/private/portal-freight-bills/pending" ] || exit 0 + pending="$(find "$storage_root/app/private/portal-freight-bills/pending" -maxdepth 1 -type f -print -quit)" + [ -n "$pending" ] || exit 0 +fi if [ "$1" = 'account-bills:exports:run' ]; then storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" [ -n "$storage_root" ] && [ -d "$storage_root" ] || exit 65 @@ -51,6 +58,15 @@ if [ "$1" = 'business-mirror:process-ding-refresh-requests' ]; then pending_request="$(find "$storage_root/app/ding-process-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)" [ -n "$pending_request" ] || exit 0 fi +if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = '--pending' ]; then + storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" + [ -n "$storage_root" ] || exit 0 + pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.pending' -print -quit 2>/dev/null || true)" + if [ -z "$pending_request" ]; then + pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.running' -mmin +15 -print -quit 2>/dev/null || true)" + fi + [ -n "$pending_request" ] || exit 0 +fi if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" [ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0 @@ -99,4 +115,14 @@ if [ "$1" = 'jushuitan:sync-shipping' ]; then sleep "${CAIWU_JST_SYNC_RETRY_WAIT:-300}" done fi +if [ "$1" = 'account-mapping:refresh-coverage' ]; then + container_name="caiwu_account_mapping_coverage_$$" + cleanup_coverage_batch() { + docker rm --force "$container_name" >/dev/null 2>&1 || true + } + trap cleanup_coverage_batch EXIT INT TERM + /usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps \ + --name "$container_name" batch "$@" + exit $? +fi docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@" diff --git a/docs/厂家门户运费账单上传.md b/docs/厂家门户运费账单上传.md new file mode 100644 index 000000000..193564a40 --- /dev/null +++ b/docs/厂家门户运费账单上传.md @@ -0,0 +1,15 @@ +# 厂家门户上传运费账单 + +厂家和快递通过原有钉钉入口进入门户,下载统一模板后提交账单。账号仅能给绑定的厂家或快递上传。财务账号沿用原页面权限,可为选定对象代传。 + +模板第一行依次为:单号、省、重量、运费、送货备注、面单、费率。仅一张可见账单表,单号及运费必填;单号须完整,数字列须为有效数字。支持 XLSX、XLS、CSV,单份最多50MB、100,000行;XLS沿用现有读取器20MB限制。 + +网页只保存文件并显示等待处理。服务器每分钟通过现有独立批容器执行 `portal-freight:import-pending`,每次处理一份。使用共享同步锁,1 CPU、1GiB容器内存、PHP512MiB和一小时上限。无待办时不启动容器。校验失败在上传记录显示原因;进程中断不自动重导,下一次标记失败,财务核对已有记录后再决定重传。 + +后台继续使用现有代发/快递账单读取与对账规则,重复上传、已结算月份等限制仍生效。门户快递上传不会通过文件名或合并分组设置扩大目标范围。成功回执使用实际读入行数和金额;未配置群机器人时不发送。 + +不新增数据库表。任务文件沿用私有共享storage目录,原账单由现有账单存储流程留存。页面仅查当前对象的近期任务及最近10份已读入账单。 + +验证需包含:两类门户上传、未授权对象拒绝、停用账号拒绝、模板错误、多表拒绝、后台隔离、重复导入和原有对账回归。性能基准以线上已有约7,500行账单为参照,使用10,000行合成账单在隔离环境测量,不向真实厂家群发送测试消息。 + +本次隔离SQLite验证:10,000行代发账单,文件222,830字节,读入0.482秒,45次数据库查询,数据库累计44.89ms;7,500行快递账单,文件167878字节,读入1.003秒,7609次查询,数据库累计243.36ms。进程峰值分别约128.7MiB和130MiB;包含测试框架开销。未对生产执行压测。 diff --git a/modules/EcommerceFinance/Services/AccountMappingCoverage.php b/modules/EcommerceFinance/Services/AccountMappingCoverage.php new file mode 100644 index 000000000..6e341e5ef --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingCoverage.php @@ -0,0 +1,603 @@ + ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null], + '淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null], + '拼多多' => ['table' => 'pdd_settlement_bill_rows', 'date' => 'occurred_at', 'periods' => null], + '京东账单' => ['table' => 'jd_daily_bill_rows', 'date' => 'occurred_at', 'periods' => 'jd_daily_bill_periods'], + '京东钱包' => ['table' => 'jd_wallet_bill_rows', 'date' => 'occurred_at', 'periods' => 'jd_wallet_bill_periods'], + '抖音' => ['table' => 'douyin_authoritative_bills', 'date' => 'occurred_at', 'periods' => 'douyin_authoritative_periods'], + '得物' => ['table' => 'dewu_settlement_bill_rows', 'date' => 'bill_date', 'periods' => null], + ]; + + private const PLATFORM_PREFIX = [ + '天猫' => '天猫', + '淘宝' => '淘宝', + '京东' => '京东', + '京喜' => '京喜', + '京喜小店' => '京喜', + '拼多多' => '拼多多', + '抖音' => '抖音', + '头条放心购' => '抖音', + '得物' => '得物', + '阿里巴巴' => '阿里巴巴', + '新佰广1688' => '阿里巴巴', + '淘工厂' => '阿里巴巴', + '唯品会MP' => '唯品会MP', + '唯品会JX' => '唯品会JX', + '支付宝' => '支付宝', + ]; + + /** @var array> */ + private array $generationCache = []; + + public function __construct( + private readonly DatabaseManager $databases, + private readonly AccountMappingStore $store, + ) { + } + + public function defaultMonth(): string + { + $timezone = trim((string) config('app.platform_timezone', '')); + if ($timezone === '') { + $timezone = (string) config('app.timezone', 'UTC'); + } + + try { + return CarbonImmutable::now($timezone)->subMonthNoOverflow()->format('Y-m'); + } catch (Throwable) { + return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m'); + } + } + + /** @return list */ + public function monthOptions(int $months = 18): array + { + $months = min(max($months, 1), 60); + $start = CarbonImmutable::createFromFormat('!Y-m', $this->defaultMonth()); + $options = []; + for ($index = 0; $index < $months; $index++) { + $options[] = $start->subMonthsNoOverflow($index)->format('Y-m'); + } + + return $options; + } + + /** + * @return array{ + * status:string, + * month:string, + * source_rows:int, + * missing_item_count:int, + * missing_row_count:int, + * pending_sources:list, + * items:list>, + * months:list + * } + */ + public function missingForMonth(?string $month = null, bool $refresh = false): array + { + $period = $this->parseMonth($month); + $raw = Cache::get($this->rawCacheKey($period)); + $status = Cache::get($this->statusCacheKey($period), []); + + if (! $refresh && is_array($raw)) { + return $this->missingPayload( + $period, + $raw, + is_array($status) ? (string) ($status['refreshed_at'] ?? '') : '', + ); + } + + if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'refreshing') { + return $this->waitingPayload($period, 'refreshing'); + } + if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'failed') { + return $this->waitingPayload($period, 'failed', (string) ($status['message'] ?? '')); + } + + $requested = $this->requestRefresh($period); + if (($requested['status'] ?? '') === 'failed') { + return $this->waitingPayload($period, 'failed', (string) ($requested['message'] ?? '')); + } + + return $this->waitingPayload($period, 'refreshing'); + } + + /** + * 后台命令使用:重建某月账单项目聚合,并写入长期缓存。 + * + * @return array{status:string,source_rows:int,pending_sources:list,pairs:list>} + */ + public function refreshForMonth(?string $month = null): array + { + $period = $this->parseMonth($month); + $lock = Cache::lock('account-mapping-coverage-refresh:' . $period, 900); + + try { + return $lock->block(20, function () use ($period): array { + Cache::put($this->statusCacheKey($period), [ + 'status' => 'refreshing', + 'started_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + + try { + $raw = $this->buildSourceCoverage($period); + Cache::put($this->rawCacheKey($period), $raw, now()->addHours(self::CACHE_HOURS)); + Cache::put($this->statusCacheKey($period), [ + 'status' => 'ready', + 'refreshed_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + + return $raw; + } catch (Throwable $exception) { + $this->markFailed($period, $exception->getMessage()); + throw $exception; + } + }); + } catch (\Illuminate\Contracts\Cache\LockTimeoutException) { + return [ + 'status' => 'refreshing', + 'source_rows' => 0, + 'pending_sources' => [], + 'pairs' => [], + ]; + } + } + + public function markFailed(string $month, string $message): void + { + $period = $this->parseMonth($month); + Cache::put($this->statusCacheKey($period), [ + 'status' => 'failed', + 'message' => $message, + 'failed_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + } + + /** + * @param array{status:string,source_rows:int,pending_sources:list,pairs:list>} $raw + * @return array + */ + private function missingPayload(string $period, array $raw, string $refreshedAt = ''): array + { + $mapping = $this->coverageMappingKeys($this->store->all()); + $items = []; + $missingRows = 0; + foreach ($raw['pairs'] as $pair) { + if ($this->isMapped($pair, $mapping)) { + continue; + } + + $missingRows += (int) $pair['source_rows']; + $items[] = $pair; + } + + usort($items, static fn (array $left, array $right): int => ( + $right['source_rows'] <=> $left['source_rows'] + ) ?: ( + strcmp((string) $left['platform'], (string) $right['platform']) + ) ?: strcmp((string) $left['item'], (string) $right['item'])); + + return [ + 'status' => $raw['status'], + 'month' => $period, + 'source_rows' => $raw['source_rows'], + 'missing_item_count' => count($items), + 'missing_row_count' => $missingRows, + 'pending_sources' => $raw['pending_sources'], + 'items' => $items, + 'months' => $this->monthOptions(), + 'retry_after' => null, + 'message' => '', + 'refreshed_at' => $refreshedAt, + ]; + } + + /** @return array */ + private function waitingPayload(string $period, string $status, string $message = ''): array + { + return [ + 'status' => $status, + 'month' => $period, + 'source_rows' => 0, + 'missing_item_count' => 0, + 'missing_row_count' => 0, + 'pending_sources' => [], + 'items' => [], + 'months' => $this->monthOptions(), + 'retry_after' => 4, + 'message' => $message, + 'refreshed_at' => null, + ]; + } + + /** @return array{status:string,message:string} */ + private function requestRefresh(string $period): array + { + Cache::put($this->statusCacheKey($period), [ + 'status' => 'refreshing', + 'started_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + + try { + $directory = $this->requestDirectory(); + File::ensureDirectoryExists($directory, 0775, true); + $pending = $directory . DIRECTORY_SEPARATOR . $period . '.pending'; + $temporary = $pending . '.' . getmypid() . '.tmp'; + $payload = json_encode([ + 'month' => $period, + 'requested_at' => now()->toDateTimeString(), + ], JSON_UNESCAPED_UNICODE); + if ($payload === false || File::put($temporary, $payload, true) === false) { + throw new RuntimeException('无法写入未映射清单刷新请求。'); + } + File::move($temporary, $pending, true); + } catch (Throwable $exception) { + $this->markFailed($period, $exception->getMessage()); + report($exception); + + return ['status' => 'failed', 'message' => '刷新请求写入失败,请稍后重试。']; + } + + return ['status' => 'refreshing', 'message' => '']; + } + + /** @return array{month:string,path:string}|null */ + public function claimPendingRefresh(): ?array + { + $directory = $this->requestDirectory(); + if (! File::isDirectory($directory)) { + return null; + } + + $staleBefore = now()->subMinutes(self::REQUEST_STALE_MINUTES)->getTimestamp(); + foreach (File::glob($directory . DIRECTORY_SEPARATOR . '*.running') as $running) { + if (@filemtime($running) > $staleBefore) { + continue; + } + $month = basename((string) $running, '.running'); + if ($this->isValidMonth($month)) { + File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true); + } + } + + $pendingFiles = File::glob($directory . DIRECTORY_SEPARATOR . '*.pending') ?: []; + sort($pendingFiles); + foreach ($pendingFiles as $pending) { + $month = basename((string) $pending, '.pending'); + if (! $this->isValidMonth($month)) { + continue; + } + $running = $directory . DIRECTORY_SEPARATOR . $month . '.running'; + if (File::exists($running) && @filemtime($running) > $staleBefore) { + continue; + } + File::move($pending, $running, true); + + return ['month' => $month, 'path' => $running]; + } + + return null; + } + + public function finishPendingRefresh(string $runningPath, bool $succeeded, string $error = ''): void + { + if (! File::exists($runningPath)) { + return; + } + + if ($succeeded) { + File::delete($runningPath); + + return; + } + + $directory = dirname($runningPath); + $month = basename($runningPath, '.running'); + $failed = $directory . DIRECTORY_SEPARATOR . $month . '.failed'; + File::move($runningPath, $failed, true); + File::put($failed, json_encode([ + 'month' => $month, + 'failed_at' => now()->toDateTimeString(), + 'message' => $error, + ], JSON_UNESCAPED_UNICODE), true); + } + + public function requeuePendingRefresh(string $runningPath): void + { + if (! File::exists($runningPath)) { + return; + } + $month = basename($runningPath, '.running'); + if (! $this->isValidMonth($month)) { + return; + } + File::move( + $runningPath, + dirname($runningPath) . DIRECTORY_SEPARATOR . $month . '.pending', + true, + ); + } + + public function requestDirectory(): string + { + return storage_path('app/account-mapping/coverage-requests'); + } + + /** + * @return array{ + * status:string, + * source_rows:int, + * pending_sources:list, + * pairs:list> + * } + */ + private function buildSourceCoverage(string $month): array + { + $start = CarbonImmutable::createFromFormat('!Y-m', $month)->startOfMonth(); + $end = $start->endOfMonth(); + $connection = $this->databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + $schema = $connection->getSchemaBuilder(); + $pairs = []; + $sourceRows = 0; + $pendingSources = []; + + foreach (self::SOURCES as $label => $source) { + $table = (string) $source['table']; + if (! $schema->hasTable($table)) { + throw new RuntimeException('账单表尚未迁移:' . $table); + } + + $query = $connection->table($table); + $dateColumn = (string) $source['date']; + if ($dateColumn === 'bill_date') { + $query->whereBetween($dateColumn, [$start->toDateString(), $end->toDateString()]); + } else { + $query->whereBetween($dateColumn, [ + $start->toDateString() . ' 00:00:00', + $end->toDateString() . ' 23:59:59', + ]); + } + + if ($source['periods'] !== null) { + $generations = $this->generations( + (string) $source['periods'], + $start->toDateString(), + $end->toDateString(), + ); + if ($generations === []) { + $pendingSources[] = $label; + continue; + } + $query->whereIn('generation', $generations); + } + + $platformExpression = $this->platformSql($connection); + $itemExpression = $this->normalizedItemSql(); + $groups = $query + ->selectRaw($platformExpression . ' AS platform, ' . $itemExpression . ' AS item') + ->selectRaw('COUNT(*) AS source_rows, COUNT(DISTINCT store_name) AS store_count') + ->groupByRaw($platformExpression . ', ' . $itemExpression) + ->cursor(); + + foreach ($groups as $group) { + $rows = (int) $group->source_rows; + $sourceRows += $rows; + $item = trim((string) $group->item); + $displayItem = $item === '' ? '(未填写账单项目)' : $item; + $platform = trim((string) $group->platform); + $key = $platform . "\0" . $displayItem; + + if (! isset($pairs[$key])) { + $pairs[$key] = [ + 'platform' => $platform, + 'platform_label' => $platform === '' ? '未识别平台' : $platform, + 'item' => $displayItem, + 'source_rows' => 0, + 'store_count' => 0, + 'source_labels' => [], + 'raw_items' => [], + ]; + } + + $pairs[$key]['source_rows'] += $rows; + $pairs[$key]['source_labels'][$label] = ($pairs[$key]['source_labels'][$label] ?? 0) + $rows; + $pairs[$key]['raw_items'][$displayItem] = true; + $pairs[$key]['store_count'] = max( + (int) $pairs[$key]['store_count'], + (int) $group->store_count, + ); + } + } + + foreach ($pairs as &$pair) { + $pair['raw_items'] = array_values(array_filter( + array_keys($pair['raw_items']), + static fn (string $item): bool => $item !== '', + )); + $pair['source_labels'] = array_keys($pair['source_labels']); + } + unset($pair); + + return [ + 'status' => $sourceRows > 0 ? 'ready' : 'unavailable', + 'source_rows' => $sourceRows, + 'pending_sources' => $pendingSources, + 'pairs' => array_values($pairs), + ]; + } + + private function rawCacheKey(string $month): string + { + $start = CarbonImmutable::createFromFormat('!Y-m', $month)->startOfMonth(); + $end = $start->endOfMonth(); + $parts = []; + foreach (self::SOURCES as $label => $source) { + if ($source['periods'] === null) { + $parts[] = $label . ':none'; + continue; + } + $parts[] = $label . ':' . implode(',', $this->generations( + (string) $source['periods'], + $start->toDateString(), + $end->toDateString(), + )); + } + + return self::CACHE_PREFIX . $month . ':' . hash('sha256', implode('|', $parts)); + } + + private function statusCacheKey(string $month): string + { + return self::STATUS_PREFIX . $month; + } + + /** @return array */ + private function coverageMappingKeys(array $rules): array + { + $keys = []; + foreach ($rules as $rule) { + $platform = trim((string) ($rule['platform'] ?? '')); + $item = trim((string) ($rule['item'] ?? '')); + if ($platform === '' || $item === '') { + continue; + } + $keys[$platform . '|' . $this->normalizeItem($item)] = true; + } + + return $keys; + } + + private function isMapped(array $pair, array $mapping): bool + { + $platform = (string) ($pair['platform'] ?? ''); + $item = (string) ($pair['item'] ?? ''); + if ($platform === '' || $item === '') { + return false; + } + + return isset($mapping[$platform . '|' . $item]); + } + + /** @return list */ + private function generations(string $periodsTable, string $start, string $end): array + { + $cacheKey = $periodsTable . '|' . $start . '|' . $end; + if (array_key_exists($cacheKey, $this->generationCache)) { + return $this->generationCache[$cacheKey]; + } + + $connection = $this->databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + $schema = $connection->getSchemaBuilder(); + if (! $schema->hasTable($periodsTable)) { + throw new RuntimeException('账期表尚未迁移:' . $periodsTable); + } + + $query = $connection->table($periodsTable)->whereNotNull('active_generation'); + if ($schema->hasColumn($periodsTable, 'period_start') + && $schema->hasColumn($periodsTable, 'period_end')) { + $query->where('period_start', '<=', $end)->where('period_end', '>=', $start); + } + + $generations = $query->distinct()->pluck('active_generation') + ->filter(static fn (mixed $value): bool => is_string($value) && $value !== '') + ->unique() + ->values() + ->all(); + + sort($generations); + + return $this->generationCache[$cacheKey] = $generations; + } + + private function platformSql(\Illuminate\Database\ConnectionInterface $connection): string + { + $cases = []; + foreach (self::PLATFORM_PREFIX as $prefix => $platform) { + $quotedPrefix = $connection->getPdo()->quote($prefix); + $quotedPlatform = $connection->getPdo()->quote($platform); + $cases[] = 'WHEN store_name = ' . $quotedPrefix + . ' OR store_name LIKE ' . $connection->getPdo()->quote($prefix . '-%') + . ' THEN ' . $quotedPlatform; + } + + return 'CASE ' . implode(' ', $cases) . " ELSE '' END"; + } + + private function normalizeItem(string $item): string + { + $item = trim($item); + + return preg_match('/^wx/i', $item) === 1 ? ltrim(substr($item, 2)) : $item; + } + + private function normalizedItemSql(): string + { + return "(CASE WHEN LOWER(COALESCE(bill_item, '')) LIKE 'wx%' " + . "THEN LTRIM(SUBSTR(bill_item, 3)) ELSE COALESCE(bill_item, '') END)"; + } + + private function parseMonth(?string $month): string + { + $month = trim((string) $month); + if ($month === '') { + $month = $this->defaultMonth(); + } + + try { + $parsed = preg_match('/^\d{4}-\d{2}$/', $month) === 1 + ? CarbonImmutable::createFromFormat('!Y-m', $month) + : null; + } catch (Throwable) { + $parsed = null; + } + if ($parsed === null || $parsed->format('Y-m') !== $month) { + throw new \InvalidArgumentException('账单月份格式必须是 YYYY-MM。'); + } + + return $month; + } + + private function isValidMonth(string $month): bool + { + try { + return preg_match('/^\d{4}-\d{2}$/', $month) === 1 + && CarbonImmutable::createFromFormat('!Y-m', $month)->format('Y-m') === $month; + } catch (Throwable) { + return false; + } + } +} diff --git a/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php b/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php index 844f057db..81db6a4f2 100644 --- a/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php +++ b/modules/EcommerceFinance/Services/PayablesUnpricedCycleProcessor.php @@ -3,8 +3,12 @@ namespace Modules\EcommerceFinance\Services; use DateTimeImmutable; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; use Illuminate\Validation\ValidationException; +use Modules\EcommerceFinance\Repositories\SupplierPayableForecastRepository; use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate; +use RuntimeException; use Throwable; /** @@ -41,16 +45,74 @@ class PayablesUnpricedCycleProcessor int $companyId, ?int $userId = null, ): array { - if (preg_match('/^\d{4}-\d{2}$/', $period) !== 1) { - throw ValidationException::withMessages(['period' => '账期必须为 YYYY-MM 格式。']); - } + $this->assertInputs($period, $cutoff); if (! is_file($priceFile)) { throw ValidationException::withMessages(['price_file' => '价格文件不存在。']); } + $priceMap = $this->readPriceMap($priceFile, $cutoff); + + return $this->processWithPriceMap( + $priceMap, + $period, + $cutoff, + $companyId, + $userId, + [ + 'price_file' => basename($priceFile), + 'price_source' => 'file', + ], + ); + } + + /** + * 使用已经同步到共享业务镜像的工作平台定价历史。 + * + * @return array + */ + public function processFromPlatformPrices( + string $period, + string $cutoff, + int $companyId, + ?int $userId = null, + ): array { + $this->assertInputs($period, $cutoff); + + return $this->processWithPriceMap( + $this->readPlatformPriceMap($cutoff), + $period, + $cutoff, + $companyId, + $userId, + [ + 'price_file' => SupplierPayableForecastRepository::PRICE_TABLE, + 'price_source' => 'platform_mirror', + ], + ); + } + + private function assertInputs(string $period, string $cutoff): void + { + if (preg_match('/^\d{4}-\d{2}$/', $period) !== 1) { + throw ValidationException::withMessages(['period' => '账期必须为 YYYY-MM 格式。']); + } if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $cutoff) !== 1) { throw ValidationException::withMessages(['cutoff' => '价格截止日必须为 YYYY-MM-DD 格式。']); } + } + /** + * @param array $priceMap + * @param array{price_file:string,price_source:string} $priceMetadata + * @return array + */ + private function processWithPriceMap( + array $priceMap, + string $period, + string $cutoff, + int $companyId, + ?int $userId, + array $priceMetadata, + ): array { $completedRun = $this->store->findLatestRow(self::RUN_DATASET, [ 'summary_month' => $period, 'status' => 'completed', @@ -61,9 +123,12 @@ class PayablesUnpricedCycleProcessor ]); } - $priceMap = $this->readPriceMap($priceFile, $cutoff); if ($priceMap === []) { - throw ValidationException::withMessages(['price_file' => '价格文件中没有可用定价记录。']); + throw ValidationException::withMessages([ + 'price_file' => $priceMetadata['price_source'] === 'platform_mirror' + ? '工作平台价格镜像中没有可用定价记录。' + : '价格文件中没有可用定价记录。', + ]); } $deliveryHistory = $this->store->listRows(self::DELIVERY_HISTORY_DATASET, $companyId); @@ -91,18 +156,29 @@ class PayablesUnpricedCycleProcessor ); $newDelivery = $this->newDeliveryUnpriced( - $this->store->listRows(self::DELIVERY_RECONCILIATION_DATASET, $companyId), + $this->store->listUnpricedRowsForMonth( + self::DELIVERY_RECONCILIATION_DATASET, + $companyId, + $period, + 'amount', + 'guessAmount', + ), $period, ); $newReturn = $this->newReturnUnpriced( - $this->store->listRows(self::RETURN_RECONCILIATION_DATASET, $companyId), + $this->store->listUnpricedRowsForMonth( + self::RETURN_RECONCILIATION_DATASET, + $companyId, + $period, + 'amount', + 'guess_amount', + ), $period, ); - $summary = [ + $summary = $priceMetadata + [ 'period' => $period, 'cutoff' => $cutoff, - 'price_file' => basename($priceFile), 'price_codes' => count($priceMap), 'matched_delivery_rows' => count($deliveryMatched['rows']), 'matched_return_rows' => count($returnMatched['rows']), @@ -185,6 +261,90 @@ class PayablesUnpricedCycleProcessor return $summary; } + /** @return array */ + private function readPlatformPriceMap(string $cutoff): array + { + $connectionName = (string) config('upstream_mirrors.connection', 'business_mirror'); + $schema = Schema::connection($connectionName); + if (! $schema->hasTable(SupplierPayableForecastRepository::PRICE_TABLE) + || ! $schema->hasTable('business_mirror_table_states')) { + throw new RuntimeException('工作平台价格镜像尚未初始化,无法执行自动定价。'); + } + + $state = DB::connection($connectionName) + ->table('business_mirror_table_states') + ->where('dataset_key', SupplierPayableForecastRepository::PRICE_DATASET) + ->first(); + if ($state === null) { + throw new RuntimeException('工作平台价格镜像尚未初始化,无法执行自动定价。'); + } + + $lastSucceededAt = $this->date($state->last_succeeded_at ?? null); + $cutoffStart = new DateTimeImmutable($cutoff . ' 00:00:00'); + if ((string) ($state->status ?? '') !== 'succeeded' + || ($state->initial_completed_at ?? null) === null + || $lastSucceededAt === null + || $lastSucceededAt < $cutoffStart) { + throw new RuntimeException( + '工作平台价格镜像未同步到 ' . $cutoff . ',为避免使用旧价格,本次自动定价未执行。', + ); + } + + $cutoffAt = new DateTimeImmutable($cutoff . ' 23:59:59'); + $rows = DB::connection($connectionName) + ->table(SupplierPayableForecastRepository::PRICE_TABLE) + ->where('effectStartTime', '<=', $cutoffAt->format('Y-m-d H:i:s')) + ->where(static function ($query) use ($cutoffAt): void { + $query->whereNull('createTime') + ->orWhere('createTime', '<=', $cutoffAt->format('Y-m-d H:i:s')); + }) + ->where(static function ($query) use ($cutoffAt): void { + $query->whereNull('effectEndTime') + ->orWhere('effectEndTime', '') + ->orWhere('effectEndTime', '>=', $cutoffAt->format('Y-m-d H:i:s')); + }) + ->orderBy('effectStartTime') + ->orderBy('createTime') + ->orderBy('Id') + ->get(['Id', 'skucode', 'afterPrice', 'effectStartTime', 'effectEndTime', 'createTime']); + + $latest = []; + foreach ($rows as $row) { + $code = $this->normalizeCode($row->skucode ?? null); + $price = $this->number($row->afterPrice ?? null); + $start = $this->date($row->effectStartTime ?? null); + $completed = $this->date($row->createTime ?? null); + $end = $this->date($row->effectEndTime ?? null); + if ($code === '' || $price === null || $start === null + || $start > $cutoffAt + || ($completed !== null && $completed > $cutoffAt) + || ($end !== null && $end < $cutoffAt)) { + continue; + } + + $sortKey = implode('|', [ + $start->format('Y-m-d H:i:s'), + $completed?->format('Y-m-d H:i:s') ?? '', + str_pad((string) ($row->Id ?? ''), 20, '0', STR_PAD_LEFT), + ]); + if (! isset($latest[$code]) || $sortKey > $latest[$code]['sort']) { + $latest[$code] = [ + 'sort' => $sortKey, + 'price' => $price, + 'start' => $start->format('Y-m-d H:i:s'), + ]; + } + } + + return array_map( + static fn (array $entry): array => [ + 'price' => $entry['price'], + 'start' => $entry['start'], + ], + $latest, + ); + } + /** * @param list> $rows * @param array $priceMap diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index e60658b03..49791461d 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -505,6 +505,65 @@ class SupplierDingTalkNotifier return true; } + /** 代发运费:提醒厂家到厂家对账入口(钉钉登录)上传这个月的代发运费账单。 */ + public function pushDropshipUploadReminder(string $supplier, string $month, string $portalUrl): void + { + [$webhook, $config] = $this->robotFor($supplier, 'dropship_upload_reminder'); + $this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false), + $supplier . ' · 代发运费账单上传提醒 · ' . $this->displayMonth($month), implode("\n", [ + '### 代发运费账单上传提醒 · ' . $supplier, + '- 请上传 **' . $this->displayMonth($month) . '** 代发运费账单', + '- 按上传模板填写(单号、省、重量、运费、送货备注、面单、费率),单号和运费必填', + '', + '#### [打开厂家对账入口](' . $portalUrl . ')', + '- 钉钉登录后,在「上传运费账单」里选「代发运费账单」,可先下载上传模板。', + '- 上传后群里会收到回执;如无法登录或上传,请在群里联系财务。', + ])); + $this->touch($supplier, 1); + } + + /** 快递账单:往这家快递的钉钉对账群推免登录上传链接(机器人在快递账单对账 → 对账分组里配置)。 */ + public function pushCourierUploadLink(string $courier, string $month, string $url): void + { + [$webhook, $config] = $this->robotFor($courier, 'courier_upload_link'); + $this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false), + $courier . ' · 运费账单上传 · ' . $this->displayMonth($month), implode("\n", [ + '### 运费账单上传 · ' . $courier, + '- 账单月份:**' . $this->displayMonth($month) . '**', + '- 请按上传模板填写(单号、省、重量、运费、送货备注、面单、费率),单号和运费必填', + '', + '#### [打开账单上传页](' . $url . ')', + '- 页面上可下载上传模板;同一个月可以分几次上传,上传后群里会收到回执。', + '', + '> 无需登录;链接只能上传本快递本月的账单,有效期 ' . \App\Support\CourierBills\CourierUploadLink::TTL_DAYS . ' 天。', + ])); + $this->touch($courier, 1); + } + + /** @param array{rows:int,waybills:int,amount:float} $summary */ + public function sendFreightBillUploadReceipt(string $name, string $kind, string $month, string $fileName, array $summary): bool + { + $configs = $this->configs(); + $config = is_array($configs[$name] ?? null) ? $configs[$name] : []; + $webhook = trim((string) ($config['webhook'] ?? '')); + if ($webhook === '') { + return false; + } + $this->assertWebhook($webhook); + $fileName = mb_strimwidth(trim((string) preg_replace('/[\r\n`]+/u', ' ', basename($fileName))), 0, 120, '…', 'UTF-8'); + $this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false), + $name . ' · ' . $kind . '上传回执 · ' . $this->displayMonth($month), implode("\n", [ + '### ' . $kind . '上传回执 · ' . $name, + '- 账单月份:**' . $this->displayMonth($month) . '**', + '- 上传文件:' . ($fileName !== '' ? $fileName : '未命名文件'), + '- 账单:**' . $summary['rows'] . '** 行,运费合计 **¥' . number_format((float) $summary['amount'], 2) . '**', + '- 上传时间:' . $this->platformTimestamp(), + '- 数据状态:**已进入财务核对**', + ])); + + return true; + } + public function sendStatementReminder( string $supplier, string $accountingMonth, @@ -568,6 +627,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/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php b/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php index 8fe196b0f..d117ee72b 100644 --- a/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php +++ b/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php @@ -324,6 +324,59 @@ class SupplierPayableOverrideStore ->all(); } + /** + * 只读取指定账期仍未定价的记录,避免月度自动定价把整张对账宽表载入内存。 + * + * @return array> + */ + public function listUnpricedRowsForMonth( + string $dataset, + int $companyId, + string $month, + string $amountField, + string $guessAmountField, + ): array { + if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { + return []; + } + + $connection = $this->connection(); + $query = $connection->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset); + $schema = Schema::connection($connection->getName()); + + if ($connection->getDriverName() === 'mysql' + && $schema->hasColumn('supplier_payable_overrides', 'summary_month_key')) { + $query->where('summary_month_key', $month); + } else { + $monthExpression = $connection->getDriverName() === 'mysql' + ? 'LEFT(REPLACE(REPLACE(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.summary_month")), "/", "-"), ".", "-"), 7)' + : "substr(replace(replace(json_extract(`values`, '$.summary_month'), '/', '-'), '.', '-'), 1, 7)"; + $query->whereRaw("{$monthExpression} = ?", [$month]); + } + + $amountExpression = $connection->getDriverName() === 'mysql' + ? "CAST(COALESCE(NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.{$amountField}'))), ''), '0') AS DECIMAL(20,4))" + : "CAST(COALESCE(NULLIF(TRIM(json_extract(`values`, '$.{$amountField}')), ''), '0') AS REAL)"; + $guessAmountExpression = $connection->getDriverName() === 'mysql' + ? "CAST(COALESCE(NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.{$guessAmountField}'))), ''), '0') AS DECIMAL(20,4))" + : "CAST(COALESCE(NULLIF(TRIM(json_extract(`values`, '$.{$guessAmountField}')), ''), '0') AS REAL)"; + + return $query + ->whereRaw("{$amountExpression} = 0") + ->whereRaw("{$guessAmountExpression} > 0") + ->orderBy('id') + ->get(['record_key', 'values']) + ->map(static function (object $record): array { + $values = json_decode((string) $record->values, true) ?: []; + $values['_action_key'] = (string) $record->record_key; + + return $values; + }) + ->all(); + } + /** * 只读取指定供应商的数据,避免厂家页面把整个共享数据集解码到 PHP。 * diff --git a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php index a089a695b..88a1387bf 100644 --- a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php +++ b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php @@ -331,6 +331,9 @@ class SupplierReconciliationPageData ) as $name) { $suppliers[$name] = true; } + foreach (app(\App\Support\CourierBills\PortalFreightBills::class)->names() as $name) { + $suppliers[$name] = true; + } $supplierNames = array_keys($suppliers); sort($supplierNames); @@ -350,8 +353,17 @@ class SupplierReconciliationPageData ? $this->returnPanelData($selected, $companyId, request()->query()) : ['returnPanel' => null, 'returnWarehouses' => []]; + $freightPanel = $selected !== '' ? app(\App\Support\CourierBills\PortalFreightBills::class)->panel($selected) : null; + // 只是快递(不是供应商、也不是代发厂家)的账号:不显示货款对账单和退货,只上传快递账单 + $courierOnly = $freightPanel !== null && $freightPanel['groups'] !== [] && $freightPanel['factory'] === null + && $statementPage['total'] === 0 && ! $this->isSupplier($selected); + return [ 'view' => 'business.pages.supplier-reconciliation.supplier-data', + 'freightPanel' => $freightPanel, + 'courierOnly' => $courierOnly, + 'freightTemplateUrl' => route('business.supplier-reconciliation.freight-bill.template'), + 'freightUploadUrl' => route('business.supplier-reconciliation.freight-bill.upload'), 'supplierNames' => $supplierNames, 'supplierQuery' => $supplierQuery, 'supplierNotFound' => $supplierNotFound, @@ -374,6 +386,16 @@ class SupplierReconciliationPageData ] + $this->vendorPeriodContext(); } + private function isSupplier(string $name): bool + { + try { + return app(\Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository::class)->suppliersByNames([$name]) !== []; + } catch (\Throwable) { + // 供应商主档镜像暂时读不到:名字已经对上快递分组、又没有货款对账单,按快递处理 + return false; + } + } + /** * 厂家门户只读取当前登录联系人绑定的供应商数据。 * diff --git a/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php b/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php index 8f4d284d2..f4f296eb6 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/groups.blade.php @@ -101,7 +101,7 @@

对账分组({{ count($cbGroups) }})

- + @forelse ($cbGroups as $group) @@ -112,13 +112,36 @@ + @php($robot = $cbRobots[$group->name] ?? []) + @empty - + @endforelse
分组名称快递名称1归到承运商合并账单负责人文件名关键字指定表头
分组名称快递名称1归到承运商合并账单负责人文件名关键字指定表头钉钉对账群
{{ $group->owner }} {{ $group->keywords }} {{ collect([$group->waybill_header, $group->amount_header, $group->weight_header])->filter()->implode(' / ') ?: '自动' }} +
+ + @if ($robot['configured'] ?? false) + 已配 {{ $robot['webhook_hint'] ?? '' }} + @else + 未配 + @endif + +
@csrf + + + +
+
+ @if ($robot['configured'] ?? false) +
@csrf + +
+ @endif +
编辑
@csrf
还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。
还没有对账分组。一份账单对应发货数据里哪些「快递名称1」、小汇总归到快递应付汇总的哪个承运商,都在这里设。
diff --git a/resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php b/resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php new file mode 100644 index 000000000..95e2bab58 --- /dev/null +++ b/resources/views/business/pages/courier-payables/courier-bills/upload-share.blade.php @@ -0,0 +1,72 @@ + + {{ $group->name }} · {{ $monthLabel }} 账单上传 + + + 下载上传模板 + + + + +
+ @if (is_string(session('success')) && session('success') !== '') +
{{ session('success') }}
+ @endif + @if ($errors->any()) + + @endif +
+

{{ $group->name }} · {{ $monthLabel }} 运费账单上传

+
+ 请先点右上角「下载上传模板」,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」; + 单号、运费必填,重量、面单、费率填数字,省、送货备注可空。不按模板的文件会被退回并提示哪里要改。 + 同一个月可以分几次上传,每份最多 50MB、100,000 行。上传后等待校验和读入,刷新本页查看结果。 + 链接有效至 {{ $expiresAt->format('Y-m-d H:i') }},无需登录,只能上传本快递本月的账单。 +
+
+
+ @if ($confirmed) +
这个月的账单财务已确认结算,不能再上传;有问题请在群里联系财务。
+ @else +
+ @csrf + + +
+ @endif +
+
+ 本月已上传({{ count($files) }}) + @if (count($files) > 0) + + + + @foreach ($files as $f) + + + + + @endforeach + +
文件行数运费合计状态上传时间
{{ $f->original_name }}{{ number_format((int) $f->row_count) }}{{ number_format((float) $f->amount, 2) }}{{ match ($f->status) { 'parsed' => '已读入', 'failed' => '未读入:' . $f->message, 'queued' => '等待处理', 'running' => '正在校验和读入', default => '待财务处理' } }}{{ substr((string) $f->created_at, 0, 16) }}
+ @else +

还没有上传。

+ @endif +
+
+
+
diff --git a/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php b/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php index 8ee8c4d29..09730ed58 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/upload.blade.php @@ -1,3 +1,15 @@ +
+

让快递自己上传账单

+
+ @csrf + + + 每家快递的钉钉对账群配一个群机器人(在「对账分组」里配,群设置 → 机器人 → 自定义,安全设置选「加签」),这里一键往这些群推本月的免登录上传链接。 + 快递点开链接、下载模板(单号、省、重量、运费、送货备注、面单、费率)填好上传,后台校验读入后进入对账;链接只能传那一家那个月,30 天有效。已有 {{ collect($cbRobots ?? [])->where('configured', true)->count() }} 家配了机器人。 +
+
+

上传账单 · {{ $month }}

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/factories.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/factories.blade.php index 3fac89da3..2d0c28581 100644 --- a/resources/views/business/pages/courier-payables/dropship-freight/factories.blade.php +++ b/resources/views/business/pages/courier-payables/dropship-freight/factories.blade.php @@ -34,6 +34,10 @@ @php $editData = json_encode(['id' => $f->id, 'name' => $f->name, 'warehouse' => $f->warehouse, 'keywords' => $f->keywords, 'note' => $f->note], JSON_UNESCAPED_UNICODE); @endphp +
@csrf + +
@csrf
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 +
+