diff --git a/app/Console/Commands/RemindDropshipFreightUpload.php b/app/Console/Commands/RemindDropshipFreightUpload.php new file mode 100644 index 000000000..78c45c252 --- /dev/null +++ b/app/Console/Commands/RemindDropshipFreightUpload.php @@ -0,0 +1,74 @@ +option('date')); + if ($date !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) { + $this->error('日期格式无效,应为 Y-m-d。'); + + return self::FAILURE; + } + $today = $date !== '' ? CarbonImmutable::createFromFormat('Y-m-d', $date, DropshipUploadReminder::TIMEZONE)->startOfDay() : DropshipUploadReminder::today(); + $force = (bool) $this->option('force'); + if ($today->day > DropshipUploadReminder::DEADLINE_DAY && ! $force) { + $this->line($today->format('Y-m-d') . ':只在每月 1–' . DropshipUploadReminder::DEADLINE_DAY . ' 日提醒。'); + + return self::SUCCESS; + } + $month = DropshipUploadReminder::billMonth($today); + $failed = false; + foreach (Company::enabled()->orderBy('id')->get() as $company) { + $company->makeCurrent(); + $label = "#{$company->id} {$company->name} {$month}"; + if (! DropshipUploadReminder::enabled() && ! $force) { + $this->line($label . ':自动提醒已关闭'); + continue; + } + $portal = route('business.supplier-portal.home', ['company_id' => $company->id]); + if ($this->option('dry-run')) { + $plan = $reminder->targets($month); + $this->line($label . ':会提醒 ' . count($plan['targets']) . ' 家:' . implode('、', array_map(static fn ($f): string => (string) $f->name, $plan['targets'])) + . ';已上传 ' . count($plan['done']) . ' 家;没有代发发货 ' . count($plan['no_shipment']) . ' 家;没配机器人 ' . count($plan['no_robot']) . ' 家' + . ($plan['no_robot'] !== [] ? ':' . implode('、', $plan['no_robot']) : '') . ';入口 ' . $portal); + continue; + } + $lock = sprintf('dropship-upload-reminder:%d:%s:%s', $company->id, $month, $today->format('Y-m-d')); + if (! $force && ! Cache::add($lock, true, now()->addDays(2))) { + $this->line($label . ':今天已经提醒过'); + continue; + } + try { + $result = $reminder->remind($month, $portal, null, $today); + $this->info($label . ':' . DropshipFreightController::reminderSummary($month, $result)); + $failed = $failed || $result['failed'] !== []; + } catch (Throwable $error) { + Cache::forget($lock); + report($error); + $this->error($label . ':自动提醒失败:' . $error->getMessage()); + $failed = true; + } + } + + return $failed ? self::FAILURE : self::SUCCESS; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 92ff26e36..c12c49db4 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -103,6 +103,14 @@ class Kernel extends ConsoleKernel ->appendOutputTo(storage_path('logs/supplier-negative-alert-dingtalk.log')) ->runInBackground(); + // 代发运费:每月 1–14 日 10:00 提醒还没上传上月代发运费账单的厂家(14 日截止,逾期本月货款和运费不予结算)。 + $schedule->command('dropship-freight:remind-upload') + ->cron('0 10 1-14 * *') + ->timezone('Asia/Shanghai') + ->withoutOverlapping(60) + ->appendOutputTo(storage_path('logs/dropship-upload-reminder.log')) + ->runInBackground(); + // 进销存月报导入后检查仓库简称映射;每日补偿检查避免导入与提醒步骤间断。 $schedule->command('inventory:sync-warehouse-mapping-alert') ->dailyAt('10:15') diff --git a/app/Http/Controllers/Business/CourierBillController.php b/app/Http/Controllers/Business/CourierBillController.php index db697a8dd..2733f0bd7 100644 --- a/app/Http/Controllers/Business/CourierBillController.php +++ b/app/Http/Controllers/Business/CourierBillController.php @@ -37,8 +37,10 @@ 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')); + // 推送上传链接默认推上个月(新月份还没有对账单时,$month 会停在最近有对账单的月份) + $pushMonth = self::monthParam($request->query('month')) ?? max($month, now()->subMonthNoOverflow()->format('Y-m')); $groups = $this->store->groups(); - $data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $groups, + $data += ['cbMonth' => $month, 'cbPushMonth' => $pushMonth, '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), @@ -199,10 +201,11 @@ final class CourierBillController extends Controller $search = Waybill::normalize((string) $request->query('waybill')); return [ - 'cbLedgerStats' => $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id') - ->groupBy('g.name', 'l.settle_month')->selectRaw('g.name as group_name, l.settle_month, COUNT(*) as n, SUM(l.amount) as amount, SUM(CASE WHEN l.statement_id IS NULL THEN 1 ELSE 0 END) as imported') + 'cbLedgerStats' => $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id') + ->groupBy('g.name', 'l.settle_month')->selectRaw(sprintf('%s as group_name, %s as settle_month, COUNT(*) as n, SUM(%s) as amount, SUM(CASE WHEN %s IS NULL THEN 1 ELSE 0 END) as imported', + ...array_map(static fn (string $c): string => $db->getQueryGrammar()->wrap($c), ['g.name', 'l.settle_month', 'l.amount', 'l.statement_id']))) ->orderByDesc('l.settle_month')->orderBy('g.name')->limit(500)->get(), - 'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id') + 'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'l.group_id') ->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']), 'cbSearch' => $search, ]; @@ -428,7 +431,7 @@ final class CourierBillController extends Controller $result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension)); $message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号'; if ($result['rejected'] > 0) { - $message .= ',' . $result['rejected'] . ' 行未导入' . ($result['unknown_groups'] ? '(分组不存在:' . implode('、', array_slice($result['unknown_groups'], 0, 10)) . ')' : ''); + $message .= ',' . $result['rejected'] . ' 行单号或结算月份认不出,未导入'; } return $this->back($request, ['cb_view' => 'ledger'], $message . '。'); diff --git a/app/Http/Controllers/Business/DropshipFreightController.php b/app/Http/Controllers/Business/DropshipFreightController.php index 0f3260b19..17c44721e 100644 --- a/app/Http/Controllers/Business/DropshipFreightController.php +++ b/app/Http/Controllers/Business/DropshipFreightController.php @@ -6,9 +6,11 @@ use App\Support\CourierBills\Category; use App\Support\CourierBills\StreamingWorkbook; use App\Support\DropshipFreight\DropshipConfirmation; use App\Support\DropshipFreight\DropshipExporter; +use App\Support\DropshipFreight\DropshipFees; use App\Support\DropshipFreight\DropshipFreightStore; use App\Support\DropshipFreight\DropshipReconciler; use App\Support\DropshipFreight\DropshipShareLink; +use App\Support\DropshipFreight\DropshipUploadReminder; use Illuminate\Database\QueryException; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; @@ -70,7 +72,14 @@ final class DropshipFreightController extends Controller $notifier = app(SupplierDingTalkNotifier::class); + $fees = app(DropshipFees::class)->rows($month, array_column($rows, 'settle', 'factory_id'), self::companyId()); + $feeTotals = []; + foreach ([...array_keys(DropshipFees::COLUMNS), 'total'] as $key) { + $feeTotals[$key] = round(array_sum(array_map(static fn (array $f): float => $key === 'total' ? $f['total'] : $f['values'][$key], $fees)), 2); + } + return ['dfRows' => $rows, 'dfWithout' => $without, 'dfStates' => $this->confirmations->states($month, self::companyId()), + 'dfFees' => $fees, 'dfFeeTotals' => $feeTotals, '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')), @@ -107,7 +116,8 @@ final class DropshipFreightController extends Controller $files = $this->store->db()->table('dropship_bill_files as f')->leftJoin('dropship_factories as d', 'd.id', '=', 'f.factory_id') ->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'd.name as factory_name']); - return ['dfFiles' => $files]; + return ['dfFiles' => $files, 'dfAutoRemind' => DropshipUploadReminder::enabled(), + 'dfDeadline' => DropshipUploadReminder::deadline($month)->format('n月j日')]; } public function upload(Request $request) @@ -205,6 +215,21 @@ final class DropshipFreightController extends Controller : '已撤销「' . $f->name . '」的核对完成。'); } + /** 各厂家汇总:改这家这个月的快递记账、补运费、退回费等(空着 = 用厂家附加费表自动带入的值)和备注。 */ + public function saveFees(Request $request, int $factory) + { + $rules = ['month' => ['required', 'date_format:Y-m'], 'note' => ['nullable', 'string', 'max:255']]; + foreach (DropshipFees::EDITABLE as $key) { + $rules['fees.' . $key] = ['nullable', 'numeric', 'between:-99999999,99999999']; + } + $data = $request->validate($rules, [], array_combine(array_map(static fn (string $k): string => 'fees.' . $k, DropshipFees::EDITABLE), + array_map(static fn (string $k): string => DropshipFees::COLUMNS[$k], DropshipFees::EDITABLE))); + $f = $this->factory($factory); + app(DropshipFees::class)->save($data['month'], (int) $f->id, (array) ($data['fees'] ?? []), (string) ($data['note'] ?? ''), self::companyId(), user()?->id); + + return $this->back($request, [], '已保存「' . $f->name . '」' . $data['month'] . ' 的费用和备注。'); + } + /** 推送到厂家钉钉群(和供应商货款对账同一个群机器人),附免登录确认页链接;重新推送版本号加一,旧链接作废。 */ public function push(Request $request, int $factory) { @@ -240,43 +265,39 @@ final class DropshipFreightController extends Controller { $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); + abort_if(collect($this->store->factories())->where('id', (int) $data['factory'])->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) { + $result = app(DropshipUploadReminder::class)->remind($month, route('business.supplier-portal.home', ['company_id' => self::companyId()]), + $single ? (int) $data['factory'] : null); + if ($single && $result['no_robot'] !== []) { 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) : '') . '。'); + return $this->back($request, [], self::reminderSummary($month, $result) . '。'); + } + + /** 自动提醒开关。 */ + public function autoRemind(Request $request) + { + $on = $request->boolean('enabled'); + DropshipUploadReminder::setEnabled($on); + + return $this->back($request, [], $on + ? '已开启自动提醒:每月 1–' . DropshipUploadReminder::DEADLINE_DAY . ' 日 ' . DropshipUploadReminder::SEND_TIME . ' 提醒还没上传上月代发运费账单的厂家。' + : '已关闭自动提醒。'); + } + + /** @param array{sent:list,failed:list,done:list,no_shipment:list,no_robot:list,deadline:mixed} $r */ + public static function reminderSummary(string $month, array $r): string + { + return '已通知 ' . count($r['sent']) . ' 家上传 ' . $month . ' 代发运费账单' . ($r['sent'] !== [] ? ':' . implode('、', array_slice($r['sent'], 0, 40)) : '') + . ($r['deadline'] !== null ? '(写明 ' . $r['deadline']->format('n月j日') . ' 截止,逾期本月货款和运费不予结算)' : '') + . ($r['done'] !== [] ? ';' . count($r['done']) . ' 家已经上传,没再通知' : '') + . ($r['no_shipment'] !== [] ? ';' . count($r['no_shipment']) . ' 家这个月没有代发发货,没通知' : '') + . ($r['no_robot'] !== [] ? ';' . count($r['no_robot']) . ' 家没配钉钉群机器人:' . implode('、', array_slice($r['no_robot'], 0, 40)) : '') + . ($r['failed'] !== [] ? ';发送失败:' . implode('、', $r['failed']) : ''); } /** 厂家开了运费、但不是「一致」的单:不结算或运费有差,确认页上请厂家重点看。 */ @@ -339,8 +360,8 @@ final class DropshipFreightController extends Controller return response()->streamDownload(function () use ($factories, $month, $own): void { $book = new StreamingWorkbook(); - $book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '结算运费(按我方核算)', - '差额(厂家−结算)', ...array_values(DropshipReconciler::LABELS)], true); + $book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '最终结算运费', + '差额(厂家−最终结算)', ...array_values(DropshipReconciler::LABELS)], true); $details = []; foreach ($factories as $factory) { $result = $this->reconciler->factoryMonth($factory, $month, $own); @@ -351,10 +372,10 @@ final class DropshipFreightController extends Controller } foreach ($details as [$factory, $rows]) { $sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28); - $book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true); + $book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '最终结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true); foreach ($rows as $r) { $book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settle'], - $r['diff'], $r['label'], $r['note'], $r['formula']]); + $r['final'] ?? $r['settle'], $r['diff'], $r['label'], $r['note'], $r['formula']]); } } $book->writeTo(fopen('php://output', 'wb')); diff --git a/app/Http/Controllers/Business/DropshipFreightShare.php b/app/Http/Controllers/Business/DropshipFreightShare.php index 1b1f0b2e9..a8a613cce 100644 --- a/app/Http/Controllers/Business/DropshipFreightShare.php +++ b/app/Http/Controllers/Business/DropshipFreightShare.php @@ -141,8 +141,8 @@ final class DropshipFreightShare extends Controller } $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->row('明细', [$r['waybill'], $r['ship_time'], $r['express'], $r['bill'], $r['final'] ?? $r['settle'] ?? 0, + round((float) $r['bill'] - (float) ($r['final'] ?? $r['settle'] ?? 0), 2), $r['label'], $r['note']]); } $book->writeTo(fopen('php://output', 'wb')); }, $name); diff --git a/app/Support/CourierBills/CourierBillMatcher.php b/app/Support/CourierBills/CourierBillMatcher.php index 8c828693b..716248b76 100644 --- a/app/Support/CourierBills/CourierBillMatcher.php +++ b/app/Support/CourierBills/CourierBillMatcher.php @@ -44,9 +44,10 @@ final class CourierBillMatcher $settled = []; foreach (array_chunk($waybills, 500) as $chunk) { - foreach ($db->table('courier_bill_ledger')->where('group_id', $statement->group_id)->whereIn('waybill_no', $chunk) - ->where('settle_month', '<>', $month)->get(['waybill_no', 'settle_month']) as $row) { - $settled[strtoupper($row->waybill_no)] = $row->settle_month; + // 查重按单号:别的月份结算过(不论哪个分组、系统确认还是历史导入)就算重复,取最早那个月 + foreach ($db->table('courier_bill_ledger')->whereIn('waybill_no', $chunk) + ->where('settle_month', '<>', $month)->orderBy('settle_month')->get(['waybill_no', 'settle_month']) as $row) { + $settled[strtoupper($row->waybill_no)] ??= $row->settle_month; } } $unshipped = $this->unshipped->unshippedSources($waybills); diff --git a/app/Support/CourierBills/CourierBillStore.php b/app/Support/CourierBills/CourierBillStore.php index 2447cc377..9a174037a 100644 --- a/app/Support/CourierBills/CourierBillStore.php +++ b/app/Support/CourierBills/CourierBillStore.php @@ -1097,19 +1097,21 @@ final class CourierBillStore }); } + /** 历史导入的已结算单号不分对账分组,group_id 记 0;查重按单号,不看分组。 */ + public const LEDGER_NO_GROUP = 0; + /** - * 导入历史已结算单号:表头含 分组、单号、结算月份,可选 金额。 + * 导入系统上线前已结算的单号:只要「单号」「结算月份」两列(可带「金额」)。导入后这些单号再出现在任何一家的账单里, + * 只要结算月份不是本月,就归「重复」。 * - * @return array{rows:int,inserted:int,unknown_groups:list,rejected:int} + * @return array{rows:int,inserted:int,rejected:int} */ public function importLedger(string $path, string $extension): array { - $groups = collect($this->groups())->keyBy('name'); $reader = new BillWorkbookReader(); $rows = 0; $inserted = 0; $rejected = 0; - $unknown = []; $buffer = []; $flush = function () use (&$buffer, &$inserted): void { if ($buffer !== []) { @@ -1124,32 +1126,26 @@ final class CourierBillStore $header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row); $find = static fn (array $names): ?int => collect($names)->map(static fn ($n) => array_search($n, $header, true)) ->first(static fn ($i) => $i !== false); - $columns = ['group' => $find(['分组', '对账分组']), 'waybill' => $find(['单号', '快递单号', '运单号', '运单编号']), + $columns = ['waybill' => $find(['单号', '快递单号', '运单号', '运单编号']), 'month' => $find(['结算月份', '月份']), 'amount' => $find(['金额', '运费', '结算金额'])]; - if ($columns['group'] === null || $columns['waybill'] === null || $columns['month'] === null) { - throw new RuntimeException('表头须含「分组」「单号」「结算月份」三列(金额可选)。'); + if ($columns['waybill'] === null || $columns['month'] === null) { + throw new RuntimeException('表头须含「单号」「结算月份」两列(金额可选)。'); } continue; } - $groupName = trim((string) ($row[$columns['group']] ?? '')); $waybillRaw = trim((string) ($row[$columns['waybill']] ?? '')); - if ($groupName === '' && $waybillRaw === '') { + $monthRaw = trim((string) ($row[$columns['month']] ?? '')); + if ($waybillRaw === '' && $monthRaw === '') { continue; } $rows++; - $group = $groups->get($groupName); - if ($group === null) { - $unknown[$groupName] = true; - $rejected++; - continue; - } $waybill = Waybill::normalize($waybillRaw); - $month = self::month((string) ($row[$columns['month']] ?? '')); + $month = self::month($monthRaw); if ($waybill === null || $month === null) { $rejected++; continue; } - $buffer[] = ['group_id' => $group->id, 'waybill_no' => $waybill, 'settle_month' => $month, + $buffer[] = ['group_id' => self::LEDGER_NO_GROUP, 'waybill_no' => $waybill, 'settle_month' => $month, 'amount' => $columns['amount'] === null ? null : BillParser::number($row[$columns['amount']] ?? null), 'statement_id' => null, 'created_at' => now()]; if (count($buffer) >= 500) { @@ -1160,7 +1156,7 @@ final class CourierBillStore } $flush(); - return ['rows' => $rows, 'inserted' => $inserted, 'unknown_groups' => array_keys($unknown), 'rejected' => $rejected]; + return ['rows' => $rows, 'inserted' => $inserted, 'rejected' => $rejected]; } private function assertOpen(int $statementId): void diff --git a/app/Support/CourierBills/FreightBillTemplate.php b/app/Support/CourierBills/FreightBillTemplate.php index 2dd5f413a..0b5a15c7d 100644 --- a/app/Support/CourierBills/FreightBillTemplate.php +++ b/app/Support/CourierBills/FreightBillTemplate.php @@ -20,7 +20,7 @@ final class FreightBillTemplate public const SURCHARGE_SHEET = '附加费'; public const SURCHARGE_HEADERS = ['快递单号', '附加费金额', '附加费类型']; /** 写在附加费表表头右边(空一列)的说明,校验时不算表头。 */ - public const SURCHARGE_NOTE = '注:无附加费无需填写,这张表空着即可'; + public const SURCHARGE_NOTE = '注:无附加费无需填写,这张表空着即可;附加费类型填:补运费、退回费、拦截费、改地址费、翻箱费、超长费'; private const MAX_ERRORS = 10; private const TOTAL_WORDS = ['合计', '总计', '小计']; @@ -71,6 +71,47 @@ final class FreightBillTemplate return $result + $surcharge; } + /** + * 「附加费」表按附加费类型汇总金额(表头不对、没有这张表都返回空)。代发汇总按类型自动带入各费用列。 + * + * @return array 附加费类型 => 金额 + */ + public function surchargesByType(string $path, string $extension): array + { + $result = []; + try { + foreach ($this->reader->sheets($path, $extension) as $name => $rows) { + if (trim((string) $name) !== self::SURCHARGE_SHEET) { + continue; + } + $header = null; + foreach ($rows as $row) { + $cells = array_slice(array_map(static fn ($v): string => trim((string) $v), $row), 0, count(self::SURCHARGE_HEADERS)); + if (implode('', $cells) === '') { + continue; + } + if ($header === null) { + $header = array_values(self::trimTail($cells)); + if ($header !== self::SURCHARGE_HEADERS) { + return []; + } + continue; + } + $fee = BillParser::number($cells[1] ?? null); + $type = $cells[2] ?? ''; + if ($fee === null || $type === '' || ($cells[0] ?? '') === '' || in_array($cells[0], self::TOTAL_WORDS, true)) { + continue; + } + $result[$type] = round(($result[$type] ?? 0) + $fee, 2); + } + } + } catch (Throwable) { + return []; + } + + return $result; + } + /** @return array{rows:int,waybills:int,amount:float} */ private function validateBill(?iterable $rows): array { diff --git a/app/Support/DropshipFreight/DropshipExporter.php b/app/Support/DropshipFreight/DropshipExporter.php index 5beb43cf2..8fbbd5239 100644 --- a/app/Support/DropshipFreight/DropshipExporter.php +++ b/app/Support/DropshipFreight/DropshipExporter.php @@ -77,7 +77,7 @@ final class DropshipExporter [$originals, $sources, $original] = $this->writeOriginal($book, $files, $baseFileId, $index, $baseCount); $lookup = $index->prepare('SELECT raw FROM originals WHERE file = ? AND sheet = ? AND row = ?'); $rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(StatementExporter::FRONT, static fn ($f) => $f[0] !== '_'))); - $tail = ['厂家运费(这一单合计)', '结算运费', '分类', '说明']; + $tail = ['厂家运费(这一单合计)', '结算运费', '最终结算运费', '分类', '说明']; // 对账类:本月一致 / 运费有差 / 系统未核算,和前月补提供、跨月订单(按月份各一张) $sheets = ['对账' => static fn (array $r): bool => in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)]; @@ -103,7 +103,7 @@ final class DropshipExporter foreach (array_keys($rest) as $field) { $cells[] = self::value($field, $ship[$field] ?? null); } - $book->row($name, [...$cells, $r['bill'], $r['settle'], $r['label'], $r['note']]); + $book->row($name, [...$cells, $r['bill'], $r['settle'], $r['final'] ?? $r['settle'], $r['label'], $r['note']]); } } } @@ -150,8 +150,9 @@ final class DropshipExporter if ($r['bill'] !== null) { $billTotal = (float) $billTotal + (float) $r['bill']; } - if ($r['settle'] !== null) { - $settleTotal = (float) $settleTotal + (float) $r['settle']; + $final = $r['final'] ?? $r['settle']; + if ($final !== null) { + $settleTotal = (float) $settleTotal + (float) $final; } } $labels = $template['labels']; diff --git a/app/Support/DropshipFreight/DropshipFees.php b/app/Support/DropshipFreight/DropshipFees.php new file mode 100644 index 000000000..83b351c7b --- /dev/null +++ b/app/Support/DropshipFreight/DropshipFees.php @@ -0,0 +1,133 @@ + '快递运费', 'booking' => '快递记账', 'extra_freight' => '补运费', 'extra_booking' => '补记账', + 'returned' => '退回费', 'intercept' => '拦截费', 'readdress' => '改地址费', 'repack' => '翻箱费', 'overlength' => '超长费']; + + /** 财务可以改的列(快递运费取结算运费,不在这里改)。 */ + public const EDITABLE = ['booking', 'extra_freight', 'extra_booking', 'returned', 'intercept', 'readdress', 'repack', 'overlength']; + + /** 附加费类型里出现这些字就归到这一列,按顺序认(「补记账」先于「记账」)。 */ + private const MATCH = ['extra_booking' => ['补记账'], 'booking' => ['记账'], 'extra_freight' => ['补运费', '补运'], + 'returned' => ['退回', '退件', '退货'], 'intercept' => ['拦截'], 'readdress' => ['改地址', '改址'], 'repack' => ['翻箱'], 'overlength' => ['超长']]; + + public function __construct( + private readonly DropshipFreightStore $store, + private readonly SupplierPayableOverrideStore $overrides, + ) {} + + public static function classify(string $type): ?string + { + foreach (self::MATCH as $key => $words) { + foreach ($words as $word) { + if (str_contains($type, $word)) { + return $key; + } + } + } + + return null; + } + + /** @param array $v */ + public static function total(array $v): float + { + $plus = ['freight', 'extra_freight', 'returned', 'intercept', 'readdress', 'repack', 'overlength', 'extra_booking']; + + return round(array_sum(array_map(static fn (string $k): float => (float) ($v[$k] ?? 0), $plus)) - abs((float) ($v['booking'] ?? 0)), 2); + } + + /** + * 各厂家这个月的费用列。 + * + * @param array $settle 厂家 id => 结算运费 + * @return array,auto:array,manual:array,other:array,note:string,total:float}> + */ + public function rows(string $month, array $settle, int $companyId): array + { + $auto = $this->auto($month); + $manual = []; + foreach ($this->overrides->listRows(self::DATASET . $month, $companyId) as $row) { + $manual[(int) $row['_action_key']] = $row; + } + $result = []; + foreach ($settle as $factoryId => $freight) { + $values = ['freight' => round((float) $freight, 2)]; + $flags = []; + foreach (self::EDITABLE as $key) { + $set = $manual[$factoryId]['fees'][$key] ?? null; + $flags[$key] = $set !== null; + $values[$key] = round((float) ($set ?? $auto[$factoryId]['fees'][$key] ?? 0), 2); + } + $values['booking'] = abs($values['booking']); + $autoValues = array_map(static fn ($v): float => round((float) $v, 2), $auto[$factoryId]['fees'] ?? []); + if (isset($autoValues['booking'])) { + $autoValues['booking'] = abs($autoValues['booking']); + } + $result[$factoryId] = ['values' => $values, 'auto' => $autoValues, 'manual' => $flags, 'other' => $auto[$factoryId]['other'] ?? [], + 'note' => (string) ($manual[$factoryId]['note'] ?? ''), 'total' => self::total($values)]; + } + + return $result; + } + + /** + * 保存手工改的值:空着的列回到自动值。 + * + * @param array $fees 列 => 金额(空 = 自动) + */ + public function save(string $month, int $factoryId, array $fees, string $note, int $companyId, ?int $userId): void + { + $values = []; + foreach (self::EDITABLE as $key) { + $raw = trim((string) ($fees[$key] ?? '')); + if ($raw !== '') { + $values[$key] = round($key === 'booking' ? abs((float) $raw) : (float) $raw, 2); + } + } + $this->overrides->save(self::DATASET . $month, (string) $factoryId, ['fees' => $values, 'note' => mb_substr(trim($note), 0, 255)], + $companyId, $userId, 'dropship_fees'); + } + + /** + * 厂家上传的账单里「附加费」表按类型汇总的金额。 + * + * @return array,other:array}> + */ + public function auto(string $month): array + { + $result = []; + $files = $this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->where('status', 'parsed') + ->whereNotNull('factory_id')->get(['factory_id', 'sheets']); + foreach ($files as $file) { + foreach ((array) json_decode((string) $file->sheets, true) as $sheet) { + foreach ((array) ($sheet['fees'] ?? []) as $type => $amount) { + $id = (int) $file->factory_id; + $key = self::classify((string) $type); + if ($key === null) { + $result[$id]['other'][(string) $type] = round(($result[$id]['other'][(string) $type] ?? 0) + (float) $amount, 2); + } else { + $result[$id]['fees'][$key] = round(($result[$id]['fees'][$key] ?? 0) + (float) $amount, 2); + } + } + } + } + + return $result; + } +} diff --git a/app/Support/DropshipFreight/DropshipFreightStore.php b/app/Support/DropshipFreight/DropshipFreightStore.php index aa389fe90..a6050a920 100644 --- a/app/Support/DropshipFreight/DropshipFreightStore.php +++ b/app/Support/DropshipFreight/DropshipFreightStore.php @@ -4,6 +4,7 @@ namespace App\Support\DropshipFreight; use App\Support\CourierBills\BillWorkbookReader; use App\Support\CourierBills\CourierBillStore; +use App\Support\CourierBills\FreightBillTemplate; use App\Support\CourierBills\ShippingLookup; use Illuminate\Database\ConnectionInterface; use Illuminate\Http\UploadedFile; @@ -220,14 +221,14 @@ final class DropshipFreightStore $row = $this->db()->table('dropship_summary_templates')->where('factory_id', $factory->id)->where('bill_month', '<=', $month) ->orderByDesc('bill_month')->first(); if ($row === null) { - return DropshipSummaryTemplate::fallback($month, (string) $factory->name) + ['from' => null]; + return DropshipSummaryTemplate::withoutDropped(DropshipSummaryTemplate::fallback($month, (string) $factory->name)) + ['from' => null]; } $delta = ((int) substr($month, 0, 4) - (int) substr((string) $row->bill_month, 0, 4)) * 12 + (int) substr($month, 5, 2) - (int) substr((string) $row->bill_month, 5, 2); $template = DropshipSummaryTemplate::roll(['title' => (string) $row->title, 'headers' => array_values((array) json_decode((string) $row->headers, true)), 'labels' => array_values((array) json_decode((string) $row->labels, true)), 'total' => (string) $row->total_label], $delta); - return $template + ['from' => (string) $row->bill_month]; + return DropshipSummaryTemplate::withoutDropped($template) + ['from' => (string) $row->bill_month]; } /** @@ -331,6 +332,23 @@ final class DropshipFreightStore return; } $lines = $result['lines']; + // 按上传模板填的「附加费」表:按类型记下金额,各厂家汇总里自动带入退回费、拦截费等列 + $fees = (new FreightBillTemplate(new BillWorkbookReader()))->surchargesByType(Storage::disk(self::DISK)->path($file->stored_path), + pathinfo($file->stored_path, PATHINFO_EXTENSION)); + if ($fees !== []) { + $found = false; + foreach ($result['sheets'] as &$sheet) { + if ($sheet['sheet'] === FreightBillTemplate::SURCHARGE_SHEET) { + $sheet['fees'] = $fees; + $sheet['note'] = '附加费按类型记入各厂家汇总'; + $found = true; + } + } + unset($sheet); + if (! $found) { + $result['sheets'][] = ['sheet' => FreightBillTemplate::SURCHARGE_SHEET, 'read' => false, 'note' => '附加费按类型记入各厂家汇总', 'fees' => $fees]; + } + } $notes = []; if ($lines === []) { $notes[] = '没读到厂家运费:要有一张表同时有单号列(快递单号/运单号/单号…)和运费列(快递运费/运费/快递费…),且运费不为空'; diff --git a/app/Support/DropshipFreight/DropshipReconciler.php b/app/Support/DropshipFreight/DropshipReconciler.php index 9d59cc864..b9398b34f 100644 --- a/app/Support/DropshipFreight/DropshipReconciler.php +++ b/app/Support/DropshipFreight/DropshipReconciler.php @@ -136,35 +136,49 @@ final class DropshipReconciler private static function row(string $waybill, ?array $i, ?float $billed, string $status, ?string $statusMonth, ?string $note): array { $calc = $i['calc'] ?? null; + $settle = in_array($status, self::PAYABLE, true) ? $calc : null; return ['waybill' => $waybill, 'ship_time' => $i['ship_time'] ?? null, 'express' => $i['express'] ?? null, 'warehouse' => $i['warehouse'] ?? null, 'bill' => $billed, 'calc' => $calc, - 'settle' => in_array($status, self::PAYABLE, true) ? $calc : null, + 'settle' => $settle, 'final' => self::final($billed, $settle), 'diff' => $billed !== null && $calc !== null ? round($billed - $calc, 2) : null, 'status' => $status, 'status_month' => $statusMonth, 'label' => self::label($status, $statusMonth), 'note' => $note, 'formula' => $i['formula'] ?? null]; } + /** 最终结算运费:按我方核算结算,但厂家开得比核算少(厂家运费 − 结算运费 < 0)就按厂家运费结。 */ + public static function final(?float $billed, ?float $settle): ?float + { + return $settle !== null && $billed !== null && $billed < $settle ? round($billed, 2) : $settle; + } + /** @param list> $rows */ public static function summarize(object $factory, string $month, array $rows): array { $counts = array_fill_keys(array_keys(self::LABELS), 0); - $bill = $settle = 0.0; - $billedCount = $over = $under = 0; + $bill = $settle = $calcSettle = 0.0; + $billedCount = $over = $under = $capped = 0; foreach ($rows as $row) { $counts[$row['status']]++; if ($row['bill'] !== null) { $billedCount++; $bill += $row['bill']; } - $settle += (float) $row['settle']; + $calcSettle += (float) $row['settle']; + $final = array_key_exists('final', $row) ? $row['final'] : self::final($row['bill'], $row['settle']); + $settle += (float) $final; + if ($final !== null && $row['settle'] !== null && $final < $row['settle']) { + $capped++; + } if ($row['status'] === Category::DIFF) { $row['diff'] > 0 ? $over++ : $under++; } } return ['factory_id' => (int) $factory->id, 'factory' => $factory->name, 'warehouse' => $factory->warehouse, 'month' => $month, + // settle = 最终结算运费(各厂家汇总、小汇总、推送厂家确认都用它);calc_settle = 按我方核算的结算运费;capped = 按厂家运费结的单数 'keywords' => $factory->keywords, 'billed' => $billedCount, 'bill' => round($bill, 2), 'settle' => round($settle, 2), + 'calc_settle' => round($calcSettle, 2), 'capped' => $capped, 'diff' => round($bill - $settle, 2), 'counts' => $counts, 'over' => $over, 'under' => $under, 'attention' => array_sum(array_intersect_key($counts, array_flip(self::ATTENTION)))]; } @@ -180,6 +194,14 @@ final class DropshipReconciler return false; } + /** 这家这个月有没有代发发货(批量催上传账单时,没有代发发货的厂家不催)。 @param list|null $own 自有快递名称 */ + public function hasDropship(object $factory, string $month, ?array $own = null): bool + { + $keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords); + + return $this->dropshipWaybills($factory, $keywords, array_flip($own ?? $this->store->ownExpressNames()), $month) !== []; + } + /** 系统认出的这家本月代发单号:代发仓发出、快递名称1 含关键字、不是自有快递。 @return list */ private function dropshipWaybills(object $factory, array $keywords, array $own, string $month): array { diff --git a/app/Support/DropshipFreight/DropshipSummaryTemplate.php b/app/Support/DropshipFreight/DropshipSummaryTemplate.php index b1532f886..f20f495dc 100644 --- a/app/Support/DropshipFreight/DropshipSummaryTemplate.php +++ b/app/Support/DropshipFreight/DropshipSummaryTemplate.php @@ -17,7 +17,9 @@ final class DropshipSummaryTemplate public const TOTALS = ['合计', '汇总', '总计']; /** 没有手工汇总可参照时用的样子(手工汇总里最常见的那种)。 */ - public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账', '代发', '退货'], 'total' => '合计']; + public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账'], 'total' => '合计']; + /** 小汇总里不要的类目(手工汇总里带了也去掉)。 */ + public const DROPPED = ['代发', '退货']; /** * 从手工做好的代发账单里找汇总块:标题格以「X月」开头,右边三格里有「简尚…」和「差异/差额」。优先看名字带「汇总」的表。 @@ -95,6 +97,15 @@ final class DropshipSummaryTemplate return $template; } + /** 去掉「代发」「退货」这类不要的类目(带月份的如「10月退货」也算)。 */ + public static function withoutDropped(array $template): array + { + $template['labels'] = array_values(array_filter($template['labels'], static fn (string $l): bool => ! in_array( + trim(preg_replace('/^\d{1,2}月|\d{1,2}月$/u', '', trim($l)) ?? ''), self::DROPPED, true))); + + return $template; + } + public static function fallback(string $month, string $factory): array { $template = self::DEFAULT; diff --git a/app/Support/DropshipFreight/DropshipUploadReminder.php b/app/Support/DropshipFreight/DropshipUploadReminder.php new file mode 100644 index 000000000..e95981587 --- /dev/null +++ b/app/Support/DropshipFreight/DropshipUploadReminder.php @@ -0,0 +1,124 @@ +set(self::SETTING_KEY, $on ? '1' : '0'); + setting()->save(); + } + + public static function today(): CarbonImmutable + { + return CarbonImmutable::now(self::TIMEZONE)->startOfDay(); + } + + /** 这天要催的账单月:上个月。 */ + public static function billMonth(CarbonInterface $day): string + { + return CarbonImmutable::parse($day->format('Y-m-d'), self::TIMEZONE)->startOfMonth()->subMonth()->format('Y-m'); + } + + /** 账单月的上传截止日:次月 14 日。 */ + public static function deadline(string $month): CarbonImmutable + { + return CarbonImmutable::createFromFormat('Y-m-d', $month . '-01', self::TIMEZONE)->startOfDay()->addMonth()->day(self::DEADLINE_DAY); + } + + /** 今天还在这个账单月的上传期(次月 1–14 日)里,就返回截止日,提醒里写明截止和逾期后果;否则 null。 */ + public static function deadlineFor(string $month, CarbonInterface $today): ?CarbonImmutable + { + $deadline = self::deadline($month); + $day = CarbonImmutable::parse($today->format('Y-m-d'), self::TIMEZONE); + + return $day->greaterThanOrEqualTo($deadline->startOfMonth()) && $day->lessThanOrEqualTo($deadline) ? $deadline : null; + } + + /** + * 这个月要提醒的厂家。 + * + * @return array{targets:list,done:list,no_shipment:list,no_robot:list} + */ + public function targets(string $month, ?int $factoryId = null): array + { + $factories = collect($this->store->factories()); + $single = $factoryId !== null; + if ($single) { + $factories = $factories->where('id', $factoryId)->values(); + } + $uploaded = array_flip($this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->whereNotNull('factory_id') + ->where('status', '!=', 'failed')->distinct()->pluck('factory_id')->map('intval')->all()); + $robots = $this->notifier->configurationMap($factories->pluck('name')->map('strval')->all()); + $own = $single ? [] : $this->store->ownExpressNames(); + $result = ['targets' => [], 'done' => [], 'no_shipment' => [], 'no_robot' => []]; + foreach ($factories as $factory) { + $name = (string) $factory->name; + if (! $single && isset($uploaded[(int) $factory->id])) { + $result['done'][] = $name; + } elseif (! ($robots[$name]['configured'] ?? false)) { + $result['no_robot'][] = $name; + } elseif (! $single && ! $this->reconciler->hasDropship($factory, $month, $own)) { + $result['no_shipment'][] = $name; + } else { + $result['targets'][] = $factory; + } + } + + return $result; + } + + /** + * 发提醒。 + * + * @return array{sent:list,failed:list,done:list,no_shipment:list,no_robot:list,deadline:?CarbonImmutable} + */ + public function remind(string $month, string $portalUrl, ?int $factoryId = null, ?CarbonInterface $today = null): array + { + $today ??= self::today(); + $deadline = self::deadlineFor($month, $today); + $plan = $this->targets($month, $factoryId); + $sent = $failed = []; + foreach ($plan['targets'] as $factory) { + try { + $this->notifier->pushDropshipUploadReminder((string) $factory->name, $month, $portalUrl, $deadline, $today); + $sent[] = (string) $factory->name; + } catch (Throwable $error) { + report($error); + $failed[] = (string) $factory->name; + } + } + unset($plan['targets']); + + return ['sent' => $sent, 'failed' => $failed, 'deadline' => $deadline] + $plan; + } +} diff --git a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php index 6d2575f81..85704871b 100644 --- a/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php +++ b/modules/EcommerceFinance/Services/SupplierDingTalkNotifier.php @@ -524,14 +524,29 @@ class SupplierDingTalkNotifier return true; } - /** 代发运费:提醒厂家到厂家对账入口(钉钉登录)上传这个月的代发运费账单。 */ - public function pushDropshipUploadReminder(string $supplier, string $month, string $portalUrl): void + /** + * 代发运费:提醒厂家到厂家对账入口(钉钉登录)上传这个月的代发运费账单。 + * 给了截止日(次月 14 日)就写明截止日、还剩几天,以及逾期本月货款和运费不予结算。 + */ + public function pushDropshipUploadReminder(string $supplier, string $month, string $portalUrl, + ?\Carbon\CarbonInterface $deadline = null, ?\Carbon\CarbonInterface $today = null): void { [$webhook, $config] = $this->robotFor($supplier, 'dropship_upload_reminder'); + $deadlineLines = []; + $title = '代发运费账单上传提醒'; + if ($deadline !== null) { + $left = $today === null ? null : (int) \Carbon\CarbonImmutable::parse($today->format('Y-m-d'))->diffInDays(\Carbon\CarbonImmutable::parse($deadline->format('Y-m-d')), false); + $title .= $left === 0 ? '(今天截止)' : ''; + $deadlineLines = [ + '- 请于 **' . (int) $deadline->format('n') . '月' . (int) $deadline->format('j') . '日** 前上传 **' . $this->displayMonth($month) . '** 代发运费账单' + . ($left === 0 ? ',**今天截止**' : ($left !== null && $left > 0 ? ',还剩 ' . $left . ' 天' : '')), + '- **逾期未上传,本月货款和运费将不予结算**', + ]; + } $this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false), - $supplier . ' · 代发运费账单上传提醒 · ' . $this->displayMonth($month), implode("\n", [ - '### 代发运费账单上传提醒 · ' . $supplier, - '- 请上传 **' . $this->displayMonth($month) . '** 代发运费账单', + $supplier . ' · ' . $title . ' · ' . $this->displayMonth($month), implode("\n", [ + '### ' . $title . ' · ' . $supplier, + ...($deadlineLines ?: ['- 请上传 **' . $this->displayMonth($month) . '** 代发运费账单']), '- 按上传模板填写(单号、省、重量、运费、快递名称、面单、费率),单号和运费必填', '- 有附加费的填模板里的「附加费」表(快递单号、附加费金额、附加费类型),没有就空着', '', 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 d53a33907..90509b4a0 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 @@ -99,6 +99,13 @@

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

