CaiWuXiTong/modules/EcommerceFinance/Services/SupplierPayableOverrideStore.php
苏木 ded2789a17 fix: 降低月度未定价自动生成内存占用
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-02 19:21:15 +08:00

690 lines
26 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\EcommerceFinance\Services;
use Closure;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class SupplierPayableOverrideStore
{
private ?bool $supplierNameIndexAvailable = null;
public function key(string $dataset, array $row): string
{
if (isset($row['sourceId']) && $row['sourceId'] !== '') {
return 'id:' . (string) ($row['recordType'] ?? '') . ':' . (string) $row['sourceId'];
}
if (isset($row['id']) && $row['id'] !== '') {
return 'id:' . (string) $row['id'];
}
$immutable = $row;
unset($immutable['_action_key'], $immutable['_overridden']);
return 'hash:' . hash('sha256', json_encode($immutable, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
/** @param array<int,array<string,mixed>> $rows */
public function decorate(string $dataset, array $rows, int $companyId): array
{
if ($rows === []) {
return [];
}
$keys = [];
foreach ($rows as $row) {
$keys[] = $this->key($dataset, $row);
}
$overrides = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset)
->whereIn('record_key', $keys)
->get()
->keyBy('record_key');
foreach ($rows as $index => &$row) {
$key = $keys[$index];
$row['_action_key'] = $key;
$override = $overrides->get($key);
if ($override) {
$values = json_decode((string) $override->values, true) ?: [];
$row = array_merge($row, $values);
$row['_overridden'] = true;
} else {
$row['_overridden'] = false;
}
}
unset($row);
return $rows;
}
/** @return array{created:int,updated:int} */
public function save(string $dataset, string $recordKey, array $values, int $companyId, ?int $userId, string $source = 'manual'): array
{
$connection = $this->connection();
$existing = $connection->table('supplier_payable_overrides')
->where(['company_id' => $companyId, 'dataset' => $dataset, 'record_key' => $recordKey])
->first();
$before = $existing ? (json_decode((string) $existing->values, true) ?: []) : null;
$now = now();
$connection->transaction(function () use ($connection, $existing, $dataset, $recordKey, $values, $companyId, $userId, $now, $source, $before): void {
$connection->table('supplier_payable_overrides')->updateOrInsert(
['company_id' => $companyId, 'dataset' => $dataset, 'record_key' => $recordKey],
[
'values' => json_encode($values, JSON_UNESCAPED_UNICODE),
'updated_by' => $userId,
'created_by' => $existing->created_by ?? $userId,
'created_at' => $existing->created_at ?? $now,
'updated_at' => $now,
],
);
$connection->table('supplier_payable_override_events')->insert([
'company_id' => $companyId,
'dataset' => $dataset,
'record_key' => $recordKey,
'source' => $source,
'before_values' => $before === null ? null : json_encode($before, JSON_UNESCAPED_UNICODE),
'after_values' => json_encode($values, JSON_UNESCAPED_UNICODE),
'user_id' => $userId,
'created_at' => $now,
]);
});
return ['created' => $existing ? 0 : 1, 'updated' => $existing ? 1 : 0];
}
/**
* 批量保存(大文件导入用):按记录键 upsert,并批量写审计事件。
*
* @param array<string,array<string,mixed>> $records 记录键 => 字段值
* @return array{created:int,updated:int}
*/
public function saveBatch(string $dataset, array $records, int $companyId, ?int $userId, string $source = 'import'): array
{
if ($records === []) {
return ['created' => 0, 'updated' => 0];
}
$connection = $this->connection();
$now = now();
$created = 0;
$updated = 0;
$connection->transaction(function () use ($connection, $dataset, $records, $companyId, $userId, $source, $now, &$created, &$updated): void {
$existing = [];
foreach (array_chunk(array_keys($records), 1000) as $keys) {
foreach ($connection->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset)
->whereIn('record_key', $keys)
->get() as $row) {
$existing[(string) $row->record_key] = $row;
}
}
$upserts = [];
$events = [];
foreach ($records as $key => $values) {
$before = $existing[$key] ?? null;
$before === null ? $created++ : $updated++;
$encoded = $this->encodeValues($values);
$upserts[] = [
'company_id' => $companyId,
'dataset' => $dataset,
'record_key' => $key,
'values' => $encoded,
'created_by' => $before->created_by ?? $userId,
'updated_by' => $userId,
'created_at' => $before->created_at ?? $now,
'updated_at' => $now,
];
$events[] = [
'company_id' => $companyId,
'dataset' => $dataset,
'record_key' => $key,
'source' => $source,
'before_values' => $before === null ? null : (string) $before->values,
'after_values' => $encoded,
'user_id' => $userId,
'created_at' => $now,
];
}
foreach (array_chunk($upserts, 500) as $chunk) {
$connection->table('supplier_payable_overrides')->upsert(
$chunk,
['company_id', 'dataset', 'record_key'],
['values', 'updated_by', 'updated_at'],
);
}
foreach (array_chunk($events, 500) as $chunk) {
$connection->table('supplier_payable_override_events')->insert($chunk);
}
});
return ['created' => $created, 'updated' => $updated];
}
public function transaction(Closure $callback): mixed
{
return $this->connection()->transaction($callback);
}
/**
* 按记录键批量移出某个数据集,并保留删除前值供追溯。
*
* @param list<string> $recordKeys
*/
public function deleteBatch(
string $dataset,
array $recordKeys,
int $companyId,
?int $userId = null,
string $source = 'cycle',
): int {
$recordKeys = array_values(array_unique(array_filter(array_map(
static fn (mixed $key): string => trim((string) $key),
$recordKeys,
))));
if ($recordKeys === []) {
return 0;
}
$connection = $this->connection();
$now = now();
$deleted = 0;
$connection->transaction(function () use (
$connection,
$dataset,
$recordKeys,
$companyId,
$userId,
$source,
$now,
&$deleted,
): void {
foreach (array_chunk($recordKeys, 500) as $keys) {
$rows = $connection->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset)
->whereIn('record_key', $keys)
->get();
if ($rows->isEmpty()) {
continue;
}
$events = [];
foreach ($rows as $row) {
$events[] = [
'company_id' => $companyId,
'dataset' => $dataset,
'record_key' => (string) $row->record_key,
'source' => $source,
'before_values' => (string) $row->values,
'after_values' => '{}',
'user_id' => $userId,
'created_at' => $now,
];
}
$connection->table('supplier_payable_override_events')->insert($events);
$deleted += $connection->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset)
->whereIn('record_key', $keys)
->delete();
}
});
return $deleted;
}
/**
* 整份替换某个数据集(厂家对账单:以最新一版为准),不写逐行审计事件。
*
* @param array<string,array<string,mixed>> $records
*/
public function replaceAll(string $dataset, array $records, int $companyId, ?int $userId): int
{
$connection = $this->connection();
$now = now();
$rows = [];
foreach ($records as $key => $values) {
$rows[] = [
'company_id' => $companyId,
'dataset' => $dataset,
'record_key' => (string) $key,
'values' => $this->encodeValues($values),
'created_by' => $userId,
'updated_by' => $userId,
'created_at' => $now,
'updated_at' => $now,
];
}
$connection->transaction(function () use ($connection, $dataset, $companyId, $rows): void {
$connection->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset)
->delete();
foreach (array_chunk($rows, 500) as $chunk) {
$connection->table('supplier_payable_overrides')->insert($chunk);
}
});
return count($rows);
}
/** @return list<string> 某个前缀下已有的数据集名 */
public function datasetsWithPrefix(string $prefix, int $companyId): array
{
return $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', 'like', addcslashes($prefix, '%_\\') . '%')
->distinct()
->orderBy('dataset')
->pluck('dataset')
->map(static fn (mixed $value): string => (string) $value)
->all();
}
/** 值编码为 JSON;脏字节(非法 UTF-8)用替代字符,避免整批写入失败。 */
private function encodeValues(array $values): string
{
return (string) json_encode($values, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
}
/**
* 列出某个数据集已经保存的全部记录(「终版」目录的独立数据就是这些行)。
*
* @return array<int,array<string,mixed>>
*/
public function listRows(string $dataset, int $companyId): array
{
return $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset)
->orderBy('id')
->get()
->map(static function (object $record): array {
$values = json_decode((string) $record->values, true) ?: [];
$values['_action_key'] = (string) $record->record_key;
return $values;
})
->all();
}
/**
* 只读取指定账期仍未定价的记录,避免月度自动定价把整张对账宽表载入内存。
*
* @return array<int,array<string,mixed>>
*/
public function listUnpricedRowsForMonth(
string $dataset,
int $companyId,
string $month,
string $amountField,
string $guessAmountField,
): 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);
$schema = Schema::connection($connection->getName());
if ($connection->getDriverName() === 'mysql'
&& $schema->hasColumn('supplier_payable_overrides', 'summary_month_key')) {
$query->where('summary_month_key', $month);
} else {
$monthExpression = $connection->getDriverName() === 'mysql'
? 'LEFT(REPLACE(REPLACE(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.summary_month")), "/", "-"), ".", "-"), 7)'
: "substr(replace(replace(json_extract(`values`, '$.summary_month'), '/', '-'), '.', '-'), 1, 7)";
$query->whereRaw("{$monthExpression} = ?", [$month]);
}
$amountExpression = $connection->getDriverName() === 'mysql'
? "CAST(COALESCE(NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.{$amountField}'))), ''), '0') AS DECIMAL(20,4))"
: "CAST(COALESCE(NULLIF(TRIM(json_extract(`values`, '$.{$amountField}')), ''), '0') AS REAL)";
$guessAmountExpression = $connection->getDriverName() === 'mysql'
? "CAST(COALESCE(NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.{$guessAmountField}'))), ''), '0') AS DECIMAL(20,4))"
: "CAST(COALESCE(NULLIF(TRIM(json_extract(`values`, '$.{$guessAmountField}')), ''), '0') AS REAL)";
return $query
->whereRaw("{$amountExpression} = 0")
->whereRaw("{$guessAmountExpression} > 0")
->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();
}
/**
* 只读取指定供应商的数据,避免厂家页面把整个共享数据集解码到 PHP。
*
* @return array<int,array<string,mixed>>
*/
public function listRowsForSupplier(string $dataset, string $supplier, int $companyId): array
{
$query = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
$this->whereSupplier($query, $supplier);
return $query
->orderBy('id')
->get()
->map(static function (object $record): array {
$values = json_decode((string) $record->values, true) ?: [];
$values['_action_key'] = (string) $record->record_key;
return $values;
})
->all();
}
/**
* 只读取指定厂家、月份的终版数据,避免厂家分享页加载整个历史数据集。
*
* @return array<int,array<string,mixed>>
*/
public function listRowsForSupplierMonth(
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);
$monthExpression = $connection->getDriverName() === 'mysql'
? '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 LEFT(REPLACE(REPLACE(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.summary_month")), "/", "-"), ".", "-"), 7) END'
: "CASE WHEN COALESCE(NULLIF(NULLIF(json_extract(`values`, '$.send_time'), 'null'), ''), '') <> '' "
. "THEN substr(replace(replace(json_extract(`values`, '$.send_time'), '/', '-'), '.', '-'), 1, 7) "
. "ELSE substr(replace(replace(json_extract(`values`, '$.summary_month'), '/', '-'), '.', '-'), 1, 7) END";
return $query
->whereRaw("{$monthExpression} = ?", [$month])
->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();
}
/**
* 只返回指定账期涉及的供应商,供月度催办统计使用。
*
* @return list<string>
*/
public function distinctSuppliersForMonth(
string $dataset,
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);
$schema = Schema::connection($connection->getName());
if ($connection->getDriverName() === 'mysql'
&& $schema->hasColumn('supplier_payable_overrides', 'summary_month_key')
&& $schema->hasColumn('supplier_payable_overrides', 'supplier_name_key')) {
$values = $query
->where('summary_month_key', $month)
->whereNotNull('supplier_name_key')
->where('supplier_name_key', '<>', '')
->distinct()
->pluck('supplier_name_key');
} else {
$monthExpression = $connection->getDriverName() === 'mysql'
? 'LEFT(REPLACE(REPLACE(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.summary_month")), "/", "-"), ".", "-"), 7)'
: "substr(replace(replace(json_extract(`values`, '$.summary_month'), '/', '-'), '.', '-'), 1, 7)";
$supplierExpression = $connection->getDriverName() === 'mysql'
? 'TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, "$.supplier")))'
: "TRIM(json_extract(`values`, '$.supplier'))";
$values = $query
->whereRaw("{$monthExpression} = ?", [$month])
->selectRaw("{$supplierExpression} AS supplier")
->distinct()
->pluck('supplier');
}
$suppliers = $values
->map(static fn (mixed $value): string => trim((string) $value))
->filter(static fn (string $value): bool => $value !== '')
->unique()
->values()
->all();
natcasesort($suppliers);
return array_values($suppliers);
}
/** @return list<string> */
public function distinctSuppliersInDataset(string $dataset, int $companyId): array
{
$query = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
if ($this->supportsSupplierNameIndex()) {
$values = $query
->whereNotNull('supplier_name_key')
->where('supplier_name_key', '<>', '')
->distinct()
->pluck('supplier_name_key');
} else {
$expression = $this->connection()->getDriverName() === 'mysql'
? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.supplier')))"
: "TRIM(json_extract(\"values\", '$.supplier'))";
$values = $query
->selectRaw("DISTINCT {$expression} AS supplier_name")
->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;
}
/**
* 按数据库分页读取终版明细,避免宽表在历史数据较多时整表解码。
*
* @return array{rows:list<array<string,mixed>>,total:int}
*/
public function paginateRows(
string $dataset,
int $companyId,
int $perPage,
int $page,
string $keyword = '',
bool $latestFirst = false,
array $exactFilters = [],
): array {
$perPage = max(1, min($perPage, 200));
$page = max(1, $page);
$query = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
foreach ($exactFilters as $field => $value) {
if ($value === null || $value === '') {
continue;
}
$query->where('values->' . $field, $value);
}
$keyword = trim($keyword);
if ($keyword !== '') {
$query->where('values', 'like', '%' . $keyword . '%');
}
$total = (int) (clone $query)->count();
$page = min($page, max((int) ceil($total / $perPage), 1));
if ($latestFirst && $this->connection()->getDriverName() === 'sqlite') {
$query->orderByRaw(
"(json_extract(`values`, '$.summary_month') IS NULL"
. " OR json_extract(`values`, '$.summary_month') IN ('', 'null'))"
)
->orderByRaw("json_extract(`values`, '$.summary_month') DESC")
->orderByRaw(
"(json_extract(`values`, '$.date') IS NULL"
. " OR json_extract(`values`, '$.date') IN ('', 'null'))"
)
->orderByRaw("json_extract(`values`, '$.date') DESC")
->orderByDesc('id');
} elseif ($latestFirst) {
$query->orderByRaw(
"(summary_month_key IS NULL OR summary_month_key IN ('', 'null'))"
)
->orderByDesc('summary_month_key')
->orderByRaw(
"(record_date_key IS NULL OR record_date_key IN ('', 'null'))"
)
->orderByDesc('record_date_key')
->orderByDesc('id');
} else {
$query->orderBy('id');
}
$rows = $query
->forPage($page, $perPage)
->get()
->map(static function (object $record): array {
$values = json_decode((string) $record->values, true) ?: [];
$values['_action_key'] = (string) $record->record_key;
return $values;
})
->all();
return ['rows' => $rows, 'total' => $total];
}
/**
* 按记录键读取一条本地业务记录,找不到时返回 null。
*
* @return array<string,mixed>|null
*/
public function findRow(string $dataset, string $recordKey, int $companyId): ?array
{
$record = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset)
->where('record_key', $recordKey)
->first();
if ($record === null) {
return null;
}
$values = json_decode((string) $record->values, true) ?: [];
$values['_action_key'] = (string) $record->record_key;
return $values;
}
/**
* 按 JSON 字段等值条件读取最新一条记录,避免财务页轮询时解码整个数据集。
*
* @param array<string,scalar> $criteria
* @return array<string,mixed>|null
*/
public function findLatestRow(
string $dataset,
array $criteria,
int $companyId,
): ?array {
$query = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
foreach ($criteria as $field => $value) {
$query->where('values->' . $field, $value);
}
$record = $query->orderByDesc('id')->first();
if ($record === null) {
return null;
}
$values = json_decode((string) $record->values, true) ?: [];
$values['_action_key'] = (string) $record->record_key;
return $values;
}
private function connection(): ConnectionInterface
{
return DB::connection(config('database.supplier_payable_maintenance_connection'));
}
private function whereSupplier(\Illuminate\Database\Query\Builder $query, string $supplier): void
{
if ($this->supportsSupplierNameIndex()) {
$query->where('supplier_name_key', $supplier);
return;
}
$expression = $this->connection()->getDriverName() === 'mysql'
? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.supplier')))"
: "TRIM(json_extract(\"values\", '$.supplier'))";
$query->whereRaw("{$expression} = ?", [$supplier]);
}
private function supportsSupplierNameIndex(): bool
{
if ($this->supplierNameIndexAvailable !== null) {
return $this->supplierNameIndexAvailable;
}
$schema = Schema::connection($this->connection()->getName());
$this->supplierNameIndexAvailable = $schema->hasTable('supplier_payable_overrides')
&& $schema->hasColumn('supplier_payable_overrides', 'supplier_name_key');
return $this->supplierNameIndexAvailable;
}
}