option('company'))->makeCurrent(true); $id = (int) $this->argument('statement'); $lock = Cache::lock('courier-bills:match-reverse:' . $id, 600); if (! $lock->get()) { $this->error('该账单正在核对'); return self::FAILURE; } try { $start = microtime(true); $db = CourierBillMatcher::db(); $statement = $db->table('courier_bill_statements')->find($id); if (! $statement || $statement->status === 'confirmed') { $this->error('账单不存在或已确认'); return self::FAILURE; } $group = $db->table('courier_bill_groups')->find($statement->group_id); $names = (array) json_decode($group->express_names, true); if (! ReturnPickupLookup::supports($names)) { $this->error('指定账单不属于逆向快递'); return self::FAILURE; } $lines = $db->table('courier_bill_lines')->where('statement_id', $id)->orderBy('id')->get(); $rows = $lookup->summaries($lines->pluck('waybill_no')->unique()->all(), $names); $total = $calculated = $matched = 0; foreach ($rows as $row) { $matched += ($row['data_source'] ?? '') === '退件取件管理' ? 1 : 0; if ($row['calc_freight'] !== null) { $calculated++; $total += $row['calc_freight']; } } $this->line(json_encode(['statement' => $id, 'group' => $group->name, 'month' => $statement->bill_month, 'lines' => $lines->count(), 'return_matches' => $matched, 'calculated_waybills' => $calculated, 'calculated_total' => round($total, 2)], JSON_UNESCAPED_UNICODE)); if ($this->option('apply')) { $path = 'private/operation-backups/reverse-bill-' . $id . '-' . gmdate('Ymd-His') . '.json'; $tables = ['courier_bill_lines', 'courier_bill_unprovided', 'courier_bill_summary_items']; $backup = ['statement' => $statement, 'group' => $group]; foreach ($tables as $table) $backup[$table] = $db->table($table)->where('statement_id', $id)->get()->all(); Storage::disk('local')->put($path, json_encode($backup, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)); $this->line('备份:' . $path); $matcher->match($id); $this->line(json_encode(['categories' => $db->table('courier_bill_lines')->where('statement_id', $id) ->groupBy('category')->selectRaw('category, COUNT(*) as count, SUM(bill_amount) as bill, SUM(self_amount) as self')->get(), 'unprovided' => $db->table('courier_bill_unprovided')->where('statement_id', $id)->count()], JSON_UNESCAPED_UNICODE)); } $this->line(json_encode(['elapsed_seconds' => round(microtime(true) - $start, 3), 'peak_memory_mb' => round(memory_get_peak_usage(true) / 1048576, 1)])); return self::SUCCESS; } finally { $lock->release(); } } }