Integrate feature/limeng-stock-quote-billing-rules at bca3c074 and port the snapshot purpose of feature/jushuitan-cost-price-snapshot at 4c2c422c onto current main. Keep authoritative operation history and accounting readers separate from observations; retain deployment guards and existing source data.
43 lines
2.1 KiB
PHP
43 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\Repositories;
|
|
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Modules\EcommerceFinance\Services\JushuitanCostPriceSnapshotDiffer;
|
|
|
|
class JushuitanCostPriceObservationRepository
|
|
{
|
|
public function __construct(private readonly GenericBusinessMirrorRepository $mirror) {}
|
|
|
|
/** 仅当前页每个源商品最近 20 条观测;不混入正式财务取价历史。 */
|
|
public function attach(array $rows): void
|
|
{
|
|
foreach ($rows as $row) {
|
|
$row->jushuitan_cost_price_observations = [];
|
|
}
|
|
$db = $this->mirror->connection();
|
|
if ($rows === [] || ! Schema::connection($db->getName())->hasTable(JushuitanCostPriceSnapshotDiffer::OBSERVATIONS)) {
|
|
return;
|
|
}
|
|
$keys = collect($rows)->pluck('_mirror_key')->filter()->unique()->values()->all();
|
|
if ($keys === []) {
|
|
return;
|
|
}
|
|
$ranked = $db->table(JushuitanCostPriceSnapshotDiffer::OBSERVATIONS)
|
|
->whereIn('source_key', $keys)
|
|
->select('*')->selectRaw('ROW_NUMBER() OVER (PARTITION BY source_key ORDER BY observed_at DESC, id DESC) AS observation_rank');
|
|
$events = $db->query()->fromSub($ranked, 'ranked')->where('observation_rank', '<=', 20)
|
|
->orderBy('observed_at', 'desc')->get()->groupBy('source_key');
|
|
foreach ($rows as $row) {
|
|
$row->jushuitan_cost_price_observations = ($events->get($row->_mirror_key ?? '') ?? collect())->map(static fn ($event) => [
|
|
'id' => $event->id, 'source' => '镜像价格观测(非完整改价历史)',
|
|
'record_type_label' => '观测到成本价变化', 'effect_start_time' => $event->observed_at,
|
|
'before_price' => $event->before_price, 'after_price' => $event->after_price,
|
|
'diff_amount' => (float) $event->after_price - (float) $event->before_price,
|
|
'operator' => '-', 'operation' => '镜像快照比较',
|
|
'remark' => '上次观测:' . $event->previous_observed_at . ';本次为发现时间,不是真实改价时间。',
|
|
])->all();
|
|
}
|
|
}
|
|
}
|