+ @php($pushMonth = $cbPushMonth ?? $month) +
+ + + + 下面「推送上传链接」按钮推的是这个月份的账单,默认上个月。 +
@@ -134,9 +141,9 @@ @if ($robot['configured'] ?? false) @csrf - - + onsubmit="return confirm('往「{{ $group->name }}」钉钉对账群推送 {{ $pushMonth }} 账单上传链接?')">@csrf + + @endif @forelse ($cbLedgerStats as $row) - + @empty @endforelse 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 168d25e7c..50ea45d8c 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 @@ -3,7 +3,7 @@ @csrf - + 对账分组已复用工作平台「应付群机器人配置」中对应快递的群机器人;未匹配的可在「对账分组」里补充。这里一键往已配置的群推本月的免登录上传链接。 快递点开链接、下载模板(单号、省、重量、运费、快递名称、面单、费率)填好上传,后台校验读入后进入对账;链接只能传那一家那个月,30 天有效。已有 {{ collect($cbRobots ?? [])->where('configured', true)->count() }} 家配了机器人。 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 839ac1577..aaa4ffc0e 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 @@ -15,8 +15,9 @@
{{ $dfFactory->name }} · {{ $dfFactory->warehouse }}关键字:{{ $dfFactory->keywords }}
厂家开运费 {{ number_format($s['billed']) }} 单{{ $money($s['bill']) }}
-
结算运费(按我方核算){{ $money($s['settle']) }}
-
差额(厂家 − 结算){{ $money($s['diff']) }}
+
结算运费(按我方核算){{ $money($s['calc_settle'] ?? $s['settle']) }}
+
最终结算运费@if (($s['capped'] ?? 0) > 0)({{ number_format($s['capped']) }} 单厂家开得少,按厂家运费)@endif{{ $money($s['settle']) }}
+
差额(厂家 − 最终结算){{ $money($s['diff']) }}
@@ -51,7 +52,7 @@
分组名称快递名称1归到承运商合并账单负责人文件名关键字指定表头钉钉对账群
diff --git a/resources/views/business/pages/courier-payables/courier-bills/ledger.blade.php b/resources/views/business/pages/courier-payables/courier-bills/ledger.blade.php index 9132fe3d8..5309df785 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/ledger.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/ledger.blade.php @@ -9,7 +9,7 @@ @if ($cbSearch)
@forelse ($cbLedgerHits as $hit) -
{{ $hit->group_name }} · {{ $hit->settle_month }} 已结算 {{ $money($hit->amount) }}{{ $hit->statement_id ? '' : '(历史导入)' }}
+
{{ $hit->group_name ?? '历史导入(不分组)' }} · {{ $hit->settle_month }} 已结算 {{ $money($hit->amount) }}{{ $hit->statement_id ? '' : '(历史导入)' }}
@empty
{{ $cbSearch }} 没有结算记录。
@endforelse @@ -22,7 +22,7 @@ @csrf -

