CaiWuXiTong/modules/EcommerceFinance/Services/JushuitanShopPromotionFeeSynchronizer.php

235 lines
7.7 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Repositories\JushuitanShopPromotionFeeMirrorRepository;
use RuntimeException;
use Throwable;
class JushuitanShopPromotionFeeSynchronizer
{
public function __construct(
private readonly JushuitanShopPromotionFeeClient $client,
private readonly JushuitanShopPromotionFeeMirrorRepository $repository,
) {
}
/**
* @return array{
* mode:string,
* time_type:string,
* from:string,
* to:string,
* pages:int,
* source_rows:int,
* stored_rows:int
* }
*/
public function sync(
Carbon $from,
Carbon $to,
string $mode,
string $timeType,
?int $maxPages = null,
): array {
$from = $from->copy()->startOfDay();
$to = $to->copy()->startOfDay();
if ($from->gt($to)) {
throw new RuntimeException('jushuitan_shop_promotion_fee_invalid_date_range');
}
$this->repository->startRun($mode, $timeType, $from, $to);
try {
$shopNames = $this->repository->shopNameMap();
$pageSize = (int) config('services.jushuitan.shop_promotion_fee_page_size', 100);
$pageLimit = $maxPages ?? (int) config('services.jushuitan.shop_promotion_fee_max_pages', 500);
$pageLimit = max($pageLimit, 1);
$pages = 0;
$sourceRows = 0;
$storedRows = 0;
for ($windowStart = $from->copy(); $windowStart->lte($to); $windowStart->addDay()) {
$windowEnd = $windowStart->copy()->endOfMonth()->startOfDay();
if ($windowEnd->gt($to)) {
$windowEnd = $to->copy();
}
$window = $this->syncWindow(
$windowStart,
$windowEnd,
$timeType,
$shopNames,
$pageSize,
$pageLimit,
);
$pages += $window['pages'];
$sourceRows += $window['source_rows'];
$storedRows += $window['stored_rows'];
$windowStart = $windowEnd;
}
$this->repository->complete($mode, $from, $to, $sourceRows, $storedRows);
return [
'mode' => $mode,
'time_type' => $timeType,
'from' => $from->toDateString(),
'to' => $to->toDateString(),
'pages' => $pages,
'source_rows' => $sourceRows,
'stored_rows' => $storedRows,
];
} catch (Throwable $exception) {
$this->repository->fail($exception->getMessage());
throw $exception;
}
}
/**
* @param array<string,string> $shopNames
* @return array{pages:int,source_rows:int,stored_rows:int}
*/
private function syncWindow(
Carbon $from,
Carbon $to,
string $timeType,
array $shopNames,
int $pageSize,
int $pageLimit,
): array {
$cursor = 0;
$pages = 0;
$sourceRows = 0;
$storedRows = 0;
do {
$page = $this->client->getPage(
$from,
$to->copy()->addDay(),
$timeType,
$cursor,
$pageSize,
);
$pages++;
$sourceRows += $page['source_rows'];
$records = [];
foreach ($page['records'] as $record) {
$normalized = $this->normalizeRecord($record, $shopNames);
if ($normalized !== null) {
$records[] = $normalized;
}
}
$storedRows += $this->repository->upsertRecords($records);
if (! $page['has_next']) {
break;
}
if ($page['cursor'] === $cursor) {
throw new RuntimeException('jushuitan_shop_promotion_fee_cursor_not_advanced');
}
if ($pages >= $pageLimit) {
throw new RuntimeException('jushuitan_shop_promotion_fee_page_limit');
}
$cursor = $page['cursor'];
} while (true);
return [
'pages' => $pages,
'source_rows' => $sourceRows,
'stored_rows' => $storedRows,
];
}
/**
* @param array<string,mixed> $record
* @param array<string,string> $shopNames
* @return array<string,mixed>|null
*/
private function normalizeRecord(array $record, array $shopNames): ?array
{
$shopId = (int) ($record['shop_id'] ?? 0);
if ($shopId <= 0) {
return null;
}
$feeTime = $this->dateTime($record['fee_time'] ?? null);
$primaryKey = trim((string) (
$record['primary_key']
?? $record['primaryKey']
?? ''
));
if ($primaryKey === '' || $primaryKey === '0') {
$primaryKey = hash('sha256', implode('|', [
$shopId,
(string) ($record['auto_id'] ?? ''),
(string) ($record['fee_time'] ?? ''),
(string) ($record['fee_name'] ?? ''),
(string) ($record['csg_code'] ?? ''),
(string) ($record['amount'] ?? ''),
]));
} elseif (mb_strlen($primaryKey) > 191) {
$primaryKey = hash('sha256', $primaryKey);
}
$values = [
'source_key' => 'jushuitan_open_api',
'source_record_key' => $primaryKey,
'auto_id' => $this->nullableInt($record['auto_id'] ?? null),
'shop_id' => $shopId,
'shop_name' => $shopNames[(string) $shopId] ?? null,
'fee_date' => $feeTime?->toDateString(),
'fee_time' => $feeTime,
'fee_name' => $this->nullableString($record['fee_name'] ?? null, 191),
'csg_code' => $this->nullableString($record['csg_code'] ?? null, 64),
'csg_name' => $this->nullableString($record['csg_name'] ?? null, 191),
'channel' => $this->nullableString($record['channel'] ?? null, 64),
'description' => $this->nullableString($record['description'] ?? null),
'journal_type_name' => $this->nullableString($record['journal_type_name'] ?? null, 191),
'account_code' => $this->nullableString($record['account_code'] ?? null, 64),
'amount' => round((float) ($record['amount'] ?? 0), 2),
'oc_amount' => is_numeric($record['oc_amount'] ?? null)
? round((float) $record['oc_amount'], 2)
: null,
'currency' => $this->nullableString($record['currency'] ?? null, 16),
'del_flag' => max((int) ($record['del_flag'] ?? 0), 0),
];
$values['row_hash'] = hash(
'sha256',
json_encode($values, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
);
return $values;
}
private function dateTime(mixed $value): ?Carbon
{
$value = trim((string) $value);
if ($value === '') {
return null;
}
try {
return Carbon::parse($value, 'Asia/Shanghai');
} catch (Throwable) {
return null;
}
}
private function nullableInt(mixed $value): ?int
{
return $value === null || $value === '' ? null : (int) $value;
}
private function nullableString(mixed $value, ?int $maxLength = null): ?string
{
if ($value === null) {
return null;
}
$value = trim((string) $value);
if ($value === '') {
return null;
}
return $maxLength === null ? $value : mb_substr($value, 0, $maxLength);
}
}