CaiWuXiTong/modules/EcommerceFinance/Services/BillSyncWindowAuditor.php

152 lines
5.3 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
use Throwable;
class BillSyncWindowAuditor
{
private const SOURCES = [
'taobao_alipay' => [
'label' => '淘系支付宝',
'table' => 'taobao_alipay_bill_rows',
'date_column' => 'occurred_at',
],
'pinduoduo' => [
'label' => '拼多多',
'table' => 'pdd_settlement_bill_rows',
'date_column' => 'occurred_at',
],
'taobao_wechat' => [
'label' => '淘系微信',
'table' => 'taobao_wechat_bill_rows',
'date_column' => 'occurred_at',
],
'dewu' => [
'label' => '得物',
'table' => 'dewu_settlement_bill_rows',
'date_column' => 'bill_date',
],
];
/** @return array<string,mixed> */
public function audit(string $from, string $to): array
{
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$result = [
'window' => ['from' => $from, 'to' => $to],
'platforms' => [],
'has_gaps' => false,
'has_anomalies' => false,
];
foreach (self::SOURCES as $key => $source) {
try {
$platform = $this->auditPlatform($connection, $source, $from, $to);
} catch (Throwable $exception) {
report($exception);
$result['platforms'][$key] = [
'label' => $source['label'],
'status' => 'failed',
'error' => '账单表读取失败,详细原因已记录到受保护日志。',
];
$result['has_anomalies'] = true;
continue;
}
$result['platforms'][$key] = $platform;
$result['has_gaps'] = $result['has_gaps'] || $platform['missing_dates'] !== [];
$result['has_anomalies'] = $result['has_anomalies'] || $platform['suspicious_dates'] !== [];
}
return $result;
}
/**
* @param array{label:string,table:string,date_column:string} $source
* @return array<string,mixed>
*/
private function auditPlatform($connection, array $source, string $from, string $to): array
{
$table = $source['table'];
$dateColumn = $source['date_column'];
$endExclusive = (new DateTimeImmutable($to))->modify('+1 day')->format('Y-m-d');
$rows = $connection->select(
"SELECT DATE({$dateColumn}) AS bill_date, COUNT(*) AS row_count, "
. "COUNT(DISTINCT NULLIF(TRIM(store_name), '')) AS store_count, "
. 'SUM(income_amount) AS income_total, SUM(expense_amount) AS expense_total '
. "FROM `{$table}` "
. "WHERE {$dateColumn} >= ? AND {$dateColumn} < ? "
. 'GROUP BY DATE(' . $dateColumn . ') ORDER BY bill_date',
[$from, $endExclusive]
);
$byDate = [];
foreach ($rows as $row) {
$byDate[(string) $row->bill_date] = [
'date' => (string) $row->bill_date,
'row_count' => (int) $row->row_count,
'store_count' => (int) $row->store_count,
'income' => bcadd((string) $row->income_total, '0', 2),
'expense' => bcadd((string) $row->expense_total, '0', 2),
];
}
$days = [];
$missing = [];
$end = new DateTimeImmutable($to);
for ($date = new DateTimeImmutable($from); $date <= $end; $date = $date->modify('+1 day')) {
$key = $date->format('Y-m-d');
if (! isset($byDate[$key])) {
$missing[] = $key;
$days[] = [
'date' => $key,
'row_count' => 0,
'store_count' => 0,
'income' => '0.00',
'expense' => '0.00',
];
continue;
}
$days[] = $byDate[$key];
}
$medianRows = $this->median(array_map(static fn (array $day): int => $day['row_count'], $days));
$medianStores = $this->median(array_map(static fn (array $day): int => $day['store_count'], $days));
$suspicious = [];
foreach ($days as $day) {
if ($day['row_count'] === 0) {
continue;
}
$lowRows = $medianRows > 0 && $day['row_count'] < ($medianRows * 0.5);
$lowStores = $medianStores > 1 && $day['store_count'] < max(1, (int) floor($medianStores * 0.5));
if ($lowRows || $lowStores) {
$suspicious[] = $day['date'];
}
}
return [
'label' => $source['label'],
'status' => $missing !== [] || $suspicious !== [] ? 'attention' : 'ok',
'days' => $days,
'missing_dates' => $missing,
'suspicious_dates' => $suspicious,
'median_row_count' => $medianRows,
'median_store_count' => $medianStores,
];
}
/** @param list<int> $values */
private function median(array $values): int
{
if ($values === []) {
return 0;
}
sort($values);
return (int) $values[(int) floor((count($values) - 1) / 2)];
}
}