CaiWuXiTong/app/Console/Commands/AuditBillSyncWindow.php

99 lines
3.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Console\Commands;
use DateTimeImmutable;
use Illuminate\Console\Command;
use InvalidArgumentException;
use Modules\EcommerceFinance\Services\BillSyncWindowAuditor;
class AuditBillSyncWindow extends Command
{
protected $signature = 'bill-sync:audit-window
{--from= : 开始日期 YYYY-MM-DD;默认以前一自然日结束的最近 7 天}
{--to= : 结束日期 YYYY-MM-DD;默认前一自然日}
{--days=7 : 未指定 --from 时回看的自然日数,最大 93}
{--json : 输出 JSON,供每日账单自动化读取}';
protected $description = '核对最近账单窗口的日期、行数、店铺数和收支,识别漏日及异常低量';
public function handle(BillSyncWindowAuditor $auditor): int
{
try {
[$from, $to] = $this->window();
} catch (InvalidArgumentException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$result = $auditor->audit($from, $to);
if ((bool) $this->option('json')) {
$this->line(json_encode(
$result,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
));
} else {
$this->renderText($result);
}
return $result['has_gaps'] || $result['has_anomalies']
? self::FAILURE
: self::SUCCESS;
}
/** @return array{0:string,1:string} */
private function window(): array
{
$to = trim((string) $this->option('to'));
$to = $to !== ''
? $this->date($to, '--to')
: now('Asia/Shanghai')->subDay()->toDateString();
$from = trim((string) $this->option('from'));
if ($from !== '') {
$from = $this->date($from, '--from');
} else {
$days = max(1, (int) $this->option('days'));
if ($days > 93) {
throw new InvalidArgumentException('--days 最大为 93。');
}
$from = (new DateTimeImmutable($to))->modify('-' . ($days - 1) . ' days')->format('Y-m-d');
}
if ($from > $to) {
throw new InvalidArgumentException('开始日期不能晚于结束日期。');
}
return [$from, $to];
}
private function date(string $value, string $option): string
{
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if (! $parsed || $parsed->format('Y-m-d') !== $value) {
throw new InvalidArgumentException("{$option} 日期格式必须为 YYYY-MM-DD。");
}
return $value;
}
/** @param array<string,mixed> $result */
private function renderText(array $result): void
{
$this->line("账单窗口:{$result['window']['from']} 至 {$result['window']['to']}");
foreach ($result['platforms'] as $platform) {
if (($platform['status'] ?? '') === 'failed') {
$this->line("{$platform['label']} | FAILED | {$platform['error']}");
continue;
}
$missing = $platform['missing_dates'] !== [] ? implode(',', $platform['missing_dates']) : '-';
$suspicious = $platform['suspicious_dates'] !== [] ? implode(',', $platform['suspicious_dates']) : '-';
$this->line(
"{$platform['label']} | {$platform['status']} | missing={$missing} | suspicious={$suspicious}"
);
}
}
}