CaiWuXiTong/app/Support/UnshippedWaybills.php

354 lines
18 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 App\Support\CourierBills\WaybillMatch;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
final class UnshippedWaybills
{
public const START = '2026-09-01';
public const HISTORY_PREFIX = 'history:';
public const SOURCES = ['intercept' => '现场拦截入库签收', 'replacement' => '换单未发出', 'warehouse' => '仓内未发'];
public const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F';
public const WAREHOUSE_EXCLUDED_STATUSES = [
'REJECT_AUDIT', 'DISABLED', 'REJECTED', 'REFUSED', 'CANCELED', 'CANCELLED', '已拒绝', '已取消',
];
private const INTERCEPT_TABLES = [
'intercept_regular' => ['ops_jst_return_refund_info', 'ops_jst_return_refund_item', 'ops_jst_orders'],
'intercept_taobao' => ['ops_jst_qmcust_refunds', 'ops_jst_qmcust_refund_items', 'ops_jst_qmcust_orders'],
];
public const SYNC_SOURCES = [
'intercept_regular' => '现场拦截入库签收 · 普通店铺',
'intercept_taobao' => '现场拦截入库签收 · 淘系店铺',
'replacement' => '换单未发出',
'warehouse' => '仓内未发',
];
public static function label(string $source): string
{
return self::SOURCES[isset(self::INTERCEPT_TABLES[$source]) ? 'intercept' : $source];
}
public static function storedSources(array $sources): array
{
if (in_array('intercept', $sources, true)) {
return [...$sources, ...array_keys(self::INTERCEPT_TABLES)];
}
return $sources;
}
public function connection()
{
return DB::connection('business_mirror');
}
public static function normalize(?string $number): string
{
return ltrim(preg_replace('/\s+/u', '', $number ?? '') ?? '', '@');
}
private static function isPlaceholder(?string $number): bool
{
// 外部仓占位标记不是运单号,不能作为未发出或换单依据。
return strcasecmp(self::normalize($number), 'OuterWMS') === 0;
}
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 (self::isPlaceholder($number) || !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 = [];
$numbers = array_values(array_unique(array_filter(array_map(self::normalize(...), $waybills),
fn ($number) => $number !== '' && !self::isPlaceholder($number))));
foreach (WaybillMatch::find($this->results(), 'waybill_no', $numbers, ['waybill_no', 'source']) as $number => $match) {
foreach ($match['rows'] as $row) {
$label = self::label($row->source);
$result[$number][$label] = $label;
}
}
return array_map(array_values(...), $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_regular', 'intercept_taobao' => $this->intercepts($source),
'replacement' => $this->replacements(),
'warehouse' => $this->warehouse(),
};
$historySource = isset(self::INTERCEPT_TABLES[$source]) ? 'intercept' : $source;
$history = $this->results()->where('source', $historySource)->where('evidence_no', 'like', self::HISTORY_PREFIX.'%');
$cutoff = (clone $history)->max('evidence_time');
if ($cutoff !== null) {
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
$rows = array_filter($rows, fn ($row) => (str_starts_with($row['evidence_no'], 'shipping:') || substr($row['evidence_time'], 0, 10) > substr($cutoff, 0, 10))
&& !isset($covered[$row['waybill_no']]));
}
$db->transaction(function () use ($db, $source, $rows, $missing): void {
$this->results()->where('source', $source)->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->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,
]);
if (isset(self::INTERCEPT_TABLES[$source]) && $db->table('courier_unshipped_sync')
->whereIn('source', array_keys(self::INTERCEPT_TABLES))->whereNotNull('last_success_at')->count() === 2) {
$this->results()->where('source', 'intercept')->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->delete();
}
});
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(string $source): array
{
$db = $this->connection();
$rows = [];
$missing = 0;
[$refunds, $items, $orders] = self::INTERCEPT_TABLES[$source];
$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' => $source, '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 (self::isPlaceholder($log->old_waybill) || self::isPlaceholder($log->new_waybill)) continue;
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 ($this->connection()->getSchemaBuilder()->hasColumn('jst_oms_shipping', 'front_no')) {
$ships = $this->connection()->table('jst_oms_shipping')->where('ship_time', '>=', self::START)
->whereNotNull('front_no')->where('front_no', '<>', '')->whereColumn('front_no', '<>', 'express_no')
->select(['id', 'source_id', 'front_no', 'express_no', 'trade_no', 'ship_time', 'express_name1'])->lazyById(500);
foreach ($ships as $ship) {
$old = self::normalize($ship->front_no); $new = self::normalize($ship->express_no);
if ($old === '' || $new === '' || $old === $new || self::isPlaceholder($old) || self::isPlaceholder($new)) continue;
// 旧号码仍是现有发货包裹时,不因另一条换单记录把它排除。
if ($this->connection()->table('jst_oms_shipping')->whereIn('express_no', [$old, '@'.$old])->exists()) continue;
$rows['shipping:'.$ship->source_id.'|'.$old] = [
'source' => 'replacement', 'waybill_no' => $old, 'courier_name' => null,
'evidence_no' => 'shipping:'.$ship->source_id, 'trade_no' => $ship->trade_no,
'evidence_time' => $ship->ship_time, 'new_courier_name' => $ship->express_name1,
'new_waybill_no' => $new, 'evidence_text' => '发货镜像明确记录换单前单号;依据时间为发货时间,非换单操作时间',
];
}
}
if ($currentOrder === null && $rows === []) throw new RuntimeException('尚无订单操作日志或发货换单记录。');
return [$rows, 0];
}
/** 完整批次才发布;失败/中断保留上一版及历史导入。 */
public function publishStage(string $source, string $generation, int $missing): int
{
$db = $this->connection();
return $db->transaction(function () use ($db, $source, $generation, $missing): int {
$historySource = in_array($source, ['intercept_regular', 'intercept_taobao'], true) ? 'intercept' : $source;
$history = $this->results()->where('source', $historySource)->where('evidence_no', 'like', self::HISTORY_PREFIX.'%');
$cutoff = (clone $history)->max('evidence_time');
$covered = array_fill_keys((clone $history)->pluck('waybill_no')->all(), true);
$this->results()->where('source', $source)->where('evidence_no', 'not like', self::HISTORY_PREFIX.'%')->delete();
$count = 0;
$db->table('courier_unshipped_stage')->where('source', $source)->where('generation', $generation)
->orderBy('row_key')->chunkById(300, function ($batch) use ($cutoff, $covered, &$count): void {
$rows = [];
foreach ($batch as $row) {
if ($cutoff !== null && (substr($row->evidence_time, 0, 10) <= substr($cutoff, 0, 10) || isset($covered[$row->waybill_no]))) continue;
$values = (array) $row; unset($values['generation'], $values['row_key']); $rows[] = $values;
}
if ($rows !== []) { $this->results()->insert($rows); $count += count($rows); }
}, 'row_key');
$db->table('courier_unshipped_sync')->updateOrInsert(['source' => $source], [
'last_success_at' => now(), 'row_count' => $count, 'missing_count' => $missing, 'warning' => null,
]);
return $count;
});
}
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()) {
return [$this->withWarehouseCouriers($this->warehouseFromJiansun()), 0];
}
$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),
];
}
return [$this->withWarehouseCouriers($rows), 0];
}
private function warehouseFromJiansun(): array
{
// The verified warehouse work orders are mirrored from jst_workOrderInfo.
$table = 'js_jst_work_order_info';
$this->assertMirrorReady([$table]);
$workOrders = $this->connection()->table($table)->where('woTypeId', self::WAREHOUSE_WORK_TYPE)
->where('createTime', '>=', self::START)
->where(fn ($q) => $q->whereNull('status')->orWhereNotIn('status', self::WAREHOUSE_EXCLUDED_STATUSES))
->select(['Id', 'woNo', 'status', 'title', 'createTime', 'businessFieldList']);
$rows = [];
foreach ($workOrders->lazyById(500, 'Id') as $order) {
$fields = [];
foreach (json_decode((string) $order->businessFieldList, true) ?? [] as $field) {
if (is_array($field) && isset($field['fieldId']) && is_scalar($field['value'] ?? null)) {
$fields[$field['fieldId']] = (string) $field['value'];
}
}
$number = self::normalize($fields['lIdField'] ?? null);
if ($number === '') continue;
$rows[$order->woNo.'|'.$number] = [
'source' => 'warehouse', 'waybill_no' => $number, 'courier_name' => '',
'evidence_no' => $order->woNo, 'evidence_time' => $order->createTime,
'o_id' => $fields['o_id'] ?? null, 'evidence_text' => trim(($order->status ?? '').' '.$order->title),
];
}
return $rows;
}
private function withWarehouseCouriers(array $rows): array
{
$db = $this->connection();
$numbers = array_unique(array_column(array_filter($rows, fn ($row) => $row['courier_name'] === ''), 'waybill_no'));
$shipping = [];
if ($numbers !== [] && !$db->getSchemaBuilder()->hasTable('jst_oms_shipping')) {
return $rows;
}
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;
}
}