每日汇总快递未发出明细 (#1512)

This commit is contained in:
limeng 2026-11-27 15:40:40 +08:00
parent 0a7cc700fb
commit 92f88fb60b
12 changed files with 681 additions and 1 deletions

View File

@ -0,0 +1,28 @@
<?php
namespace App\Console\Commands;
use App\Support\UnshippedWaybills;
use Illuminate\Console\Command;
final class SyncUnshippedWaybills extends Command
{
protected $signature = 'courier:sync-unshipped-waybills';
protected $description = '从共享镜像和已导入订单日志重算未发出明细';
public function handle(UnshippedWaybills $waybills): int
{
$failed = false;
foreach (UnshippedWaybills::SOURCES as $source => $label) {
if (!$waybills->sync($source)) {
$this->warn($label.':未就绪或同步失败。');
$failed = true;
} else {
$state = $waybills->connection()->table('courier_unshipped_sync')->where('source', $source)->first();
$this->info($label.':'.$state->row_count.' 行,缺单号 '.$state->missing_count.' 行。');
}
}
return $failed ? self::FAILURE : self::SUCCESS;
}
}

View File

@ -5724,6 +5724,7 @@ class Pages extends Controller
'courier-surcharge-settlement' => $this->contentForCourierSurchargeSettlementPage(),
'freight-difference', 'other-surcharge-summary', 'return-fee' => $this->contentForCourierPayableSummary($page),
'accessory-reship-deductions' => app(\Modules\EcommerceFinance\View\AccessoryReshipPageData::class)->page(),
'unshipped-waybills' => app(\App\Http\Controllers\Business\UnshippedWaybillController::class)->page(request()),
'shipping-data' => $this->contentForShippingData(),
'return-pickup-management' => $this->contentForReturnPickupManagement(),
'withdrawal-management' => $this->contentForWithdrawalManagement(),

View File

@ -0,0 +1,168 @@
<?php
namespace App\Http\Controllers\Business;
use Illuminate\Routing\Controller;
use App\Support\UnshippedWaybills;
use App\Utilities\SystemAccess;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Throwable;
final class UnshippedWaybillController extends Controller
{
public function __construct(private readonly UnshippedWaybills $waybills) {}
public function page(Request $request): array
{
$data = ['view' => 'business.pages.courier-payables.unshipped-waybills', 'sources' => UnshippedWaybills::SOURCES,
'canImport' => $this->canImport(), 'rows' => null, 'states' => collect(), 'coverage' => null, 'unavailable' => false];
try {
$data['rows'] = $this->filtered($request)->orderByDesc('evidence_time')->orderByDesc('id')->paginate(50)->withQueryString();
$db = $this->waybills->connection();
$data['states'] = $db->table('courier_unshipped_sync')->get()->keyBy('source');
$data['coverage'] = $db->table('courier_unshipped_order_logs')->selectRaw('min(operated_at) as start_at,max(operated_at) as end_at')->first();
} catch (\Illuminate\Database\QueryException $error) {
report($error);
$data['unavailable'] = true;
}
return $data;
}
private function filtered(Request $request)
{
$filters = $request->validate([
'waybills' => ['nullable', 'string', 'max:15000'],
'sources' => ['nullable', 'array', 'max:3'],
'sources.*' => [Rule::in(array_keys(UnshippedWaybills::SOURCES))],
'courier' => ['nullable', 'string', 'max:255'],
'from' => ['nullable', 'date_format:Y-m-d'],
'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'],
]);
$query = $this->waybills->results();
$numbers = array_values(array_unique(array_filter(array_map(UnshippedWaybills::normalize(...),
preg_split('/[\r\n,,]+/u', $filters['waybills'] ?? '') ?: []), fn ($number) => $number !== '')));
if (count($numbers) > 500) throw ValidationException::withMessages(['waybills' => '最多同时查询 500 个快递单号。']);
if ($numbers !== []) $query->whereIn('waybill_no', $numbers);
if (!empty($filters['sources'])) $query->whereIn('source', $filters['sources']);
if (!empty($filters['courier'])) $query->where('courier_name', trim($filters['courier']));
if (!empty($filters['from'])) $query->where('evidence_time', '>=', $filters['from']);
if (!empty($filters['to'])) $query->where('evidence_time', '<', CarbonImmutable::parse($filters['to'])->addDay()->toDateString());
return $query;
}
public function export(Request $request)
{
$query = $this->filtered($request);
return response()->streamDownload(function () use ($query): void {
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->fromArray(['来源', '未发出单号', '快递名称', '交易单号', '店铺', '依据单号', '依据时间', '依据说明', '换单后快递', '换单后单号', '操作人']);
$line = 2;
foreach ($query->orderBy('id')->lazyById(1000) as $row) {
$values = [UnshippedWaybills::SOURCES[$row->source], $row->waybill_no, $row->courier_name, $row->trade_no,
$row->shop_name, $row->evidence_no, $row->evidence_time, $row->evidence_text, $row->new_courier_name, $row->new_waybill_no, $row->operator];
foreach ($values as $column => $value) {
$sheet->setCellValueExplicit(chr(65 + $column).$line, (string) $value, DataType::TYPE_STRING);
}
$line++;
}
(new Xlsx($book))->save('php://output');
$book->disconnectWorksheets();
}, '未发出明细.xlsx');
}
public function import(Request $request)
{
abort_unless($this->canImport(), 403);
$file = $request->validate(['log' => ['required', 'file', 'mimes:xlsx,csv,txt', 'max:10240']])['log'];
$isCsv = strtolower($file->getClientOriginalExtension()) === 'csv';
$entries = [];
$header = null;
$errors = [];
foreach ($this->fileRows($file->getRealPath(), $isCsv) as $line => $row) {
if ($header === null) {
$header = array_flip(array_map(fn ($value) => trim((string) $value, "\xEF\xBB\xBF \t"), $row));
if (array_diff(['订单编号', '类型', '操作备注', '操作时间', '操作人'], array_keys($header))) {
throw ValidationException::withMessages(['log' => '文件缺少订单编号、类型、操作备注、操作时间或操作人列。']);
}
continue;
}
if (trim((string) ($row[$header['类型']] ?? '')) !== '修改快递单号') continue;
$remark = (string) ($row[$header['操作备注']] ?? '');
$parsed = UnshippedWaybills::parseRemark($remark);
$order = trim((string) ($row[$header['订单编号']] ?? ''));
$time = $row[$header['操作时间']] ?? null;
try {
$operated = is_int($time) || is_float($time)
? CarbonImmutable::instance(Date::excelToDateTimeObject($time))
: (filled($time) ? CarbonImmutable::parse($time) : null);
} catch (Throwable) {
$operated = null;
}
if (!$parsed || !$operated || !preg_match('/^[A-Za-z0-9-]{1,96}$/', $order) || preg_match('/^\d+e[+-]?\d+$/i', $order)) {
if (count($errors) < 10) $errors[] = $line;
continue;
}
if ($operated->toDateString() < UnshippedWaybills::START || $operated->toDateString() >= today()->toDateString()) continue;
$entries[] = $parsed + ['order_no' => $order, 'operated_at' => $operated->toDateTimeString(),
'operator' => trim((string) ($row[$header['操作人']] ?? '')), 'remark' => $remark];
}
if ($errors !== []) {
throw ValidationException::withMessages(['log' => '这些行的订单编号、时间或备注格式有误(含科学计数法单号):'.implode('、', $errors).'。请修正后重新上传。']);
}
if ($entries === []) throw ValidationException::withMessages(['log' => '没有符合日期及操作类型的记录。']);
$db = $this->waybills->connection();
$count = $db->transaction(function () use ($db, $entries): int {
$count = 0;
foreach (array_chunk($entries, 500) as $batch) {
$count += $db->table('courier_unshipped_order_logs')->insertOrIgnore($batch);
}
return $count;
});
return back()->with('unshipped_import', '已新增 '.$count.' 条日志,下次每日同步后更新换单明细。');
}
private function fileRows(string $path, bool $isCsv): iterable
{
if ($isCsv) {
$file = new \SplFileObject($path);
$file->setCsvControl(',', '"', '');
$file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
foreach ($file as $index => $row) {
if ($row !== [null]) yield $index + 1 => $row;
}
return;
}
$reader = IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(true);
$book = $reader->load($path);
try {
foreach ($book->getSheet(0)->getRowIterator() as $row) {
yield $row->getRowIndex() => array_map(
fn ($cell) => $cell->getValue(),
iterator_to_array($row->getCellIterator(), false)
);
}
} finally {
$book->disconnectWorksheets();
}
}
private function canImport(): bool
{
return in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true);
}
}

