CaiWuXiTong/modules/EcommerceFinance/Console/ImportShengsuanOrderProfitDetails.php
renshen d79a1eedfe feat: 成本运费异常接入完整订单商品明细 (#1004)
合并 PR #1004:补全订单商品明细并按条码识别缺成本。
2026-11-09 11:02:21 +08:00

72 lines
2.7 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 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;
}
}