Files
zyt/server/app/command/SyncTrackingNumbers.php
T
2026-04-30 09:27:42 +08:00

122 lines
4.6 KiB
PHP

<?php
declare(strict_types=1);
namespace app\command;
use app\common\service\ExpressTrackingService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
/**
* 同步现有订单快递单号到物流追踪表
*
* 使用方法:
* php think express:sync
*/
class SyncTrackingNumbers extends Command
{
protected function configure()
{
$this->setName('express:sync')
->setDescription('同步现有订单快递单号到物流追踪表');
}
protected function execute(Input $input, Output $output)
{
$output->writeln('开始同步现有订单快递单号...');
$startTime = microtime(true);
try {
// 终态订单不再触发查件:已完成(3)/已取消(4)/已签收(6)/暂不制药(8)/拒收(9)/退款(10)/保留药方(11)/制药缓发(12)
$terminalFulfillmentStatus = [3, 4, 6, 8, 9, 10, 11, 12];
// 查询所有有快递单号、未结案、且未上传甘草的订单
// 已上传甘草(gancao_reciperl_order_no 非空)的物流由甘草侧 GancaoLogisticsRouteService 拉取,不重复走快递100
$orders = Db::name('tcm_prescription_order')
->where('tracking_number', '<>', '')
->whereNull('delete_time')
->whereNotIn('fulfillment_status', $terminalFulfillmentStatus)
->whereRaw("TRIM(COALESCE(gancao_reciperl_order_no, '')) = ''")
->field([
'id',
'tracking_number',
'express_company',
'recipient_name',
'recipient_phone',
'shipping_address',
])
->select()
->toArray();
$total = count($orders);
$success = 0;
$skipped = 0;
$failed = 0;
$output->writeln("找到 {$total} 个有快递单号、未结案、未上传甘草的订单(已跳过已完成/已取消/已签收等终态及甘草已托管订单)");
foreach ($orders as $order) {
try {
// 检查是否已存在
$exists = Db::name('express_tracking')
->where('tracking_number', $order['tracking_number'])
->whereNull('delete_time')
->count();
if ($exists > 0) {
$skipped++;
$output->writeln("跳过: {$order['tracking_number']} (已存在)");
continue;
}
// 创建追踪记录
$result = ExpressTrackingService::createOrUpdate([
'order_id' => $order['id'],
'order_type' => 'prescription',
'tracking_number' => $order['tracking_number'],
'express_company' => $order['express_company'] ?: 'auto',
'recipient_phone' => $order['recipient_phone'],
'recipient_name' => $order['recipient_name'],
'recipient_address' => $order['shipping_address'],
]);
if ($result) {
$success++;
$output->writeln("成功: {$order['tracking_number']}");
} else {
$failed++;
$output->writeln("失败: {$order['tracking_number']}");
}
} catch (\Throwable $e) {
$failed++;
$output->error("错误: {$order['tracking_number']} - {$e->getMessage()}");
}
}
$duration = round(microtime(true) - $startTime, 2);
$output->writeln('');
$output->writeln('========================================');
$output->writeln('同步完成!');
$output->writeln('========================================');
$output->writeln("总数: {$total}");
$output->writeln("成功: {$success}");
$output->writeln("跳过: {$skipped}");
$output->writeln("失败: {$failed}");
$output->writeln("耗时: {$duration}秒");
$output->writeln('');
$output->writeln('现在可以运行定时任务测试:');
$output->writeln(' php think express:auto-update');
return 0;
} catch (\Throwable $e) {
$output->error("同步失败: " . $e->getMessage());
return 1;
}
}
}