View File

@ -0,0 +1,218 @@
<?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];
}
}

View File

@ -827,6 +827,7 @@ $navigation = [
['slug' => 'agreement-signing', 'title' => '协议签署'],
['slug' => 'shipping-data', 'title' => '发货数据'],
['slug' => 'accessory-reship-deductions', 'title' => '配件补发扣款'],
['slug' => 'unshipped-waybills', 'title' => '未发出明细'],
['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'],
['slug' => 'bookkeeping-details', 'title' => '记账明细'],
['slug' => 'compensation-details', 'title' => '赔偿明细'],
@ -893,6 +894,7 @@ $navigation = [
],
['slug' => 'shipping-data', 'title' => '发货数据'],
['slug' => 'accessory-reship-deductions', 'title' => '配件补发扣款'],
['slug' => 'unshipped-waybills', 'title' => '未发出明细'],
['slug' => 'return-pickup-management', 'title' => '退货取件管理'],
['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'],
['slug' => 'warehouse-freight', 'title' => '仓储费'],

View File

@ -0,0 +1,51 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
$schema = Schema::connection('business_mirror');
$schema->create('courier_unshipped_waybills', function (Blueprint $table): void {
$table->id();
$table->string('source', 32);
$table->string('waybill_no', 96)->index();
$table->string('evidence_no', 96);
$table->dateTime('evidence_time')->index();
foreach (['courier_name', 'trade_no', 'o_id', 'shop_name', 'new_courier_name', 'new_waybill_no', 'operator'] as $column) {
$table->string($column)->nullable();
}
$table->text('evidence_text')->nullable();
$table->unique(['source', 'evidence_no', 'waybill_no'], 'unshipped_source_evidence_waybill');
});
$schema->create('courier_unshipped_sync', function (Blueprint $table): void {
$table->string('source', 32)->primary();
$table->dateTime('last_success_at')->nullable();
$table->unsignedInteger('row_count')->default(0);
$table->unsignedInteger('missing_count')->default(0);
$table->string('warning')->nullable();
});
$schema->create('courier_unshipped_order_logs', function (Blueprint $table): void {
$table->id();
$table->string('order_no', 96);
$table->dateTime('operated_at')->index();
$table->string('old_waybill', 96);
$table->string('new_waybill', 96);
$table->string('old_courier');
$table->string('new_courier');
$table->string('operator')->nullable();
$table->text('remark');
$table->unique(['order_no', 'operated_at', 'old_waybill'], 'unshipped_log_identity');
});
}
public function down(): void
{
$schema = Schema::connection('business_mirror');
$schema->dropIfExists('courier_unshipped_order_logs');
$schema->dropIfExists('courier_unshipped_sync');
$schema->dropIfExists('courier_unshipped_waybills');
}
};

