CaiWuXiTong/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php

138 lines
8.3 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
/** 按进仓时间同步商品级退回件;分页落暂存表,完整校验后才发布新快照。 */
class ReturnedParcelSynchronizer
{
public const DATASET = 'derived.courier-returned-parcels';
public const START = '2026-10-01';
public const TABLE = 'courier_returned_parcels';
public const STAGE = 'courier_returned_parcels_stage';
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) {}
public function sync(string $from, string $to, ?callable $progress = null, int $batchSize = 2000): array
{
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
$until = Carbon::parse($to, 'Asia/Shanghai')->addDay()->toDateString();
$state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first();
$cursor = $state ? json_decode($state->cursor ?? 'null', true) : null;
$resume = $state && in_array($state->status, ['running', 'failed'], true)
&& is_array($cursor) && ($cursor['from'] ?? null) === $from && ($cursor['to'] ?? null) === $to;
$generation = $resume ? $state->generation : (string) Str::uuid();
$last = $resume ? (int) $cursor['last_id'] : 0;
$batchSize = min(max($batchSize, 1), 2000);
$started = microtime(true);
$base = ['source_key' => 'operations_replica', 'source_object' => 'rpt.jst_returnAndRefundInfo + rpt.jst_returnAndRefundItem',
'target_table' => self::TABLE, 'status' => 'running', 'run_mode' => 'full', 'generation' => $generation,
'last_attempted_at' => now(), 'last_error_code' => null, 'updated_at' => now()];
$db->table('business_mirror_table_states')->updateOrInsert(['dataset_key' => self::DATASET], $base +
($state ? [] : ['created_at' => now()]));
try {
if (! $resume) $db->table(self::STAGE)->delete();
$expected = $this->sourceCount($from, $until);
while (true) {
$items = $this->items($from, $until, $last, $batchSize);
if ($items === []) break;
$headers = $this->headers(array_values(array_unique(array_column($items, 'as_id'))));
$rows = [];
foreach ($items as $item) {
$header = $headers[(string) $item['as_id']] ?? null;
if ($header === null) throw new RuntimeException('missing_after_sales_header');
$rows[] = $this->row($item, $header, $generation);
}
$last = (int) end($items)['Id'];
$db->transaction(function () use ($db, $rows, $last, $generation, $from, $to): void {
foreach (array_chunk($rows, 400) as $part) {
$db->table(self::STAGE)->upsert($part, ['source_id'], array_keys($part[0]));
}
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
'cursor' => json_encode(['from' => $from, 'to' => $to, 'last_id' => $last]),
'last_upserted_rows' => $db->table(self::STAGE)->where('generation', $generation)->count(),
'updated_at' => now(),
]);
});
$progress && $progress($db->table(self::STAGE)->where('generation', $generation)->count(), $expected);
if (count($items) < $batchSize) break;
}
$count = $db->table(self::STAGE)->where('generation', $generation)->count();
if ($count !== $expected || $count !== $this->sourceCount($from, $until)) {
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update(['cursor' => null]);
throw new RuntimeException('source_count_changed_retry_required');
}
// 同一事务替换范围,失败或中断不影响页面上一版;只操作派生镜像。
$db->transaction(function () use ($db, $from, $until, $generation, $count): void {
$db->table(self::TABLE)->where('received_at', '>=', $from)->where('received_at', '<', $until)->delete();
$columns = $db->getSchemaBuilder()->getColumnListing(self::TABLE);
$db->table(self::TABLE)->insertUsing($columns, $db->table(self::STAGE)->select($columns)->where('generation', $generation));
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
'status' => 'succeeded', 'cursor' => null, 'initial_completed_at' => now(),
'last_succeeded_at' => now(), 'last_full_succeeded_at' => now(),
'window_started_at' => $from, 'window_ends_at' => $until,
'last_upserted_rows' => $count, 'mirror_row_count' => $db->table(self::TABLE)->count(),
'updated_at' => now(),
]);
$db->table(self::STAGE)->where('generation', $generation)->delete();
});
return ['rows' => $count, 'from' => $from, 'to' => $to, 'seconds' => round(microtime(true) - $started, 2),
'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2)];
} catch (Throwable $exception) {
$db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([
'status' => 'failed', 'last_error_code' => class_basename($exception), 'updated_at' => now(),
]);
throw $exception;
}
}
protected function sourceCount(string $from, string $until): int
{
return (int) $this->upstream()->scalar('SELECT COUNT_BIG(*) FROM rpt.jst_returnAndRefundItem WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime)', [$from, $until]);
}
protected function items(string $from, string $until, int $last, int $limit): array
{
return $this->upstream()->select('SELECT TOP (' . $limit . ') Id,as_id,asi_id,CONVERT(varchar(27),receive_date,126) AS receive_date,'
. 'sku_id,i_id,name,properties_value,qty,r_qty,price,amount,remark FROM rpt.jst_returnAndRefundItem'
. ' WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime) AND Id > ? ORDER BY Id', [$from, $until, $last]);
}
protected function headers(array $ids): array
{
$rows = $this->upstream()->select('SELECT Id,as_id,outer_as_id,o_id,so_id,l_id,logistics_company,shop_name,warehouse,'
. 'status,type,good_status,question_type,refund,remark,CONVERT(varchar(27),updateTime,126) AS updateTime'
. ' FROM rpt.jst_returnAndRefundInfo WHERE as_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')', $ids);
$headers = [];
foreach ($rows as $row) {
$key = (string) $row['as_id'];
if (! isset($headers[$key]) || (int) $row['Id'] > (int) $headers[$key]['Id']) $headers[$key] = $row;
}
return $headers;
}
private function upstream(): UpstreamReadOnlyQuery
{
return $this->queries->forSourceWithTimeout('operations_replica', 60);
}
private function row(array $i, array $h, string $generation): array
{
return ['source_id' => $i['Id'], 'after_sales_id' => $i['as_id'], 'item_id' => $i['asi_id'],
'received_at' => $i['receive_date'], 'online_after_sales_no' => $h['outer_as_id'],
'order_id' => $h['o_id'], 'online_order_no' => $h['so_id'], 'waybill' => $h['l_id'],
'courier' => $h['logistics_company'], 'shop' => $h['shop_name'], 'warehouse' => $h['warehouse'],
'sku' => $i['sku_id'], 'style_code' => $i['i_id'], 'product_name' => $i['name'], 'properties' => $i['properties_value'],
'applied_qty' => $i['qty'], 'returned_qty' => $i['r_qty'], 'price' => $i['price'], 'item_amount' => $i['amount'],
'order_refund' => $h['refund'], 'status' => $h['status'], 'type' => $h['type'], 'goods_status' => $h['good_status'],
'reason' => $h['question_type'], 'remark' => trim(($h['remark'] ?? '') . "\n" . ($i['remark'] ?? '')),
'source_updated_at' => $h['updateTime'], 'generation' => $generation, 'synced_at' => now()];
}
}