72 lines
2.7 KiB
PHP
72 lines
2.7 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Console;
|
||
|
||
use Illuminate\Console\Command;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Modules\EcommerceFinance\Services\ShengsuanOrderProfitDetailMapper;
|
||
|
||
class ImportShengsuanOrderProfitDetails extends Command
|
||
{
|
||
protected $signature = 'order-profit:import-shengsuan-details
|
||
{--file= : 聚胜算订单明细接口返回的 JSON 文件路径}
|
||
{--stdin : 从标准输入读取 JSON,忽略 --file}';
|
||
|
||
protected $description = '导入聚胜算订单及退货商品明细快照,供成本/运费异常页面按条码核查';
|
||
|
||
public function handle(ShengsuanOrderProfitDetailMapper $mapper): int
|
||
{
|
||
$path = trim((string) $this->option('file'));
|
||
$raw = $this->option('stdin')
|
||
? stream_get_contents(STDIN)
|
||
: (($path !== '' && is_file($path)) ? file_get_contents($path) : '');
|
||
if (! is_string($raw) || trim($raw) === '') {
|
||
$this->error('未读取到聚胜算订单明细 JSON。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
try {
|
||
$decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
|
||
} catch (\JsonException) {
|
||
$this->error('聚胜算订单明细 JSON 无法解析。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
$snapshots = $mapper->snapshots(is_array($decoded) ? $decoded : []);
|
||
if ($snapshots === []) {
|
||
$this->warn('JSON 中没有可导入的订单商品明细。');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
||
foreach (array_chunk($snapshots, 50) as $chunk) {
|
||
$connection->transaction(static function () use ($connection, $mapper, $chunk): void {
|
||
$connection->table($mapper->table())->upsert(
|
||
$chunk,
|
||
['order_key'],
|
||
[
|
||
'shop_name', 'online_order_no', 'internal_order_no',
|
||
'item_count', 'after_item_count', 'missing_cost_item_count',
|
||
'order_headers', 'order_items', 'after_headers', 'after_items',
|
||
'missing_cost_barcodes', 'synced_at', 'updated_at',
|
||
],
|
||
);
|
||
});
|
||
}
|
||
|
||
$items = array_sum(array_column($snapshots, 'item_count'));
|
||
$missing = array_sum(array_column($snapshots, 'missing_cost_item_count'));
|
||
$this->info(sprintf(
|
||
'聚胜算订单明细导入完成:%d 单、%d 条销售商品,其中缺成本商品 %d 条。',
|
||
count($snapshots),
|
||
$items,
|
||
$missing,
|
||
));
|
||
|
||
return self::SUCCESS;
|
||
}
|
||
}
|