197 lines
7.5 KiB
PHP
197 lines
7.5 KiB
PHP
<?php
|
||
|
||
namespace App\Console\Commands;
|
||
|
||
use Illuminate\Console\Command;
|
||
use Illuminate\Support\Facades\Cache;
|
||
use Illuminate\Support\Facades\DB;
|
||
use JsonException;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
class ImportVipshopJxActualBills extends Command
|
||
{
|
||
protected $signature = 'vipshop-jx:import
|
||
{file : 唯品会JX账期明细 JSON}
|
||
{--period= : 账单期间,格式 YYYY-MM}
|
||
{--company=1 : 公司 ID}
|
||
{--dry-run : 只校验,不写数据库}';
|
||
|
||
protected $description = '导入唯品会JX账期明细,按账单期间写入账户账单';
|
||
|
||
public function handle(): int
|
||
{
|
||
$path = realpath((string) $this->argument('file'));
|
||
if ($path === false || ! is_file($path) || ! is_readable($path)) {
|
||
$this->error('唯品会JX账期明细文件不存在或不可读。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
$period = trim((string) $this->option('period'));
|
||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
||
$this->error('账单期间必须是 YYYY-MM。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
$companyId = (int) $this->option('company');
|
||
if ($companyId < 1) {
|
||
$this->error('公司 ID 无效。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
try {
|
||
$rows = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
|
||
} catch (JsonException) {
|
||
$this->error('唯品会JX账期明细不是有效 JSON。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
if (! is_array($rows) || $rows === []) {
|
||
$this->error('唯品会JX账期明细为空。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
try {
|
||
[$income, $expense] = $this->validateRows($rows, $period);
|
||
} catch (RuntimeException $exception) {
|
||
$this->error($exception->getMessage());
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
$existing = DB::table('ec_account_bills')
|
||
->where('company_id', $companyId)
|
||
->where('bill_type', 'vipshop-jx')
|
||
->where('payload->settle_period', $period)
|
||
->whereNull('deleted_at')
|
||
->count();
|
||
|
||
$this->table(['账期', '状态', '明细行数', '收入', '支出', '净额', '现有行数'], [[
|
||
$period,
|
||
$this->option('dry-run') ? 'validated' : 'ready',
|
||
count($rows),
|
||
number_format($income, 2, '.', ''),
|
||
number_format($expense, 2, '.', ''),
|
||
number_format($income - $expense, 2, '.', ''),
|
||
$existing,
|
||
]]);
|
||
|
||
if ($existing > 0) {
|
||
$this->error("{$period} 已有 {$existing} 行唯品会JX账单,为避免重复写入已停止。");
|
||
|
||
return self::FAILURE;
|
||
}
|
||
if ($this->option('dry-run')) {
|
||
return self::SUCCESS;
|
||
}
|
||
|
||
$lock = Cache::lock("vipshop-jx-import-{$companyId}-{$period}", 900);
|
||
if (! $lock->get()) {
|
||
$this->error('唯品会JX账单导入正在运行,请稍后重试。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
try {
|
||
DB::transaction(function () use ($rows, $companyId, $period): void {
|
||
$now = now();
|
||
foreach (array_chunk($rows, 500) as $chunk) {
|
||
$payload = array_map(static function (array $row) use ($companyId, $period, $now): array {
|
||
return [
|
||
'company_id' => $companyId,
|
||
'bill_type' => 'vipshop-jx',
|
||
'record_code' => (string) $row['record_code'],
|
||
'store_name' => (string) $row['store_name'],
|
||
'order_no' => (string) ($row['order_no'] ?? ''),
|
||
'amount' => (string) $row['amount'],
|
||
'bill_item' => (string) $row['bill_item'],
|
||
'occurred_at' => filled($row['occurred_at'] ?? null) ? (string) $row['occurred_at'] : null,
|
||
'income' => (string) $row['income'],
|
||
'expense' => (string) $row['expense'],
|
||
'balance' => '0',
|
||
'payload' => json_encode(
|
||
$row['payload'],
|
||
JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR,
|
||
),
|
||
'modifier' => '唯品会JX账单导入',
|
||
'created_from' => 'vipshop-jx:import',
|
||
'created_at' => $now,
|
||
'updated_at' => $now,
|
||
];
|
||
}, $chunk);
|
||
DB::table('ec_account_bills')->insert($payload);
|
||
}
|
||
});
|
||
} catch (Throwable $exception) {
|
||
report($exception);
|
||
$this->error('唯品会JX账单写入失败,详细原因已记录到受保护日志。');
|
||
|
||
return self::FAILURE;
|
||
} finally {
|
||
$lock->release();
|
||
}
|
||
|
||
$inserted = DB::table('ec_account_bills')
|
||
->where('company_id', $companyId)
|
||
->where('bill_type', 'vipshop-jx')
|
||
->where('payload->settle_period', $period)
|
||
->whereNull('deleted_at')
|
||
->selectRaw('COUNT(*) AS rows_count, COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense')
|
||
->first();
|
||
|
||
$this->table(['账期', '状态', '明细行数', '收入', '支出', '净额'], [[
|
||
$period,
|
||
'succeeded',
|
||
(int) $inserted->rows_count,
|
||
number_format((float) $inserted->income, 2, '.', ''),
|
||
number_format((float) $inserted->expense, 2, '.', ''),
|
||
number_format((float) $inserted->income - (float) $inserted->expense, 2, '.', ''),
|
||
]]);
|
||
|
||
return self::SUCCESS;
|
||
}
|
||
|
||
/**
|
||
* @param list<mixed> $rows
|
||
* @return array{0:float,1:float}
|
||
*/
|
||
private function validateRows(array $rows, string $period): array
|
||
{
|
||
$recordCodes = [];
|
||
$income = 0.0;
|
||
$expense = 0.0;
|
||
foreach ($rows as $index => $row) {
|
||
if (! is_array($row)) {
|
||
throw new RuntimeException('第 ' . ($index + 1) . ' 行不是有效对象。');
|
||
}
|
||
$recordCode = trim((string) ($row['record_code'] ?? ''));
|
||
if ($recordCode === '' || isset($recordCodes[$recordCode])) {
|
||
throw new RuntimeException('第 ' . ($index + 1) . ' 行记录编码为空或重复。');
|
||
}
|
||
$recordCodes[$recordCode] = true;
|
||
if (($row['payload']['settle_period'] ?? null) !== $period) {
|
||
throw new RuntimeException("第 " . ($index + 1) . " 行账单期间不是 {$period}。");
|
||
}
|
||
|
||
$amountRaw = $row['amount'] ?? '';
|
||
$incomeRaw = $row['income'] ?? '';
|
||
$expenseRaw = $row['expense'] ?? '';
|
||
if (! is_numeric($amountRaw) || ! is_numeric($incomeRaw) || ! is_numeric($expenseRaw)) {
|
||
throw new RuntimeException('第 ' . ($index + 1) . ' 行金额无效。');
|
||
}
|
||
$amount = (float) $amountRaw;
|
||
$rowIncome = (float) $incomeRaw;
|
||
$rowExpense = (float) $expenseRaw;
|
||
if (abs($amount - ($rowIncome - $rowExpense)) > 0.000001) {
|
||
throw new RuntimeException('第 ' . ($index + 1) . ' 行金额与收支不一致。');
|
||
}
|
||
$income += $rowIncome;
|
||
$expense += $rowExpense;
|
||
}
|
||
|
||
return [round($income, 6), round($expense, 6)];
|
||
}
|
||
}
|