299 lines
14 KiB
PHP
299 lines
14 KiB
PHP
<?php
|
||
|
||
namespace App\Support;
|
||
|
||
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' => '仓内未发'];
|
||
|
||
private const WAREHOUSE_WORK_TYPE = '78FC156B524645E886F21A32ED67133F';
|
||
private 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 ?? '') ?? '', '@');
|
||
}
|
||
|
||
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) {
|
||
$label = self::label($row->source);
|
||
$result[$row->waybill_no][$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) => 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 ($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()) {
|
||
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;
|
||
}
|
||
}
|