CaiWuXiTong/modules/EcommerceFinance/Services/JushuitanCostPriceSnapshotDiffer.php
limeng 4c2c422c78 feat(普通商品资料): 聚水潭成本价记录改为镜像快照比对
- 副本库 rpt.jst_sku 一商品一行、无历史;开放平台操作日志接口暂无授权
- 新增 JushuitanCostPriceSnapshotDiffer:ops_jst_sku 当前成本价与快照比对,
  变化写入 jushuitan_cost_price_history_rows(变更前/后/差额,时间取聚水潭 modified)
- 新表 jushuitan_cost_price_snapshots(迁移 + 运行时幂等建表)
- business-mirror:sync-jushuitan-cost-price-history 默认走 snapshot,
  JUSHUITAN_COST_PRICE_HISTORY_SOURCE=open_api 可切回接口
- 生产 cron 由每日 00:00 改为每 10 分钟
- 页面“聚水潭成本价记录”列显示最近一次变价(前→后 · 时间)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192A1X1EDtdzpaAVMhBj2nh
2026-10-08 11:04:26 +08:00

209 lines
8.4 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Modules\EcommerceFinance\Repositories\JushuitanCostPriceHistoryMirrorRepository;
use RuntimeException;
use Throwable;
/**
* 聚水潭成本价变价记录(快照比对版)。
*
* 副本库 rpt.jst_sku 每个商品只有一行、同步即覆盖,没有历史;聚水潭开放平台
* 操作日志接口暂无授权。因此改为:定时把共享镜像 ops_jst_sku 的当前成本价与
* 上一次快照比对,变了就记一条“变更前 → 变更后”,变更时间取聚水潭 modified
* (商品最后修改时间,比对频率足够高时即为改价时间)。
*
* 首次运行只建立基线快照,不产生变价记录;之后每次运行只记录新发生的变化。
*/
class JushuitanCostPriceSnapshotDiffer
{
public const SNAPSHOT_TABLE = 'jushuitan_cost_price_snapshots';
public function __construct(
private readonly JushuitanCostPriceHistoryMirrorRepository $history,
private readonly BusinessMirrorDatasetRegistry $datasets,
) {
}
/** @return array{status:string,mode:string,baseline_rows:int,new_skus:int,changes:int} */
public function sync(): array
{
$db = $this->history->connection();
$schema = Schema::connection($db->getName());
$productTable = $this->productTable();
$this->ensureSnapshotTable();
if (! $this->history->available()
|| ! $schema->hasTable(self::SNAPSHOT_TABLE)
|| ! $schema->hasTable($productTable)) {
throw new RuntimeException('jushuitan_cost_price_snapshot_schema_missing');
}
$state = $this->history->state();
$baseline = ($state['initial_completed_at'] ?? null) === null;
$mode = $baseline ? 'full' : 'incremental';
$generation = (string) Str::uuid();
$this->history->startRun($mode, $generation, now(), now(), false);
try {
$changes = 0;
if (! $baseline) {
$changes = $this->recordChanges($productTable, $generation);
}
// 新出现的商品(含首次基线)只入快照,不算变价。
$newSkus = $this->insertNewSkus($productTable);
$this->history->complete($mode, $generation, now(), $newSkus, $changes);
return [
'status' => 'succeeded',
'mode' => $mode,
'baseline_rows' => $baseline ? $newSkus : 0,
'new_skus' => $baseline ? 0 : $newSkus,
'changes' => $changes,
];
} catch (Throwable $exception) {
$this->history->fail($exception::class);
throw $exception;
}
}
private function recordChanges(string $productTable, string $generation): int
{
$db = $this->history->connection();
$snapshot = self::SNAPSHOT_TABLE;
$rows = $db->select(
"SELECT p.sku_id_normalized, s.sku_id, s.i_id, s.name, s.properties_value, s.sku_type,
p.cost_price AS before_price,
CAST(s.cost_price AS DECIMAL(20,4)) AS after_price,
s.modified
FROM `{$productTable}` s
JOIN `{$snapshot}` p ON p.sku_id_normalized = UPPER(TRIM(s.sku_id))
WHERE NOT (CAST(s.cost_price AS DECIMAL(20,4)) <=> p.cost_price)",
[],
false,
);
if ($rows === []) {
return 0;
}
$now = now();
$seen = [];
$records = [];
foreach ($rows as $row) {
$sku = (string) $row->sku_id_normalized;
if (isset($seen[$sku])) {
continue;
}
$seen[$sku] = true;
$before = $row->before_price === null ? null : (float) $row->before_price;
$after = $row->after_price === null ? null : (float) $row->after_price;
$operatedAt = $row->modified ?? $now->format('Y-m-d H:i:s');
$values = [
'operation_id' => 'snap:' . hash('sha256', implode('|', [
$sku, (string) $row->before_price, (string) $row->after_price, (string) $operatedAt,
])),
'sku_id' => trim((string) $row->sku_id),
'sku_id_normalized' => $sku,
'i_id' => $this->nullable($row->i_id ?? null),
'product_name' => $this->nullable($row->name ?? null),
'properties_value' => $this->nullable($row->properties_value ?? null),
'sku_type' => $this->nullable($row->sku_type ?? null),
'operation_type' => '成本价变更',
'operation_description' => sprintf(
'成本价 %s → %s',
$before === null ? '空' : number_format($before, 2, '.', ''),
$after === null ? '空' : number_format($after, 2, '.', ''),
),
'operator_name' => null,
'operated_at' => $operatedAt,
'before_price' => $row->before_price,
'after_price' => $row->after_price,
'diff_amount' => $before === null || $after === null ? null : round($after - $before, 4),
];
$records[] = $values + [
'_mirror_generation' => $generation,
'row_hash' => hash('sha256', json_encode($values, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)),
'_mirror_synced_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
}
foreach (array_chunk($records, 500) as $chunk) {
$db->transaction(function () use ($db, $chunk, $now): void {
$db->table(JushuitanCostPriceHistoryMirrorRepository::TABLE)->upsert(
$chunk,
['operation_id'],
['row_hash', '_mirror_synced_at', 'updated_at'],
);
foreach ($chunk as $record) {
$db->table(self::SNAPSHOT_TABLE)
->where('sku_id_normalized', $record['sku_id_normalized'])
->update([
'cost_price' => $record['after_price'],
'source_modified' => $record['operated_at'],
'captured_at' => $now,
'updated_at' => $now,
]);
}
});
}
return count($records);
}
private function insertNewSkus(string $productTable): int
{
$snapshot = self::SNAPSHOT_TABLE;
return $this->history->connection()->affectingStatement(
"INSERT IGNORE INTO `{$snapshot}`
(sku_id_normalized, sku_id, cost_price, source_modified, captured_at, created_at, updated_at)
SELECT UPPER(TRIM(s.sku_id)), MAX(s.sku_id), MAX(CAST(s.cost_price AS DECIMAL(20,4))),
MAX(s.modified), NOW(6), NOW(), NOW()
FROM `{$productTable}` s
LEFT JOIN `{$snapshot}` p ON p.sku_id_normalized = UPPER(TRIM(s.sku_id))
WHERE p.sku_id_normalized IS NULL
AND s.sku_id IS NOT NULL
AND TRIM(s.sku_id) <> ''
GROUP BY UPPER(TRIM(s.sku_id))",
);
}
/** 共享镜像可能尚未跑本迁移(本地 bootstrap 模式会跳过),这里幂等兜底建表。 */
private function ensureSnapshotTable(): void
{
$schema = Schema::connection($this->history->connection()->getName());
if ($schema->hasTable(self::SNAPSHOT_TABLE)) {
return;
}
$schema->create(self::SNAPSHOT_TABLE, function (Blueprint $table): void {
$table->string('sku_id_normalized', 191)->primary();
$table->string('sku_id', 255);
$table->decimal('cost_price', 20, 4)->nullable();
$table->dateTime('source_modified', 6)->nullable();
$table->dateTime('captured_at', 6);
$table->timestamps();
});
}
private function productTable(): string
{
return $this->datasets->get((string) config(
'upstream_mirrors.product_catalog.dataset_key',
'operations_replica.rpt.jst_sku',
))->targetTable();
}
private function nullable(mixed $value): ?string
{
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}