View File

@ -224,6 +224,7 @@ CRON_TZ=Asia/Shanghai
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。
50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1

View File

@ -228,6 +228,7 @@ CRON_TZ=Asia/Shanghai
# 商品月加权与成本:先算月加权单价,再同步商品成本,避免成本先于价格生成。
0 18 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh finance:monthly-weighted-product-cost:auto >/dev/null 2>&1
# 店铺违规信息预警:每天 05:30 把副本库抓取结果追平到统一表(本地补充字段不覆盖)。
10 5 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh courier:sync-unshipped-waybills --quiet >/dev/null 2>&1
30 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan store-violations:sync --quiet >/dev/null 2>&1
# 顾家发货明细:每天补齐货号到物料编号的唯一映射;无唯一命中时保留空值。
50 5 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-kuka-posting-material-map --quiet >/dev/null 2>&1

View File

@ -9,7 +9,7 @@ CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:calc-freight) ;;
jushuitan:calc-freight|courier:sync-unshipped-waybills) ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
esac

View File

@ -0,0 +1,83 @@
@php
$activeSection = request()->route('section') === 'courier-payables-final' ? 'courier-payables-final' : 'courier-payables';
$routePrefix = 'business.' . $activeSection . '.unshipped-waybills.';
@endphp
<section class="rounded-lg border border-gray-200 bg-white p-4" aria-label="未发出明细">
@if($unavailable)
<p role="alert" class="rounded bg-yellow-50 p-3 text-yellow-900">未发出明细暂不可用,请确认共享镜像结果表可读取。</p>
@else
<div class="grid gap-3 md:grid-cols-3">
@foreach($sources as $key => $label)
@php($state = $states->get($key))
<div class="rounded border border-gray-200 p-3">
<strong>{{ $label }}</strong>
<div>最近成功 {{ $state->last_success_at ?? '—' }} · {{ isset($state->last_success_at) ? number_format($state->row_count) . ' 行' : '待同步' }}</div>
@if($state->missing_count ?? 0)
<div>缺少原订单单号 {{ number_format($state->missing_count) }} 行</div>
@endif
@if($state->warning ?? !isset($state->last_success_at))
<p class="mt-2 rounded bg-yellow-50 p-2 text-yellow-900" role="status">{{ $state->warning ?? '等候首次同步。' }}</p>
@endif
</div>
@endforeach
</div>
@if(isset($errors) && $errors->any())
<ul class="my-3 rounded bg-yellow-50 p-3 text-yellow-900" role="alert">
@foreach($errors->all() as $message)<li>{{ $message }}</li>@endforeach
</ul>
@endif
@if(session('unshipped_import'))
<p class="my-3" role="status">{{ session('unshipped_import') }}</p>
@endif
<form method="get" class="my-4 flex flex-wrap items-end gap-3">
<label>快递单号<textarea name="waybills" rows="2" class="block rounded border-gray-300" placeholder="多个单号用逗号或换行分隔">{{ request('waybills') }}</textarea></label>
<fieldset>
<legend>来源</legend>
@foreach($sources as $key => $label)
<label class="mr-2"><input type="checkbox" name="sources[]" value="{{ $key }}" @checked(in_array($key, (array) request('sources', []), true))> {{ $label }}</label>
@endforeach
</fieldset>
<label>快递名称<input name="courier" value="{{ request('courier') }}" class="block rounded border-gray-300"></label>
<label>依据时间起<input type="date" name="from" value="{{ request('from') }}" class="block rounded border-gray-300"></label>
<label>依据时间止<input type="date" name="to" value="{{ request('to') }}" class="block rounded border-gray-300"></label>
<button class="rounded border border-gray-300 px-3 py-2" type="submit">查询</button>
<a class="rounded border border-gray-300 px-3 py-2" href="{{ route($routePrefix . 'export', request()->only(['waybills', 'sources', 'courier', 'from', 'to'])) }}">导出 XLSX</a>
</form>
<div class="overflow-x-auto">
<table class="w-full text-left text-sm">
<thead class="bg-gray-50"><tr>
@foreach(['来源', '未发出单号', '快递名称', '交易单号', '店铺', '依据单号', '依据时间', '依据说明', '换单后快递及单号'] as $heading)
<th scope="col" class="p-2 whitespace-nowrap">{{ $heading }}</th>
@endforeach
</tr></thead>
<tbody>
@forelse($rows as $row)
<tr class="border-t border-gray-200">
@foreach([$sources[$row->source], $row->waybill_no, $row->courier_name, $row->trade_no, $row->shop_name, $row->evidence_no, $row->evidence_time, $row->evidence_text, trim(($row->new_courier_name ?? '') . ' ' . ($row->new_waybill_no ?? ''))] as $value)
<td class="p-2">{{ filled($value) ? $value : '—' }}</td>
@endforeach
</tr>
@empty
<tr><td colspan="9" class="p-4 text-center">当前条件下没有明细。</td></tr>
@endforelse
</tbody>
</table>
</div>
{{ $rows->links() }}
<div class="mt-4 border-t border-gray-200 pt-3">
<p>订单操作日志已导入记录日期:{{ $coverage->start_at ? substr($coverage->start_at, 0, 10) . ' 至 ' . substr($coverage->end_at, 0, 10) : '尚未导入' }}</p>
@if($canImport)
<form method="post" action="{{ route($routePrefix . 'import') }}" enctype="multipart/form-data" class="mt-2 flex flex-wrap items-end gap-2">
@csrf
<label>上传订单操作日志<input type="file" name="log" required accept=".xlsx,.csv" class="block"></label>
<button type="submit" class="rounded border border-gray-300 px-3 py-2">导入</button>
</form>
@endif
</div>
@endif
</section>

