CaiWuXiTong/modules/EcommerceFinance/Console/ApplyShippingCorrections.php

83 lines
6.0 KiB
PHP
Raw Permalink 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\Freight\ShippingFreightService;
use Modules\EcommerceFinance\Services\Jushuitan\ShippingWeightPrecision;
use RuntimeException;
/** 有限、已核对的运单修正;备份原值,事务中写入并仅重算目标包裹。 */
class ApplyShippingCorrections extends Command
{
protected $signature = 'jushuitan:apply-shipping-corrections {file : JSON确认值文件,最多1000票} {--month= : YYYY-MM} {--dry-run}';
protected $description = '备份并应用确认的发货重量、地区、返货线路,定向重算运费';
public function handle(ShippingFreightService $freight): int
{
$month = (string) $this->option('month');
if (! preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month)) throw new RuntimeException('需要有效月份 YYYY-MM');
$path = (string) $this->argument('file');
if (! is_file($path) || filesize($path) > 262144) throw new RuntimeException('修正文件不存在或超过256KiB');
$input = json_decode(file_get_contents($path), true, 16, JSON_THROW_ON_ERROR);
if (! is_array($input) || ! array_is_list($input) || $input === [] || count($input) > 1000) throw new RuntimeException('需要1至1000条修正记录');
$allowed = ['online_weight', 'return_origin', 'return_destination', 'receiver_state', 'receiver_city', 'receiver_district'];
$byWaybill = [];
foreach ($input as $row) {
$waybill = $row['express_no'] ?? '';
if (! is_string($waybill) || ! preg_match('/^[A-Za-z0-9]{5,100}$/', $waybill) || isset($byWaybill[$waybill])) throw new RuntimeException('运单号无效或重复');
$values = array_intersect_key($row, array_flip($allowed));
if ($values === [] || array_diff(array_keys($row), ['express_no', ...$allowed]) !== []) throw new RuntimeException('修正字段无效');
foreach ($values as $key => $value) {
if ($key === 'online_weight') {
if (! is_numeric($value) || ShippingWeightPrecision::positive($value) === null || abs((float) $value - round((float) $value, 4)) > 0.000000001) throw new RuntimeException('线上重量必须是最多4位小数的正数');
} elseif (! is_string($value) || trim($value) === '' || mb_strlen($value) > 100) throw new RuntimeException('地区或线路名称无效');
}
$byWaybill[$waybill] = $values;
}
$db = DB::connection((string) config('jushuitan.connection', 'business_mirror'));
$db->disableQueryLog();
$from = $month . '-01 00:00:00';
$to = date('Y-m-d H:i:s', strtotime($from . ' +1 month'));
$variants = [...array_keys($byWaybill), ...array_map(static fn ($w) => '@' . $w, array_keys($byWaybill))];
$rows = $db->table('jst_oms_shipping')->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
->whereIn('express_no', $variants)->orderBy('id')->get();
$groups = [];
foreach ($rows as $row) $groups[ltrim((string) $row->express_no, '@')][] = $row;
$before = $db->table(ShippingWeightPrecision::CORRECTIONS)->where('ship_month', $month)->whereIn('express_no', array_keys($byWaybill))->get();
$existing = $before->keyBy('express_no');
$corrections = [];
foreach ($byWaybill as $waybill => $values) {
$matches = $groups[$waybill] ?? [];
if ($matches === [] || count(array_unique(array_column($matches, 'source_id'))) !== 1 || count(array_unique(array_column($matches, 'express_name1'))) !== 1) throw new RuntimeException('运单缺失或匹配多个包裹:' . $waybill);
$record = array_fill_keys($allowed, null);
if (isset($existing[$waybill])) $record = array_intersect_key((array) $existing[$waybill], $record);
$corrections[] = array_replace($record, $values, ['ship_month' => $month, 'express_no' => (string) $waybill,
'carrier' => $matches[0]->express_name1, 'source' => 'user-confirmed',
'created_at' => $existing[$waybill]->created_at ?? now(), 'updated_at' => now()]);
}
$ids = $rows->pluck('source_id')->unique()->values()->all();
$this->info('匹配:' . count($byWaybill) . '个运单,' . count($ids) . '个包裹,' . $rows->count() . '行。');
if ($this->option('dry-run')) return self::SUCCESS;
$backup = ['month' => $month, 'input_sha256' => hash_file('sha256', $path), 'shipping' => $rows->all(),
'freight' => $db->table('jst_oms_shipping_freight')->whereIn('source_id', $ids)->get()->all(), 'corrections' => $before->all()];
$folder = storage_path('app/private/shipping-corrections');
if (! is_dir($folder) && ! mkdir($folder, 0700, true)) throw new RuntimeException('无法建立备份目录');
$backupPath = $folder . '/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.json';
if (file_put_contents($backupPath, json_encode($backup, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX) === false) throw new RuntimeException('备份失败');
chmod($backupPath, 0600);
$result = $db->transaction(function () use ($db, $rows, $corrections, $allowed, $ids, $freight): array {
$db->table(ShippingWeightPrecision::CORRECTIONS)->upsert($corrections, ['ship_month', 'express_no', 'carrier'], [...$allowed, 'source', 'updated_at']);
foreach (app(ShippingWeightPrecision::class)->shipmentRows($rows->map(static fn ($r) => (array) $r)->all()) as $row) {
$db->table('jst_oms_shipping')->where('id', $row['id'])->update(array_intersect_key($row, array_flip(['online_weight', 'receiver_state', 'receiver_city', 'receiver_district'])));
}
return $freight->recalculateSourceIds($ids);
});
$this->info('备份:' . $backupPath);
$this->info('修正并核算完成:' . json_encode($result, JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
}
}