76 lines
2.6 KiB
PHP
76 lines
2.6 KiB
PHP
<?php
|
||
|
||
namespace App\Console\Commands;
|
||
|
||
use Illuminate\Console\Command;
|
||
use InvalidArgumentException;
|
||
use Modules\EcommerceFinance\Services\PinduoduoPlatformBalanceImporter;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
class ImportPinduoduoPlatformBalances extends Command
|
||
{
|
||
protected $signature = 'business-mirror:import-pdd-platform-balances
|
||
{path : 聚水潭平台资金账户余额 XLSX/XLS/CSV}
|
||
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD;文件名含 YYYY-MM 时可省略}';
|
||
|
||
protected $description = '导入拼多多“期初余额”和“平台实际期末余额”,并自动维护待补期初队列';
|
||
|
||
public function handle(PinduoduoPlatformBalanceImporter $importer): int
|
||
{
|
||
$periodEnd = trim((string) $this->option('period-end'));
|
||
if ($periodEnd === '') {
|
||
$periodEnd = $this->periodEndFromFilename((string) $this->argument('path'));
|
||
}
|
||
if ($periodEnd === '') {
|
||
$this->error('无法从文件名识别账期,请使用 --period-end=YYYY-MM-DD 指定月末。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
try {
|
||
$result = $importer->import((string) $this->argument('path'), $periodEnd);
|
||
} catch (InvalidArgumentException|RuntimeException $exception) {
|
||
$this->error($exception->getMessage());
|
||
|
||
return self::FAILURE;
|
||
} catch (Throwable $exception) {
|
||
report($exception);
|
||
$this->error('拼多多平台期末余额导入失败,详细原因已记录到受保护日志。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
$this->table(['截止日期', '店铺数', '期初行数', '期初合计', '期末余额合计', '替换旧行数', '来源文件'], [[
|
||
$result['period_end'],
|
||
$result['total'],
|
||
$result['opening_total'],
|
||
$result['opening_balance_total'],
|
||
$result['balance_total'],
|
||
$result['replaced'],
|
||
$result['source_filename'],
|
||
]]);
|
||
|
||
return self::SUCCESS;
|
||
}
|
||
|
||
private function periodEndFromFilename(string $path): string
|
||
{
|
||
$filename = basename($path);
|
||
if (preg_match('/(20\d{2})[-_年](\d{1,2})/u', $filename, $matches) !== 1) {
|
||
return '';
|
||
}
|
||
|
||
$month = (int) $matches[2];
|
||
if ($month < 1 || $month > 12) {
|
||
return '';
|
||
}
|
||
$date = \DateTimeImmutable::createFromFormat(
|
||
'!Y-n-j',
|
||
sprintf('%d-%d-1', (int) $matches[1], $month),
|
||
);
|
||
|
||
return $date === false ? '' : $date->format('Y-m-t');
|
||
}
|
||
}
|