表头须含「分组」「单号」「结算月份」,可带「金额」。分组名称要和「对账分组」里的一致。系统上线前的月份没有台账,导入后这些单号再出现在账单里会归为「重复」;不导入的话会归为「前月补提供」。

+

表头须含「单号」「结算月份」,可带「金额」,不用分组。按单号查重:导入后这些单号再出现在任何一家的账单里(结算月份不是本月),就归为「重复」;不导入的话会归为「前月补提供」。同一单号同一月份重复导入只记一次。

@@ -34,7 +34,7 @@
结算月份对账分组单号数其中历史导入结算金额
{{ $row->settle_month }}{{ $row->group_name }}{{ number_format($row->n) }}{{ number_format($row->imported) }}{{ $money($row->amount) }}
{{ $row->settle_month }}{{ $row->group_name ?? '历史导入(不分组)' }}{{ number_format($row->n) }}{{ number_format($row->imported) }}{{ $money($row->amount) }}
还没有结算记录。对账单「确认结算」后,单号会记到这里。
- + @forelse ($dfLines as $r) @@ -61,12 +62,14 @@ + @php $capped = $r['final'] !== null && $r['settle'] !== null && $r['final'] < $r['settle']; @endphp + @empty - + @endforelse
快递单号发货时间快递名称1厂家运费我方核算结算运费差额状态说明
快递单号发货时间快递名称1厂家运费我方核算结算运费最终结算运费差额状态说明
{{ $money($r['bill']) }} {{ $money($r['calc']) }} {{ $money($r['settle']) }}{{ $money($r['final']) }} {{ $money($r['diff']) }} @php $st = $r['status']; @endphp{{ $r['label'] }} {{ $r['note'] }}
没有明细。
没有明细。
diff --git a/resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php index 871148ded..01f41553e 100644 --- a/resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php +++ b/resources/views/business/pages/courier-payables/dropship-freight/overview.blade.php @@ -8,7 +8,7 @@
本月有账单的厂家{{ number_format(count($dfRows)) }}
厂家运费合计{{ $money($dfTotals['bill']) }}
-
结算运费(按我方核算){{ $money($dfTotals['settle']) }}
+
结算运费(最终){{ $money($dfTotals['settle']) }}
差额(厂家 − 结算){{ $money($dfTotals['diff']) }}
要看一眼的单{{ number_format($dfTotals['attention']) }}
@@ -17,15 +17,45 @@
- + + @foreach (\App\Support\DropshipFreight\DropshipFees::COLUMNS as $label)@endforeach + + @forelse ($dfRows as $row) - @php $other = $row['attention'] - $row['counts']['diff']; @endphp + @php + $other = $row['attention'] - $row['counts']['diff']; + $fee = $dfFees[$row['factory_id']] ?? ['values' => [], 'auto' => [], 'manual' => [], 'other' => [], 'note' => '', 'total' => 0]; + @endphp + @foreach (\App\Support\DropshipFreight\DropshipFees::COLUMNS as $key => $label) + @php $v = (float) ($fee['values'][$key] ?? 0); @endphp + + @endforeach + + @@ -41,13 +71,25 @@ @empty - + @endforelse + @if ($dfRows !== []) + + + @foreach (\App\Support\DropshipFreight\DropshipFees::COLUMNS as $key => $label) + @php $t = (float) ($dfFeeTotals[$key] ?? 0); @endphp + + @endforeach + + + + @endif
厂家代发仓关键字厂家{{ $label }}合计运费备注代发仓关键字 厂家开运费单数厂家运费结算运费差额 运费有差·厂家多开运费有差·厂家少开厂家未提供(不付)其他要看的厂家确认操作
{{ $row['factory'] }}{{ $v == 0 ? '' : $money($key === 'booking' ? -$v : $v) }}{{ $money($fee['total']) }} + {{ $fee['note'] }} + @if ($fee['other'] !== [])
未归类附加费(不计入合计):@foreach ($fee['other'] as $type => $amount){{ $type }} {{ $money($amount) }}@if (! $loop->last)、@endif @endforeach
@endif +
+ 改费用 / 备注 + + @csrf + + @foreach (\App\Support\DropshipFreight\DropshipFees::EDITABLE as $key) + + @endforeach + + + 空着 = 用厂家附加费表自动带入的值。 + +
+
{{ $row['warehouse'] }} {{ $row['keywords'] }} {{ number_format($row['billed']) }}打开明细
{{ $month }} 还没有上传厂家账单。先在「代发厂家设置」里建好厂家,再到「上传厂家账单」批量上传。
{{ $month }} 还没有上传厂家账单。先在「代发厂家设置」里建好厂家,再到「上传厂家账单」批量上传。
合计{{ $t == 0 ? '' : $money($key === 'booking' ? -$t : $t) }}{{ $money($dfFeeTotals['total'] ?? 0) }}
@if ($dfWithout !== []) @endif
-

