CaiWuXiTong/app/Console/Commands/BackfillDropshipBillWeights.php

77 lines
5.4 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use App\Support\DropshipFreight\{DropshipConfirmation, FactoryBillParser};
use Illuminate\Console\Command;
use Illuminate\Support\Facades\{Cache, DB, Storage};
/** 只从已上传原件回补缺失重量,不重导运费、附加费或确认记录。 */
final class BackfillDropshipBillWeights extends Command
{
protected $signature = 'dropship-freight:backfill-weights {--file=*} {--all} {--company=1} {--apply}';
protected $description = '预演或备份回补厂家原账单重量,保留所有已有金额';
public function handle(FactoryBillParser $parser, DropshipConfirmation $confirmation): int
{
if (! $this->option('all') && $this->option('file') === []) {
$this->error('请选择 --file 或 --all'); return self::FAILURE;
}
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
$this->error('请通过 run-finance-batch.sh 执行'); return self::FAILURE;
}
$company = (int) $this->option('company'); Company::findOrFail($company)->makeCurrent(true);
$lock = Cache::lock('dropship-freight:backfill-weights', 3900);
if (! $lock->get()) { $this->error('重量回补正在执行'); return self::FAILURE; }
$db = DB::connection('business_mirror'); $started = microtime(true); $queries = 0; $sqlMs = 0;
DB::listen(static function ($q) use (&$queries, &$sqlMs) { $queries++; $sqlMs += $q->time; });
$folder = 'private/dropship-weight/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4));
try {
foreach ($db->table('dropship_bill_files')->where('status', 'parsed')->whereNotNull('factory_id')
->when(! $this->option('all'), fn ($q) => $q->whereIn('id', $this->option('file')))->orderBy('id')->lazyById(20) as $file) {
if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') {
$this->line(json_encode(['file' => $file->id, 'skipped' => '厂家已确认'], JSON_UNESCAPED_UNICODE)); continue;
}
$path = Storage::disk('local')->path($file->stored_path);
if (! is_file($path)) throw new \RuntimeException('原件缺失:' . $file->id);
$parsed = $parser->parse($path, pathinfo($path, PATHINFO_EXTENSION))['lines'];
$report = $db->transaction(function () use ($db, $file, $parsed, $folder, $confirmation, $company) {
$db->table('dropship_bill_files')->where('id', $file->id)->lockForUpdate()->first();
if (($confirmation->state($file->bill_month, $file->factory_id, $company)['status'] ?? '') === 'confirmed') {
return ['file' => $file->id, 'skipped' => '厂家已确认'];
}
$stream = null; $scanned = $filled = $missing = $mismatched = 0;
if ($this->option('apply')) {
Storage::disk('local')->put($folder . '/' . $file->id . '.ndjson', '');
$stream = fopen(Storage::disk('local')->path($folder . '/' . $file->id . '.ndjson'), 'wb');
if (! $stream) throw new \RuntimeException('无法创建备份');
fwrite($stream, json_encode(['file' => $file], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
}
try {
foreach ($db->table('dropship_bill_lines')->where('file_id', $file->id)->orderBy('id')->lazyById(500) as $line) {
$scanned++;
if ($stream) fwrite($stream, json_encode(['line' => $line], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
if ($line->bill_weight !== null) continue;
$source = $parsed[$line->waybill_no] ?? null;
if ($source === null || mb_substr($source['sheet'], 0, 64) !== $line->sheet || $source['row'] !== $line->row_no
|| abs($source['amount'] - (float) $line->amount) > 0.0001) { $mismatched++; continue; }
if ($source['weight'] === null) { $missing++; continue; }
$filled++;
if ($this->option('apply')) $db->table('dropship_bill_lines')->where('id', $line->id)->whereNull('bill_weight')
->update(['bill_weight' => $source['weight']]);
}
} finally { if ($stream) fclose($stream); }
return ['file' => $file->id, 'month' => $file->bill_month, 'factory' => $file->factory_id,
'scanned' => $scanned, 'filled' => $filled, 'missing' => $missing, 'mismatched' => $mismatched, 'applied' => (bool) $this->option('apply')];
});
unset($parsed); $this->line(json_encode($report, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
$this->info(json_encode(['backup' => $this->option('apply') ? $folder : null, 'seconds' => round(microtime(true) - $started, 3),
'peak_mib' => memory_get_peak_usage(true) / 1048576, 'queries' => $queries, 'sql_ms' => round($sqlMs, 2)], JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
} catch (\Throwable $e) { report($e); $this->error($e->getMessage()); return self::FAILURE; }
finally { $lock->release(); }
}
}