option('all-open') && $this->option('statement') === []) { $this->error('请选择对账单或 --all-open'); return self::FAILURE; } if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) { $this->error('请通过 run-finance-batch.sh 执行'); return self::FAILURE; } Company::findOrFail((int) $this->option('company'))->makeCurrent(true); $lock = Cache::lock('courier-bills:refresh-settlement', 3900); if (! $lock->get()) { $this->error('结算刷新正在运行'); return self::FAILURE; } $started = microtime(true); $queries = 0; $sqlMs = 0.0; DB::listen(static function ($query) use (&$queries, &$sqlMs): void { $queries++; $sqlMs += $query->time; }); $db = CourierBillMatcher::db(); $folder = 'private/courier-settlement/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4)); try { $ids = $db->table('courier_bill_statements')->where('status', '<>', 'confirmed') ->when(! $this->option('all-open'), fn ($q) => $q->whereIn('id', $this->option('statement'))) ->where('line_count', '>', 0)->orderBy('id')->pluck('id'); foreach ($ids as $id) { $result = $db->transaction(function () use ($db, $id, $matcher, $subsidy, $folder) { $statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first(); if (! $statement || $statement->status === 'confirmed') return ['statement' => $id, 'skipped' => true]; $beforeSummary = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('id')->get(); $beforeFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->orderBy('id')->get(); $stream = null; if ($this->option('apply')) { $path = $folder . '/' . $id . '.ndjson'; Storage::disk('local')->put($path, ''); $stream = fopen(Storage::disk('local')->path($path), 'wb'); if (! $stream) throw new \RuntimeException('无法保存备份'); fwrite($stream, json_encode(['statement' => $statement, 'summary' => $beforeSummary, 'surcharges' => $beforeFees], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n"); } $changed = 0; $decrease = 0.0; $scanned = 0; try { foreach ($db->table('courier_bill_lines')->where('statement_id', $id) ->when($this->option('express') !== [], fn ($q) => $q->whereIn('express_name', $this->option('express'))) ->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->resolution !== null || ! in_array($line->category, [...Category::PAYABLE, Category::PRIOR], true)) continue; $amount = CourierBillMatcher::selfAmount((string) $line->category, $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $line->resolution, $line->express_name); if (($amount === null) === ($line->self_amount === null) && ($amount === null || abs($amount - (float) $line->self_amount) < 0.00001)) continue; $changed++; $decrease += (float) $line->self_amount - (float) $amount; if ($this->option('apply')) $db->table('courier_bill_lines')->where('id', $line->id)->update(['self_amount' => $amount]); } } finally { if ($stream) fclose($stream); } $weight = $subsidy->summary((int) $id); $existing = $beforeSummary->firstWhere('label', WeightDifferenceSubsidy::LABEL); $subsidyChanged = ! ($existing?->manual) && abs((float) ($existing?->self_amount ?? 0) - $weight['amount']) > 0.00001; $feeChanges = 0; $feeDecrease = 0.0; foreach ($beforeFees as $fee) { if ($this->option('express') === [] && $fee->self_amount !== null && $fee->bill_amount !== null && (float) $fee->bill_amount < (float) $fee->self_amount) { $feeChanges++; $feeDecrease += (float) $fee->self_amount - round((float) $fee->bill_amount, 2); if ($this->option('apply')) $db->table('bill_surcharge_matches')->where('id', $fee->id)->update([ 'self_amount' => round((float) $fee->bill_amount, 2), 'match_note' => $fee->match_note . ';快递提供金额较低,按快递金额结算', ]); } } if ($this->option('apply') && ($changed > 0 || $subsidyChanged || $feeChanges > 0)) { $matcher->refreshSummary((int) $id, false); // 只允许报价核价金额按较低的快递提供金额下调。 $fields = ['file_id', 'sheet', 'row_no', 'waybill_no', 'item', 'bill_amount', 'self_amount']; $normalize = static fn ($rows) => $rows->map(fn ($r) => array_intersect_key((array) $r, array_flip($fields)))->sortBy(fn ($r) => json_encode($r))->values()->all(); $expectedFees = $beforeFees->map(function ($fee) { $copy = clone $fee; if ($this->option('express') === [] && $copy->self_amount !== null && $copy->bill_amount !== null && (float) $copy->bill_amount < (float) $copy->self_amount) $copy->self_amount = number_format((float) $copy->bill_amount, 2, '.', ''); return $copy; }); $afterFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->get(); if ($normalize($expectedFees) != $normalize($afterFees)) throw new \RuntimeException('附加费来源发生变化,本张账单已回退'); $protected = static fn ($rows) => $rows->filter(fn ($r) => $r->manual || ($r->label !== WeightDifferenceSubsidy::LABEL && in_array(SummaryMapper::classify($r->label), ['AL', 'supplement'], true))) ->map(fn ($r) => [$r->label, $r->bill_amount === null ? null : (float) $r->bill_amount, $r->self_amount === null ? null : (float) $r->self_amount, (bool) $r->manual]) ->sortBy(fn ($r) => json_encode($r))->values()->all(); if ($protected($beforeSummary) != $protected($db->table('courier_bill_summary_items')->where('statement_id', $id)->get())) { throw new \RuntimeException('人工金额、配件扣款或补记账发生变化,本张账单已回退'); } } return ['statement' => $id, 'month' => $statement->bill_month, 'scanned' => $scanned, 'changed' => $changed, 'settlement_decrease' => round($decrease, 2), 'weight_subsidy' => $weight, 'fee_changes' => $feeChanges, 'fee_decrease' => round($feeDecrease, 2), 'applied' => (bool) $this->option('apply')]; }); $this->line(json_encode($result, 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' => round(memory_get_peak_usage(true) / 1048576, 2), '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(); } } }