差额 = 厂家运费 − 结算运费;正数是厂家多开、按我方核算扣掉的。分类和自有快递对账一样:重复 → 未发出 → 匹配不到(发货数据哪个月都查不到)→ 快递不符(不是这家代发仓发的、不是这家代发快递或是自有快递)→ 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算)。一致类和前月补提供按我方核算结算;换单的旧单号按实际发出的新单号判断(新单号是这家代发单就照付,否则算快递不符);其他要看的 = 除运费有差外需要人工看的单。厂家确认:核对完成后点「推送厂家确认」,推送到这家的钉钉对账群(和货款对账同一个群机器人),厂家在免登录确认页逐单确认,对某一单有异议可写原因,结果实时回到这里。

+

结算运费 = 最终结算运费:逐单按我方核算,厂家开得比核算少(厂家运费 − 结算运费 < 0)的单按厂家运费结。费用列:快递运费 = 最终结算运费;快递记账、补运费、补记账、退回费、拦截费、改地址费、翻箱费、超长费先按厂家上传模板「附加费」表的附加费类型自动带入,可在「改费用 / 备注」里逐家改(加粗 = 手工改过,清空回到自动值);合计运费 = 快递运费 + 补运费 + 退回费 + 拦截费 + 改地址费 + 翻箱费 + 超长费 − 快递记账 + 补记账。

