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/Http/Controllers/Business/PortalFreightBillController.php b/app/Http/Controllers/Business/PortalFreightBillController.php index 757627be7..6cfd40b99 100644 --- a/app/Http/Controllers/Business/PortalFreightBillController.php +++ b/app/Http/Controllers/Business/PortalFreightBillController.php @@ -3,18 +3,14 @@ namespace App\Http\Controllers\Business; use App\Services\Auth\SupplierPortalAccess; -use App\Support\CourierBills\CourierBillStore; use App\Support\CourierBills\FreightBillTemplate; use App\Support\CourierBills\PortalFreightBills; -use App\Support\DropshipFreight\DropshipFreightStore; +use App\Support\CourierBills\PortalFreightBillImports; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Validation\ValidationException; -use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier; -use RuntimeException; use Symfony\Component\HttpFoundation\StreamedResponse; -use Throwable; /** * 厂家门户(钉钉登录的供应商对账入口)上传运费账单:代发厂家传代发运费账单,快递传快递账单,统一模板、严格校验。 @@ -52,48 +48,22 @@ final class PortalFreightBillController extends Controller throw ValidationException::withMessages(['freight_bill' => '只支持 xlsx、xls、csv,请用上传模板。']); } $name = $this->effectiveName($request); - $original = (string) $file->getClientOriginalName(); - try { - $summary = $this->template->validate((string) $file->getRealPath(), $extension); - } catch (RuntimeException $error) { - throw ValidationException::withMessages(['freight_bill' => $error->getMessage()]); - } - $uploader = mb_substr((string) ($request->user()?->name ?: $request->user()?->email ?: '厂家门户') . '(门户)', 0, 64); - if ($data['kind'] === 'dropship') { - $factory = $this->portal->factory($name); - if ($factory === null) { - throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在代发厂家里,请联系财务。']); - } - $id = app(DropshipFreightStore::class)->uploadFor($original, (string) $file->getRealPath(), $data['month'], (int) $factory->id, $uploader); - $row = app(DropshipFreightStore::class)->db()->table('dropship_bill_files')->find($id); + $target = $this->portal->factory($name); } else { $groups = $this->portal->groups($name); - if ($groups === []) { - throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在快递账单对账分组里,请联系财务。']); - } - $group = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0)); - if ($group === null) { - throw ValidationException::withMessages(['freight_bill' => '请选择是哪一个快递的账单。']); - } - $ids = app(CourierBillStore::class)->upload([$file], $data['month'], [(int) $group->id], $uploader); - $row = app(CourierBillStore::class)->db()->table('courier_bill_files')->find($ids[0] ?? 0); + $target = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0)); } - if ($row === null || $row->status !== 'parsed') { - throw ValidationException::withMessages(['freight_bill' => '文件已收到,但没有读入:' . ($row->message ?? '未知原因') . '。请联系财务。']); + 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), + ]); - $message = '已上传' . self::KINDS[$data['kind']] . ':' . $name . ' ' . $data['month'] . ',' . number_format($summary['rows']) . ' 行,运费合计 ' - . number_format($summary['amount'], 2) . ' 元,已进入财务核对'; - try { - if (app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($name, self::KINDS[$data['kind']], $data['month'], $original, $summary)) { - $message .= ';上传回执已发到钉钉群'; - } - } catch (Throwable $error) { - report($error); - } - - return back()->with('success', $message . '。'); + return back()->with('success', '文件已收到,正在等待校验和读入。处理结果请在下方上传记录查看。'); } /** 厂家/快递账号只能是钉钉组织绑定的那几家;财务账号按页面上选的那家。 */ diff --git a/app/Support/CourierBills/CourierBillStore.php b/app/Support/CourierBills/CourierBillStore.php index b88c9e4e6..38ebf5175 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('这家快递本月对账单已确认结算,先撤销确认再上传。'); } @@ -550,7 +560,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/FreightBillTemplate.php b/app/Support/CourierBills/FreightBillTemplate.php index 3d8e2dd52..7c05889f8 100644 --- a/app/Support/CourierBills/FreightBillTemplate.php +++ b/app/Support/CourierBills/FreightBillTemplate.php @@ -43,6 +43,9 @@ final class FreightBillTemplate if ($rows === null) { throw new RuntimeException('文件是空的。'); } + if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) { + throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。'); + } $errors = []; $header = null; $count = 0; @@ -69,13 +72,16 @@ final class FreightBillTemplate } if ($waybill === '') { $errors[] = '第 ' . $line . ' 行没有单号'; + } elseif (Waybill::normalize($waybill) === null) { + $errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本'; } $freight = BillParser::number($cells[3] ?? null); - if ($freight === null) { + if ($freight === null || ! is_finite($freight)) { $errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字'); } foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) { - if (($cells[$col] ?? '') !== '' && BillParser::number($cells[$col]) === null) { + $value = BillParser::number($cells[$col] ?? null); + if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) { $errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字'; } } @@ -83,6 +89,7 @@ final class FreightBillTemplate break; } $count++; + if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。'); $amount += (float) $freight; $waybills[$waybill] = true; } @@ -96,6 +103,8 @@ final class FreightBillTemplate if ($count === 0) { throw new RuntimeException('模板里还没有填账单明细。'); } + $sheets->next(); + if ($sheets->valid()) throw new RuntimeException('请只保留模板的一张账单工作表,不要附带其他工作表。'); return ['rows' => $count, 'waybills' => count($waybills), 'amount' => round($amount, 2)]; } diff --git a/app/Support/CourierBills/PortalFreightBillImports.php b/app/Support/CourierBills/PortalFreightBillImports.php new file mode 100644 index 000000000..1ec472600 --- /dev/null +++ b/app/Support/CourierBills/PortalFreightBillImports.php @@ -0,0 +1,126 @@ +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): array + { + $files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: []; + rsort($files); + $out = []; + foreach (array_slice($files, 0, 10) 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; + $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']]; + } + 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 + { + $user = User::find($task['user_id']); + if (! $user || ! $user->enabled || ! $user->companies()->where('companies.id', $task['company_id'])->exists()) throw new RuntimeException('上传账号已停用或授权已变化,请联系财务。'); + \App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true); + 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 index b57a0f703..e54959c93 100644 --- a/app/Support/CourierBills/PortalFreightBills.php +++ b/app/Support/CourierBills/PortalFreightBills.php @@ -66,7 +66,7 @@ final class PortalFreightBills { $factory = $this->factory($name); $groups = $this->groups($name); - $files = []; + $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) diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 4df7df62a..b2218f4ea 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -264,6 +264,7 @@ CRON_TZ=Asia/Shanghai # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * 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-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 9be94d000..4b380ebb4 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -268,6 +268,7 @@ CRON_TZ=Asia/Shanghai # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * 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-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 b511c81d3..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", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 72b7d251e..d2b81db3c 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -8,6 +8,7 @@ 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|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) ;; @@ -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 diff --git a/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php b/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php index 1bf718fd7..725e6d38f 100644 --- a/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php +++ b/resources/views/business/pages/supplier-reconciliation/_freight-bills.blade.php @@ -3,7 +3,7 @@ $kinds = []; if ($fp['factory'] !== null) { $kinds['dropship'] = '代发运费账单'; } if ($fp['groups'] !== []) { $kinds['courier'] = '快递账单'; } - $defaultMonth = $accountingMonthKey ?? now()->subMonth()->format('Y-m'); + $defaultMonth = $accountingMonthKey ?? now()->startOfMonth()->subMonth()->format('Y-m'); @endphp