feat(发货数据): 合并/明细双模式,还原工作平台 导出/导出明细
- 同步改为"一个发货单×每件商品一行"(明细底座);新增 pkg_count 列存"1/N"件数 - 体积=数量×长×宽×高;包裹级(实称重量/运费)仅落首件,合并求和不重复 - 仓储 paginate/exportRows 支持 mode: 合并=按 source_id 归并(条码/商品ID逗号拼接、数量/重量/体积/金额/运费求和、长宽高取最大、其余取值); 明细=每件一行 - 页面加"合并/明细"切换 + 两个导出(导出/导出明细) + 件数列 - 同步内存加固(1.5G、关本地查询日志、每批释放+gc),避免全量 OOM 实测:包裹199602/明细222311,多件包裹11667,补差0; 7件样例合并体积=各件求和、运费不重复、明细每行1/7。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf
This commit is contained in:
parent
b9bbba31b7
commit
2a1b663da2
@ -13,13 +13,27 @@ class JstCount extends Command
|
||||
public function handle(): int
|
||||
{
|
||||
$c = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
|
||||
$t = $c->table('jst_oms_shipping');
|
||||
$this->line('total='.$t->count());
|
||||
$this->line('autoship(source>=1e9)='.(clone $t)->where('source_id', '>=', 1000000000)->count());
|
||||
$this->line('express_rows(source<9e6)='.(clone $t)->where('source_id', '<', 9000000)->count());
|
||||
$this->line('buchai_left='.(clone $t)->where('product_name', 'like', '%补收差价%')->count());
|
||||
$this->line('express_no_filled='.(clone $t)->whereNotNull('express_no')->where('express_no', '<>', '')->count());
|
||||
$this->line('express_no_empty='.(clone $t)->where(function ($q) { $q->whereNull('express_no')->orWhere('express_no', ''); })->count());
|
||||
$t = fn () => $c->table('jst_oms_shipping');
|
||||
$this->line('明细行数 total='.$t()->count());
|
||||
$this->line('包裹数(distinct source_id)='.$t()->distinct()->count('source_id'));
|
||||
$this->line('自动发货仓行(source>=1e9)='.$t()->where('source_id', '>=', 1000000000)->count());
|
||||
$this->line('补差残留='.$t()->where('product_name', 'like', '%补收差价%')->count());
|
||||
$this->line('快递单号非空='.$t()->whereNotNull('express_no')->where('express_no', '<>', '')->count());
|
||||
$this->line('件数pkg_count非空='.$t()->whereNotNull('pkg_count')->where('pkg_count', '<>', '')->count());
|
||||
// 多件包裹数(pkg_count 不是 1/1)
|
||||
$multi = $t()->where('pkg_count', 'not like', '1/1')->where('pkg_count', 'like', '1/%')->distinct()->count('source_id');
|
||||
$this->line('多件包裹数(件数≠1/1)='.$multi);
|
||||
// 一个多件包裹样例
|
||||
$sample = $t()->where('pkg_count', 'like', '1/%')->where('pkg_count', '<>', '1/1')->orderByDesc('source_id')->first();
|
||||
if ($sample) {
|
||||
$rows = $t()->where('source_id', $sample->source_id)->get(['barcode', 'product_name', 'qty', 'pkg_count', 'actual_weight', 'freight', 'volume_cm3']);
|
||||
$this->line('--- 样例多件包裹 source_id='.$sample->source_id.' 快递单号='.$sample->express_no.' ---');
|
||||
foreach ($rows as $r) {
|
||||
$this->line(sprintf(' 条码=%s 名称=%s 数量=%s 件数=%s 实称=%s 运费=%s 体积=%s',
|
||||
$r->barcode, mb_substr((string) $r->product_name, 0, 12), $r->qty, $r->pkg_count, $r->actual_weight, $r->freight, $r->volume_cm3));
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
@ -549,9 +549,38 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
try {
|
||||
return CourierAgreementSignature::query()
|
||||
$type = $this->agreementFilterType();
|
||||
if ($type === 'quote-confirmation') {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$query = CourierAgreementSignature::query();
|
||||
$search = $this->agreementFilterSearch();
|
||||
$status = $this->agreementFilterStatus();
|
||||
|
||||
if ($search !== '') {
|
||||
$like = '%' . addcslashes($search, '%_\\') . '%';
|
||||
$query->where(function ($builder) use ($like): void {
|
||||
$builder
|
||||
->where('business_no', 'like', $like)
|
||||
->orWhere('courier_name', 'like', $like)
|
||||
->orWhere('organization_name', 'like', $like)
|
||||
->orWhere('operator_name', 'like', $like)
|
||||
->orWhere('company_full_name', 'like', $like);
|
||||
});
|
||||
}
|
||||
|
||||
if ($status !== null) {
|
||||
$query->where('status', $status);
|
||||
}
|
||||
|
||||
if ($type !== null) {
|
||||
$query->where('document_type', $type);
|
||||
}
|
||||
|
||||
return $query
|
||||
->latest('id')
|
||||
->paginate(50, ['*'], 'agreement_page')->withQueryString();
|
||||
->paginate(50, ['*'], 'agreement_task_page')->withQueryString();
|
||||
} catch (QueryException $exception) {
|
||||
// 迁移尚未执行时仍允许打开页面;发送接口会明确提示数据库未就绪。
|
||||
report($exception);
|
||||
@ -559,6 +588,38 @@ class Pages extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
protected function agreementFilterSearch(): string
|
||||
{
|
||||
return mb_substr(trim((string) request('agreement_search', '')), 0, 191);
|
||||
}
|
||||
|
||||
protected function agreementFilterStatus(): ?string
|
||||
{
|
||||
$status = trim((string) request('agreement_status', ''));
|
||||
$allowed = [
|
||||
CourierAgreementSignature::STATUS_PREPARED,
|
||||
CourierAgreementSignature::STATUS_SENDING,
|
||||
CourierAgreementSignature::STATUS_SIGNING,
|
||||
CourierAgreementSignature::STATUS_COMPLETED,
|
||||
CourierAgreementSignature::STATUS_ARCHIVED,
|
||||
CourierAgreementSignature::STATUS_REVOKED,
|
||||
CourierAgreementSignature::STATUS_EXPIRED,
|
||||
CourierAgreementSignature::STATUS_REJECTED,
|
||||
CourierAgreementSignature::STATUS_FAILED,
|
||||
CourierAgreementSignature::STATUS_UNKNOWN,
|
||||
];
|
||||
|
||||
return in_array($status, $allowed, true) ? $status : null;
|
||||
}
|
||||
|
||||
protected function agreementFilterType(): ?string
|
||||
{
|
||||
$type = trim((string) request('agreement_type', ''));
|
||||
$allowed = array_keys(CourierAgreementSignature::DOCUMENTS);
|
||||
|
||||
return in_array($type, $allowed, true) ? $type : null;
|
||||
}
|
||||
|
||||
protected function agreementSubjects(?string $page): Collection
|
||||
{
|
||||
if ($page !== 'agreement-signing') {
|
||||
@ -584,10 +645,36 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
try {
|
||||
return CourierQuoteSignature::query()
|
||||
->with('version')
|
||||
$type = $this->agreementFilterType();
|
||||
if ($type !== null && $type !== 'quote-confirmation') {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$query = CourierQuoteSignature::query()->with('version');
|
||||
$search = $this->agreementFilterSearch();
|
||||
$status = $this->agreementFilterStatus();
|
||||
|
||||
if ($search !== '') {
|
||||
$like = '%' . addcslashes($search, '%_\\') . '%';
|
||||
$query->where(function ($builder) use ($like): void {
|
||||
$builder
|
||||
->where('organization_name', 'like', $like)
|
||||
->orWhere('operator_name', 'like', $like)
|
||||
->orWhereHas('version', function ($versionQuery) use ($like): void {
|
||||
$versionQuery
|
||||
->where('version_code', 'like', $like)
|
||||
->orWhere('carrier_name', 'like', $like);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if ($status !== null) {
|
||||
$query->where('status', $status);
|
||||
}
|
||||
|
||||
return $query
|
||||
->latest('id')
|
||||
->paginate(50, ['*'], 'agreement_page')->withQueryString();
|
||||
->paginate(50, ['*'], 'agreement_quote_page')->withQueryString();
|
||||
} catch (QueryException $exception) {
|
||||
// 报价签署迁移尚未执行时仍允许打开协议签署页。
|
||||
report($exception);
|
||||
@ -757,6 +844,7 @@ class Pages extends Controller
|
||||
{
|
||||
$request = request();
|
||||
$filters = $this->shippingDataFilters($request);
|
||||
$mode = $request->query('mode') === 'detail' ? 'detail' : 'merged';
|
||||
$page = max((int) $request->query('page', 1), 1);
|
||||
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
|
||||
$rows = new LengthAwarePaginator([], 0, $limit, $page, [
|
||||
@ -767,7 +855,7 @@ class Pages extends Controller
|
||||
$error = null;
|
||||
|
||||
try {
|
||||
$result = $this->shippingOrders->paginate($filters, $page, $limit);
|
||||
$result = $this->shippingOrders->paginate($filters, $page, $limit, $mode);
|
||||
$rows = new LengthAwarePaginator(
|
||||
Collection::make($result['data'] ?? []),
|
||||
(int) ($result['total'] ?? 0),
|
||||
@ -787,6 +875,7 @@ class Pages extends Controller
|
||||
'shippingFilters' => $filters,
|
||||
'shippingSync' => $sync,
|
||||
'shippingError' => $error,
|
||||
'shippingMode' => $mode,
|
||||
'shippingExportUrl' => route('business.courier-payables.shipping-data.export'),
|
||||
];
|
||||
}
|
||||
@ -794,9 +883,10 @@ class Pages extends Controller
|
||||
public function exportShippingData(Request $request): StreamedResponse
|
||||
{
|
||||
$filters = $this->shippingDataFilters($request);
|
||||
$mode = $request->query('mode') === 'detail' ? 'detail' : 'merged';
|
||||
$columns = $this->shippingDataColumns();
|
||||
|
||||
return response()->streamDownload(function () use ($filters, $columns): void {
|
||||
return response()->streamDownload(function () use ($filters, $columns, $mode): void {
|
||||
$csv = fopen('php://output', 'w');
|
||||
if ($csv === false) {
|
||||
throw new \RuntimeException('无法创建发货数据导出流。');
|
||||
@ -805,7 +895,7 @@ class Pages extends Controller
|
||||
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($csv, array_column($columns, 'label'));
|
||||
|
||||
foreach ($this->shippingOrders->exportRows($filters) as $row) {
|
||||
foreach ($this->shippingOrders->exportRows($filters, 1000, $mode) as $row) {
|
||||
fputcsv($csv, array_map(function (array $column) use ($row): mixed {
|
||||
$value = data_get($row, $column['field']);
|
||||
|
||||
@ -818,7 +908,7 @@ class Pages extends Controller
|
||||
}
|
||||
|
||||
fclose($csv);
|
||||
}, '发货数据_' . now()->format('Ymd_His') . '.csv', [
|
||||
}, '发货数据' . ($mode === 'detail' ? '明细' : '合并') . '_' . now()->format('Ymd_His') . '.csv', [
|
||||
'Content-Type' => 'text/csv; charset=UTF-8',
|
||||
'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
@ -903,6 +993,7 @@ class Pages extends Controller
|
||||
['field' => 'barcode', 'label' => '条形码', 'type' => 'identifier'],
|
||||
['field' => 'product_name', 'label' => '商品名称', 'type' => 'text'],
|
||||
['field' => 'qty', 'label' => '数量', 'type' => 'number'],
|
||||
['field' => 'pkg_count', 'label' => '件数', 'type' => 'text'],
|
||||
['field' => 'receiver_state', 'label' => '省', 'type' => 'text'],
|
||||
['field' => 'buyer_nick', 'label' => '买家昵称', 'type' => 'text'],
|
||||
['field' => 'receiver_name', 'label' => '收货姓名', 'type' => 'text'],
|
||||
|
||||
@ -23,6 +23,8 @@ class SyncJushuitanShipping extends Command
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
@ini_set('memory_limit', '1536M');
|
||||
@set_time_limit(0);
|
||||
$from = $this->option('from') ? Carbon::parse($this->option('from')) : null;
|
||||
$to = $this->option('to') ? Carbon::parse($this->option('to')) : null;
|
||||
|
||||
|
||||
@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private function conn(): \Illuminate\Database\Schema\Builder
|
||||
{
|
||||
return Schema::connection((string) config('jushuitan.connection', 'jushuitan_local'));
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = $this->conn();
|
||||
if (! $schema->hasTable('jst_oms_shipping')) {
|
||||
return;
|
||||
}
|
||||
if (! $schema->hasColumn('jst_oms_shipping', 'pkg_count')) {
|
||||
$schema->table('jst_oms_shipping', function (Blueprint $table): void {
|
||||
$table->string('pkg_count', 16)->nullable()->comment('件数 1/N')->after('package_no');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$schema = $this->conn();
|
||||
if ($schema->hasTable('jst_oms_shipping') && $schema->hasColumn('jst_oms_shipping', 'pkg_count')) {
|
||||
$schema->table('jst_oms_shipping', function (Blueprint $table): void {
|
||||
$table->dropColumn('pkg_count');
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -23,50 +23,114 @@ class ShippingOrderRepository
|
||||
* @param array<string,string> $filters
|
||||
* @return array{data:array,total:int}
|
||||
*/
|
||||
public function paginate(array $filters, int $page, int $perPage): array
|
||||
public function paginate(array $filters, int $page, int $perPage, string $mode = 'merged'): array
|
||||
{
|
||||
$page = max($page, 1);
|
||||
$perPage = min(max($perPage, 1), 100);
|
||||
|
||||
$q = $this->filteredQuery($filters);
|
||||
if ($mode === 'detail') {
|
||||
$q = $this->filteredQuery($filters);
|
||||
$total = (clone $q)->count();
|
||||
$rows = (clone $q)
|
||||
->orderByDesc('ship_time')
|
||||
->orderByDesc('source_id')
|
||||
->orderBy('sku_source_id')
|
||||
->forPage($page, $perPage)
|
||||
->get()->map(fn ($r) => (array) $r)->all();
|
||||
|
||||
$total = (clone $q)->count();
|
||||
$rows = (clone $q)
|
||||
return ['data' => $rows, 'total' => $total];
|
||||
}
|
||||
|
||||
// 合并:按包裹(source_id)归并
|
||||
$base = $this->filteredQuery($filters);
|
||||
$total = (clone $base)->distinct()->count('source_id');
|
||||
$rows = (clone $base)
|
||||
->groupBy('source_id')
|
||||
->selectRaw($this->mergedSelectRaw())
|
||||
->orderByDesc('ship_time')
|
||||
->orderByDesc('id')
|
||||
->orderByDesc('source_id')
|
||||
->forPage($page, $perPage)
|
||||
->get()
|
||||
->map(fn ($r) => (array) $r)
|
||||
->all();
|
||||
->get()->map(fn ($r) => (array) $r)->all();
|
||||
|
||||
return ['data' => $rows, 'total' => $total];
|
||||
}
|
||||
|
||||
/** 合并聚合 SELECT:条码/商品ID 逗号拼接、数量/重量/体积/金额/运费求和、长宽高取最大、其余取值。 */
|
||||
private function mergedSelectRaw(): string
|
||||
{
|
||||
$sum = ['qty', 'freight', 'online_weight', 'actual_weight', 'volume_cm3', 'weight_kg',
|
||||
'settle_weight_kg', 'settle_volume_cm3', 'recon_weight_kg', 'recon_volume_cm3', 'amount', 'settle_freight'];
|
||||
$concat = ['item_id', 'barcode'];
|
||||
$min = ['product_name', 'supplier_name', 'product_code'];
|
||||
$all = ['express_no', 'trade_no', 'item_id', 'barcode', 'product_name', 'qty', 'pkg_count',
|
||||
'receiver_state', 'buyer_nick', 'receiver_name', 'shop_name', 'express_name1', 'warehouse_name',
|
||||
'ship_time', 'freight', 'online_weight', 'actual_weight', 'length_cm', 'width_cm', 'height_cm',
|
||||
'volume_cm3', 'receiver_city', 'receiver_district', 'supplier_name', 'receiver_address',
|
||||
'receiver_mobile', 'receiver_phone', 'express_name2', 'platform', 'buyer_memo', 'seller_memo',
|
||||
'package_no', 'amount', 'product_code', 'download_time', 'pay_time', 'freight_rate', 'freight_formula',
|
||||
'weight_kg', 'settle_weight_kg', 'settle_volume_cm3', 'recon_weight_kg', 'recon_volume_cm3',
|
||||
'finished_barcode', 'finished_name', 'finished_supplier', 'settle_freight', 'front_no'];
|
||||
|
||||
$parts = ['MAX(id) as id', 'source_id'];
|
||||
foreach ($all as $c) {
|
||||
if (in_array($c, $sum, true)) {
|
||||
$parts[] = "SUM(`{$c}`) as `{$c}`";
|
||||
} elseif (in_array($c, $concat, true)) {
|
||||
$parts[] = "GROUP_CONCAT(DISTINCT `{$c}` SEPARATOR ',') as `{$c}`";
|
||||
} elseif (in_array($c, $min, true)) {
|
||||
$parts[] = "MIN(`{$c}`) as `{$c}`";
|
||||
} else {
|
||||
$parts[] = "MAX(`{$c}`) as `{$c}`";
|
||||
}
|
||||
}
|
||||
|
||||
return implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string> $filters
|
||||
* @return \Generator<int,array<string,mixed>>
|
||||
*/
|
||||
public function exportRows(array $filters, int $batchSize = 1000): \Generator
|
||||
public function exportRows(array $filters, int $batchSize = 1000, string $mode = 'merged'): \Generator
|
||||
{
|
||||
$batchSize = min(max($batchSize, 1), 5000);
|
||||
$lastId = null;
|
||||
$last = null;
|
||||
|
||||
if ($mode === 'detail') {
|
||||
while (true) {
|
||||
$query = $this->filteredQuery($filters);
|
||||
if ($last !== null) {
|
||||
$query->where('id', '>', $last);
|
||||
}
|
||||
$rows = $query->orderBy('id')->limit($batchSize)->get()->all();
|
||||
if ($rows === []) {
|
||||
return;
|
||||
}
|
||||
foreach ($rows as $row) {
|
||||
yield (array) $row;
|
||||
}
|
||||
$last = (int) $rows[array_key_last($rows)]->id;
|
||||
if (count($rows) < $batchSize) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 合并导出:按 source_id 键集分页 + 归并
|
||||
while (true) {
|
||||
$query = $this->filteredQuery($filters);
|
||||
if ($lastId !== null) {
|
||||
$query->where('id', '>', $lastId);
|
||||
if ($last !== null) {
|
||||
$query->where('source_id', '>', $last);
|
||||
}
|
||||
|
||||
$rows = $query->orderBy('id')->limit($batchSize)->get()->all();
|
||||
$rows = $query->groupBy('source_id')->selectRaw($this->mergedSelectRaw())
|
||||
->orderBy('source_id')->limit($batchSize)->get()->all();
|
||||
if ($rows === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($rows as $row) {
|
||||
yield (array) $row;
|
||||
}
|
||||
|
||||
$lastId = (int) $rows[array_key_last($rows)]->id;
|
||||
$last = (int) $rows[array_key_last($rows)]->source_id;
|
||||
if (count($rows) < $batchSize) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -8,34 +8,35 @@ use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 直读经营分析副本库(operations_replica)的聚水潭发货明细,清洗写入 jst_oms_shipping。
|
||||
* 不经工作平台、不用聚水潭 API。
|
||||
* 直读经营分析副本库(operations_replica)聚水潭发货明细,清洗写入 jst_oms_shipping。
|
||||
* 对齐工作平台口径:明细=一个发货单×每件商品一行(导出明细);合并由查询层按包裹归并(导出)。
|
||||
*
|
||||
* 口径对齐工作平台(erp.dlv.query tradetype=1&sendsgn=1):
|
||||
* - 主口径:rpt.jst_order_express_details 发货单(dlv)镜像,一行一发货单。logistic_id=快递单号(postcode)。
|
||||
* - 快递单号回落:logistic_id 空 -> jst_Orders.l_id -> 运费表 expressNo。
|
||||
* - 发货时间回落:send_time 空 -> jst_Orders.send_date(修滞后单)。
|
||||
* - 剔除补差虚拟单(商品名含 补收差价/差价专用),与工作平台一致。
|
||||
* - 并入自动发货仓:jst_Orders 已发货(Sent) 但不在发货明细表的单。
|
||||
* - 窗口重跑:先按发货时间删掉该窗口旧行再重建,避免历史残留。
|
||||
* 每行 = 一个发货单(包裹, express_details) × 其一件商品(OrderItem)。
|
||||
* - source_id = 发货单 id(包裹)
|
||||
* - sku_source_id = 商品明细 id(件)
|
||||
* - pkg_count = '1/N'(同包裹件数)
|
||||
* - 体积 volume_cm3 = 数量 × 长 × 宽 × 高(工作平台 Svolume 规则)
|
||||
* - 包裹级字段(实称重量/运费)只落在首件,其余置空 —— 便于合并 SUM 不重复
|
||||
* - 剔除补差虚拟单;并入自动发货仓(jst_Orders 已发货但不在发货明细表)
|
||||
*/
|
||||
class ShippingReplicaSynchronizer
|
||||
{
|
||||
private const SOURCE = 'operations_replica';
|
||||
private const DATASET = 'jst.sctrade';
|
||||
private const AUTOSHIP_OFFSET = 1000000000; // 自动发货仓行的 source_id 偏移,避免与 express_details.id 撞号
|
||||
private const FLUSH = 200;
|
||||
private const AUTOSHIP_OFFSET = 1000000000;
|
||||
private const FLUSH = 300;
|
||||
|
||||
private readonly \Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery $up;
|
||||
private readonly \Illuminate\Database\ConnectionInterface $db;
|
||||
|
||||
/** @var array<int,array> 待批量写入缓冲 */
|
||||
/** @var array<int,array> */
|
||||
private array $buffer = [];
|
||||
|
||||
public function __construct(UpstreamReadOnlyQueryFactory $factory)
|
||||
{
|
||||
$this->up = $factory->forSource(self::SOURCE);
|
||||
$this->db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
|
||||
$this->db->disableQueryLog();
|
||||
}
|
||||
|
||||
public static function make(): self
|
||||
@ -52,10 +53,8 @@ class ShippingReplicaSynchronizer
|
||||
$fromS = $windowed ? $from->format('Y-m-d H:i:s') : null;
|
||||
$toS = $windowed ? $to->format('Y-m-d H:i:s') : null;
|
||||
|
||||
// 清 demo 行
|
||||
$this->db->table('jst_oms_shipping')->where('source_id', '>=', 9000000)
|
||||
->where('source_id', '<', self::AUTOSHIP_OFFSET)->delete();
|
||||
// 窗口重跑:先删该窗口旧行(含补差历史残留)再重建
|
||||
if ($windowed) {
|
||||
$this->db->table('jst_oms_shipping')
|
||||
->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS)->delete();
|
||||
@ -75,11 +74,11 @@ class ShippingReplicaSynchronizer
|
||||
}
|
||||
}
|
||||
|
||||
/** 主口径:发货明细表(dlv 镜像)。 */
|
||||
/** 主口径:发货单(dlv 镜像) × 每件商品。 */
|
||||
private function syncExpress(bool $windowed, ?string $fromS, ?string $toS, int $limit, $now): int
|
||||
{
|
||||
$batch = 500;
|
||||
$maxBatches = 2000;
|
||||
$batch = 400;
|
||||
$maxBatches = 3000;
|
||||
$cols = 'e.id, e.so_id, e.inner_order_id, e.logistic_id, e.logistic_company_name, e.send_time, e.pay_time, '
|
||||
. 'e.shop_name, e.platform_name, e.dis_co_name, e.warehouse_name, e.receiver_address, '
|
||||
. 'e.weight, e.f_weight, e.buyer_message, jo.l_id AS jo_lid, jo.send_date AS jo_send';
|
||||
@ -100,56 +99,50 @@ class ShippingReplicaSynchronizer
|
||||
$bind[] = $lastId;
|
||||
}
|
||||
$sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_order_express_details e "
|
||||
. "LEFT JOIN rpt.jst_Orders jo ON jo.o_id = e.inner_order_id "
|
||||
. 'LEFT JOIN rpt.jst_Orders jo ON jo.o_id = e.inner_order_id '
|
||||
. "WHERE {$where} ORDER BY e.id DESC";
|
||||
$rows = $this->up->select($sql, $bind);
|
||||
if ($rows === []) {
|
||||
break;
|
||||
}
|
||||
$cnt = count($rows);
|
||||
|
||||
$oids = [];
|
||||
$soIds = [];
|
||||
foreach ($rows as $r) {
|
||||
$so = (string) ($r['so_id'] ?? '');
|
||||
if ($so !== '') {
|
||||
$soIds[$so] = true;
|
||||
}
|
||||
$oid = (string) ($r['inner_order_id'] ?? '');
|
||||
if ($oid !== '') {
|
||||
$oids[$oid] = true;
|
||||
}
|
||||
$lastId = $r['id'];
|
||||
}
|
||||
$soIds = array_keys($soIds);
|
||||
|
||||
$items = $this->loadItems($soIds);
|
||||
$skuIds = [];
|
||||
foreach ($items as $it) {
|
||||
if (! empty($it['sku'])) {
|
||||
$skuIds[(string) $it['sku']] = true;
|
||||
}
|
||||
}
|
||||
$skus = $this->loadSkus(array_keys($skuIds));
|
||||
$freight = $this->loadFreight($soIds);
|
||||
[$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds));
|
||||
$skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo));
|
||||
$freight = $this->loadFreight(array_keys($soIds));
|
||||
|
||||
foreach ($rows as $r) {
|
||||
$id = $r['id'] ?? null;
|
||||
if ($id === null) {
|
||||
$pkgId = (int) ($r['id'] ?? 0);
|
||||
if ($pkgId === 0) {
|
||||
continue;
|
||||
}
|
||||
$so = (string) ($r['so_id'] ?? '');
|
||||
$it = $items[$so] ?? [];
|
||||
if ($this->isPricePatch($it['name'] ?? null)) {
|
||||
continue; // 剔除补差虚拟单
|
||||
}
|
||||
$expno = (string) ($r['logistic_id'] ?? '');
|
||||
$sk = (! empty($it['sku']) && isset($skus[(string) $it['sku']])) ? $skus[(string) $it['sku']] : [];
|
||||
$f = $freight[$so . '|' . $expno] ?? ($freight[$so . '|'] ?? []);
|
||||
|
||||
$tracking = $expno !== '' ? $expno : ((string) ($r['jo_lid'] ?? '') ?: (string) ($f['no'] ?? ''));
|
||||
$tracking = $tracking !== '' ? $tracking : null;
|
||||
$oid = (string) ($r['inner_order_id'] ?? '');
|
||||
$items = $this->itemsFor($byOid, $bySo, $oid, $so);
|
||||
$tracking = $this->tracking((string) ($r['logistic_id'] ?? ''), (string) ($r['jo_lid'] ?? ''), $freight, $so);
|
||||
$shipTime = $this->ts($r['send_time'] ?? null) ?? $this->ts($r['jo_send'] ?? null);
|
||||
|
||||
$this->push((int) $id, $this->buildPayload($r, $it, $sk, $f, $tracking, $shipTime, $now));
|
||||
$total++;
|
||||
$pkg = $this->pkgFromExpress($r, $tracking, $shipTime);
|
||||
$total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now);
|
||||
}
|
||||
|
||||
if (count($rows) < $batch) {
|
||||
unset($rows, $byOid, $bySo, $skus, $freight);
|
||||
if ($b % 30 === 0) {
|
||||
gc_collect_cycles();
|
||||
}
|
||||
if ($cnt < $batch) {
|
||||
break;
|
||||
}
|
||||
if (! $windowed && $total >= $limit) {
|
||||
@ -157,16 +150,17 @@ class ShippingReplicaSynchronizer
|
||||
}
|
||||
}
|
||||
$this->flush();
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
||||
/** 并入自动发货仓:jst_Orders 已发货但不在发货明细表。 */
|
||||
private function syncAutoShip(string $fromS, string $toS, $now): int
|
||||
{
|
||||
$batch = 500;
|
||||
$maxBatches = 400;
|
||||
$cols = 'o.Id AS rid, o.o_id, o.so_id, o.l_id, o.lc_id, o.logistics_company, o.order_from, '
|
||||
. 'o.shop_name, o.send_date, o.pay_date, o.weight, o.f_weight, o.buyer_message, '
|
||||
$batch = 400;
|
||||
$maxBatches = 600;
|
||||
$cols = 'o.Id AS rid, o.o_id, o.so_id, o.l_id, o.logistics_company, o.order_from, '
|
||||
. 'o.shop_name, o.send_date, o.pay_date, o.weight, o.buyer_message, '
|
||||
. 'o.receiver_state, o.receiver_city, o.receiver_district, o.receiver_address, '
|
||||
. 'o.receiver_name, o.receiver_mobile, o.receiver_phone';
|
||||
|
||||
@ -187,74 +181,278 @@ class ShippingReplicaSynchronizer
|
||||
break;
|
||||
}
|
||||
|
||||
$oids = [];
|
||||
$soIds = [];
|
||||
foreach ($rows as $r) {
|
||||
$so = (string) ($r['so_id'] ?? '');
|
||||
if ($so !== '') {
|
||||
$soIds[$so] = true;
|
||||
}
|
||||
$oid = (string) ($r['o_id'] ?? '');
|
||||
if ($oid !== '') {
|
||||
$oids[$oid] = true;
|
||||
}
|
||||
$lastRid = $r['rid'];
|
||||
}
|
||||
$soIds = array_keys($soIds);
|
||||
$items = $this->loadItems($soIds);
|
||||
$skuIds = [];
|
||||
foreach ($items as $it) {
|
||||
if (! empty($it['sku'])) {
|
||||
$skuIds[(string) $it['sku']] = true;
|
||||
}
|
||||
}
|
||||
$skus = $this->loadSkus(array_keys($skuIds));
|
||||
$freight = $this->loadFreight($soIds);
|
||||
[$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds));
|
||||
$skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo));
|
||||
$freight = $this->loadFreight(array_keys($soIds));
|
||||
|
||||
$cnt = count($rows);
|
||||
foreach ($rows as $r) {
|
||||
$oid = (string) ($r['o_id'] ?? '');
|
||||
if ($oid === '') {
|
||||
continue;
|
||||
}
|
||||
$so = (string) ($r['so_id'] ?? '');
|
||||
$oid = $r['o_id'] ?? null;
|
||||
if ($oid === null) {
|
||||
continue;
|
||||
}
|
||||
$it = $items[$so] ?? [];
|
||||
if ($this->isPricePatch($it['name'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
$sk = (! empty($it['sku']) && isset($skus[(string) $it['sku']])) ? $skus[(string) $it['sku']] : [];
|
||||
$f = $freight[$so . '|'] ?? [];
|
||||
$tracking = ((string) ($r['l_id'] ?? '')) ?: ((string) ($f['no'] ?? '')) ?: null;
|
||||
$items = $this->itemsFor($byOid, $bySo, $oid, $so);
|
||||
$tracking = $this->tracking((string) ($r['l_id'] ?? ''), '', $freight, $so);
|
||||
$shipTime = $this->ts($r['send_date'] ?? null);
|
||||
$sid = self::AUTOSHIP_OFFSET + (int) $oid;
|
||||
|
||||
$mapped = [
|
||||
'so_id' => $so,
|
||||
'logistic_id' => $tracking,
|
||||
'logistic_company_name' => $r['logistics_company'] ?? null,
|
||||
'send_time' => $shipTime,
|
||||
'pay_time' => $r['pay_date'] ?? null,
|
||||
'shop_name' => $r['shop_name'] ?? null,
|
||||
'platform_name' => $r['order_from'] ?? null,
|
||||
'dis_co_name' => null,
|
||||
'warehouse_name' => $it['warehouse'] ?? null,
|
||||
'receiver_address' => $r['receiver_address'] ?? '',
|
||||
'weight' => $r['weight'] ?? null,
|
||||
'buyer_message' => $r['buyer_message'] ?? null,
|
||||
'r_state' => $r['receiver_state'] ?? null,
|
||||
'r_city' => $r['receiver_city'] ?? null,
|
||||
'r_district' => $r['receiver_district'] ?? null,
|
||||
];
|
||||
$this->push($sid, $this->buildPayload($mapped, $it, $sk, $f, $tracking, $shipTime, $now, true));
|
||||
$total++;
|
||||
$pkg = $this->pkgFromOrder($r, $tracking, $shipTime);
|
||||
$pkgId = self::AUTOSHIP_OFFSET + (int) $oid;
|
||||
$total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now, true);
|
||||
}
|
||||
if (count($rows) < $batch) {
|
||||
unset($rows, $byOid, $bySo, $skus, $freight);
|
||||
if ($b % 30 === 0) {
|
||||
gc_collect_cycles();
|
||||
}
|
||||
if ($cnt < $batch) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$this->flush();
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
||||
/** 入缓冲,满 FLUSH 条批量写。窗口已预删,用 insert 更快。 */
|
||||
private function push(int $sid, array $payload): void
|
||||
/**
|
||||
* 输出一个包裹的所有明细行(每件一行;无商品则一行空商品)。
|
||||
* @return int 写入行数
|
||||
*/
|
||||
private function emitPackage(int $pkgId, array $pkg, array $items, array $skus, array $freight, string $so, ?string $tracking, $now, bool $auto = false): int
|
||||
{
|
||||
$payload['source_id'] = $sid;
|
||||
$payload['sku_source_id'] = $sid;
|
||||
$items = array_values(array_filter($items, fn ($it) => ! $this->isPricePatch($it['name'] ?? null)));
|
||||
$n = count($items);
|
||||
$f = $freight[$so . '|' . ($tracking ?? '')] ?? ($freight[$so . '|'] ?? []);
|
||||
|
||||
if ($n === 0) {
|
||||
$this->push($pkgId, $pkgId, $this->buildRow($pkg, [], [], $f, true, '1/1', $now, $auto));
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
$count = 0;
|
||||
foreach ($items as $idx => $it) {
|
||||
$first = ($idx === 0);
|
||||
$sk = (! empty($it['sku']) && isset($skus[(string) $it['sku']])) ? $skus[(string) $it['sku']] : [];
|
||||
$skuSid = (int) ($it['id'] ?? ($pkgId * 100 + $idx));
|
||||
$this->push($pkgId, $skuSid, $this->buildRow($pkg, $it, $sk, $f, $first, '1/' . $n, $now, $auto));
|
||||
$count++;
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/** 组装一件明细行。包裹级字段(实称重量/运费)仅首件携带。 */
|
||||
private function buildRow(array $pkg, array $it, array $sk, array $f, bool $first, string $countStr, $now, bool $auto): array
|
||||
{
|
||||
$qty = (float) ($it['qty'] ?? 0);
|
||||
$skuW = (float) ($sk['weight'] ?? 0);
|
||||
$onlineW = $skuW > 0 ? round($skuW * ($qty > 0 ? $qty : 1), 4) : null;
|
||||
$L = $sk['l'] ?? null;
|
||||
$W = $sk['w'] ?? null;
|
||||
$H = $sk['h'] ?? null;
|
||||
$vol = ($L && $W && $H) ? round(($qty > 0 ? $qty : 1) * (float) $L * (float) $W * (float) $H, 4) : null;
|
||||
|
||||
$pkgWeight = (float) ($pkg['weight'] ?? 0) ?: null;
|
||||
$freightW = (float) ($f['w'] ?? 0);
|
||||
$settleW = $freightW > 0 ? $freightW : ($pkgWeight ?: $onlineW);
|
||||
|
||||
return $this->cleanPayload([
|
||||
'express_no' => $pkg['tracking'],
|
||||
'trade_no' => $pkg['so_id'],
|
||||
'item_id' => $it['shopid'] ?? null,
|
||||
'barcode' => $it['sku'] ?? null,
|
||||
'product_name' => $it['name'] ?? null,
|
||||
'qty' => $it['qty'] ?? null,
|
||||
'pkg_count' => $countStr,
|
||||
'product_code' => $it['iid'] ?? null,
|
||||
'express_name1' => $pkg['express_name1'],
|
||||
'express_name2' => ($f['name'] ?? null) ?: $pkg['express_name1'],
|
||||
'ship_time' => $pkg['ship_time'],
|
||||
'pay_time' => $pkg['pay_time'],
|
||||
'shop_name' => $pkg['shop_name'],
|
||||
'platform' => $pkg['platform'],
|
||||
'supplier_name' => ($sk['supplier'] ?? null) ?: $pkg['dis_co_name'],
|
||||
'warehouse_name' => $pkg['warehouse_name'] ?: ($it['warehouse'] ?? null),
|
||||
'receiver_state' => $pkg['r_state'],
|
||||
'receiver_city' => $pkg['r_city'],
|
||||
'receiver_district' => $pkg['r_district'],
|
||||
'receiver_address' => $pkg['r_address'],
|
||||
'receiver_name' => $pkg['r_name'],
|
||||
'receiver_mobile' => $pkg['r_mobile'],
|
||||
'receiver_phone' => $pkg['r_phone'],
|
||||
'online_weight' => $onlineW,
|
||||
'actual_weight' => $first ? $pkgWeight : null,
|
||||
'length_cm' => $L,
|
||||
'width_cm' => $W,
|
||||
'height_cm' => $H,
|
||||
'volume_cm3' => $vol,
|
||||
'weight_kg' => $first ? $settleW : null,
|
||||
'settle_weight_kg' => $first ? $settleW : null,
|
||||
'amount' => $it['amount'] ?? null,
|
||||
'freight' => $first ? ($f['cost'] ?? null) : null,
|
||||
'settle_freight' => $first ? ($f['cost'] ?? null) : null,
|
||||
'buyer_memo' => $pkg['buyer_memo'],
|
||||
'modified' => $pkg['ship_time'],
|
||||
'synced_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
/** 发货明细表行 → 包裹级字段(省市区从地址拆) */
|
||||
private function pkgFromExpress(array $r, ?string $tracking, ?string $shipTime): array
|
||||
{
|
||||
$addr = (string) ($r['receiver_address'] ?? '');
|
||||
$parts = $addr !== '' ? array_values(array_filter(explode('-', $addr))) : [];
|
||||
|
||||
return [
|
||||
'tracking' => $tracking,
|
||||
'so_id' => $r['so_id'] ?? null,
|
||||
'express_name1' => $r['logistic_company_name'] ?? null,
|
||||
'ship_time' => $shipTime,
|
||||
'pay_time' => $this->ts($r['pay_time'] ?? null),
|
||||
'shop_name' => $r['shop_name'] ?? null,
|
||||
'platform' => $r['platform_name'] ?? null,
|
||||
'dis_co_name' => $r['dis_co_name'] ?? null,
|
||||
'warehouse_name' => $r['warehouse_name'] ?? null,
|
||||
'r_state' => $parts[0] ?? null,
|
||||
'r_city' => $parts[1] ?? null,
|
||||
'r_district' => $parts[2] ?? null,
|
||||
'r_address' => $addr,
|
||||
'r_name' => null,
|
||||
'r_mobile' => null,
|
||||
'r_phone' => null,
|
||||
'buyer_memo' => $r['buyer_message'] ?? null,
|
||||
'weight' => $r['weight'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
/** jst_Orders 行(自动发货仓) → 包裹级字段 */
|
||||
private function pkgFromOrder(array $r, ?string $tracking, ?string $shipTime): array
|
||||
{
|
||||
return [
|
||||
'tracking' => $tracking,
|
||||
'so_id' => $r['so_id'] ?? null,
|
||||
'express_name1' => $r['logistics_company'] ?? null,
|
||||
'ship_time' => $shipTime,
|
||||
'pay_time' => $this->ts($r['pay_date'] ?? null),
|
||||
'shop_name' => $r['shop_name'] ?? null,
|
||||
'platform' => $r['order_from'] ?? null,
|
||||
'dis_co_name' => null,
|
||||
'warehouse_name' => null,
|
||||
'r_state' => $r['receiver_state'] ?? null,
|
||||
'r_city' => $r['receiver_city'] ?? null,
|
||||
'r_district' => $r['receiver_district'] ?? null,
|
||||
'r_address' => $r['receiver_address'] ?? '',
|
||||
'r_name' => $r['receiver_name'] ?? null,
|
||||
'r_mobile' => $r['receiver_mobile'] ?? null,
|
||||
'r_phone' => $r['receiver_phone'] ?? null,
|
||||
'buyer_memo' => $r['buyer_message'] ?? null,
|
||||
'weight' => $r['weight'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
private function tracking(string $logisticId, string $joLid, array $freight, string $so): ?string
|
||||
{
|
||||
if ($logisticId !== '') {
|
||||
return $logisticId;
|
||||
}
|
||||
if ($joLid !== '') {
|
||||
return $joLid;
|
||||
}
|
||||
$f = $freight[$so . '|'] ?? [];
|
||||
$no = (string) ($f['no'] ?? '');
|
||||
|
||||
return $no !== '' ? $no : null;
|
||||
}
|
||||
|
||||
/** @return array{0:array<string,array>,1:array<string,array>} [byOid, bySo] */
|
||||
private function loadAllItems(array $oids, array $soIds): array
|
||||
{
|
||||
$byOid = [];
|
||||
$bySo = [];
|
||||
$sel = 'o_id, raw_so_id, sku_id, i_id, shop_i_id, name, qty, amount, send_warehouse, Id';
|
||||
|
||||
foreach (array_chunk($oids, 800) as $chunk) {
|
||||
if ($chunk === []) {
|
||||
continue;
|
||||
}
|
||||
$ph = implode(',', array_fill(0, count($chunk), '?'));
|
||||
foreach ($this->up->select("SELECT {$sel} FROM rpt.jst_OrderItem WHERE o_id IN ({$ph}) ORDER BY Id", $chunk) as $r) {
|
||||
$k = (string) ($r['o_id'] ?? '');
|
||||
if ($k !== '') {
|
||||
$byOid[$k][] = $this->itemArr($r);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (array_chunk($soIds, 800) as $chunk) {
|
||||
if ($chunk === []) {
|
||||
continue;
|
||||
}
|
||||
$ph = implode(',', array_fill(0, count($chunk), '?'));
|
||||
foreach ($this->up->select("SELECT {$sel} FROM rpt.jst_OrderItem WHERE raw_so_id IN ({$ph}) ORDER BY Id", $chunk) as $r) {
|
||||
$k = (string) ($r['raw_so_id'] ?? '');
|
||||
if ($k !== '') {
|
||||
$bySo[$k][] = $this->itemArr($r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [$byOid, $bySo];
|
||||
}
|
||||
|
||||
private function itemArr(array $r): array
|
||||
{
|
||||
return [
|
||||
'id' => $r['Id'] ?? null, 'sku' => $r['sku_id'] ?? null, 'iid' => $r['i_id'] ?? null,
|
||||
'shopid' => $r['shop_i_id'] ?? null, 'name' => $r['name'] ?? null,
|
||||
'qty' => $r['qty'] ?? null, 'amount' => $r['amount'] ?? null, 'warehouse' => $r['send_warehouse'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
/** 该包裹的商品:优先 o_id 精确,取不到回落 so_id。 */
|
||||
private function itemsFor(array $byOid, array $bySo, string $oid, string $so): array
|
||||
{
|
||||
if ($oid !== '' && ! empty($byOid[$oid])) {
|
||||
return $byOid[$oid];
|
||||
}
|
||||
if ($so !== '' && ! empty($bySo[$so])) {
|
||||
return $bySo[$so];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private function collectSkuIds(array $byOid, array $bySo): array
|
||||
{
|
||||
$ids = [];
|
||||
foreach ([$byOid, $bySo] as $map) {
|
||||
foreach ($map as $items) {
|
||||
foreach ($items as $it) {
|
||||
if (! empty($it['sku'])) {
|
||||
$ids[(string) $it['sku']] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($ids);
|
||||
}
|
||||
|
||||
private function push(int $sourceId, int $skuSourceId, array $payload): void
|
||||
{
|
||||
$payload['source_id'] = $sourceId;
|
||||
$payload['sku_source_id'] = $skuSourceId;
|
||||
$this->buffer[] = $payload;
|
||||
if (count($this->buffer) >= self::FLUSH) {
|
||||
$this->flush();
|
||||
@ -266,106 +464,17 @@ class ShippingReplicaSynchronizer
|
||||
if ($this->buffer === []) {
|
||||
return;
|
||||
}
|
||||
// 去重同一 source_id(同窗口内极少见,保底)
|
||||
$this->db->table('jst_oms_shipping')->insertOrIgnore($this->buffer);
|
||||
$this->buffer = [];
|
||||
}
|
||||
|
||||
/** 组装写入行。$auto=true 时省级市区直接取 jst_Orders 字段。 */
|
||||
private function buildPayload(array $r, array $it, array $sk, array $f, ?string $tracking, ?string $shipTime, $now, bool $auto = false): array
|
||||
{
|
||||
$addr = (string) ($r['receiver_address'] ?? '');
|
||||
$parts = $addr !== '' ? array_values(array_filter(explode('-', $addr))) : [];
|
||||
|
||||
$qty = (float) ($it['qty'] ?? 0);
|
||||
$skuW = (float) ($sk['weight'] ?? 0);
|
||||
$onlineW = $skuW > 0 ? round($skuW * ($qty > 0 ? $qty : 1), 4) : null;
|
||||
$actualW = (float) ($r['weight'] ?? 0) ?: null;
|
||||
$freightW = (float) ($f['w'] ?? 0);
|
||||
$settleW = $freightW > 0 ? $freightW : ($actualW ?: $onlineW);
|
||||
$L = $sk['l'] ?? null;
|
||||
$W = $sk['w'] ?? null;
|
||||
$H = $sk['h'] ?? null;
|
||||
$vol = ($sk['vol'] ?? null);
|
||||
if (($vol === null || (float) $vol <= 0) && $L && $W && $H) {
|
||||
$vol = (float) $L * (float) $W * (float) $H;
|
||||
}
|
||||
|
||||
$state = $auto ? ($r['r_state'] ?? null) : (($f['state'] ?? null) ?: ($parts[0] ?? null));
|
||||
$city = $auto ? ($r['r_city'] ?? null) : ($parts[1] ?? null);
|
||||
$district = $auto ? ($r['r_district'] ?? null) : ($parts[2] ?? null);
|
||||
|
||||
return $this->cleanPayload([
|
||||
'express_no' => $tracking,
|
||||
'trade_no' => $r['so_id'] ?? null,
|
||||
'item_id' => $it['shopid'] ?? null,
|
||||
'barcode' => $it['sku'] ?? null,
|
||||
'product_name' => $it['name'] ?? null,
|
||||
'qty' => $it['qty'] ?? null,
|
||||
'product_code' => $it['iid'] ?? null,
|
||||
'express_name1' => $r['logistic_company_name'] ?? null,
|
||||
'express_name2' => ($f['name'] ?? null) ?: ($r['logistic_company_name'] ?? null),
|
||||
'ship_time' => $shipTime,
|
||||
'pay_time' => $this->ts($r['pay_time'] ?? null),
|
||||
'shop_name' => $r['shop_name'] ?? null,
|
||||
'platform' => $r['platform_name'] ?? null,
|
||||
'supplier_name' => ($sk['supplier'] ?? null) ?: ($r['dis_co_name'] ?? null),
|
||||
'warehouse_name' => $r['warehouse_name'] ?? null,
|
||||
'receiver_state' => $state,
|
||||
'receiver_city' => $city,
|
||||
'receiver_district' => $district,
|
||||
'receiver_address' => $addr,
|
||||
'online_weight' => $onlineW,
|
||||
'actual_weight' => $actualW,
|
||||
'length_cm' => $L,
|
||||
'width_cm' => $W,
|
||||
'height_cm' => $H,
|
||||
'volume_cm3' => $vol,
|
||||
'weight_kg' => $settleW,
|
||||
'settle_weight_kg' => $settleW,
|
||||
'settle_volume_cm3' => $vol,
|
||||
'amount' => $it['amount'] ?? null,
|
||||
'freight' => $f['cost'] ?? null,
|
||||
'settle_freight' => $f['cost'] ?? null,
|
||||
'buyer_memo' => $r['buyer_message'] ?? null,
|
||||
'modified' => $shipTime,
|
||||
'synced_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
private function isPricePatch(?string $name): bool
|
||||
{
|
||||
if ($name === null || $name === '') {
|
||||
return false;
|
||||
}
|
||||
return str_contains($name, '补收差价') || str_contains($name, '差价专用');
|
||||
}
|
||||
|
||||
/** @return array<string,array> so_id => 第一条商品 */
|
||||
private function loadItems(array $soIds): array
|
||||
{
|
||||
$out = [];
|
||||
foreach (array_chunk($soIds, 800) as $chunk) {
|
||||
if ($chunk === []) {
|
||||
continue;
|
||||
}
|
||||
$ph = implode(',', array_fill(0, count($chunk), '?'));
|
||||
$sql = "SELECT raw_so_id, sku_id, i_id, shop_i_id, name, qty, amount, send_warehouse, Id FROM rpt.jst_OrderItem "
|
||||
. "WHERE raw_so_id IN ({$ph}) ORDER BY Id";
|
||||
foreach ($this->up->select($sql, $chunk) as $r) {
|
||||
$so = (string) ($r['raw_so_id'] ?? '');
|
||||
if ($so === '' || isset($out[$so])) {
|
||||
continue;
|
||||
}
|
||||
$out[$so] = [
|
||||
'sku' => $r['sku_id'] ?? null, 'iid' => $r['i_id'] ?? null,
|
||||
'shopid' => $r['shop_i_id'] ?? null, 'name' => $r['name'] ?? null,
|
||||
'qty' => $r['qty'] ?? null, 'amount' => $r['amount'] ?? null,
|
||||
'warehouse' => $r['send_warehouse'] ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
return str_contains($name, '补收差价') || str_contains($name, '差价专用');
|
||||
}
|
||||
|
||||
/** @return array<string,array> sku_id => 尺寸/重量/供应商 */
|
||||
@ -377,9 +486,7 @@ class ShippingReplicaSynchronizer
|
||||
continue;
|
||||
}
|
||||
$ph = implode(',', array_fill(0, count($chunk), '?'));
|
||||
$sql = "SELECT sku_id, l, w, h, pack_volume, weight, supplier_name FROM rpt.jst_sku "
|
||||
. "WHERE sku_id IN ({$ph})";
|
||||
foreach ($this->up->select($sql, $chunk) as $r) {
|
||||
foreach ($this->up->select("SELECT sku_id, l, w, h, pack_volume, weight, supplier_name FROM rpt.jst_sku WHERE sku_id IN ({$ph})", $chunk) as $r) {
|
||||
$out[(string) $r['sku_id']] = [
|
||||
'l' => $r['l'] ?? null, 'w' => $r['w'] ?? null, 'h' => $r['h'] ?? null,
|
||||
'vol' => $r['pack_volume'] ?? null, 'weight' => $r['weight'] ?? null,
|
||||
@ -387,10 +494,11 @@ class ShippingReplicaSynchronizer
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** @return array<string,array> so_id|expressNo => 运费 (并含 so_id| 兜底键) */
|
||||
/** @return array<string,array> so_id|expressNo => 运费 (含 so_id| 兜底键) */
|
||||
private function loadFreight(array $soIds): array
|
||||
{
|
||||
$out = [];
|
||||
@ -409,6 +517,7 @@ class ShippingReplicaSynchronizer
|
||||
$out[((string) $r['so_id']) . '|'] ??= $val;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
@ -419,6 +528,7 @@ class ShippingReplicaSynchronizer
|
||||
$data[$k] = $this->cleanStr($v);
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
@ -429,6 +539,7 @@ class ShippingReplicaSynchronizer
|
||||
if ($clean === false) {
|
||||
$clean = mb_convert_encoding($v, 'UTF-8', 'UTF-8');
|
||||
}
|
||||
|
||||
return $clean;
|
||||
}
|
||||
|
||||
|
||||
@ -11,6 +11,7 @@
|
||||
['barcode','条形码','left','text'],
|
||||
['product_name','商品名称','left','text'],
|
||||
['qty','数量','right','int'],
|
||||
['pkg_count','件数','center','text'],
|
||||
['receiver_state','省','left','text'],
|
||||
['buyer_nick','买家昵称','left','text'],
|
||||
['receiver_name','收货姓名','left','text'],
|
||||
@ -108,6 +109,8 @@
|
||||
.shipping-data-page .sd-dd-opt:hover { background: #f3ece0; }
|
||||
.shipping-data-page .sd-dd-opt > span { overflow: hidden; text-overflow: ellipsis; }
|
||||
.shipping-data-page .sd-dd-empty { padding: .4rem; color: #9a9182; font-size: .75rem; }
|
||||
.shipping-data-page .sd-tab { padding: .3rem .7rem; border: 1px solid #d8d2c7; border-radius: 999px; color: #6f675c; background: #fff; }
|
||||
.shipping-data-page .sd-tab--on { background: #856632; color: #fff; border-color: #856632; }
|
||||
</style>
|
||||
|
||||
<div class="flex flex-col gap-4 mb-5 sm:flex-row sm:items-start sm:justify-between">
|
||||
@ -126,7 +129,16 @@
|
||||
@endif
|
||||
|
||||
<div class="mb-5 rounded-lg border border-[#e7e0d5] bg-white p-4 shadow-sm">
|
||||
@php $mode = $shippingMode ?? 'merged'; $modeQuery = array_merge(request()->query(), []); @endphp
|
||||
<div class="mb-3 flex items-center gap-2 text-xs">
|
||||
<span class="text-gray-500">口径:</span>
|
||||
<a href="{{ url()->current() }}?{{ http_build_query(array_merge(request()->except('page','mode'), ['mode'=>'merged'])) }}"
|
||||
class="sd-tab {{ $mode==='merged' ? 'sd-tab--on' : '' }}">合并(一个快递单号一行)</a>
|
||||
<a href="{{ url()->current() }}?{{ http_build_query(array_merge(request()->except('page','mode'), ['mode'=>'detail'])) }}"
|
||||
class="sd-tab {{ $mode==='detail' ? 'sd-tab--on' : '' }}">明细(每件商品一行)</a>
|
||||
</div>
|
||||
<form method="GET" class="flex flex-wrap items-end gap-3" aria-label="发货数据筛选" data-suggest-url="{{ route('business.courier-payables.shipping-data.suggest') }}">
|
||||
<input type="hidden" name="mode" value="{{ $shippingMode ?? 'merged' }}">
|
||||
<label class="sd-filter sd-filter--wide flex flex-col gap-1 text-xs text-gray-500" for="shipping-express-no"><span>快递单号</span><input id="shipping-express-no" class="sd-control" type="text" name="express_no" value="{{ $filters['express_no'] ?? '' }}" placeholder="精确匹配"></label>
|
||||
<label class="sd-filter sd-filter--wide flex flex-col gap-1 text-xs text-gray-500" for="shipping-trade-no"><span>交易单号</span><input id="shipping-trade-no" class="sd-control" type="text" name="sourceno" value="{{ $filters['sourceno'] ?? '' }}" placeholder="精确匹配"></label>
|
||||
<label class="sd-filter flex flex-col gap-1 text-xs text-gray-500" for="shipping-barcode"><span>条形码</span><input id="shipping-barcode" class="sd-control" type="text" name="barcode" value="{{ $filters['barcode'] ?? '' }}" placeholder="条形码关键词"></label>
|
||||
@ -164,7 +176,9 @@
|
||||
<label class="sd-filter flex flex-col gap-1 text-xs text-gray-500" for="shipping-to"><span>发货时间止</span><span class="sd-date-picker"><input id="shipping-to" class="sd-control" type="date" name="ship_to" value="{{ $filters['ship_to'] ?? '' }}"><button type="button" data-date-picker-input="shipping-to" aria-label="选择发货结束日期" title="选择发货结束日期"><span class="material-icons-outlined" aria-hidden="true">calendar_today</span></button></span></label>
|
||||
<div class="flex gap-2">
|
||||
<button class="sd-button sd-button--primary" type="submit"><span class="material-icons-outlined" aria-hidden="true">search</span><span>查询</span></button>
|
||||
<a class="sd-button sd-button--secondary" href="{{ $shippingExportUrl ?? route('business.courier-payables.shipping-data.export') }}?{{ http_build_query(array_filter($filters, static fn ($value) => is_array($value) ? $value !== [] : $value !== '')) }}" aria-label="导出当前筛选结果" title="导出当前筛选结果"><span class="material-icons-outlined" aria-hidden="true">download</span><span>导出</span></a>
|
||||
@php $expBase = ($shippingExportUrl ?? route('business.courier-payables.shipping-data.export')) . '?' . http_build_query(array_filter($filters, static fn ($value) => is_array($value) ? $value !== [] : $value !== '')); @endphp
|
||||
<a class="sd-button sd-button--secondary" href="{{ $expBase }}&mode=merged" title="导出合并(一个快递单号一行)"><span class="material-icons-outlined" aria-hidden="true">download</span><span>导出</span></a>
|
||||
<a class="sd-button sd-button--secondary" href="{{ $expBase }}&mode=detail" title="导出明细(每件商品一行)"><span class="material-icons-outlined" aria-hidden="true">list</span><span>导出明细</span></a>
|
||||
<a class="sd-button sd-button--secondary" href="{{ url()->current() }}"><span class="material-icons-outlined" aria-hidden="true">refresh</span><span>重置</span></a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user