CaiWuXiTong/modules/EcommerceFinance/Repositories/PromotionExpenseMirrorRepository.php

406 lines
15 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* 聚水潭推广费用日汇总镜像。
*
* 页面只读此表;上游按“日期 + 平台 + 店铺”聚合后再落库,避免订单级
* 大表在页面请求中现场扫描。
*/
class PromotionExpenseMirrorRepository
{
public const TABLE = 'promotion_expense_daily_rows';
public const STATE_TABLE = 'business_mirror_table_states';
public const DATASET_KEY = 'derived.promotion-expenses-daily';
private readonly ConnectionInterface $connection;
public function __construct()
{
$this->connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
}
public function available(): bool
{
try {
return Schema::connection($this->connection->getName())->hasTable(self::TABLE);
} catch (Throwable) {
return false;
}
}
/** @return array{code:string,status:string,last_succeeded_at:?string,last_error:?string,latest_date:?string,row_count:int} */
public function syncStatus(): array
{
if (! $this->available()) {
return [
'code' => 'unavailable',
'status' => 'unavailable',
'last_succeeded_at' => null,
'last_error' => null,
'latest_date' => null,
'row_count' => 0,
];
}
$state = Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)
? $this->connection->table(self::STATE_TABLE)
->where('dataset_key', self::DATASET_KEY)
->first()
: null;
$latestDate = $this->connection->table(self::TABLE)->max('report_date');
$status = (string) ($state->status ?? 'pending');
$lastSucceededAt = $state->last_succeeded_at ?? null;
return [
'code' => match (true) {
$state === null => 'pending',
$status === 'failed' => 'failed',
$lastSucceededAt === null => 'pending',
default => 'ready',
},
'status' => $status,
'last_succeeded_at' => $lastSucceededAt === null ? null : (string) $lastSucceededAt,
'last_error' => $state->last_error_code ?? null,
'latest_date' => $latestDate === null ? null : substr((string) $latestDate, 0, 10),
'row_count' => (int) ($state->mirror_row_count ?? 0),
];
}
/** @return list<string> */
public function monthOptions(string $fromMonth, string $toMonth): array
{
if (! $this->available()) {
return [];
}
$month = $this->monthExpression();
$months = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$fromMonth . '-01', $this->monthEnd($toMonth)])
->selectRaw($month . ' AS report_month')
->distinct()
->orderByDesc('report_month')
->pluck('report_month')
->map(static fn (mixed $value): string => substr((string) $value, 0, 7))
->filter(static fn (string $value): bool => preg_match('/^\d{4}-\d{2}$/', $value) === 1)
->values()
->all();
return array_values(array_unique($months));
}
/** @return list<string> */
public function platforms(): array
{
if (! $this->available()) {
return [];
}
return $this->connection->table(self::TABLE)
->whereNotNull('platform')
->where('platform', '<>', '')
->distinct()
->orderBy('platform')
->pluck('platform')
->map(static fn (mixed $value): string => trim((string) $value))
->filter()
->values()
->all();
}
/** @return list<string> */
public function stores(string $month, string $platform = ''): array
{
if (! $this->available()) {
return [];
}
$query = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$month . '-01', $this->monthEnd($month)])
->whereNotNull('store_name')
->where('store_name', '<>', '');
if ($platform !== '') {
$query->where('platform', $platform);
}
return $query->distinct()
->orderBy('store_name')
->pluck('store_name')
->map(static fn (mixed $value): string => trim((string) $value))
->filter()
->values()
->all();
}
/** @return array<int,array{period:string,source_rows:int,push_fee_total:float,marketing_fee_total:float,total_fee:float}> */
public function periods(
string $fromMonth,
string $toMonth,
string $platform = '',
string $store = '',
): array {
if (! $this->available()) {
return [];
}
$query = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$fromMonth . '-01', $this->monthEnd($toMonth)]);
$this->applyScope($query, $platform, $store);
$month = $this->monthExpression();
$rows = $query
->selectRaw($month . ' AS period')
->selectRaw('COALESCE(SUM(source_rows), 0) AS source_rows')
->selectRaw('COALESCE(SUM(push_fee_total), 0) AS push_fee_total')
->selectRaw('COALESCE(SUM(marketing_fee_total), 0) AS marketing_fee_total')
->selectRaw('COALESCE(SUM(total_fee), 0) AS total_fee')
->groupByRaw($month)
->orderBy('period')
->get();
return $rows->map(static fn (object $row): array => [
'period' => substr((string) $row->period, 0, 7),
'source_rows' => (int) $row->source_rows,
'push_fee_total' => round((float) $row->push_fee_total, 2),
'marketing_fee_total' => round((float) $row->marketing_fee_total, 2),
'total_fee' => round((float) $row->total_fee, 2),
])->values()->all();
}
/**
* @return array{
* rows:list<array<string,mixed>>,
* total:int,
* current_page:int,
* last_page:int,
* per_page:int,
* totals:array{push_fee:float,shared_push_fee:float,push_fee_total:float,marketing_fee:float,shared_marketing_fee:float,marketing_fee_total:float,total_fee:float}
* }
*/
public function details(
string $month,
string $platform = '',
string $store = '',
int $page = 1,
int $limit = 50,
): array {
$page = max(1, $page);
$limit = min(max($limit, 1), 100);
if (! $this->available()) {
return $this->emptyDetails($page, $limit);
}
$aggregated = $this->aggregateDetails($month, $platform, $store);
$total = $aggregated['total'];
return [
'rows' => array_slice($aggregated['rows'], ($page - 1) * $limit, $limit),
'total' => $total,
'current_page' => $page,
'last_page' => max(1, (int) ceil($total / $limit)),
'per_page' => $limit,
'totals' => $aggregated['totals'],
];
}
/** @return list<array<string,mixed>> */
public function exportDetails(string $month, string $platform = '', string $store = ''): array
{
if (! $this->available()) {
return [];
}
return $this->aggregateDetails($month, $platform, $store)['rows'];
}
/**
* @return array{
* rows:list<array<string,mixed>>,
* total:int,
* totals:array{push_fee:float,shared_push_fee:float,push_fee_total:float,marketing_fee:float,shared_marketing_fee:float,marketing_fee_total:float,total_fee:float}
* }
*/
private function aggregateDetails(string $month, string $platform, string $store): array
{
$query = $this->connection->table(self::TABLE)
->whereBetween('report_date', [$month . '-01', $this->monthEnd($month)]);
$this->applyScope($query, $platform, $store);
$rows = $query
->select(['platform', 'store_name'])
->selectRaw('COALESCE(SUM(source_rows), 0) AS source_rows')
->selectRaw('COALESCE(SUM(push_fee), 0) AS push_fee')
->selectRaw('COALESCE(SUM(shared_push_fee), 0) AS shared_push_fee')
->selectRaw('COALESCE(SUM(push_fee_total), 0) AS push_fee_total')
->selectRaw('COALESCE(SUM(marketing_fee), 0) AS marketing_fee')
->selectRaw('COALESCE(SUM(shared_marketing_fee), 0) AS shared_marketing_fee')
->selectRaw('COALESCE(SUM(marketing_fee_total), 0) AS marketing_fee_total')
->selectRaw('COALESCE(SUM(total_fee), 0) AS total_fee')
->groupBy('platform', 'store_name')
->get()
->map(static fn (object $row): array => [
'platform' => (string) $row->platform,
'store_name' => (string) $row->store_name,
'source_rows' => (int) $row->source_rows,
'push_fee' => round((float) $row->push_fee, 2),
'shared_push_fee' => round((float) $row->shared_push_fee, 2),
'push_fee_total' => round((float) $row->push_fee_total, 2),
'marketing_fee' => round((float) $row->marketing_fee, 2),
'shared_marketing_fee' => round((float) $row->shared_marketing_fee, 2),
'marketing_fee_total' => round((float) $row->marketing_fee_total, 2),
'total_fee' => round((float) $row->total_fee, 2),
])
->sort(static function (array $left, array $right): int {
return ([$right['total_fee'], $right['push_fee_total']]
<=> [$left['total_fee'], $left['push_fee_total']])
?: strcmp($left['platform'], $right['platform'])
?: strcmp($left['store_name'], $right['store_name']);
})
->values();
$totals = [
'push_fee' => round((float) $rows->sum('push_fee'), 2),
'shared_push_fee' => round((float) $rows->sum('shared_push_fee'), 2),
'push_fee_total' => round((float) $rows->sum('push_fee_total'), 2),
'marketing_fee' => round((float) $rows->sum('marketing_fee'), 2),
'shared_marketing_fee' => round((float) $rows->sum('shared_marketing_fee'), 2),
'marketing_fee_total' => round((float) $rows->sum('marketing_fee_total'), 2),
'total_fee' => round((float) $rows->sum('total_fee'), 2),
];
return [
'rows' => $rows->all(),
'total' => $rows->count(),
'totals' => $totals,
];
}
/** @param list<array<string,mixed>> $rows */
public function replaceDate(string $date, array $rows): int
{
$now = now();
$normalized = array_map(fn (array $row): array => [
'report_date' => $date,
'platform' => (string) ($row['platform'] ?? '未标记'),
'store_name' => (string) ($row['store_name'] ?? '未标记'),
'source_rows' => (int) ($row['source_rows'] ?? 0),
'push_fee' => round((float) ($row['push_fee'] ?? 0), 2),
'shared_push_fee' => round((float) ($row['shared_push_fee'] ?? 0), 2),
'push_fee_total' => round((float) ($row['push_fee_total'] ?? 0), 2),
'marketing_fee' => round((float) ($row['marketing_fee'] ?? 0), 2),
'shared_marketing_fee' => round((float) ($row['shared_marketing_fee'] ?? 0), 2),
'marketing_fee_total' => round((float) ($row['marketing_fee_total'] ?? 0), 2),
'total_fee' => round(
(float) ($row['push_fee_total'] ?? 0) + (float) ($row['marketing_fee_total'] ?? 0),
2,
),
'synced_at' => $now,
], $rows);
$this->connection->transaction(function () use ($date, $normalized): void {
$this->connection->table(self::TABLE)->where('report_date', $date)->delete();
foreach (array_chunk($normalized, 1000) as $chunk) {
$this->connection->table(self::TABLE)->insert($chunk);
}
});
return count($normalized);
}
public function recordSyncState(string $status, int $rowCount, ?string $error = null): void
{
if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) {
return;
}
$now = now();
$values = [
'source_key' => 'operations_replica',
'source_object' => 'rpt.dws_sn_sales_full_info_di',
'target_table' => self::TABLE,
'status' => $status,
'last_attempted_at' => $now,
'mirror_row_count' => $rowCount,
'last_error_code' => $error,
'updated_at' => $now,
];
if ($status === 'succeeded') {
$values['last_succeeded_at'] = $now;
$values['initial_completed_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($values + [
'dataset_key' => self::DATASET_KEY,
'created_at' => $now,
]);
}
public function count(): int
{
return $this->available() ? (int) $this->connection->table(self::TABLE)->count() : 0;
}
private function applyScope(Builder $query, string $platform, string $store): void
{
if ($platform !== '') {
$query->where('platform', $platform);
}
if ($store !== '') {
$query->where('store_name', $store);
}
}
private function monthExpression(): string
{
return $this->connection->getDriverName() === 'sqlite'
? "strftime('%Y-%m', report_date)"
: "DATE_FORMAT(report_date, '%Y-%m')";
}
private function monthEnd(string $month): string
{
return Carbon::createFromFormat('Y-m-d', $month . '-01', 'Asia/Shanghai')
->endOfMonth()
->toDateString();
}
/** @return array{rows:list<mixed>,total:int,current_page:int,last_page:int,per_page:int,totals:array<string,float>} */
private function emptyDetails(int $page, int $limit): array
{
return [
'rows' => [],
'total' => 0,
'current_page' => $page,
'last_page' => 1,
'per_page' => $limit,
'totals' => [
'push_fee' => 0.0,
'shared_push_fee' => 0.0,
'push_fee_total' => 0.0,
'marketing_fee' => 0.0,
'shared_marketing_fee' => 0.0,
'marketing_fee_total' => 0.0,
'total_fee' => 0.0,
],
];
}
}