connection = $databases->connection( (string) config('upstream_mirrors.connection', 'business_mirror'), ); } public function available(): bool { $schema = Schema::connection($this->connection->getName()); return $schema->hasTable(self::OPENING_TABLE) && $schema->hasTable(self::TASK_TABLE) && $schema->hasTable(self::BILL_TABLE); } public function cacheVersion(): string { $version = Cache::get(self::CACHE_VERSION_KEY); if (is_string($version) && $version !== '') { return $version; } $version = '1:' . Str::lower(Str::random(20)); Cache::forever(self::CACHE_VERSION_KEY, $version); return $version; } public function invalidateBalanceCache(): void { Cache::forever( self::CACHE_VERSION_KEY, now()->format('YmdHisv') . ':' . Str::lower(Str::random(12)), ); } public function monthStart(string $value): string { $value = trim($value); if (preg_match('/^\d{4}-\d{2}$/', $value) === 1) { $value .= '-01'; } $date = CarbonImmutable::parse($value, 'Asia/Shanghai'); return $date->startOfMonth()->format('Y-m-d'); } /** * @param list|null $storeNames * @return array{pending:int,resolved:int} */ public function syncPendingStores(?array $storeNames = null): array { if (! $this->available()) { return ['pending' => 0, 'resolved' => 0]; } $storeNames = $storeNames === null ? null : array_values(array_unique(array_filter(array_map( static fn (mixed $name): string => trim((string) $name), $storeNames, )))); if ($storeNames === []) { return ['pending' => 0, 'resolved' => 0]; } $query = $this->connection->table(self::BILL_TABLE) ->whereNotNull('store_name') ->where('store_name', '<>', ''); if ($storeNames !== null && $storeNames !== []) { $query->whereIn('store_name', $storeNames); } $firstBills = []; foreach ($query ->select('store_name') ->selectRaw('MIN(occurred_at) AS first_bill_at, MAX(occurred_at) AS last_bill_at') ->groupBy('store_name') ->get() as $row) { $storeName = trim((string) $row->store_name); $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); if ($normalized === '' || ! isset($row->first_bill_at)) { continue; } if (! isset($firstBills[$normalized]) || (string) $row->first_bill_at < $firstBills[$normalized]['first_bill_at']) { $firstBills[$normalized] = [ 'store_name' => $storeName, 'normalized_store_name' => $normalized, 'first_bill_at' => (string) $row->first_bill_at, 'last_bill_at' => (string) ($row->last_bill_at ?? $row->first_bill_at), ]; } } if ($firstBills === []) { return ['pending' => 0, 'resolved' => 0]; } $openingMonths = $this->openingMonthsByStore(array_keys($firstBills)); $existing = $this->connection->table(self::TASK_TABLE) ->whereIn('normalized_store_name', array_keys($firstBills)) ->get() ->keyBy('normalized_store_name'); $now = now(); $pending = 0; $resolved = 0; $this->connection->transaction(function () use ( $firstBills, $openingMonths, $existing, $now, &$pending, &$resolved, ): void { foreach ($firstBills as $normalized => $bill) { $firstMonth = substr($bill['first_bill_at'], 0, 7) . '-01'; $openingMonth = null; foreach ($openingMonths[$normalized] ?? [] as $candidate) { if ($candidate > $firstMonth) { break; } $openingMonth = $candidate; } $status = $openingMonth === null ? 'pending' : 'resolved'; if ($status === 'pending') { $pending++; } else { $resolved++; } $payload = [ 'store_name' => mb_substr($bill['store_name'], 0, 255), 'first_bill_month' => $firstMonth, 'first_bill_at' => $bill['first_bill_at'], 'last_bill_at' => $bill['last_bill_at'], 'status' => $status, 'resolved_opening_month' => $openingMonth, 'resolved_at' => $openingMonth === null ? null : $now, 'last_checked_at' => $now, 'updated_at' => $now, ]; if (isset($existing[$normalized])) { $this->connection->table(self::TASK_TABLE) ->where('normalized_store_name', $normalized) ->update($payload); } else { $this->connection->table(self::TASK_TABLE)->insert($payload + [ 'normalized_store_name' => $normalized, 'created_at' => $now, ]); } } }); return ['pending' => $pending, 'resolved' => $resolved]; } /** * Target month start balances after each store's latest opening has been * rolled forward with that store's own bill movements. * * @param list|null $normalizedStoreNames * @return array */ public function rolledOpeningContext( string $monthStart, ?array $normalizedStoreNames = null, ): array { if (! $this->available()) { return []; } $monthStart = $this->monthStart($monthStart); $taskQuery = $this->connection->table(self::TASK_TABLE) ->where('first_bill_month', '<=', $monthStart); if ($normalizedStoreNames !== null && $normalizedStoreNames !== []) { $taskQuery->whereIn('normalized_store_name', $normalizedStoreNames); } $tasks = $taskQuery->get()->keyBy('normalized_store_name'); $openingQuery = $this->connection->table(self::OPENING_TABLE) ->where('opening_month', '<=', $monthStart) ->orderBy('opening_month'); if ($normalizedStoreNames !== null && $normalizedStoreNames !== []) { $openingQuery->whereIn('normalized_store_name', $normalizedStoreNames); } $openings = []; foreach ($openingQuery->get([ 'store_name', 'normalized_store_name', 'opening_month', 'opening_balance', 'source_filename', ]) as $row) { $openings[(string) $row->normalized_store_name] = $row; } $normalizedNames = array_values(array_unique(array_merge( $tasks->keys()->map(static fn (mixed $value): string => (string) $value)->all(), array_keys($openings), ))); if ($normalizedNames === []) { return []; } $earliestOpening = null; foreach ($openings as $opening) { $month = (string) $opening->opening_month; if ($earliestOpening === null || $month < $earliestOpening) { $earliestOpening = $month; } } $movement = $earliestOpening === null ? [] : $this->movementByStoreMonth($earliestOpening, $monthStart, $normalizedStoreNames); $contexts = []; foreach ($normalizedNames as $normalized) { $task = $tasks->get($normalized); $opening = $openings[$normalized] ?? null; if ($task === null && $opening === null) { continue; } $openingMonth = $opening === null ? null : (string) $opening->opening_month; $balance = null; if ($opening !== null) { $balance = (float) $opening->opening_balance; $openingMonthKey = substr($openingMonth, 0, 7); foreach ($movement[$normalized] ?? [] as $month => $row) { if ($month < $openingMonthKey || $month >= substr($monthStart, 0, 7)) { continue; } $balance += (float) $row['income'] - (float) $row['expense']; } $balance = round($balance, 2); } $contexts[$normalized] = [ 'store_name' => (string) ($task?->store_name ?? $opening?->store_name ?? '未标注店铺'), 'normalized_store_name' => $normalized, 'opening_balance' => $balance, 'opening_month' => $openingMonth, 'opening_source' => $opening === null ? null : (string) ($opening->source_filename ?? ''), 'opening_status' => $opening === null ? 'pending' : 'ready', 'first_bill_month' => (string) ($task?->first_bill_month ?? $openingMonth), 'first_bill_at' => (string) ($task?->first_bill_at ?? ''), ]; } return $contexts; } /** @return list> */ public function openingExceptions(?string $throughDate = null): array { if (! $this->available()) { return []; } $query = $this->connection->table(self::TASK_TABLE) ->where('status', 'pending') ->orderBy('first_bill_at') ->orderBy('store_name'); if ($throughDate !== null) { $query->where('first_bill_at', '<', CarbonImmutable::parse( $throughDate, 'Asia/Shanghai', )->addDay()->format('Y-m-d') . ' 00:00:00'); } return $query->get()->map(static fn (object $row): array => [ 'store_name' => (string) $row->store_name, 'normalized_store_name' => (string) $row->normalized_store_name, 'first_bill_month' => (string) $row->first_bill_month, 'first_bill_at' => (string) $row->first_bill_at, 'status' => 'pending', 'status_label' => '期初未就绪', 'reason' => '该店铺已有账单,但首次业务月份尚无“平台资金账户余额”的期初余额。', 'action' => '请在聚水潭平台资金账户余额导出“期初余额”后重新导入。', ])->all(); } /** * @param list $normalizedStoreNames * @return array> */ private function openingMonthsByStore(array $normalizedStoreNames): array { $result = []; foreach ($this->connection->table(self::OPENING_TABLE) ->whereIn('normalized_store_name', $normalizedStoreNames) ->orderBy('opening_month') ->get(['normalized_store_name', 'opening_month']) as $row) { $result[(string) $row->normalized_store_name][] = (string) $row->opening_month; } return $result; } /** * @param list|null $normalizedStoreNames * @return array> */ private function movementByStoreMonth( string $fromMonth, string $toMonth, ?array $normalizedStoreNames, ): array { $monthExpression = in_array( $this->connection->getDriverName(), ['mysql', 'mariadb'], true, ) ? "DATE_FORMAT(occurred_at, '%Y-%m')" : "substr(occurred_at, 1, 7)"; $query = $this->connection->table(self::BILL_TABLE) ->where('occurred_at', '>=', $fromMonth . ' 00:00:00') ->where('occurred_at', '<', $toMonth . ' 00:00:00') ->select('store_name') ->selectRaw( $monthExpression . ' AS activity_month, ' . 'COALESCE(SUM(income_amount), 0) AS income_total, ' . 'COALESCE(SUM(expense_amount), 0) AS expense_total', ) ->groupBy('store_name') ->groupByRaw($monthExpression); $result = []; foreach ($query->get() as $row) { $normalized = JushuitanShopBalanceRepository::normalizeStoreName( (string) $row->store_name, ); if ($normalized === '' || ($normalizedStoreNames !== null && ! in_array($normalized, $normalizedStoreNames, true))) { continue; } $result[$normalized][(string) $row->activity_month] = [ 'income' => round((float) $row->income_total, 2), 'expense' => round((float) $row->expense_total, 2), ]; } return $result; } }