CaiWuXiTong/modules/EcommerceFinance/Services/ProductCostAutoRefresh.php

129 lines
3.9 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Services;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
use Symfony\Component\Process\Process;
use Throwable;
/**
* 业绩明细写入成功后自动重算对应账期、平台的商品成本。
*/
class ProductCostAutoRefresh
{
private const PLATFORM_KEYS = [
'淘系支付宝' => 'taobao-alipay',
'淘系微信' => 'taobao-wechat',
'拼多多' => 'pinduoduo',
'得物' => 'dewu',
'京东网银钱包' => 'jd-wallet',
'京东账单' => 'jd-transactions',
'京喜账单' => 'jingxi',
'抖音' => 'douyin',
];
/** @param null|Closure(list<string>): array{success:bool,output:string} $runner */
public function __construct(private readonly ?Closure $runner = null)
{
}
/**
* @return array{status:string,platforms:list<string>,results:list<array<string,mixed>>}
*/
public function refresh(string $month, string $platform = ''): array
{
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
throw new InvalidArgumentException('商品成本自动更新月份格式应为 YYYY-MM。');
}
$keys = $platform !== ''
? [$platform]
: $this->platformKeysForMonth($month);
if ($keys === []) {
return ['status' => 'skipped', 'platforms' => [], 'results' => []];
}
$results = [];
foreach ($keys as $key) {
$command = [
PHP_BINARY ?: 'php',
'artisan',
'store-receipt:product-cost:sync',
$month,
'--platform=' . $key,
'--chunk=1000',
];
$result = $this->run($command);
$results[] = ['platform' => $key] + $result;
if (! $result['success']) {
Log::warning('业绩明细更新后商品成本自动重算失败。', [
'month' => $month,
'platform' => $key,
]);
}
}
return [
'status' => collect($results)->every(static fn (array $result): bool => $result['success'])
? 'succeeded'
: 'failed',
'platforms' => $keys,
'results' => $results,
];
}
/** @return list<string> */
private function platformKeysForMonth(string $month): array
{
$labels = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'))
->table('store_receipt_order_match_rows')
->where('report_month', $month . '-01')
->whereNotNull('platform')
->where('platform', '!=', '')
->distinct()
->orderBy('platform')
->pluck('platform')
->all();
$keys = [];
foreach ($labels as $label) {
$key = self::PLATFORM_KEYS[trim((string) $label)] ?? null;
if ($key !== null) {
$keys[$key] = $key;
}
}
return array_values($keys);
}
/** @param list<string> $command
* @return array{success:bool,output:string}
*/
protected function run(array $command): array
{
if ($this->runner !== null) {
return ($this->runner)($command);
}
try {
$process = new Process($command, base_path());
$process->setTimeout(7200);
$process->run();
return [
'success' => $process->isSuccessful(),
'output' => mb_substr(
trim($process->getOutput() . "\n" . $process->getErrorOutput()),
0,
4000,
),
];
} catch (Throwable $exception) {
return ['success' => false, 'output' => $exception->getMessage()];
}
}
}