diff --git a/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php b/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php index d117ee72b..939dfbc0c 100644 --- a/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php +++ b/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php @@ -443,6 +443,196 @@ class SupplierPayableOverrideStore ->all(); } + /** + * 按供应商、月份和对账人直接从数据库读取,避免财务端页面加载整张历史宽表。 + * + * @return array> + */ + public function listRowsForSupplierFilters( + string $dataset, + string $supplier, + int $companyId, + string $month = '', + string $reconciler = '', + bool $sendTimeFirst = false, + ): array { + $query = $this->supplierFilteredQuery( + $dataset, + $supplier, + $companyId, + $month, + $reconciler, + $sendTimeFirst, + ); + + return $query + ->orderBy('id') + ->get(['record_key', 'values']) + ->map(static function (object $record): array { + $values = json_decode((string) $record->values, true) ?: []; + $values['_action_key'] = (string) $record->record_key; + + return $values; + }) + ->all(); + } + + public function countRowsForSupplierFilters( + string $dataset, + string $supplier, + int $companyId, + string $month = '', + string $reconciler = '', + bool $sendTimeFirst = false, + ): int { + return (int) $this->supplierFilteredQuery( + $dataset, + $supplier, + $companyId, + $month, + $reconciler, + $sendTimeFirst, + )->count(); + } + + /** @return list */ + public function recordKeysForSupplierMonth( + string $dataset, + string $supplier, + string $month, + int $companyId, + ): array { + if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { + return []; + } + + $connection = $this->connection(); + $query = $connection->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset); + $this->whereSupplier($query, $supplier); + + return $query + ->whereRaw( + $this->monthExpression($connection, true) . ' = ?', + [$month], + ) + ->orderBy('id') + ->pluck('record_key') + ->map(static fn (mixed $value): string => (string) $value) + ->all(); + } + + /** @return list */ + public function distinctJsonValues(string $dataset, int $companyId, string $field): array + { + if (preg_match('/^[A-Za-z0-9_]+$/', $field) !== 1) { + return []; + } + + $connection = $this->connection(); + $expression = $connection->getDriverName() === 'mysql' + ? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.{$field}')))" + : "TRIM(json_extract(`values`, '$.{$field}'))"; + $values = $connection->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset) + ->selectRaw("{$expression} AS value") + ->distinct() + ->pluck('value'); + + $normalized = $values + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter(static fn (string $value): bool => $value !== '') + ->unique() + ->values() + ->all(); + sort($normalized, SORT_NATURAL | SORT_FLAG_CASE); + + return $normalized; + } + + /** + * @return list + */ + public function distinctMonths( + string $dataset, + int $companyId, + bool $sendTimeFirst = false, + string $supplier = '', + ): array { + $connection = $this->connection(); + $query = $connection->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset); + if ($supplier !== '') { + $this->whereSupplier($query, $supplier); + } + + $schema = Schema::connection($connection->getName()); + if (! $sendTimeFirst + && $connection->getDriverName() === 'mysql' + && $schema->hasColumn('supplier_payable_overrides', 'summary_month_key')) { + $values = $query + ->whereNotNull('summary_month_key') + ->where('summary_month_key', '<>', '') + ->distinct() + ->pluck('summary_month_key'); + } else { + $expression = $this->monthExpression($connection, $sendTimeFirst); + $values = $query + ->selectRaw("{$expression} AS month_key") + ->distinct() + ->pluck('month_key'); + } + $months = $values + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter(static fn (string $value): bool => preg_match('/^\d{4}-\d{2}$/', $value) === 1) + ->unique() + ->values() + ->all(); + rsort($months); + + return $months; + } + + /** @return list */ + public function distinctSuppliersForFilters( + string $dataset, + int $companyId, + string $month = '', + string $reconciler = '', + bool $sendTimeFirst = false, + ): array { + $connection = $this->connection(); + $query = $connection->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset); + if ($month !== '') { + $this->whereMonth($query, $connection, $month, $sendTimeFirst); + } + if ($reconciler !== '') { + $query->where('values->reconciler', $reconciler); + } + + $expression = $connection->getDriverName() === 'mysql' + ? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.supplier')))" + : "TRIM(json_extract(`values`, '$.supplier'))"; + $values = $query + ->selectRaw("{$expression} AS supplier_name") + ->distinct() + ->pluck('supplier_name'); + $suppliers = $values + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter(static fn (string $value): bool => $value !== '') + ->unique() + ->values() + ->all(); + sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE); + + return $suppliers; + } + /** * 只返回指定账期涉及的供应商,供月度催办统计使用。 * @@ -660,6 +850,73 @@ class SupplierPayableOverrideStore return DB::connection(config('database.supplier_payable_maintenance_connection')); } + private function supplierFilteredQuery( + string $dataset, + string $supplier, + int $companyId, + string $month, + string $reconciler, + bool $sendTimeFirst, + ): \Illuminate\Database\Query\Builder { + $connection = $this->connection(); + $query = $connection->table('supplier_payable_overrides') + ->where('company_id', $companyId) + ->where('dataset', $dataset); + $this->whereSupplier($query, $supplier); + if ($month !== '') { + $this->whereMonth($query, $connection, $month, $sendTimeFirst); + } + if ($reconciler !== '') { + $query->where('values->reconciler', $reconciler); + } + + return $query; + } + + private function whereMonth( + \Illuminate\Database\Query\Builder $query, + ConnectionInterface $connection, + string $month, + bool $sendTimeFirst, + ): void { + $schema = Schema::connection($connection->getName()); + if (! $sendTimeFirst + && $connection->getDriverName() === 'mysql' + && $schema->hasColumn('supplier_payable_overrides', 'summary_month_key')) { + $query->where('summary_month_key', $month); + + return; + } + + $query->whereRaw( + $this->monthExpression($connection, $sendTimeFirst) . ' = ?', + [$month], + ); + } + + private function monthExpression(ConnectionInterface $connection, bool $sendTimeFirst): string + { + if ($connection->getDriverName() === 'mysql') { + $summaryMonth = 'LEFT(REPLACE(REPLACE(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.summary_month")), "/", "-"), ".", "-"), 7)'; + if (! $sendTimeFirst) { + return $summaryMonth; + } + + return 'CASE WHEN COALESCE(NULLIF(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.send_time")), "null"), ""), "") <> "" ' + . 'THEN LEFT(REPLACE(REPLACE(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.send_time")), "/", "-"), ".", "-"), 7) ' + . 'ELSE ' . $summaryMonth . ' END'; + } + + $summaryMonth = "substr(replace(replace(json_extract(`values`, '$.summary_month'), '/', '-'), '.', '-'), 1, 7)"; + if (! $sendTimeFirst) { + return $summaryMonth; + } + + return "CASE WHEN COALESCE(NULLIF(NULLIF(json_extract(`values`, '$.send_time'), 'null'), ''), '') <> '' " + . "THEN substr(replace(replace(json_extract(`values`, '$.send_time'), '/', '-'), '.', '-'), 1, 7) " + . 'ELSE ' . $summaryMonth . ' END'; + } + private function whereSupplier(\Illuminate\Database\Query\Builder $query, string $supplier): void { if ($this->supportsSupplierNameIndex()) { diff --git a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php index 88a1387bf..88c072fe4 100644 --- a/modules/EcommerceFinance/View/SupplierReconciliationPageData.php +++ b/modules/EcommerceFinance/View/SupplierReconciliationPageData.php @@ -57,99 +57,43 @@ class SupplierReconciliationPageData public function financeData(): array { $companyId = $this->companyId(); - $mine = $this->store->listRows( - PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation', - $companyId, - ); - $returnRows = $this->store->listRows( - PayablesFinalActions::DATASET_PREFIX . 'supplier:return-reconciliation', - $companyId, - ); + $mineDataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation'; + $returnDataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:return-reconciliation'; - $reconcilers = []; - foreach ($mine as $row) { - $name = trim((string) ($row['reconciler'] ?? '')); - if ($name !== '') { - $reconcilers[$name] = true; - } - } - foreach ($returnRows as $row) { - $name = trim((string) ($row['reconciler'] ?? '')); - if ($name !== '') { - $reconcilers[$name] = true; - } - } - $reconcilers = array_keys($reconcilers); - sort($reconcilers); - - $months = []; - $returnSupplierMonths = []; - $returnSupplierMonthRows = []; - foreach ($returnRows as $row) { - $returnMonth = $this->returnRowMonth($row); - $supplier = trim((string) ($row['supplier'] ?? '')); - if ($returnMonth !== '') { - $months[$returnMonth] = true; - } - if ($returnMonth !== '' && $supplier !== '') { - $returnSupplierMonths[$supplier][$returnMonth] = - (int) ($returnSupplierMonths[$supplier][$returnMonth] ?? 0) + 1; - $returnSupplierMonthRows[$supplier][$returnMonth][] = $row; - } - } - foreach ($mine as $row) { - $month = substr(trim((string) ($row['summary_month'] ?? '')), 0, 7); - if ($month !== '') { - $months[$month] = true; - } - } - $months = array_keys($months); - rsort($months); + $reconcilers = $this->financeReconcilers($mineDataset, $returnDataset, $companyId); + $months = $this->financeMonths($mineDataset, $returnDataset, $companyId); $month = trim((string) request()->query('month', '')); if ($month !== '' && preg_match('/^\d{4}-\d{2}$/', $month) === 1) { - $mine = array_values(array_filter( - $mine, - static fn (array $row): bool => substr(trim((string) ($row['summary_month'] ?? '')), 0, 7) === $month, - )); + // Keep the selected month for database-side filtering. } else { $month = ''; } $reconciler = trim((string) request()->query('reconciler', '')); - if ($reconciler !== '') { - $mine = array_values(array_filter( - $mine, - static fn (array $row): bool => trim((string) ($row['reconciler'] ?? '')) === $reconciler, - )); - } - - $filteredReturnRows = []; - foreach ($returnRows as $row) { - if ($month !== '' && $this->returnRowMonth($row) !== $month) { - continue; - } - if ($reconciler !== '' && trim((string) ($row['reconciler'] ?? '')) !== $reconciler) { - continue; - } - $filteredReturnRows[] = $row; - } $suppliers = []; - foreach ($mine as $row) { - $name = trim((string) ($row['supplier'] ?? '')); - if ($name !== '') { - $suppliers[$name] = true; - } - } if ($month === '' && $reconciler === '') { - foreach ($this->statements->uploadedSuppliers($companyId) as $name) { + $suppliers = array_fill_keys( + $this->financeSupplierNames($mineDataset, $returnDataset, $companyId), + true, + ); + } else { + foreach ($this->store->distinctSuppliersForFilters( + $mineDataset, + $companyId, + $month, + $reconciler, + ) as $name) { $suppliers[$name] = true; } - } - foreach ($filteredReturnRows as $row) { - $name = trim((string) ($row['supplier'] ?? '')); - if ($name !== '') { + foreach ($this->store->distinctSuppliersForFilters( + $returnDataset, + $companyId, + $month, + $reconciler, + true, + ) as $name) { $suppliers[$name] = true; } } @@ -178,9 +122,17 @@ class SupplierReconciliationPageData } $detail = null; + $mine = []; $comparisonFilter = ''; $comparisonFilters = []; if ($selected !== '') { + $mine = $this->store->listRowsForSupplierFilters( + $mineDataset, + $selected, + $companyId, + $month, + $reconciler, + ); $detail = $this->detail($mine, $selected, $companyId); $comparisonFilter = $this->normalizeComparisonFilter( request()->query('comparison_filter', ''), @@ -206,23 +158,38 @@ class SupplierReconciliationPageData $returnCounts = []; $returnConfirmationSummaries = []; foreach ($supplierListRows as $supplier) { - $supplierMonths = array_keys((array) ($returnSupplierMonths[$supplier] ?? [])); - rsort($supplierMonths); + $supplierMonths = $this->store->distinctMonths( + $returnDataset, + $companyId, + true, + $supplier, + ); $latestMonth = (string) ($supplierMonths[0] ?? ''); $displayMonth = $month !== '' ? $month : $latestMonth; + $returnKeys = $displayMonth !== '' + ? $this->store->recordKeysForSupplierMonth( + $returnDataset, + $supplier, + $displayMonth, + $companyId, + ) + : []; $returnLatestMonths[$supplier] = $latestMonth; $returnDisplayMonths[$supplier] = $displayMonth; - $returnCounts[$supplier] = (int) ($returnSupplierMonths[$supplier][$displayMonth] ?? 0); - $displayRows = (array) ($returnSupplierMonthRows[$supplier][$displayMonth] ?? []); + $returnCounts[$supplier] = count($returnKeys); $returnConfirmationSummaries[$supplier] = $this->returnConfirmationSummary( - $displayRows, - $displayRows === [] ? [] : $this->returnConfirmations->statuses($supplier, $companyId), + array_map( + static fn (string $key): array => ['_action_key' => $key], + $returnKeys, + ), + $returnKeys === [] ? [] : $this->returnConfirmations->statuses($supplier, $companyId), ); } - $selectedMonths = array_keys((array) ($returnSupplierMonths[$selected] ?? [])); - rsort($selectedMonths); + $selectedMonths = $selected !== '' + ? $this->store->distinctMonths($returnDataset, $companyId, true, $selected) + : []; $selectedLatestReturnMonth = (string) ($selectedMonths[0] ?? ''); $returnPushMonth = $month !== '' ? $month @@ -463,26 +430,18 @@ class SupplierReconciliationPageData */ public function financeDetailForFilters(string $supplier, int $companyId, array $input): array { - $mine = $this->store->listRows( - PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation', - $companyId, - ); - $month = $this->filterText($input['month'] ?? ''); - if ($month !== '' && preg_match('/^\d{4}-\d{2}$/', $month) === 1) { - $mine = array_values(array_filter( - $mine, - static fn (array $row): bool => substr(trim((string) ($row['summary_month'] ?? '')), 0, 7) === $month, - )); + if ($month !== '' && preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { + $month = ''; } - $reconciler = $this->filterText($input['reconciler'] ?? ''); - if ($reconciler !== '') { - $mine = array_values(array_filter( - $mine, - static fn (array $row): bool => trim((string) ($row['reconciler'] ?? '')) === $reconciler, - )); - } + $mine = $this->store->listRowsForSupplierFilters( + PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation', + $supplier, + $companyId, + $month, + $reconciler, + ); return $this->filterComparisonDetail( $this->detail($mine, $supplier, $companyId), @@ -501,19 +460,27 @@ class SupplierReconciliationPageData string $month, string $reconciler, ): array { - $allRows = $this->returnRows($supplier, $companyId); + $dataset = PayablesFinalActions::DATASET_PREFIX . 'supplier:return-reconciliation'; + $allRows = $this->store->listRowsForSupplierFilters( + $dataset, + $supplier, + $companyId, + $month, + $reconciler, + true, + ); + $allSupplierRows = $this->store->countRowsForSupplierFilters( + $dataset, + $supplier, + $companyId, + '', + '', + true, + ); $statuses = $this->returnConfirmations->statuses($supplier, $companyId); $rows = []; foreach ($allRows as $row) { - $rowMonth = $this->returnRowMonth($row); - if ($month !== '' && $rowMonth !== $month) { - continue; - } - if ($reconciler !== '' && trim((string) ($row['reconciler'] ?? '')) !== $reconciler) { - continue; - } - $row['_status'] = $statuses[(string) ($row['_action_key'] ?? '')] ?? ''; $rows[] = $row; } @@ -522,7 +489,7 @@ class SupplierReconciliationPageData $supplier, $rows, $this->returnFilters([]), - count($allRows), + $allSupplierRows, 'finance_return_page', ); } @@ -1359,6 +1326,61 @@ class SupplierReconciliationPageData : ''; } + /** @return list */ + private function financeReconcilers(string $mineDataset, string $returnDataset, int $companyId): array + { + return cache()->remember( + "supplier-reconciliation:v2:{$companyId}:reconcilers", + now()->addMinutes(10), + function () use ($mineDataset, $returnDataset, $companyId): array { + $reconcilers = array_values(array_unique(array_merge( + $this->store->distinctJsonValues($mineDataset, $companyId, 'reconciler'), + $this->store->distinctJsonValues($returnDataset, $companyId, 'reconciler'), + ))); + sort($reconcilers); + + return $reconcilers; + }, + ); + } + + /** @return list */ + private function financeMonths(string $mineDataset, string $returnDataset, int $companyId): array + { + return cache()->remember( + "supplier-reconciliation:v2:{$companyId}:months", + now()->addMinutes(10), + function () use ($mineDataset, $returnDataset, $companyId): array { + $months = array_values(array_unique(array_merge( + $this->store->distinctMonths($mineDataset, $companyId), + $this->store->distinctMonths($returnDataset, $companyId, true), + ))); + rsort($months); + + return $months; + }, + ); + } + + /** @return list */ + private function financeSupplierNames(string $mineDataset, string $returnDataset, int $companyId): array + { + $suppliers = array_fill_keys( + $this->store->distinctSuppliersInDataset($mineDataset, $companyId), + true, + ); + foreach ($this->statements->uploadedSuppliers($companyId) as $name) { + $suppliers[$name] = true; + } + foreach ($this->store->distinctSuppliersInDataset($returnDataset, $companyId) as $name) { + $suppliers[$name] = true; + } + $names = array_keys($suppliers); + sort($names); + + return $names; + } + private function companyId(): int { return (int) (company_id() ?: 1);