View File

@ -685,6 +685,16 @@ Route::get('workspace/courier-payables/shipping-data/suggest', 'Business\\Pages@
->middleware('business.page:courier-payables,shipping-data')
->name('business.courier-payables.shipping-data.suggest');
foreach (['courier-payables', 'courier-payables-final'] as $unshippedSection) {
Route::prefix('workspace/'.$unshippedSection.'/unshipped-waybills')
->middleware('business.page:'.$unshippedSection.',unshipped-waybills')
->name('business.'.$unshippedSection.'.unshipped-waybills.')
->group(function () {
Route::get('export', [\App\Http\Controllers\Business\UnshippedWaybillController::class, 'export'])->name('export');
Route::post('import', [\App\Http\Controllers\Business\UnshippedWaybillController::class, 'import'])->name('import');
});
}
Route::get('workspace/courier-payables/return-pickup-management/export', 'Business\Pages@exportReturnPickupManagement')
->middleware('business.page:courier-payables,return-pickup-management')
->name('business.courier-payables.return-pickup-management.export');

View File

@ -0,0 +1,117 @@
<?php
namespace Tests\Feature\Business;
use App\Http\Controllers\Business\UnshippedWaybillController;
use App\Support\UnshippedWaybills;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Tests\Feature\FeatureTestCase;
final class UnshippedWaybillsTest extends FeatureTestCase
{
public function test_remark_parser_and_daily_production_cron(): void
{
$this->assertSame([
'old_waybill' => 'DPK001', 'new_waybill' => 'DPK002', 'old_courier' => '曹县-德邦', 'new_courier' => '德邦',
], UnshippedWaybills::parseRemark('曹县-德邦: @DPK001 -> 德邦: @DPK002'));
$this->assertNull(UnshippedWaybills::parseRemark('德邦:7.91508E+13->德邦:DPK002'));
$this->assertNull(UnshippedWaybills::parseRemark('没有新单号'));
foreach (['activate-release.sh', 'activate-incremental-release.sh'] as $file) {
$this->assertMatchesRegularExpression('/^10 5 \* \* \* .*run-finance-batch\.sh courier:sync-unshipped-waybills\b/m',
file_get_contents(base_path('deploy/'.$file)));
}
}
public function test_replacement_excludes_final_number_and_failure_preserves_previous_results(): void
{
$this->travelTo(now()->setDate(2026, 11, 27));
$service = app(UnshippedWaybills::class);
$db = $service->connection();
foreach ([['A', 'B', '09:00:00'], ['B', 'A', '10:00:00']] as [$old, $new, $hour]) {
$remark = '德邦:'.$old.'->圆通:'.$new;
$db->table('courier_unshipped_order_logs')->insert(UnshippedWaybills::parseRemark($remark) + [
'order_no' => '100', 'operated_at' => '2026-11-25 '.$hour, 'remark' => $remark,
]);
}
$this->assertTrue($service->sync('replacement'));
$this->assertSame(['B' => ['换单未发出']], $service->unshippedSources(['A', ' @B ']));
$db->table('courier_unshipped_order_logs')->delete();
$this->assertFalse($service->sync('replacement'));
$this->assertSame(['B' => ['换单未发出']], $service->unshippedSources(['B']));
$this->assertSame(1, (int) $db->table('courier_unshipped_sync')->where('source', 'replacement')->value('row_count'));
}
public function test_intercept_uses_earliest_qualifying_item_and_original_waybill(): void
{
$service = app(UnshippedWaybills::class);
$db = $service->connection();
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 [$refund, $item, $order]) {
$this->mirrorRows($refund, ['as_id', 'o_id', 'so_id', 'shop_name', 'question_type', 'l_id'], [
['a', '1', 't', '店铺', '现场拦截入库签收', 'RETURN'],
['b', '1', 't', '店铺', '现场拦截入库签收', 'RETURN'],
['c', '1', 't', '店铺', '其他', 'RETURN'],
]);
$this->mirrorRows($item, ['as_id', 'receive_date'], [
['a', null], ['a', '2026-09-05'], ['a', '2026-09-03'], ['b', '2026-08-31'], ['c', '2026-09-03'],
]);
$this->mirrorRows($order, ['o_id', 'l_id', 'logistics_company'], [['1', ' @ORIGINAL ', '圆通']]);
}
$this->assertTrue($service->sync('intercept'));
$this->assertSame(['ORIGINAL' => ['现场拦截入库签收']], $service->unshippedSources(['ORIGINAL', 'RETURN']));
$this->assertSame('2026-09-03', $service->results()->value('evidence_time'));
$this->assertSame(1, $service->results()->count());
}
public function test_warehouse_filters_status_and_exports_waybill_as_text(): void
{
$this->mirrorRows('ops_work_order_form_config', ['work_type', 'work_type_name'], [['type-a', '仓内未发']]);
$this->mirrorRows('ops_work_order_main', ['work_type', 'order_no', 'status', 'is_deleted', 'title', 'create_time'], [
['type-a', 'W1', '待处理', 0, '标题', '2026-10-02'],
['type-a', 'W2', '已拒绝', 0, '', '2026-10-02'],
['type-a', 'W3', '已取消', 0, '', '2026-10-02'],
['type-a', 'W4', '处理中', 0, '', '2026-10-02'],
]);
$this->mirrorRows('ops_work_order_form_value', ['main_order_no', 'field_code', 'field_name', 'field_value', 'is_deleted'], [
['W1', 'lIdField', '快递单号', '000000001234567890', 0],
['W1', 'carrier', '快递名称', '圆通', 0],
['W2', 'lIdField', '快递单号', 'NO2', 0],
['W3', 'lIdField', '快递单号', 'NO3', 0],
['W4', 'lIdField', '快递单号', '', 0],
]);
$service = app(UnshippedWaybills::class);
$this->assertTrue($service->sync('warehouse'));
$this->assertSame(1, $service->results()->count());
$this->loginAs();
$controller = app(UnshippedWaybillController::class);
$page = $controller->page(Request::create('/'));
$this->assertStringContainsString('000000001234567890', view($page['view'], $page)->render());
$response = $controller->export(Request::create('/'));
$file = tempnam(sys_get_temp_dir(), 'unshipped-xlsx');
try {
ob_start();
$response->sendContent();
file_put_contents($file, ob_get_clean());
$cell = IOFactory::createReader('Xlsx')->load($file)->getActiveSheet()->getCell('B2');
$this->assertSame('000000001234567890', $cell->getValue());
$this->assertSame('s', $cell->getDataType());
} finally {
unlink($file);
}
}
private function mirrorRows(string $table, array $fields, array $rows): void
{
$connection = app(UnshippedWaybills::class)->connection();
$connection->getSchemaBuilder()->dropIfExists($table);
$connection->getSchemaBuilder()->create($table, function (Blueprint $blueprint) use ($fields): void {
$blueprint->id();
foreach ($fields as $field) $blueprint->string($field)->nullable();
});
$connection->table($table)->insert(array_map(fn ($row) => array_combine($fields, $row), $rows));
}
}