CaiWuXiTong/app/Support/UnshippedWaybills.php

219 lines
11 KiB
PHP
Raw 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 App\Support;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
final class UnshippedWaybills
{
public const START = '2026-09-01';
public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发'];
public function connection()
{
return DB::connection('business_mirror');
}
public static function normalize(?string $number): string
{
return ltrim(preg_replace('/\s+/u', '', $number ?? '') ?? '', '@');
}
public static function parseRemark(string $remark): ?array
{
if (!preg_match('/^\s*([^::]+)[::]([^::]+?)\s*->\s*([^::]+)[::]([^::]+)\s*$/u', $remark, $parts)) {
return null;
}
$old = self::normalize($parts[2]);
$new = self::normalize($parts[4]);
foreach ([$old, $new] as $number) {
if (!preg_match('/^[A-Za-z0-9-]{1,96}$/', $number) || preg_match('/^\d+(?:\.\d+)?e[+-]?\d+$/i', $number)) return null;
}
return ['old_waybill' => $old, 'new_waybill' => $new, 'old_courier' => trim($parts[1]), 'new_courier' => trim($parts[3])];
}
public function results()
{
return $this->connection()->table('courier_unshipped_waybills');
}
public function unshippedSources(array $waybills): array
{
$result = [];
foreach (array_chunk(array_unique(array_filter(array_map(self::normalize(...), $waybills))), 500) as $chunk) {
foreach ($this->results()->whereIn('waybill_no', $chunk)->distinct()->get(['waybill_no', 'source']) as $row) {
$result[$row->waybill_no][] = self::SOURCES[$row->source];
}
}
return $result;
}
public function sync(string $source): bool
{
$db = $this->connection();
try {
// Read all dependencies before replacing a source's last successful result.
[$rows, $missing] = match ($source) {
'intercept' => $this->intercepts(),
'replacement' => $this->replacements(),
'warehouse' => $this->warehouse(),
};
$db->transaction(function () use ($db, $source, $rows, $missing): void {
$this->results()->where('source', $source)->delete();
foreach (array_chunk(array_values($rows), 500) as $chunk) {
$this->results()->insert($chunk);
}
$db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], [
'last_success_at' => now(), 'row_count' => count($rows), 'missing_count' => $missing, 'warning' => null,
]);
});
return true;
} catch (Throwable $error) {
if (!$error instanceof RuntimeException || !in_array($error->getMessage(), ['未导入订单操作日志。', '未找到仓内未发工单类型或单号字段。', '依赖镜像暂无数据。', '依赖镜像尚未完成同步。'], true)) {
report($error);
$warning = '读取失败,保留上次同步结果。';
} else {
$warning = $error->getMessage();
}
$db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], ['warning' => $warning]);
return false;
}
}
private function assertMirrorReady(array $tables): void
{
$db = $this->connection();
foreach ($tables as $table) {
if (!$db->table($table)->exists()) throw new RuntimeException('依赖镜像暂无数据。');
}
$datasets = array_keys(array_filter(config('upstream_mirrors.datasets', []),
fn ($dataset) => in_array($dataset['target'] ?? null, $tables, true)));
if ($datasets !== [] && $db->getSchemaBuilder()->hasTable('business_mirror_table_states')
&& $db->table('business_mirror_table_states')->whereIn('dataset_key', $datasets)
->where(fn ($query) => $query->whereNull('initial_completed_at')->orWhere('status', 'failed'))->exists()) {
throw new RuntimeException('依赖镜像尚未完成同步。');
}
}
private function intercepts(): array
{
$db = $this->connection();
$rows = [];
$missing = 0;
foreach ([
['ops_jst_return_refund_info', 'ops_jst_return_refund_item', 'ops_jst_orders'],
['ops_jst_qmcust_refunds', 'ops_jst_qmcust_refund_items', 'ops_jst_qmcust_orders'],
] as [$refunds, $items, $orders]) {
$this->assertMirrorReady([$refunds, $items, $orders]);
$refundRows = $db->table($refunds.' as r')->where('r.question_type', self::SOURCES['intercept'])
->join($items.' as i', 'i.as_id', '=', 'r.as_id')->where('i.receive_date', '>=', self::START)
->groupBy('r.as_id', 'r.o_id', 'r.so_id', 'r.shop_name')
->get(['r.as_id', 'r.o_id', 'r.so_id', 'r.shop_name', DB::raw('min('.$db->getQueryGrammar()->wrap('i.receive_date').') as received')]);
foreach ($refundRows->chunk(500) as $batch) {
$ordersById = $db->table($orders)->whereIn('o_id', $batch->pluck('o_id')->filter()->unique()->all())
->orderBy('l_id')->get(['o_id', 'l_id', 'logistics_company'])
->filter(fn ($order) => self::normalize($order->l_id) !== '')->groupBy('o_id');
foreach ($batch as $refund) {
$order = $ordersById->get($refund->o_id)?->first();
if (!$order) {
$missing++;
continue;
}
$number = self::normalize($order->l_id);
$key = $refund->as_id.'|'.$number;
if (isset($rows[$key]) && $rows[$key]['evidence_time'] <= $refund->received) continue;
$rows[$key] = [
'source' => 'intercept', 'waybill_no' => $number, 'evidence_no' => $refund->as_id,
'evidence_time' => $refund->received, 'courier_name' => $order->logistics_company,
'o_id' => $refund->o_id, 'trade_no' => $refund->so_id, 'shop_name' => $refund->shop_name,
'evidence_text' => self::SOURCES['intercept'],
];
}
}
}
return [$rows, $missing];
}
private function replacements(): array
{
$logs = $this->connection()->table('courier_unshipped_order_logs')->where('operated_at', '>=', self::START)
->where('operated_at', '<', today())->orderBy('order_no')->orderByDesc('operated_at')->orderByDesc('id')->cursor();
$rows = [];
$currentOrder = null;
$finalNumber = null;
foreach ($logs as $log) {
if ($currentOrder !== $log->order_no) {
$currentOrder = $log->order_no;
$finalNumber = $log->new_waybill;
}
if ($log->old_waybill === $finalNumber) continue;
$key = $log->order_no.'|'.$log->old_waybill;
$rows[$key] ??= [
'source' => 'replacement', 'waybill_no' => $log->old_waybill, 'courier_name' => $log->old_courier,
'evidence_no' => $log->order_no, 'o_id' => $log->order_no, 'evidence_time' => $log->operated_at,
'evidence_text' => $log->remark, 'operator' => $log->operator,
'new_courier_name' => $log->new_courier, 'new_waybill_no' => $log->new_waybill,
];
}
if ($currentOrder === null) throw new RuntimeException('未导入订单操作日志。');
return [$rows, 0];
}
private function warehouse(): array
{
$db = $this->connection();
$this->assertMirrorReady(['ops_work_order_form_config', 'ops_work_order_main', 'ops_work_order_form_value']);
$latest = $db->table('ops_work_order_form_config')->selectRaw('work_type, max(id) as id')->groupBy('work_type');
$types = $db->table('ops_work_order_form_config as c')->joinSub($latest, 'latest', 'latest.id', '=', 'c.id')
->where('c.work_type_name', self::SOURCES['warehouse'])->pluck('c.work_type');
if ($types->isEmpty()) {
throw new RuntimeException('未找到仓内未发工单类型或单号字段。');
}
$workFields = $db->table('ops_work_order_main as w')->join('ops_work_order_form_value as v', 'v.main_order_no', '=', 'w.order_no')
->whereIn('w.work_type', $types)->where('w.create_time', '>=', self::START)
->where(fn ($q) => $q->whereNull('w.is_deleted')->orWhere('w.is_deleted', 0))
->where(fn ($q) => $q->whereNull('v.is_deleted')->orWhere('v.is_deleted', 0));
$numberField = static fn ($q) => $q->where('v.field_code', 'lIdField')->orWhereIn('v.field_name', ['快递单号', '运单号', '物流单号']);
if (!(clone $workFields)->where($numberField)->exists()) {
throw new RuntimeException('未找到仓内未发工单类型或单号字段。');
}
$workOrders = (clone $workFields)->where($numberField)
->where(fn ($q) => $q->whereNull('w.status')->orWhereNotIn('w.status', ['已拒绝', '已取消']))
->orderByDesc('v.id')->get(['w.order_no', 'w.status', 'w.title', 'w.create_time', 'v.field_value']);
$couriers = (clone $workFields)->whereIn('v.field_name', ['快递名称', '快递公司', '物流公司'])
->orderBy('v.id')->pluck('v.field_value', 'w.order_no');
$rows = [];
foreach ($workOrders as $order) {
$number = self::normalize($order->field_value);
if ($number === '') continue;
$rows[$order->order_no.'|'.$number] ??= [
'source' => 'warehouse', 'waybill_no' => $number, 'courier_name' => trim($couriers[$order->order_no] ?? ''),
'evidence_no' => $order->order_no, 'evidence_time' => $order->create_time,
'evidence_text' => trim(($order->status ?? '').' '.$order->title),
];
}
$numbers = array_unique(array_column(array_filter($rows, fn ($row) => $row['courier_name'] === ''), 'waybill_no'));
$shipping = [];
foreach (array_chunk($numbers, 500) as $chunk) {
foreach ($db->table('jst_oms_shipping')->whereIn('express_no', $chunk)->get(['express_no', 'express_name1', 'express_name2']) as $item) {
$shipping[$item->express_no] = $item->express_name1 ?: $item->express_name2;
}
}
foreach ($rows as &$row) {
$row['courier_name'] = $row['courier_name'] ?: ($shipping[$row['waybill_no']] ?? null);
}
return [$rows, 0];
}
}