connection = $databases->connection( (string) config('upstream_mirrors.connection', 'business_mirror'), ); } /** * @param list> $rows * @return list> */ public function filterRows(array $rows, bool $lock = false): array { if ($rows === []) { return []; } $rowKeys = array_values(array_unique(array_filter( array_map(static fn (array $row): string => trim((string) ($row['row_key'] ?? '')), $rows), static fn (string $rowKey): bool => $rowKey !== '', ))); if ($rowKeys === []) { return $rows; } $overridden = []; foreach (array_chunk($rowKeys, 500) as $chunk) { $query = $this->connection->table('fin_transactions') ->whereIn('row_key', $chunk) ->where('local_override', true); if ($lock) { $query->lockForUpdate(); } foreach ($query->pluck('row_key') as $rowKey) { $overridden[(string) $rowKey] = true; } } if ($overridden === []) { return $rows; } return array_values(array_filter( $rows, static fn (array $row): bool => ! isset($overridden[(string) ($row['row_key'] ?? '')]), )); } public function excludeFromReplacement(Builder $query): void { $query->where(function (Builder $builder): void { $builder->where('local_override', false)->orWhereNull('local_override'); }); } public function refreshMappingFor(string $source, ?string $sourceValue): void { $source = trim($source); $sourceValue = trim((string) $sourceValue); if ($source === '' || $sourceValue === '') { return; } $stats = $this->connection->table('fin_transactions') ->whereNull('deleted_at') ->where('source', $source) ->where('source_value', $sourceValue) ->selectRaw('COUNT(*) AS txn_count, COALESCE(SUM(income), 0) AS income_sum, COALESCE(SUM(expense), 0) AS expense_sum') ->first(); $map = $this->connection->table('fin_account_map') ->where('source', $source) ->where('source_value', $sourceValue); if ((int) ($stats->txn_count ?? 0) === 0) { $map->delete(); return; } $now = now(); $map->update([ 'txn_count' => (int) $stats->txn_count, 'income_sum' => round((float) $stats->income_sum, 2), 'expense_sum' => round((float) $stats->expense_sum, 2), 'updated_at' => $now, ]); } }