CaiWuXiTong/modules/EcommerceFinance/Repositories/JushuitanShopPromotionFeeMirrorRepository.php

319 lines
10 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
/**
* 聚水潭「推广费(店铺)」原始记录镜像及同步状态。
*/
class JushuitanShopPromotionFeeMirrorRepository
{
public const TABLE = 'jushuitan_shop_promotion_fee_rows';
public const STATE_TABLE = 'business_mirror_table_states';
public const DATASET_KEY = 'jushuitan.shop-promotion-fee';
private const UPSERT_CHUNK_SIZE = 500;
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
public function available(): bool
{
return Schema::connection($this->connection->getName())->hasTable(self::TABLE);
}
public function initialized(): bool
{
$state = $this->state();
return is_array($state) && ($state['initial_completed_at'] ?? null) !== null;
}
/**
* @return array{
* code:string,
* status:string,
* initialized:bool,
* last_succeeded_at:?string,
* latest_date:?string,
* row_count:int
* }
*/
public function syncStatus(): array
{
if (! $this->available()) {
return [
'code' => 'unavailable',
'status' => 'unavailable',
'initialized' => false,
'last_succeeded_at' => null,
'latest_date' => null,
'row_count' => 0,
];
}
$state = $this->state();
$status = (string) ($state['status'] ?? 'pending');
$initialized = ($state['initial_completed_at'] ?? null) !== null;
$lastSucceededAt = $state['last_succeeded_at'] ?? null;
$latestDate = $this->connection->table(self::TABLE)
->where('del_flag', 0)
->max('fee_date');
return [
'code' => match (true) {
$state === null => 'pending',
! $initialized && $status === 'running' => 'initializing',
! $initialized && $status === 'failed' => 'failed',
! $initialized => 'pending',
default => 'ready',
},
'status' => $status,
'initialized' => $initialized,
'last_succeeded_at' => $lastSucceededAt === null ? null : (string) $lastSucceededAt,
'latest_date' => $latestDate === null ? null : substr((string) $latestDate, 0, 10),
'row_count' => (int) ($state['mirror_row_count'] ?? $this->connection->table(self::TABLE)->count()),
];
}
/**
* 财务分析按“账期 + 店铺”读取。店铺名优先取 ERP 店铺档案的当前名称,
* 档案缺店时回退到同步时保留的源快照。
*
* @param list<string> $reportMonths
* @return array<string,array<string,float>>
*/
public function monthlyStoreTotals(array $reportMonths): array
{
$months = array_values(array_unique(array_filter(
$reportMonths,
static fn (mixed $month): bool => is_string($month)
&& preg_match('/^\d{4}-\d{2}$/', $month) === 1,
)));
sort($months, SORT_STRING);
if ($months === [] || ! $this->available()) {
return [];
}
$start = $months[0] . '-01';
$end = Carbon::createFromFormat('Y-m-d', end($months) . '-01', 'Asia/Shanghai')
->endOfMonth()
->toDateString();
$monthExpression = $this->monthExpression('c');
$rows = $this->connection->table(self::TABLE . ' AS c')
->whereBetween('c.fee_date', [$start, $end])
->where('c.del_flag', 0)
->selectRaw($monthExpression . ' AS report_month')
->selectRaw('c.shop_id')
->selectRaw('MAX(c.shop_name) AS fallback_store_name')
->selectRaw('SUM(c.amount) AS amount')
->groupByRaw($monthExpression . ', c.shop_id')
->get();
$shopNames = $this->shopNameMap();
$buckets = [];
foreach ($rows as $row) {
$month = substr((string) $row->report_month, 0, 7);
$shopId = (string) $row->shop_id;
$storeName = trim((string) (
$shopNames[$shopId]
?? $row->fallback_store_name
?? ''
));
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1 || $storeName === '') {
continue;
}
$buckets[$month][$storeName] = round(
($buckets[$month][$storeName] ?? 0.0) + (float) $row->amount,
2,
);
}
return $buckets;
}
/** @return array<string,string> */
public function shopNameMap(): array
{
$schema = Schema::connection($this->connection->getName());
if (! $schema->hasTable('ops_jst_shop_info')) {
return [];
}
$map = [];
foreach ($this->connection->table('ops_jst_shop_info')
->whereNotNull('shop_id')
->orderBy('Id')
->get(['shop_id', 'shop_name']) as $row) {
$shopId = trim((string) $row->shop_id);
$shopName = trim((string) ($row->shop_name ?? ''));
if ($shopId !== '' && $shopName !== '') {
$map[$shopId] = $shopName;
}
}
return $map;
}
public function startRun(
string $mode,
string $timeType,
Carbon $from,
Carbon $to,
): void {
if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) {
return;
}
$now = now();
$values = [
'status' => 'running',
'run_mode' => $mode,
'window_started_at' => $from->startOfDay(),
'window_ends_at' => $to->endOfDay(),
'high_watermark' => json_encode(
['time_type' => $timeType],
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
),
'last_attempted_at' => $now,
'last_error_code' => null,
'updated_at' => $now,
];
$query = $this->connection->table(self::STATE_TABLE)
->where('dataset_key', self::DATASET_KEY);
if ($query->exists()) {
$query->update($values);
return;
}
$this->connection->table(self::STATE_TABLE)->insert([
'dataset_key' => self::DATASET_KEY,
'source_key' => 'jushuitan_open_api',
'source_object' => 'shop-promotion-fee',
'target_table' => self::TABLE,
'created_at' => $now,
] + $values);
}
/** @param list<array<string,mixed>> $records */
public function upsertRecords(array $records): int
{
if ($records === [] || ! $this->available()) {
return 0;
}
$now = now();
$normalized = array_map(static function (array $row) use ($now): array {
$row['source_key'] ??= 'jushuitan_open_api';
$row['row_hash'] ??= hash(
'sha256',
json_encode($row, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
);
return $row + [
'synced_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
}, $records);
foreach (array_chunk($normalized, self::UPSERT_CHUNK_SIZE) as $chunk) {
$this->connection->table(self::TABLE)->upsert(
$chunk,
['source_record_key'],
[
'source_key', 'auto_id', 'shop_id', 'shop_name', 'fee_date', 'fee_time',
'fee_name', 'csg_code', 'csg_name', 'channel', 'description',
'journal_type_name', 'account_code', 'amount', 'oc_amount',
'currency', 'del_flag', 'row_hash', 'synced_at', 'updated_at',
],
);
}
return count($normalized);
}
public function complete(
string $mode,
Carbon $from,
Carbon $to,
int $sourceRows,
int $storedRows,
): void {
if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) {
return;
}
$now = now();
$values = [
'status' => 'succeeded',
'run_mode' => $mode,
'window_started_at' => $from->startOfDay(),
'window_ends_at' => $to->endOfDay(),
'last_attempted_at' => $now,
'last_succeeded_at' => $now,
'last_upserted_rows' => $storedRows,
'mirror_row_count' => $this->connection->table(self::TABLE)->count(),
'last_error_code' => null,
'updated_at' => $now,
];
if ($mode === 'full' && $storedRows > 0) {
$values['initial_completed_at'] = $now;
$values['last_full_succeeded_at'] = $now;
}
$this->connection->table(self::STATE_TABLE)
->where('dataset_key', self::DATASET_KEY)
->update($values);
}
public function fail(string $errorCode): void
{
if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) {
return;
}
$this->connection->table(self::STATE_TABLE)
->where('dataset_key', self::DATASET_KEY)
->update([
'status' => 'failed',
'last_attempted_at' => now(),
'last_error_code' => mb_substr($errorCode, 0, 120),
'updated_at' => now(),
]);
}
/** @return array<string,mixed>|null */
private function state(): ?array
{
if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) {
return null;
}
$row = $this->connection->table(self::STATE_TABLE)
->where('dataset_key', self::DATASET_KEY)
->first();
return $row === null ? null : (array) $row;
}
private function monthExpression(string $alias): string
{
return $this->connection->getDriverName() === 'sqlite'
? "strftime('%Y-%m', {$alias}.fee_date)"
: "DATE_FORMAT({$alias}.fee_date, '%Y-%m')";
}
}