diff --git a/app/Console/Commands/MatchReverseCourierBill.php b/app/Console/Commands/MatchReverseCourierBill.php new file mode 100644 index 000000000..a28eb5145 --- /dev/null +++ b/app/Console/Commands/MatchReverseCourierBill.php @@ -0,0 +1,60 @@ +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(); } + } +} diff --git a/app/Support/CourierBills/BillSurchargeQuoteCalculator.php b/app/Support/CourierBills/BillSurchargeQuoteCalculator.php index 31751655d..6f9a7f939 100644 --- a/app/Support/CourierBills/BillSurchargeQuoteCalculator.php +++ b/app/Support/CourierBills/BillSurchargeQuoteCalculator.php @@ -36,8 +36,8 @@ final class BillSurchargeQuoteCalculator ->orderByDesc('effective_at')->orderByDesc('id')->get(); $waybills = array_values(array_unique(array_column($input, 'waybill_no'))); $shipping = app(ShippingLookup::class); - $ships = $shipping->details($waybills); - $freights = $shipping->summaries($waybills); + $ships = $shipping->details($waybills, $allowedCouriers); + $freights = $shipping->summaries($waybills, $allowedCouriers); $needsService = $rules->contains(fn ($r) => $r->mode === '聚工单客服核实' || ($r->mode === '取发出运费' && trim($r->condition) === '查件扣单并且买家原因')); $workOrders = $needsService ? $this->workOrders($waybills, $month) : []; diff --git a/app/Support/CourierBills/CourierBillMatcher.php b/app/Support/CourierBills/CourierBillMatcher.php index 85a2e8f82..9364517fc 100644 --- a/app/Support/CourierBills/CourierBillMatcher.php +++ b/app/Support/CourierBills/CourierBillMatcher.php @@ -52,7 +52,12 @@ final class CourierBillMatcher } $unshipped = $this->unshipped->unshippedSources($waybills); $unshipped = array_change_key_case($unshipped, CASE_UPPER); - $shipping = $this->shipping->summaries($waybills); + $shipping = $this->shipping->summaries($waybills, $names); + foreach ($shipping as $key => $ship) { + if (($ship['data_source'] ?? null) !== '退件取件管理') continue; + unset($unshipped[$key]); + if (filled($ship['unshipped_source'] ?? null)) $unshipped[$key] = [$ship['unshipped_source']]; + } // 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号 $missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w]))); foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) { @@ -89,7 +94,7 @@ final class CourierBillMatcher $unprovided[$row['waybill']] = $row; } } - $unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided)); + $unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided), $names); $db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void { foreach ($updates as $id => $values) { @@ -484,7 +489,7 @@ final class CourierBillMatcher $rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, $freightSheets, $joint, $fileId, &$result): void { $assigned = $joint ? self::db()->table('courier_bill_lines')->where('file_id', $fileId) ->whereIn('waybill_no', $chunk->pluck('waybill_no'))->pluck('statement_id', 'waybill_no')->all() : []; - $shipping = $joint || $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all()); + $shipping = $joint || $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all(), array_keys($names)); foreach ($chunk as $row) { $express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? ''; $owner = $joint ? (int) ($assigned[$row->waybill_no] ?? 0) : ($names[$express] ?? $primary); diff --git a/app/Support/CourierBills/CourierBillStore.php b/app/Support/CourierBills/CourierBillStore.php index 4b8aff37d..aeb89ade7 100644 --- a/app/Support/CourierBills/CourierBillStore.php +++ b/app/Support/CourierBills/CourierBillStore.php @@ -701,7 +701,8 @@ final class CourierBillStore } $lines = $db->table('courier_bill_lines')->where('file_id', $fileId)->where('statement_id', $primaryStatementId)->orderBy('id')->get(['id', 'waybill_no']); - $ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all()); + $ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all(), + array_values(array_unique([...array_keys($own), ...array_keys($byName)]))); $moves = []; $strangers = []; foreach ($lines as $line) { @@ -777,7 +778,7 @@ final class CourierBillStore } $counts = []; $db->table('courier_bill_lines')->where('file_id', $fileId)->orderBy('id')->chunkById(500, function ($lines) use ($db, $owners, $month, &$statements, &$counts): void { - $shipping = $this->shipping->summaries($lines->pluck('waybill_no')->all()); + $shipping = $this->shipping->summaries($lines->pluck('waybill_no')->all(), array_keys($owners)); $moves = []; foreach ($lines as $line) { $raw = json_decode((string) $line->raw, true); diff --git a/app/Support/CourierBills/ReturnPickupLookup.php b/app/Support/CourierBills/ReturnPickupLookup.php new file mode 100644 index 000000000..8f83599c2 --- /dev/null +++ b/app/Support/CourierBills/ReturnPickupLookup.php @@ -0,0 +1,235 @@ + '中通快运逆向', '中通快运逆向' => '中通快运逆向', + '德邦' => '常州德邦逆向', '常州德邦逆向' => '常州德邦逆向', + '速寄递' => '申通退货', '申通' => '申通退货', '申通退货' => '申通退货', + '好省邮' => '好省邮快递', '好省邮快递' => '好省邮快递', + '百世' => '好省邮快递', '顺心捷达' => '好省邮快递', '顺丰' => '好省邮快递', + ]; + + private const HAO_QUOTES = ['百世' => '好省邮百世', '顺心捷达' => '好省邮顺心捷达', '顺丰' => '好省邮顺丰']; + private array $versions = []; + + private const MAIN = 'js_ekf_return_pickup_management'; + private const ITEMS = 'js_ekf_return_pickup_management_item'; + private const TRUTH = 'js_ekf_return_pickup_truth_express'; + private const CHUNK = 500; + + public function __construct(private readonly ReturnPickupFreightCalculator $calculator) {} + + public static function supports(array $names): bool + { + return array_intersect($names, array_values(self::CARRIERS)) !== []; + } + + private function connection(): ConnectionInterface + { + return DB::connection('business_mirror'); + } + + private function assertReady(): void + { + $schema = Schema::connection('business_mirror'); + foreach ([self::MAIN, self::ITEMS, self::TRUTH] as $table) { + if (! $schema->hasTable($table)) { + throw new RuntimeException('退件取件镜像未就绪,未更新逆向账单。'); + } + } + if (! $schema->hasTable('business_mirror_table_states') || $this->connection()->table('business_mirror_table_states') + ->whereIn('target_table', [self::MAIN, self::ITEMS, self::TRUTH])->whereNotNull('initial_completed_at')->count() !== 3) { + throw new RuntimeException('退件取件镜像首次同步未完成,未更新逆向账单。'); + } + } + + /** @return array> 大写单号 => 与发货明细相同的导出字段 */ + public function details(array $waybills, array $names): array + { + if ($waybills === [] || ! self::supports($names)) return []; + $this->assertReady(); + $db = $this->connection(); + $result = []; + foreach (array_chunk(array_values(array_unique(array_map([self::class, 'number'], $waybills))), self::CHUNK) as $chunk) { + $links = []; + $direct = $db->table(self::MAIN)->whereIn('returnExpressNo', $chunk)->get(); + foreach ($direct as $main) $links[self::number($main->returnExpressNo)][(int) $main->Id] = true; + foreach ($db->table(self::TRUTH)->whereIn('truthExpressNumber', $chunk)->get(['mId', 'truthExpressNumber']) as $link) { + $links[self::number($link->truthExpressNumber)][(int) $link->mId] = true; + } + $ids = []; + foreach ($links as $set) $ids += $set; + if ($ids === []) continue; + $mains = $db->table(self::MAIN)->whereIn('Id', array_keys($ids))->get()->keyBy('Id'); + $items = $db->table(self::ITEMS)->whereIn('mainTableId', array_keys($ids))->orderBy('id')->get()->groupBy('mainTableId'); + $truth = $db->table(self::TRUTH)->whereIn('mId', array_keys($ids))->get(['mId', 'truthExpressNumber'])->groupBy('mId'); + foreach ($links as $number => $set) { + $candidates = $mains->only(array_keys($set))->filter(fn ($m) => isset(self::CARRIERS[trim((string) $m->express_company)])); + if ($candidates->isEmpty()) continue; + $main = $candidates->first(); + $actual = array_values(array_unique(array_filter(array_map([self::class, 'number'], ($truth[$main->Id] ?? collect())->pluck('truthExpressNumber')->all())))); + $row = $this->row($main, ($items[$main->Id] ?? collect())->all(), $number); + if ($candidates->count() !== 1 || count($actual) > 1) { + $row = $this->uncalculated($row, '同号多张取件单或一单多个实退单号,需核实包裹归属'); + } elseif ($actual !== [] && ! in_array($number, $actual, true)) { + $row = $this->uncalculated($row, '退件已换单:' . implode('、', $actual)); + $row['_unshipped'] = $row['qc_status']; + } + $result[$number] = $row; + } + } + return $result; + } + + /** 仅实际取件月份内的有效单号;分批读取,不加载整张退件表。 */ + public function monthWaybills(array $names, string $month): \Generator + { + if (! self::supports($names)) return; + $this->assertReady(); + $sources = array_keys(array_filter(self::CARRIERS, fn ($name) => in_array($name, $names, true))); + $query = $this->connection()->table(self::MAIN)->whereIn('express_company', $sources) + ->where('expressPickupTime', '>=', $month . '-01') + ->where('expressPickupTime', '<', date('Y-m-d', strtotime($month . '-01 +1 month'))) + ->whereNotIn('orderStatus', ['ExpCanceled', 'TicketTimeoutClose'])->orderBy('Id'); + $lastId = 0; + do { + $mains = (clone $query)->where('Id', '>', $lastId)->limit(self::CHUNK)->get(); + if ($mains->isEmpty()) break; + $truth = $this->connection()->table(self::TRUTH)->whereIn('mId', $mains->pluck('Id'))->get(['mId', 'truthExpressNumber'])->groupBy('mId'); + foreach ($mains as $main) { + $actual = ($truth[$main->Id] ?? collect())->pluck('truthExpressNumber')->all(); + $numbers = array_values(array_unique(array_filter(array_map([self::class, 'number'], $actual)))); + if ($numbers === []) $numbers = array_filter([self::number($main->returnExpressNo)]); + foreach ($numbers as $number) yield ['waybill' => $number, 'ship_time' => (string) $main->expressPickupTime, + 'express_name' => self::CARRIERS[$main->express_company]]; + } + $lastId = (int) $mains->last()->Id; + } while ($mains->count() === self::CHUNK); + } + + private function row(object $main, array $items, string $number): array + { + $carrier = self::CARRIERS[trim((string) $main->express_company)]; + $package = $items === [] ? null : clone $items[0]; + if ($package !== null) { + $package->grossWeight = $package->packageVolume = 0.0; + $package->length = $package->width = $package->height = 0.0; + foreach ($items as $item) { + $quantity = max(0, (float) ($item->returnQuantity ?? 0)); + $package->grossWeight += (float) $item->grossWeight * $quantity; + $package->packageVolume += (float) $item->length * (float) $item->width * (float) $item->height * $quantity; + foreach (['length', 'width', 'height'] as $dimension) $package->$dimension = max($package->$dimension, (float) $item->$dimension); + } + } + $row = ['express_no' => $number, 'express_name1' => $carrier, 'ship_time' => $main->expressPickupTime, + 'trade_no' => $main->transactionNo ?? null, 'shop_name' => $main->shopName ?? null, + 'origin_state' => $main->province, 'origin_city' => $main->city ?? null, + 'data_source' => '退件取件管理', 'qc_freight' => 0.0, 'qc_charge_weight' => 0.0, + 'qc_settle_weight' => 0.0, 'qc_miandan' => 0.0, 'qc_extra_fee' => 0.0, 'qty' => 0.0, + 'weight_kg' => 0.0, 'qc_status' => 'OK', 'qc_quote_version' => '逆向物流报价/' . $carrier]; + $formulas = $products = $barcodes = []; + $reason = $items === [] ? '退件缺少商品重量尺寸明细' : null; + $rate = $package === null ? null : $this->calculate($main, $package, $carrier); + if ($rate !== null) { + if (! $rate['covered']) $reason = $rate['reason']; + $row['qc_freight'] += (float) $rate['total']; + $row['qc_charge_weight'] += (float) $rate['billable']; + $row['qc_settle_weight'] += (float) $rate['settlement']; + $row['qc_miandan'] += (float) $rate['base_amount']; + $row['qc_extra_fee'] += (float) $rate['surcharge']; + $row['qc_rate'] = $rate['increment_amount']; + if (isset($rate['quote_version'])) $row['qc_quote_version'] = $rate['quote_version']; + $formulas[] = '整票商品重量/体积合计,面单只计一次;' . ($rate['process'] ?? $rate['reason']); + } + $destinations = []; + foreach ($items as $item) { + $quantity = max(0, (float) ($item->returnQuantity ?? 0)); + if ($quantity <= 0 || ((float) $item->grossWeight <= 0 && (float) $item->length * (float) $item->width * (float) $item->height <= 0)) { + $reason = '退件商品缺少有效数量或重量'; + } + $row['qty'] += $quantity; + $row['weight_kg'] += (float) $item->grossWeight * $quantity; + $destinations[trim((string) $item->receiverAddress)] = true; + $row['receiver_address'] ??= $item->receiverAddress; + $row['receiver_state'] ??= ReturnPickupFreightCalculator::destinationProvince((string) $item->receiverAddress); + $row['receiver_name'] ??= $item->receiverName ?? null; + $row['warehouse_name'] ??= $item->warehouse ?? null; + foreach (['length_cm' => 'length', 'width_cm' => 'width', 'height_cm' => 'height'] as $field => $source) { + $row[$field] = max((float) ($row[$field] ?? 0), (float) $item->$source); + } + $products[] = $item->productName ?? ''; + $barcodes[] = $item->barcode ?? ''; + } + $row['volume_cm3'] = $package?->packageVolume; + if (count($destinations) > 1) $reason = '同一运单存在不同收件地址,需核实'; + $row['qc_freight'] = round($row['qc_freight'], 2); + $row['product_name'] = implode(',', array_unique(array_filter($products))); + $row['barcode'] = implode(',', array_unique(array_filter($barcodes))); + $row['qc_formula'] = implode(';', array_filter($formulas)); + if (in_array($main->orderStatus, ['ExpCanceled', 'TicketTimeoutClose'], true) || empty($main->expressPickupTime)) { + $row['_unshipped'] = '退件已取消、关闭或尚无实际取件时间'; + $reason = $row['_unshipped']; + } + return $reason === null ? $row : $this->uncalculated($row, $reason); + } + + private function calculate(object $main, object $item, string $carrier): array + { + if ($carrier !== '好省邮快递') { + return $this->calculator->calculate($carrier, $main->province, $item->receiverAddress, + (float) $item->grossWeight, $item->length, $item->width, $item->height, + $main->expressPickupTime ? substr($main->expressPickupTime, 0, 10) : null, $item->packageVolume); + } + $name = self::HAO_QUOTES[trim((string) $main->express_company)] ?? null; + $empty = ['covered' => false, 'total' => null, 'billable' => null, 'settlement' => null, + 'base_amount' => null, 'surcharge' => null, 'increment_amount' => null, 'process' => null]; + if ($name === null || empty($main->expressPickupTime)) return $empty + ['reason' => '好省邮缺少实际承运快递或取件日期']; + $versions = $this->versions[$name] ??= CourierQuoteVersion::query()->with(['signature', 'change'])->where('company_name', $name)->get(); + $version = CourierRequoteService::resolveAt($versions, Carbon::parse($main->expressPickupTime)); + if ($version === null) return $empty + ['reason' => '取件日期没有生效的' . $name . '报价']; + $values = json_decode((string) $version->values_json, true) ?: []; + $destination = ReturnPickupFreightCalculator::destinationProvince((string) $item->receiverAddress); + $city = null; + if (preg_match('/^(?:.+?省|.+?自治区)(.+?(?:市|自治州|地区|盟))/u', (string) $item->receiverAddress, $m)) $city = $m[1]; + elseif (in_array($destination, ['北京', '上海', '天津', '重庆'], true)) $city = $destination; + $cfg = FreightCarrierRules::for($name) + ['_name' => $name]; + $result = app(ShippingFreightCalculator::class)->calculate([ + 'express_name1' => $name, 'sender_state' => $main->province, 'sender_city' => $main->city ?? null, + 'receiver_state' => $destination, 'receiver_city' => $city, 'weight_kg' => (float) $item->grossWeight, + 'volume_cm3' => $item->packageVolume, + ], ['id' => $version->version_code, 'p' => QuoteSheet::parse($values), 'vals' => $values, + 'rules' => (string) $version->billing_rules], $cfg); + return ['covered' => $result['status'] === 'OK', 'reason' => $result['status'], 'total' => $result['fee'], + 'billable' => $result['charge_w'], 'settlement' => $result['settle_w'], + 'base_amount' => $result['first_price'] ?? $result['miandan'], 'surcharge' => $result['extra'], + 'increment_amount' => $result['rate'], 'process' => $result['formula'], 'quote_version' => $version->version_code]; + } + + private function uncalculated(array $row, string $reason): array + { + $row['qc_freight'] = $row['qc_charge_weight'] = null; + $row['qc_status'] = $reason; + return $row; + } + + private static function number(mixed $value): string + { + return strtoupper(trim((string) $value)); + } +} diff --git a/app/Support/CourierBills/ShippingLookup.php b/app/Support/CourierBills/ShippingLookup.php index e8e5bf24b..c69862dc5 100644 --- a/app/Support/CourierBills/ShippingLookup.php +++ b/app/Support/CourierBills/ShippingLookup.php @@ -34,6 +34,8 @@ final class ShippingLookup 'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)', 'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)', 'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态', + 'data_source' => '数据来源', + 'origin_state' => '始发省', 'origin_city' => '始发市', ]; /** 文本列:导出时保持文本,长数字不变科学计数法。 */ @@ -56,7 +58,7 @@ final class ShippingLookup * @param list $waybills * @return array 键为大写单号 */ - public function summaries(array $waybills): array + public function summaries(array $waybills, array $expressNames = []): array { $result = []; foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) { @@ -100,6 +102,11 @@ final class ShippingLookup } } + foreach (app(ReturnPickupLookup::class)->details($waybills, $expressNames) as $key => $row) { + $result[$key] = ['ship_time' => $row['ship_time'], 'express_name' => $row['express_name1'], + 'calc_freight' => $row['qc_freight'], 'charge_weight' => $row['qc_charge_weight'], + 'data_source' => $row['data_source'], 'unshipped_source' => $row['_unshipped'] ?? null]; + } return $result; } @@ -109,7 +116,7 @@ final class ShippingLookup * @param list $waybills * @return array> 键为大写单号 */ - public function details(array $waybills): array + public function details(array $waybills, array $expressNames = []): array { $result = []; foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) { @@ -189,7 +196,7 @@ final class ShippingLookup } } - return $result; + return array_replace($result, app(ReturnPickupLookup::class)->details($waybills, $expressNames)); } /** @@ -203,6 +210,9 @@ final class ShippingLookup if ($expressNames === []) { return; } + yield from app(ReturnPickupLookup::class)->monthWaybills($expressNames, $month); + $expressNames = array_values(array_diff($expressNames, array_values(ReturnPickupLookup::CARRIERS))); + if ($expressNames === []) return; // 按天走 ship_time 索引,单次只扫一天的发货行。 $day = strtotime($month . '-01'); $end = strtotime($month . '-01 +1 month'); diff --git a/app/Support/CourierBills/StatementExporter.php b/app/Support/CourierBills/StatementExporter.php index 49a1e8642..75df8ebe9 100644 --- a/app/Support/CourierBills/StatementExporter.php +++ b/app/Support/CourierBills/StatementExporter.php @@ -65,6 +65,8 @@ final class StatementExporter { $db = CourierBillMatcher::db(); $ids = $this->related($statementId); + $expressNames = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id') + ->whereIn('s.id', $ids)->pluck('g.express_names')->flatMap(fn ($value) => (array) json_decode((string) $value, true))->unique()->values()->all(); $multi = count($ids) > 1; $groupNames = []; $book = new StreamingWorkbook(); @@ -121,12 +123,12 @@ final class StatementExporter } foreach ($sheets as $name => $filter) { $headerWritten = false; - $this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, &$headerWritten): void { + $this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void { if (! $headerWritten) { $book->row($name, $fullHeader, true); $headerWritten = true; } - $details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines)); + $details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines), $expressNames); foreach ($lines as $line) { $ship = $details[strtoupper($line->waybill_no)] ?? []; $cells = $this->originalCells($line, $sources, $original); @@ -165,12 +167,12 @@ final class StatementExporter // 未提供:发货数据有、账单没有 $headerWritten = false; $db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id') - ->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, &$headerWritten): void { + ->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, $expressNames, &$headerWritten): void { if (! $headerWritten) { $book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true); $headerWritten = true; } - $details = $this->shipping->details($rows->pluck('waybill_no')->all()); + $details = $this->shipping->details($rows->pluck('waybill_no')->all(), $expressNames); foreach ($rows as $row) { $ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no]; $book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]); diff --git a/app/Support/ReturnPickupFreightCalculator.php b/app/Support/ReturnPickupFreightCalculator.php index ab09e9c6f..9ecf19790 100644 --- a/app/Support/ReturnPickupFreightCalculator.php +++ b/app/Support/ReturnPickupFreightCalculator.php @@ -53,6 +53,8 @@ class ReturnPickupFreightCalculator ?float $length = null, ?float $width = null, ?float $height = null, + ?string $pickupDate = null, + ?float $volumeCm3 = null, ): array { $carrier = self::CARRIER_MAP[trim((string) $expressCompany)] ?? null; @@ -63,8 +65,8 @@ class ReturnPickupFreightCalculator $length = max((float) $length, 0); $width = max((float) $width, 0); $height = max((float) $height, 0); - $volumeWeight = ($length > 0 && $width > 0 && $height > 0) - ? round($length * $width * $height / 6000, 4) + $volumeWeight = ($volumeCm3 !== null || ($length > 0 && $width > 0 && $height > 0)) + ? round(max(0, $volumeCm3 ?? ($length * $width * $height)) / 6000, 4) : 0.0; $settlement = round(max($grossWeight, $volumeWeight), 4); @@ -82,6 +84,9 @@ class ReturnPickupFreightCalculator } $rule = $this->rules[$carrier] ?? []; + if ($pickupDate !== null && ! empty($rule['effective_date']) && $pickupDate < $rule['effective_date']) { + return $this->missing('取件日期早于该逆向物流报价执行日期'); + } $mode = (string) ($rule['pricing_mode'] ?? ''); $maxSide = max($length, $width, $height); $sideSum = $length + $width + $height; diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index 25ecb6c81..19aa2807d 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -1101,6 +1101,9 @@ return [ ['updateTime', 'Id'], ['express_company', 'createTime', 'Id'], ['transactionNo', 'Id'], + ['Id'], + ['returnExpressNo', 'Id'], + ['express_company', 'expressPickupTime', 'Id'], ], ], 'jiansun.dbo.ekf_ReturnPickupManagement_Item' => [ diff --git a/database/migrations/2026_12_04_180000_index_return_pickup_bill_lookup.php b/database/migrations/2026_12_04_180000_index_return_pickup_bill_lookup.php new file mode 100644 index 000000000..07dc6aa37 --- /dev/null +++ b/database/migrations/2026_12_04_180000_index_return_pickup_bill_lookup.php @@ -0,0 +1,37 @@ + ['Id'], + 'return_pickup_bill_number' => ['returnExpressNo', 'Id'], + 'return_pickup_bill_month' => ['express_company', 'expressPickupTime', 'Id'], + ]; + + public function up(): void + { + $schema = Schema::connection('business_mirror'); + if (! $schema->hasTable(self::TABLE)) return; + $existing = array_column($schema->getIndexes(self::TABLE), 'columns'); + foreach (self::INDEXES as $name => $columns) { + if (! in_array(array_map('strtolower', $columns), array_map(fn ($v) => array_map('strtolower', $v), $existing), true)) { + $schema->table(self::TABLE, fn (Blueprint $table) => $table->index($columns, $name)); + } + } + } + + public function down(): void + { + $schema = Schema::connection('business_mirror'); + if (! $schema->hasTable(self::TABLE)) return; + $existing = array_column($schema->getIndexes(self::TABLE), 'name'); + foreach (array_keys(self::INDEXES) as $name) { + if (in_array($name, $existing, true)) $schema->table(self::TABLE, fn (Blueprint $table) => $table->dropIndex($name)); + } + } +}; diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index 89a0de301..bc261415c 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -1,4 +1,5 @@ [ + "courier-bills:match-reverse", "portal-freight:import-pending", "courier-surcharge:match-bills", "planting-reimbursement:auto-confirm", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 98bfad32a..10324440a 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -8,7 +8,7 @@ is_import=0 CAIWU_BATCH_CALLER_DIR="$PWD" export CAIWU_BATCH_CALLER_DIR case "${1:-}" in - portal-freight:import-pending|courier-surcharge:match-bills) is_import=1 ;; + portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse) is_import=1 ;; planting-reimbursement:auto-confirm) is_import=1 ;; jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels|courier-surcharge:pull-customer-service) ;; diff --git a/docs/逆向快递账单核算.md b/docs/逆向快递账单核算.md new file mode 100644 index 000000000..fdffc3ba8 --- /dev/null +++ b/docs/逆向快递账单核算.md @@ -0,0 +1,18 @@ +# 逆向快递账单核算 + +快递账单对账中的中通快运逆向、常州德邦逆向、申通退货、好省邮快递读取退件取件管理共享镜像。按退货单号和实退单号匹配,原单号已换单时不重复付款;同号多张取件单或一单多个实退单号保留待核实,不重复分配整单运费。普通快递仍按发货数据核对,常州德邦与常州德邦逆向分别处理。 + +以实际取件时间归属月份;取消、关闭或没有实际取件时间的记录列为未发出。中通、德邦、申通复用逆向报价试算规则。按用户确认口径,同一运单各商品的毛重×退货数量、长×宽×高×退货数量分别合计,整票计费,面单只收一次;基础运费与附加费分别保留。缺少重量、路线、报价或报价尚未生效时不填零价,显示系统未核算。导出保留退件商品、重量、计算公式、报价来源。 + +好省邮按取件记录的实际承运快递选择报价管理里的好省邮百世、好省邮顺心捷达或好省邮顺丰,复用现有源目省份及城市报价计算器,以取件日选择有效版本。 + +原始账单、人工处理结果及手工小汇总保留。仅对明确指定且未确认的账单重算,确认后的账单拒绝自动重算。服务器使用独立批处理入口(既有内存、超时和互斥限制): + +```sh +sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:match-reverse 12 --company=1 +sh /opt/caiwuxitong/run-finance-batch.sh courier-bills:match-reverse 12 --company=1 --apply +``` + +不带 `--apply` 只预演;实际执行前自动备份该账单的行、未提供明细和小汇总到私有目录。失败后可在核对备份与最新状态后重新运行;不批量处理其他账单。 + +退件主表约 31 万行、明细约 40 万行、实退单号约 19 万行;查询按单号分批,月份按快递和取件时间索引,关联按取件主键。迁移仅增加共享镜像索引,不写上游业务数据。 diff --git a/tests/Feature/Business/ReverseCourierBillTest.php b/tests/Feature/Business/ReverseCourierBillTest.php new file mode 100644 index 000000000..aaa02f9fc --- /dev/null +++ b/tests/Feature/Business/ReverseCourierBillTest.php @@ -0,0 +1,169 @@ +create('js_ekf_return_pickup_management', function (Blueprint $t): void { + $t->integer('Id')->primary(); + foreach (['returnExpressNo', 'express_company', 'orderStatus', 'expressPickupTime', 'province', 'city', 'transactionNo', 'shopName'] as $c) $t->string($c)->nullable(); + }); + $schema->create('js_ekf_return_pickup_management_item', function (Blueprint $t): void { + $t->increments('id'); $t->integer('mainTableId'); + foreach (['receiverAddress', 'receiverName', 'warehouse', 'productName', 'barcode'] as $c) $t->string($c)->nullable(); + foreach (['grossWeight', 'length', 'width', 'height', 'returnQuantity'] as $c) $t->float($c)->nullable(); + }); + $schema->create('js_ekf_return_pickup_truth_express', function (Blueprint $t): void { + $t->increments('Id'); $t->integer('mId'); $t->string('truthExpressNumber'); + }); + if (! $schema->hasTable('business_mirror_table_states')) { + $schema->create('business_mirror_table_states', function (Blueprint $t): void { + $t->string('dataset_key')->primary(); $t->string('source_key'); $t->string('source_object'); + $t->string('target_table'); $t->dateTime('initial_completed_at')->nullable(); + }); + } + foreach (['js_ekf_return_pickup_management', 'js_ekf_return_pickup_management_item', 'js_ekf_return_pickup_truth_express'] as $table) { + DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ + 'dataset_key' => $table, 'source_key' => 'test', 'source_object' => $table, + 'target_table' => $table, 'initial_completed_at' => now(), + ]); + } + $this->quotePath = tempnam(sys_get_temp_dir(), 'reverse-quote-'); + file_put_contents($this->quotePath, json_encode(['sheets' => [[ + 'name' => '中通快运逆向', 'values' => [ + ['中通快运逆向2026.4.21起'], ['省份', '面单费', '省份', '0-30kg', '31-60kg', '备注'], + ['浙江省', 9, '浙江省', 0.95, 0.95, '不足15kg按15kg'], + ], + ], [ + 'name' => '常州德邦逆向', 'values' => [ + ['常州德邦逆向报价2026.4.7'], ['出发省份', '到达省份江苏', null, '备注:'], + [null, '面单价格', '续重价格'], ['浙江', 9, 1, '面单+重量*费率'], + ], + ], [ + 'name' => '申通退货', 'values' => [ + ['报价单2026.5.1'], ['出发省份', '到达省份', '江苏', null], + [null, null, '面单价格', '续重价格'], [null, '浙江', 9, 1], + ], + ]]], JSON_UNESCAPED_UNICODE)); + $this->app->instance(ReverseLogisticsQuoteSnapshot::class, new ReverseLogisticsQuoteSnapshot($this->quotePath)); + } + + protected function tearDown(): void + { + @unlink($this->quotePath); + parent::tearDown(); + } + + private function pickup(int $id, string $number, array $main = [], array $item = []): void + { + $db = DB::connection('business_mirror'); + $db->table('js_ekf_return_pickup_management')->insert($main + [ + 'Id' => $id, 'returnExpressNo' => $number, 'express_company' => '中通快运', + 'orderStatus' => 'ExpAccepted', 'expressPickupTime' => '2026-11-05 12:00:00', 'province' => '浙江省', + ]); + $db->table('js_ekf_return_pickup_management_item')->insert($item + [ + 'mainTableId' => $id, 'grossWeight' => 39.1, 'length' => 112, 'width' => 45, 'height' => 24, + 'receiverAddress' => '江苏省常州市某仓', 'returnQuantity' => 1, 'productName' => '测试桌', 'barcode' => 'ITEM1', + ]); + } + + public function test_reverse_statement_matches_without_shipping_and_exports_return_details(): void + { + $this->pickup(1, 'OLD1'); + $this->pickup(2, 'UNBILLED'); + $this->pickup(3, 'CANCELED', ['orderStatus' => 'ExpCanceled']); + $this->pickup(4, 'PRIOR', ['expressPickupTime' => '2026-10-31 23:00:00']); + $this->pickup(5, 'UNKNOWN', [], ['grossWeight' => 0, 'length' => 0]); + $db = DB::connection('business_mirror'); + $db->table('js_ekf_return_pickup_truth_express')->insert(['mId' => 1, 'truthExpressNumber' => 'NEW1']); + $group = app(CourierBillStore::class)->saveGroup(null, ['name' => '中通快运逆向', 'express_names' => ['中通快运逆向']]); + $id = $db->table('courier_bill_statements')->insertGetId(['group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open']); + foreach (['NEW1', 'NEW1', 'OLD1', 'CANCELED', 'PRIOR', 'UNKNOWN', 'MISSING'] as $i => $number) { + $db->table('courier_bill_lines')->insert(['statement_id' => $id, 'file_id' => 0, 'sheet' => '测试账单', + 'raw' => '[]', 'waybill_no' => $number, 'bill_amount' => 47, 'row_no' => $i + 1]); + } + app(CourierBillMatcher::class)->match($id); + $lines = $db->table('courier_bill_lines')->where('statement_id', $id)->orderBy('id')->get(); + $this->assertSame([Category::MATCH, Category::DUPLICATE, Category::UNSHIPPED, Category::UNSHIPPED, + Category::PRIOR, Category::UNCALCULATED, Category::UNMATCHED], $lines->pluck('category')->all()); + $this->assertSame(47.0, (float) $lines[0]->calc_freight); + $this->assertSame('中通快运逆向', $lines[0]->express_name); + $this->assertSame(['UNBILLED'], $db->table('courier_bill_unprovided')->where('statement_id', $id)->orderBy('waybill_no')->pluck('waybill_no')->all()); + $row = app(ShippingLookup::class)->details(['NEW1'], ['中通快运逆向'])['NEW1']; + $this->assertSame('退件取件管理', $row['data_source']); + $this->assertSame('ITEM1', $row['barcode']); + $this->assertSame(40.0, $row['qc_charge_weight']); + $out = fopen('php://temp', 'w+'); + app(StatementExporter::class)->export($id, $out); + rewind($out); + $this->assertSame('PK', fread($out, 2)); + fclose($out); + } + + public function test_each_reverse_carrier_is_distinct_and_does_not_override_forward_lookup(): void + { + $this->pickup(1, 'DEPPON', ['express_company' => '德邦'], ['grossWeight' => 8.7, 'length' => 100, 'width' => 10, 'height' => 10]); + $this->pickup(2, 'STO', ['express_company' => '速寄递'], ['grossWeight' => 8.7, 'length' => 100, 'width' => 10, 'height' => 10]); + $this->pickup(3, 'OLDQUOTE', ['expressPickupTime' => '2026-04-01 12:00:00']); + $rows = app(ReturnPickupLookup::class)->details(['DEPPON', 'STO', 'OLDQUOTE'], ['常州德邦逆向']); + $this->assertSame(17.7, $rows['DEPPON']['qc_freight']); + $this->assertSame(17.0, $rows['STO']['qc_freight']); + $this->assertSame('申通退货', $rows['STO']['express_name1']); + $this->assertNull($rows['OLDQUOTE']['qc_freight']); + $this->assertSame([], app(ShippingLookup::class)->summaries(['DEPPON'], ['常州德邦'])); + } + + public function test_haosheng_uses_actual_carrier_and_effective_route_quote(): void + { + CourierQuoteVersion::create(['company_id' => $this->company->id, 'company_name' => '好省邮百世', + 'source_quote_id' => 'TEST', 'source_change_id' => 1, 'sheet_name' => '好省邮百世', + 'carrier_name' => '好省邮百世', 'created_by' => $this->user->id, 'approved_by' => $this->user->id, + 'version_code' => 'HAO-TEST', 'quote_type' => '标准快递报价', 'effective_date' => '2026-10-01', + 'signature_status' => '已签署并归档', 'status' => 'approved', 'values_json' => json_encode([ + ['出发省', '到达省', '组合', '首重10kg', '续重', '首重20kg', '续重', '首重30kg', '续重'], + ['浙江', '江苏', '', 20, 1, 30, 2, 40, 3], + ])]); + $this->company->makeCurrent(); + $this->pickup(1, 'HAO1', ['express_company' => '百世'], ['grossWeight' => 35]); + $row = app(ReturnPickupLookup::class)->details(['HAO1'], ['好省邮快递'])['HAO1']; + $this->assertSame('好省邮快递', $row['express_name1']); + $this->assertSame('HAO-TEST', $row['qc_quote_version']); + $this->assertSame(55.0, $row['qc_freight']); + } + + public function test_multiple_products_sum_weight_and_volume_but_charge_one_label(): void + { + $this->pickup(1, 'MULTI', [], ['grossWeight' => 10, 'length' => 60, 'width' => 50, 'height' => 40, 'returnQuantity' => 2]); + DB::connection('business_mirror')->table('js_ekf_return_pickup_management_item')->insert([ + 'mainTableId' => 1, 'grossWeight' => 5, 'length' => 0, 'width' => 0, 'height' => 0, + 'returnQuantity' => 1, 'receiverAddress' => '江苏省常州市某仓', + ]); + $row = app(ReturnPickupLookup::class)->details(['MULTI'], ['中通快运逆向'])['MULTI']; + $this->assertSame(25.0, $row['weight_kg']); + $this->assertSame(240000.0, $row['volume_cm3']); + $this->assertSame(40.0, $row['qc_charge_weight']); + $this->assertSame(9.0, $row['qc_miandan']); + $this->assertSame(47.0, $row['qc_freight']); + } +}