+

差额 = 厂家运费 − 结算运费;正数是厂家多开、按我方核算扣掉的。分类和自有快递对账一样:重复 → 未发出 → 匹配不到(发货数据哪个月都查不到)→ 快递不符(不是这家代发仓发的、不是这家代发快递或是自有快递)→ 前月补提供 / 跨月订单 → 一致 / 一致但运费有差 / 一致(系统未核算)。一致类和前月补提供按我方核算结算,厂家开得比核算少的按厂家运费结(最终结算运费);换单的旧单号按实际发出的新单号判断(新单号是这家代发单就照付,否则算快递不符);其他要看的 = 除运费有差外需要人工看的单。厂家确认:核对完成后点「推送厂家确认」,推送到这家的钉钉对账群(和货款对账同一个群机器人),厂家在免登录确认页逐单确认,对某一单有异议可写原因,结果实时回到这里。

diff --git a/resources/views/business/pages/courier-payables/dropship-freight/share.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/share.blade.php index f727f6c7a..e750e0a4f 100644 --- a/resources/views/business/pages/courier-payables/dropship-freight/share.blade.php +++ b/resources/views/business/pages/courier-payables/dropship-freight/share.blade.php @@ -104,7 +104,7 @@ {{ $r['ship_time'] ? substr($r['ship_time'], 0, 16) : '—' }} {{ $r['express'] ?? '—' }} {{ number_format((float) $r['bill'], 2) }} - {{ number_format((float) ($r['settle'] ?? 0), 2) }} + {{ number_format((float) ($r['final'] ?? $r['settle'] ?? 0), 2) }} {{ $r['label'] }} {{ $r['note'] }} @if ($current && ! $submitted) diff --git a/resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php b/resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php index c731568ea..18c33fd79 100644 --- a/resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php +++ b/resources/views/business/pages/courier-payables/dropship-freight/upload.blade.php @@ -5,7 +5,14 @@ @csrf - 只通知这个月还没上传、且配了钉钉群机器人(供应商对账里配置,和货款对账同一个群)的厂家,已上传的不打扰。群里收到厂家对账入口链接,厂家钉钉登录后在「上传运费账单」里按模板上传。 + 只通知这个月有代发发货、还没上传、且配了钉钉群机器人(供应商对账里配置,和货款对账同一个群)的厂家,已上传的不打扰。群里收到厂家对账入口链接,厂家钉钉登录后在「上传运费账单」里按模板上传。在次月 1–{{ \App\Support\DropshipFreight\DropshipUploadReminder::DEADLINE_DAY }} 日通知的,会写明 {{ $dfDeadline ?? '' }} 截止、逾期本月货款和运费不予结算。 + +
+ @csrf + + 自动提醒:{{ ($dfAutoRemind ?? true) ? '已开启' : '已关闭' }} + + 每月 1–{{ \App\Support\DropshipFreight\DropshipUploadReminder::DEADLINE_DAY }} 日 {{ \App\Support\DropshipFreight\DropshipUploadReminder::SEND_TIME }} 自动往厂家群发提醒,催上个月的代发运费账单:只发给有代发发货、还没上传、配了机器人的厂家,写明 {{ \App\Support\DropshipFreight\DropshipUploadReminder::DEADLINE_DAY }} 日截止、逾期本月货款和运费不予结算;厂家一上传就不再提醒。
diff --git a/routes/admin.php b/routes/admin.php index 6663a8323..cb1d97973 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -823,7 +823,9 @@ foreach (['courier-payables', 'courier-payables-final'] as $courierBillSection) Route::post('factories/{factory}/delete', [$controller, 'deleteFactory'])->whereNumber('factory')->name('delete-factory')->defaults('section', $courierBillSection); Route::post('factories/{factory}/check', [$controller, 'check'])->whereNumber('factory')->name('check')->defaults('section', $courierBillSection); Route::post('factories/{factory}/push', [$controller, 'push'])->whereNumber('factory')->name('push')->defaults('section', $courierBillSection); + Route::post('factories/{factory}/fees', [$controller, 'saveFees'])->whereNumber('factory')->name('save-fees')->defaults('section', $courierBillSection); Route::post('notify-upload', [$controller, 'notifyUpload'])->name('notify-upload')->defaults('section', $courierBillSection); + Route::post('auto-remind', [$controller, 'autoRemind'])->name('auto-remind')->defaults('section', $courierBillSection); Route::get('export', [$controller, 'export'])->name('export')->defaults('section', $courierBillSection); }); diff --git a/tests/Feature/Business/CourierBillPagesTest.php b/tests/Feature/Business/CourierBillPagesTest.php index 743c653a8..d67d873c1 100644 --- a/tests/Feature/Business/CourierBillPagesTest.php +++ b/tests/Feature/Business/CourierBillPagesTest.php @@ -28,11 +28,17 @@ final class CourierBillPagesTest extends FeatureTestCase $this->get($directory)->assertOk()->assertSeeText('快递应付汇总')->assertSeeText('快递账单对账'); $page = fn (array $q = []) => route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', ...$q]); foreach (['overview', 'details', 'upload', 'ledger', 'groups'] as $view) { - $this->get($page(['cb_view' => $view, 'month' => '2026-10']))->assertOk()->assertSee('data-cbr-root', false); + $this->get($page(['cb_view' => $view, 'month' => '2026-10']))->assertOk()->assertSee('data-cbr-root', false)->assertDontSeeText('快递账单对账暂不可用'); } } $section = 'courier-payables-final'; + // 历史已结算单号不分组:台账页、查单号都能显示 + $db->table('courier_bill_ledger')->insert(['group_id' => 0, 'waybill_no' => 'HIS001', 'settle_month' => '2026-08', 'amount' => 3]); + $ledger = fn (array $q = []) => route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'ledger', ...$q]); + $this->get($ledger())->assertOk()->assertSeeText('历史导入(不分组)')->assertSeeText('「单号」「结算月份」'); + $this->get($ledger(['waybill' => 'his001']))->assertOk()->assertSeeText('历史导入(不分组) · 2026-08 已结算'); + $db->table('courier_bill_ledger')->where('waybill_no', 'HIS001')->delete(); $this->post(route("business.$section.courier-bills.save-group"), ['name' => '河北中通-江三/小件', 'express_names' => "河北中通-江三\n河北中通小件-江三", 'summary_carrier' => '河北中通', 'owner' => '张三'])->assertRedirect(); $this->assertSame(1, $db->table('courier_bill_groups')->count()); diff --git a/tests/Feature/Business/CourierBillReconciliationTest.php b/tests/Feature/Business/CourierBillReconciliationTest.php index 1c937e499..1224fa5a9 100644 --- a/tests/Feature/Business/CourierBillReconciliationTest.php +++ b/tests/Feature/Business/CourierBillReconciliationTest.php @@ -365,13 +365,24 @@ final class CourierBillReconciliationTest extends FeatureTestCase $this->seedShipping(); $store = app(CourierBillStore::class); $store->saveGroup(null, ['name' => '河北中通-江三/小件', 'express_names' => ['河北中通-江三'], 'summary_carrier' => null, 'owner' => null, 'keywords' => null]); - $path = $this->workbook(['台账' => [['分组', '单号', '结算月份', '金额'], ['河北中通-江三/小件', 'ZT001', '2026年9月', 10], ['不存在', 'X1', '2026-09', 1]]]); + // 只要单号和结算月份,不分组;同一单号同一月份只记一次;认不出的行不导入 + $path = $this->workbook(['台账' => [['单号', '结算月份'], ['ZT001', '2026年9月'], ['ZT001', '2026-09'], ['ZT002', '2026.9'], ['X1', '不知道']]]); $result = $store->importLedger($path, 'xlsx'); - $this->assertSame(1, $result['inserted']); - $this->assertSame(['不存在'], $result['unknown_groups']); - $ids = $store->upload([$this->upload('河北中通-江三.xlsx', [['运单号', '运费'], ['ZT001', 10]])], '2026-10', [], 'tester'); + $this->assertSame(['rows' => 4, 'inserted' => 2, 'rejected' => 1], $result); + $this->assertSame([0], $store->db()->table('courier_bill_ledger')->distinct()->pluck('group_id')->map('intval')->all()); + try { + $store->importLedger($this->workbook(['台账' => [['分组', '单号'], ['河北中通-江三/小件', 'ZT009']]]), 'xlsx'); + $this->fail('缺结算月份应当报错'); + } catch (\RuntimeException $e) { + $this->assertStringContainsString('「单号」「结算月份」', $e->getMessage()); + } + // 按单号查重:哪家账单里出现、结算月份不是本月,就是重复 + $ids = $store->upload([$this->upload('河北中通-江三.xlsx', [['运单号', '运费'], ['ZT001', 10], ['ZT002', 5], ['ZT003', 6]])], '2026-10', [], 'tester'); $statementId = (int) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('statement_id'); - $this->assertSame(Category::DUPLICATE, $store->db()->table('courier_bill_lines')->where('statement_id', $statementId)->value('category')); + $categories = $store->db()->table('courier_bill_lines')->where('statement_id', $statementId)->pluck('category', 'waybill_no')->all(); + $this->assertSame(Category::DUPLICATE, $categories['ZT001']); + $this->assertSame(Category::DUPLICATE, $categories['ZT002']); + $this->assertNotSame(Category::DUPLICATE, $categories['ZT003']); } public function test_groups_can_be_generated_from_summary_imported_and_completed_from_shipping_names(): void diff --git a/tests/Feature/Business/DropshipFreightConfirmTest.php b/tests/Feature/Business/DropshipFreightConfirmTest.php index 60a9621da..6c2569949 100644 --- a/tests/Feature/Business/DropshipFreightConfirmTest.php +++ b/tests/Feature/Business/DropshipFreightConfirmTest.php @@ -6,6 +6,9 @@ use App\Models\Auth\Permission; use App\Support\CourierBills\CourierBillMatcher; use App\Support\CourierBills\ShippingLookup; use App\Support\DropshipFreight\DropshipConfirmation; +use App\Support\DropshipFreight\DropshipUploadReminder; +use Carbon\Carbon; +use Illuminate\Support\Facades\Cache; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; @@ -133,39 +136,109 @@ final class DropshipFreightConfirmTest extends FeatureTestCase public function test_notify_factories_that_have_not_uploaded_this_month(): void { - Storage::fake('local'); - $this->company->makeCurrent(true); - $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); - $this->loginAs()->withExceptionHandling(); - $db = CourierBillMatcher::db(); - foreach (['临沂卿德客' => '工厂-山东卿德客代发仓', '河北丽彪' => '工厂-河北丽彪代发仓', '没配群' => '工厂-没配群代发仓'] as $name => $wh) { - $db->table('dropship_factories')->insert(['name' => $name, 'warehouse' => $wh, 'keywords' => mb_substr($name, -2), - 'created_at' => now(), 'updated_at' => now()]); - } - $notifier = app(SupplierDingTalkNotifier::class); - $notifier->save('临沂卿德客', 'https://oapi.dingtalk.com/robot/send?access_token=a', '', false); - $notifier->save('河北丽彪', 'https://oapi.dingtalk.com/robot/send?access_token=b', '', false); - $db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id'), - 'original_name' => 'x.xlsx', 'stored_path' => 'x', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]); - Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + Carbon::setTestNow(Carbon::parse('2026-12-03 10:00:00', 'Asia/Shanghai')); + $db = $this->reminderFixture(); $url = route('business.' . self::SECTION . '.dropship-freight.notify-upload'); - $this->post($url, ['month' => '2026-11'])->assertSessionHas('dropship_message', '已通知 1 家上传 2026-11 代发运费账单:临沂卿德客;1 家已经上传,没再通知;1 家没配钉钉群机器人。'); + $this->post($url, ['month' => '2026-11'])->assertSessionHas('dropship_message', '已通知 1 家上传 2026-11 代发运费账单:临沂卿德客' + . '(写明 12月14日 截止,逾期本月货款和运费不予结算);1 家已经上传,没再通知;1 家这个月没有代发发货,没通知;1 家没配钉钉群机器人:没配群。'); $this->assertCount(1, Http::recorded()); $text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''); $this->assertStringContainsString('代发运费账单上传提醒 · 临沂卿德客', $text); - $this->assertStringContainsString('请上传 **2026年11月** 代发运费账单', $text); + $this->assertStringContainsString('请于 **12月14日** 前上传 **2026年11月** 代发运费账单,还剩 11 天', $text); + $this->assertStringContainsString('**逾期未上传,本月货款和运费将不予结算**', $text); $this->assertStringContainsString('[打开厂家对账入口](', $text); - // 单独通知一家:已上传也照发;没配机器人报错 + // 不在上传期里的月份(比如单独补催 10 月):不写截止和后果;10 月没有代发发货,批量不发 + $this->post($url, ['month' => '2026-10'])->assertSessionHas('dropship_message', fn (string $m): bool => str_starts_with($m, '已通知 0 家')); + $this->post($url, ['month' => '2026-10', 'factory' => $db->table('dropship_factories')->where('name', '临沂卿德客')->value('id')]); + $text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''); + $this->assertStringContainsString('请上传 **2026年10月** 代发运费账单', $text); + $this->assertStringNotContainsString('不予结算', $text); + $count = count(Http::recorded()); + // 单独通知一家:已上传、没代发发货也照发;没配机器人报错 $this->post($url, ['month' => '2026-11', 'factory' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id')]) ->assertSessionHas('dropship_message'); - $this->assertCount(2, Http::recorded()); + $this->assertCount($count + 1, Http::recorded()); $this->post($url, ['month' => '2026-11', 'factory' => $db->table('dropship_factories')->where('name', '没配群')->value('id')]) ->assertSessionHasErrors('dropship'); $this->get(route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'factories', 'month' => '2026-11'])) ->assertOk()->assertSeeText('通知上传'); $this->get(route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'upload', 'month' => '2026-11'])) - ->assertOk()->assertSeeText('通知厂家上传'); + ->assertOk()->assertSeeText('通知厂家上传')->assertSeeText('自动提醒:已开启')->assertSeeText('关闭自动提醒'); + Carbon::setTestNow(); + } + + public function test_auto_reminder_runs_on_the_1st_to_14th_for_last_months_bill(): void + { + $db = $this->reminderFixture(); + $run = fn (string $date, array $options = []) => $this->artisan('dropship-freight:remind-upload', ['--date' => $date, ...$options]); + + // 15 日以后不发 + $run('2026-12-15')->assertExitCode(0); + $this->assertCount(0, Http::recorded()); + // 试运行只列名单 + $run('2026-12-04', ['--dry-run' => true])->expectsOutputToContain('会提醒 1 家:临沂卿德客')->assertExitCode(0); + $this->assertCount(0, Http::recorded()); + + $run('2026-12-04')->expectsOutputToContain('已通知 1 家上传 2026-11 代发运费账单:临沂卿德客')->assertExitCode(0); + $this->assertCount(1, Http::recorded()); + $this->assertStringContainsString('还剩 10 天', (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '')); + // 同一天不重复发 + $run('2026-12-04')->expectsOutputToContain('今天已经提醒过')->assertExitCode(0); + $this->assertCount(1, Http::recorded()); + // 14 日:今天截止 + $run('2026-12-14')->assertExitCode(0); + $text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''); + $this->assertStringContainsString('代发运费账单上传提醒(今天截止) · 临沂卿德客', $text); + $this->assertStringContainsString('**今天截止**', $text); + // 厂家传了(解析失败的不算),第二天就不再催 + $factory = $db->table('dropship_factories')->where('name', '临沂卿德客')->value('id'); + $db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $factory, 'original_name' => 'bad.xlsx', + 'stored_path' => 'bad', 'status' => 'failed', 'created_at' => now(), 'updated_at' => now()]); + $run('2026-12-05')->expectsOutputToContain('已通知 1 家')->assertExitCode(0); + $db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $factory, 'original_name' => 'ok.xlsx', + 'stored_path' => 'ok', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]); + $sent = count(Http::recorded()); + $run('2026-12-06')->expectsOutputToContain('已通知 0 家')->assertExitCode(0); + $this->assertCount($sent, Http::recorded()); + + // 关掉开关就不发 + $db->table('dropship_bill_files')->where('original_name', 'ok.xlsx')->delete(); + $this->post(route('business.' . self::SECTION . '.dropship-freight.auto-remind'), ['enabled' => 0])->assertSessionHas('dropship_message', '已关闭自动提醒。'); + $this->assertFalse(DropshipUploadReminder::enabled()); + $run('2026-12-07')->expectsOutputToContain('自动提醒已关闭')->assertExitCode(0); + $this->assertCount($sent, Http::recorded()); + $this->post(route('business.' . self::SECTION . '.dropship-freight.auto-remind'), ['enabled' => 1]); + $this->assertTrue(DropshipUploadReminder::enabled()); + } + + private function reminderFixture() + { + Storage::fake('local'); + Cache::flush(); + $this->company->makeCurrent(true); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs()->withExceptionHandling(); + $db = CourierBillMatcher::db(); + $notifier = app(SupplierDingTalkNotifier::class); + $source = 9100; + foreach (['临沂卿德客' => '德客', '河北丽彪' => '丽彪', '没配群' => '配群', '无代发厂' => '代发厂'] as $name => $keyword) { + $warehouse = '工厂-' . $name . '代发仓'; + $db->table('dropship_factories')->insert(['name' => $name, 'warehouse' => $warehouse, 'keywords' => $keyword, + 'created_at' => now(), 'updated_at' => now()]); + if ($name !== '无代发厂') { + $this->shipping()->table('jst_oms_shipping')->insert(['express_no' => 'DF' . $source, 'express_name1' => $keyword . '代发韵达', + 'warehouse_name' => $warehouse, 'ship_time' => '2026-11-20 10:00:00', 'source_id' => $source++]); + } + if ($name !== '没配群') { + $notifier->save($name, 'https://oapi.dingtalk.com/robot/send?access_token=' . $source++, '', false); + } + } + $db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id'), + 'original_name' => 'x.xlsx', 'stored_path' => 'x', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]); + Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); + + return $db; } private function shipping() diff --git a/tests/Feature/Business/DropshipFreightTest.php b/tests/Feature/Business/DropshipFreightTest.php index 35f31831e..53a115705 100644 --- a/tests/Feature/Business/DropshipFreightTest.php +++ b/tests/Feature/Business/DropshipFreightTest.php @@ -121,8 +121,15 @@ final class DropshipFreightTest extends FeatureTestCase $this->assertSame(11, $s['billed']); $this->assertEquals(63, $s['bill']); // 按我方核算:一致、运费有差、前月补提供、换单实际发出的代发单;跨月订单留到发货月 - $this->assertEquals(8 + 5 + 6 + 4 + 6, $s['settle']); - $this->assertEquals(63 - 29, $s['diff']); + $this->assertEquals(8 + 5 + 6 + 4 + 6, $s['calc_settle']); + // 最终结算:厂家开得比核算少的(773444000003 厂家 5、核算 6)按厂家运费结 + $this->assertEquals(8 + 5 + 5 + 4 + 6, $s['settle']); + $this->assertSame(1, $s['capped']); + $this->assertEquals(63 - 28, $s['diff']); + $under = collect($result['rows'])->firstWhere('waybill', '773444000003'); + $this->assertEquals([5, 6, 5], [$under['bill'], $under['settle'], $under['final']]); + $over = collect($result['rows'])->firstWhere('waybill', '773444000002'); + $this->assertEquals([6, 5, 5], [$over['bill'], $over['settle'], $over['final']]); $swap = collect($result['rows'])->firstWhere('waybill', 'OLD0000001'); $this->assertStringContainsString('换单:实际发出 773444000020(卿德客申通)', $swap['note']); $this->assertStringContainsString('自有快递「曹县韵达」', collect($result['rows'])->firstWhere('waybill', 'OLD0000002')['note']); @@ -134,7 +141,7 @@ final class DropshipFreightTest extends FeatureTestCase $this->assertStringContainsString('自有快递', (string) $own['note']); $this->assertNull($own['settle']); - $this->get($page(['df_view' => 'overview', 'month' => '2026-10']))->assertOk()->assertSeeText('临沂卿德客')->assertSeeText('29.00'); + $this->get($page(['df_view' => 'overview', 'month' => '2026-10']))->assertOk()->assertSeeText('临沂卿德客')->assertSeeText('28.00'); $this->get($page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']))->assertOk() ->assertSeeText('一致但运费有差')->assertSeeText('773444000004')->assertSeeText('厂家未提供(不付)')->assertSeeText('匹配不到') ->assertSeeText('自有快递「曹县韵达」'); @@ -152,6 +159,10 @@ final class DropshipFreightTest extends FeatureTestCase ->where('factory_id', $factory->id)->where('bill_month', '2026-10')->first(['title', 'labels', 'total_label']))); $november = app(DropshipFreightStore::class)->summaryTemplate($f, '2026-11'); $this->assertSame(['11月', ['运费', '货款', '记账'], '2026-10'], [$november['title'], $november['labels'], $november['from']]); + // 小汇总不要「代发」「退货」:默认样子没有,手工汇总里带了也去掉 + $this->assertSame(['运费', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::DEFAULT['labels']); + $this->assertSame(['运费', '货款', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::withoutDropped( + ['labels' => ['运费', '货款', '代发', '记账', '10月退货']])['labels']); $before = $db->table('dropship_bill_lines')->orderBy('id')->get()->toJson(); $filesBefore = $db->table('dropship_bill_files')->orderBy('id')->get()->toJson(); $export = $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10', 'factory' => $factory->id]))->assertOk(); @@ -175,12 +186,12 @@ final class DropshipFreightTest extends FeatureTestCase $summary = $sheet->toArray(null, false, false); $this->assertSame(['10月', '厂家金额', '简尚金额', '差异'], array_slice($summary[0], 0, 4)); $this->assertSame(['运费', '货款', '记账', '汇总'], [$summary[1][0], $summary[2][0], $summary[3][0], $summary[4][0]]); - $this->assertEquals([63, 29], [$summary[1][1], $summary[1][2]]); + $this->assertEquals([63, 28], [$summary[1][1], $summary[1][2]]); $this->assertNull($summary[2][1]); // 货款先空着手工填 $this->assertSame('=SUM(B2:B4)', $sheet->getCell('B5')->getValue()); // 合计是公式,手工填了跟着算 $sheet->setCellValue('C4', -100); $this->assertEquals(100, $sheet->getCell('D4')->getCalculatedValue()); - $this->assertEquals(-71, $sheet->getCell('C5')->getCalculatedValue()); + $this->assertEquals(-72, $sheet->getCell('C5')->getCalculatedValue()); $this->assertSame(5, $sheet->getHighestDataRow()); // 汇总块下面不再附别的 $this->assertSame([3, 1], [count($book->getSheetByName('快递不符')->toArray()) - 1, count($book->getSheetByName('匹配不到')->toArray()) - 1]); $book->disconnectWorksheets(); @@ -291,7 +302,8 @@ final class DropshipFreightTest extends FeatureTestCase $data = $book->getSheetByName('对账')->toArray(null, false, false); $this->assertSame(['快递单号', '运费', '备注', '备注(2)'], array_slice($data[0], 0, 4)); $this->assertSame(['00012345678901234567', 4, ' 保留空格 ', '=1+1'], array_slice($data[1], 0, 4)); - $this->assertEquals(11, $data[1][count($data[0]) - 4]); + $this->assertEquals(11, $data[1][count($data[0]) - 5]); + $this->assertSame(['厂家运费(这一单合计)', '结算运费', '最终结算运费'], array_slice($data[0], -5, 3)); $this->assertContains($book->getSheetByName('对账')->getCell('D2')->getDataType(), [ \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_INLINE, ]); @@ -355,6 +367,51 @@ final class DropshipFreightTest extends FeatureTestCase $this->assertSame('parsed', $store->db()->table('dropship_bill_files')->value('status')); } + public function test_overview_fee_columns_fill_from_the_surcharge_sheet_and_can_be_edited(): void + { + Storage::fake('local'); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs()->withExceptionHandling(); + $db = CourierBillMatcher::db(); + $id = $db->table('dropship_factories')->insertGetId(['name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客', + 'created_at' => now(), 'updated_at' => now()]); + $this->ship('773444000001', '卿德客申通', self::WAREHOUSE, '2026-11-03 09:00:00', 1, 8); + $this->ship('773444000002', '卿德客申通', self::WAREHOUSE, '2026-11-04 09:00:00', 2, 6); // 厂家开 5,比核算少,按 5 结 + $h = ['单号', '省', '重量', '运费', '快递名称', '面单', '费率']; + $path = $this->xlsx(['账单' => [$h, ['773444000001', '', 2, 8], ['773444000002', '', 1, 5]], + '附加费' => [['快递单号', '附加费金额', '附加费类型'], ['773444000001', 3, '退回费'], ['773444000002', 2, '拦截费'], ['773444000002', 1.5, '上楼费']]]); + app(DropshipFreightStore::class)->uploadFor('卿德客11月.xlsx', $path, '2026-11', $id, '测试'); + + $fees = app(\App\Support\DropshipFreight\DropshipFees::class); + $row = $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id]; + $this->assertEquals(['freight' => 13, 'returned' => 3, 'intercept' => 2], array_filter($row['values'])); + $this->assertSame(['上楼费' => 1.5], $row['other']); + $this->assertEquals(18, $row['total']); + $this->assertSame('booking', \App\Support\DropshipFreight\DropshipFees::classify('快递记账')); + $this->assertSame('extra_booking', \App\Support\DropshipFreight\DropshipFees::classify('补记账')); + $this->assertSame('readdress', \App\Support\DropshipFreight\DropshipFees::classify('改址费')); + + $section = 'courier-payables-final'; + $page = route('business.pages.show', ['section' => $section, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'overview', 'month' => '2026-11']); + $this->get($page)->assertOk()->assertSeeTextInOrder(['厂家', '快递运费', '快递记账', '补运费', '补记账', '退回费', '拦截费', '改地址费', '翻箱费', '超长费', '合计运费', '备注', '代发仓']) + ->assertSeeText('18.00')->assertSeeText('上楼费'); + // 财务改:快递记账 4(扣款)、补记账 1、退回费改成 2.5,备注 + $save = route("business.$section.dropship-freight.save-fees", ['factory' => $id]); + $this->post($save, ['month' => '2026-11', 'fees' => ['booking' => '-4', 'extra_booking' => '1', 'returned' => '2.5'], 'note' => '已和厂家核对']) + ->assertSessionHas('dropship_message'); + $row = $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id]; + $this->assertEquals(13 + 2.5 + 2 - 4 + 1, $row['total']); + $this->assertTrue($row['manual']['booking']); + $this->assertEquals(3, $row['auto']['returned']); + $this->get($page)->assertOk()->assertSeeText('-4.00')->assertSeeText('14.50')->assertSeeText('已和厂家核对'); + // 清空回到自动值 + $this->post($save, ['month' => '2026-11', 'fees' => ['booking' => '', 'returned' => ''], 'note' => ''])->assertSessionHas('dropship_message'); + $this->assertEquals(18, $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id]['total']); + $this->post($save, ['month' => '2026-11', 'fees' => ['booking' => 'abc']])->assertSessionHasErrors('fees.booking'); + // 页面上的快递运费 = 最终结算运费 + $this->assertEquals(13, app(DropshipReconciler::class)->factoryMonth(collect(app(DropshipFreightStore::class)->factories())->sole(), '2026-11')['summary']['settle']); + } + public function test_keyword_helpers(): void { $this->assertSame('卿德客', DropshipFreightStore::warehouseCore('工厂-山东卿德客代发仓')); diff --git a/tests/Feature/Business/PortalFreightBillTest.php b/tests/Feature/Business/PortalFreightBillTest.php index 18193fe42..86f2feeec 100644 --- a/tests/Feature/Business/PortalFreightBillTest.php +++ b/tests/Feature/Business/PortalFreightBillTest.php @@ -274,6 +274,14 @@ final class PortalFreightBillTest extends FeatureTestCase $this->post($action('save-robot', ['group' => $groupId]), ['webhook' => 'https://oapi.dingtalk.com/robot/send?access_token=cx', 'secret' => 'SEC-cx']) ->assertSessionHas('courier_bills_message'); $this->get($groups)->assertOk()->assertSeeText('已配')->assertSeeText('推送 2026-11 上传链接'); + // 没指定月份:最近的对账单还停在上上个月(比如 10 月),推送默认上个月(11 月),对账单月份不变 + [$older, $last] = [now()->subMonthsNoOverflow(2)->format('Y-m'), now()->subMonthNoOverflow()->format('Y-m')]; + $db->table('courier_bill_statements')->insert(['group_id' => $groupId, 'bill_month' => $older, 'created_at' => now(), 'updated_at' => now()]); + $this->get(route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'groups'])) + ->assertOk()->assertSeeText('推送 ' . $last . ' 上传链接')->assertSeeText('推送上传链接的账单月份'); + $this->get(route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', 'cb_view' => 'upload'])) + ->assertOk()->assertSee('name="month" value="' . $last . '"', false)->assertSeeText('上传账单 · ' . $older); + $db->table('courier_bill_statements')->where('bill_month', $older)->delete(); Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]); $this->post($action('push-upload-links'), ['month' => '2026-11'])->assertSessionHas('courier_bills_message'); $text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');