From 9190ecff673f1b5add8274c99393543181775619 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Tue, 15 Sep 2026 06:32:45 +0000 Subject: [PATCH 01/11] =?UTF-8?q?feat:=20=E5=8F=91=E8=B4=A7=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E9=A1=B5=E6=8E=A5=E5=85=A5(caiwu=20=E7=9B=B4=E8=BF=9E?= =?UTF-8?q?=E8=81=9A=E6=B0=B4=E6=BD=AD/=E5=A5=87=E9=97=A8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 聚水潭奇门客户端与发货同步器骨架:QimenClient(签名+POST)、ShippingDataSynchronizer(erp.sctrade.query 列表 + erp.sradesku.query 明细 + upsert + modified 水位) - 发货明细扁平展示表 jst_oms_shipping(对齐工作平台发货数据 47 列/顺序,用于快递运费核算);原始表 jst_sctrade/_items/_skus/_receiver + jst_sync_state - 快递应付新增「发货数据」页:Pages.contentForShippingData + 视图 + business_navigation 导航项(slug=shipping-data) - ShippingOrderRepository 读展示表;artisan jushuitan:sync-shipping + 每10分钟增量调度(JST_SYNC_ENABLED 默认关) - 落库连接 jushuitan_local(本地容器,env 可覆盖);演示 Seeder(6 条家具发货样例);.env.jushuitan.example Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf --- .env.jushuitan.example | 30 ++ app/Console/Kernel.php | 9 + app/Http/Controllers/Business/Pages.php | 49 +++ config/business_navigation.php | 1 + config/database.php | 18 ++ config/jushuitan.php | 46 +++ .../seeds/JushuitanShippingDemoSeeder.php | 68 +++++ .../Console/SyncJushuitanShipping.php | 37 +++ ...09_15_100001_create_jst_sctrade_tables.php | 129 ++++++++ ..._15_100002_create_jst_sync_state_table.php | 36 +++ ...5_110001_create_jst_oms_shipping_table.php | 89 ++++++ modules/EcommerceFinance/Providers/Main.php | 7 + .../Repositories/ShippingOrderRepository.php | 73 +++++ .../Services/Jushuitan/QimenClient.php | 130 ++++++++ .../Jushuitan/ShippingDataSynchronizer.php | 278 ++++++++++++++++++ .../courier-payables/shipping-data.blade.php | 134 +++++++++ 16 files changed, 1134 insertions(+) create mode 100644 .env.jushuitan.example create mode 100644 config/jushuitan.php create mode 100644 database/seeds/JushuitanShippingDemoSeeder.php create mode 100644 modules/EcommerceFinance/Console/SyncJushuitanShipping.php create mode 100644 modules/EcommerceFinance/Database/Migrations/2026_09_15_100001_create_jst_sctrade_tables.php create mode 100644 modules/EcommerceFinance/Database/Migrations/2026_09_15_100002_create_jst_sync_state_table.php create mode 100644 modules/EcommerceFinance/Database/Migrations/2026_09_15_110001_create_jst_oms_shipping_table.php create mode 100644 modules/EcommerceFinance/Repositories/ShippingOrderRepository.php create mode 100644 modules/EcommerceFinance/Services/Jushuitan/QimenClient.php create mode 100644 modules/EcommerceFinance/Services/Jushuitan/ShippingDataSynchronizer.php create mode 100644 resources/views/business/pages/courier-payables/shipping-data.blade.php diff --git a/.env.jushuitan.example b/.env.jushuitan.example new file mode 100644 index 00000000..3d483848 --- /dev/null +++ b/.env.jushuitan.example @@ -0,0 +1,30 @@ +# ============================================================ +# 聚水潭(聚石塔 / 奇门)开放平台接入 —— caiwu 直连发货数据 +# 复用工作平台现有授权。把下列键补进 runtime/.env(勿提交 Git)。 +# 值留空时同步器会安全拒绝请求,不会误拉。 +# ============================================================ + +# 奇门网关地址(对应工作平台配置 ErpJSTUrl) +JST_QIMEN_URL= + +# 授权凭证(复用现有一套) +JST_APP_KEY= +JST_APP_SECRET= +JST_CUSTOMER_ID= + +# 奇门固定参数(一般无需改) +JST_API_VERSION=2 +JST_FORMAT=json +JST_SIMPLIFY=true + +# 同步参数(可选,均有默认值) +JST_SYNC_PAGE_LIMIT=100 +JST_SYNC_OVERLAP_HOURS=48 +JST_SYNC_WINDOW_HOURS=24 +JST_SYNC_MAX_PAGES=0 +JST_REQUEST_TIMEOUT=30 +JST_RETRY_TIMES=5 +JST_RETRY_SLEEP_MS=1000 + +# 定时增量总开关:凭证填好、迁移跑完、联调校准后再设为 true +JST_SYNC_ENABLED=false diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index d7558795..7ec03ff1 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -55,6 +55,15 @@ class Kernel extends ConsoleKernel ->runInBackground(); } + // 聚水潭发货数据增量同步:每 10 分钟按 modified 水位拉销售出库单。 + // 默认关闭(JST_SYNC_ENABLED=false);填好凭证并完成迁移后再打开。 + if ((bool) env('JST_SYNC_ENABLED', false)) { + $schedule->command('jushuitan:sync-shipping') + ->everyTenMinutes() + ->withoutOverlapping(30) + ->runInBackground(); + } + } /** diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 3d5a9dca..ccec6236 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -32,6 +32,7 @@ use Modules\EcommerceFinance\Repositories\AlibabaBillRepository; use Modules\EcommerceFinance\View\BillOffsetPageData; use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository; use Modules\EcommerceFinance\Repositories\CourierFreightReconciliationMirrorRepository; +use Modules\EcommerceFinance\Repositories\ShippingOrderRepository; use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorRepository; use Modules\EcommerceFinance\Repositories\EdgeBandingRepository; use Modules\EcommerceFinance\Repositories\InventoryRepository; @@ -94,6 +95,7 @@ class Pages extends Controller private readonly CourierSurchargeQuoteRepository $courierSurchargeQuotes, private readonly CourierSurchargeTypeRepository $courierSurchargeTypes, private readonly JushuitanShopBalanceRepository $jushuitanShopBalances, + private readonly ShippingOrderRepository $shippingOrders, ) { $this->middleware('auth'); $this->middleware('company.identify'); @@ -632,6 +634,7 @@ class Pages extends Controller 'payable-cloud-warehouse-vehicle-fee' => $this->contentForDingPayableWorkflows(), 'online-daifa-price' => $this->contentForOnlineDaifaPrice(), 'courier-surcharge' => $this->contentForCourierSurcharge(), + 'shipping-data' => $this->contentForShippingData(), 'withdrawal-management' => $this->contentForWithdrawalManagement(), 'bill-offset' => app(\Modules\EcommerceFinance\View\BillOffsetPageData::class)->page(), default => null, @@ -750,6 +753,52 @@ class Pages extends Controller * 报价维护与后续附加费结算分开:本页只负责渠道、类型、结算方式、 * 计价标准和生效时间的维护展示,结算页将来根据这些规则读取业务镜像。 */ + protected function contentForShippingData(): array + { + $request = request(); + $date = static function (mixed $value): string { + $value = trim((string) $value); + return preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $value) === 1 ? $value : ''; + }; + $filters = [ + 'express_no' => mb_substr(trim((string) $request->query('express_no', '')), 0, 80), + 'sourceno' => mb_substr(trim((string) $request->query('sourceno', '')), 0, 80), + 'ship_from' => $date($request->query('ship_from', '')), + 'ship_to' => $date($request->query('ship_to', '')), + ]; + $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, [ + 'path' => $request->url(), + 'query' => $request->except('page'), + ]); + $sync = ['code' => 'unavailable', 'last_succeeded_at' => null]; + $error = null; + + try { + $result = $this->shippingOrders->paginate($filters, $page, $limit); + $rows = new LengthAwarePaginator( + Collection::make($result['data'] ?? []), + (int) ($result['total'] ?? 0), + $limit, + $page, + ['path' => $request->url(), 'query' => $request->except('page')], + ); + $sync = $this->shippingOrders->syncStatus(); + } catch (Throwable $exception) { + report($exception); + $error = '发货数据暂时无法读取(可能尚未运行迁移或同步)。'; + } + + return [ + 'view' => 'business.pages.courier-payables.shipping-data', + 'shippingRows' => $rows, + 'shippingFilters' => $filters, + 'shippingSync' => $sync, + 'shippingError' => $error, + ]; + } + protected function contentForCourierSurcharge(): array { $clean = static fn (mixed $value, int $length = 60): string => mb_substr(trim((string) $value), 0, $length); diff --git a/config/business_navigation.php b/config/business_navigation.php index 3f2e14c5..3c1d337d 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -498,6 +498,7 @@ $navigation = [ ['slug' => 'courier-information', 'title' => '快递资料'], ['slug' => 'agreement-signing', 'title' => '协议签署'], ['slug' => 'freight-reconciliation', 'title' => '运费对账'], + ['slug' => 'shipping-data', 'title' => '发货数据'], ['slug' => 'third-party-warehouse-storage', 'title' => '三方仓进销存'], ['slug' => 'bookkeeping-details', 'title' => '记账明细'], ['slug' => 'compensation-details', 'title' => '赔偿明细'], diff --git a/config/database.php b/config/database.php index 723b4175..8ba5dcc7 100644 --- a/config/database.php +++ b/config/database.php @@ -153,6 +153,24 @@ return [ 'options' => $mysqlSslOptions(), ], + // 聚水潭发货数据专用落库连接。默认指向 docker-compose.local.yml 的本地 + // MySQL 容器(网络别名 mysql / 库 akaunting),与远程共享镜像库隔离, + // 便于先本地验证真实数据。上生产时用 env 覆盖到目标库即可。 + 'jushuitan_local' => [ + 'driver' => 'mysql', + 'host' => env('JST_DB_HOST', 'mysql'), + 'port' => env('JST_DB_PORT', '3306'), + 'database' => env('JST_DB_DATABASE', 'akaunting'), + 'username' => env('JST_DB_USERNAME', 'akaunting'), + 'password' => env('JST_DB_PASSWORD', 'akaunting123'), + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci', + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => 'InnoDB ROW_FORMAT=DYNAMIC', + ], + 'mariadb' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), diff --git a/config/jushuitan.php b/config/jushuitan.php new file mode 100644 index 00000000..afbd0882 --- /dev/null +++ b/config/jushuitan.php @@ -0,0 +1,46 @@ + env('JST_QIMEN_URL', ''), + + // 授权凭证(复用现有)。 + 'app_key' => env('JST_APP_KEY', ''), + 'app_secret' => env('JST_APP_SECRET', ''), + 'customer_id' => env('JST_CUSTOMER_ID', ''), + + // 奇门固定参数。 + 'format' => env('JST_FORMAT', 'json'), + 'version' => env('JST_API_VERSION', '2'), + 'simplify' => env('JST_SIMPLIFY', 'true'), + + // 落地存储连接:默认本地 MySQL 容器(jushuitan_local,见 config/database.php), + // 与远程共享镜像库隔离;上生产时用 env JST_DB_CONNECTION 覆盖。 + 'connection' => env('JST_DB_CONNECTION', 'jushuitan_local'), + + // 同步参数。 + 'sync' => [ + 'page_limit' => (int) env('JST_SYNC_PAGE_LIMIT', 100), // 每页条数(奇门 limit) + 'overlap_hours' => (int) env('JST_SYNC_OVERLAP_HOURS', 48), // 增量重叠窗口,补迟到更新 + 'window_hours' => (int) env('JST_SYNC_WINDOW_HOURS', 24), // 单次拉取时间窗口 + 'max_pages' => (int) env('JST_SYNC_MAX_PAGES', 0), // 单次最多翻页,0=不限 + 'request_timeout' => (int) env('JST_REQUEST_TIMEOUT', 30), // 秒 + 'retry_times' => (int) env('JST_RETRY_TIMES', 5), + 'retry_sleep_ms' => (int) env('JST_RETRY_SLEEP_MS', 1000), + ], + + // 接口方法名(对应工作平台 ErpTradeData 中的调用)。 + 'methods' => [ + 'sctrade_list' => 'erp.sctrade.query', // 出库单列表(按时间窗分页) + 'sctrade_detail' => 'erp.sradesku.query', // 单据完整明细(按 tradeId) + ], +]; diff --git a/database/seeds/JushuitanShippingDemoSeeder.php b/database/seeds/JushuitanShippingDemoSeeder.php new file mode 100644 index 00000000..d79c9166 --- /dev/null +++ b/database/seeds/JushuitanShippingDemoSeeder.php @@ -0,0 +1,68 @@ +copy()->subHours(++$i); + $vol = $L * $W * $H; + $sid = 9000000 + $i; + + $db->table('jst_oms_shipping')->updateOrInsert( + ['source_id' => $sid, 'sku_source_id' => $sid], + [ + 'express_no' => $expno, 'trade_no' => $tradeno, 'item_id' => $itemid, 'barcode' => $barcode, + 'product_name' => $pname, 'qty' => $qty, 'receiver_state' => $prov, 'buyer_nick' => '', + 'receiver_name' => $rname, 'shop_name' => $shop, 'express_name1' => $express, 'warehouse_name' => $wh, + 'ship_time' => $shipTime, 'freight' => $freight, 'online_weight' => $onlineW, 'actual_weight' => $actualW, + 'length_cm' => $L, 'width_cm' => $W, 'height_cm' => $H, 'volume_cm3' => $vol, + 'receiver_city' => $city, 'receiver_district' => $dist, 'supplier_name' => $supplier, + 'receiver_address' => $prov.$city.$dist.'示例路'.($i*7).'号', 'receiver_mobile' => $mobile, 'receiver_phone' => '', + 'express_name2' => $express, 'platform' => $platform, 'buyer_memo' => '', 'seller_memo' => '', + 'package_no' => 'PH'.$shipTime->format('Ymd').str_pad((string)$i,4,'0',STR_PAD_LEFT), + 'amount' => round($actualW * 9.9 + 39, 2), 'product_code' => $procode, + 'download_time' => $shipTime->copy()->addMinutes(30), 'pay_time' => $shipTime->copy()->subHours(3), + 'freight_rate' => 1.0, 'freight_formula' => '首重+续重', + 'weight_kg' => $actualW, 'settle_weight_kg' => max($actualW, round($vol/6000, 4)), + 'settle_volume_cm3' => $vol, 'recon_weight_kg' => $actualW, 'recon_volume_cm3' => $vol, + 'finished_barcode' => '', 'finished_name' => $pname, 'finished_supplier' => $supplier, + 'settle_freight' => $settleFreight, 'front_no' => '', + 'modified' => $shipTime, 'synced_at' => $now, + ] + ); + } + + $db->table('jst_sync_state')->updateOrInsert(['dataset_key' => 'jst.sctrade'], [ + 'watermark' => $now, 'status' => 'succeeded', 'last_succeeded_at' => $now, + 'updated_at' => $now, 'created_at' => $now, + ]); + + $this->command?->info('已写入 ' . count($samples) . ' 条发货明细演示数据(47 列,source_id 9000001 起)。'); + } +} diff --git a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php new file mode 100644 index 00000000..b782fccd --- /dev/null +++ b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php @@ -0,0 +1,37 @@ +option('from') ? Carbon::parse($this->option('from')) : null; + $to = $this->option('to') ? Carbon::parse($this->option('to')) : null; + + $this->info('开始同步聚水潭发货数据...'); + try { + $result = ShippingDataSynchronizer::make()->syncIncremental($from, $to); + } catch (\Throwable $e) { + $this->error('同步失败:' . $e->getMessage()); + return self::FAILURE; + } + + $this->info(sprintf('完成:处理 %d 单,水位推进到 %s', $result['processed'], $result['watermark'] ?? '(未变)')); + return self::SUCCESS; + } +} diff --git a/modules/EcommerceFinance/Database/Migrations/2026_09_15_100001_create_jst_sctrade_tables.php b/modules/EcommerceFinance/Database/Migrations/2026_09_15_100001_create_jst_sctrade_tables.php new file mode 100644 index 00000000..3f1774a4 --- /dev/null +++ b/modules/EcommerceFinance/Database/Migrations/2026_09_15_100001_create_jst_sctrade_tables.php @@ -0,0 +1,129 @@ +connection()); + + // —— 主单 —— + if (! $schema->hasTable('jst_sctrade')) $schema->create('jst_sctrade', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->unsignedBigInteger('source_id')->comment('聚水潭单据 id'); // 稳定键 + $table->string('sourceno', 64)->nullable()->comment('交易/线上单号'); + $table->string('io_id', 64)->nullable()->comment('出库单号'); + $table->string('shop_id', 32)->nullable()->comment('店铺 id'); + $table->string('shopcode', 64)->nullable()->comment('店铺编码'); + $table->string('wms_co_id', 32)->nullable()->comment('分仓/仓库 id'); + $table->string('platform', 64)->nullable()->comment('平台'); + $table->string('status', 32)->nullable()->comment('单据状态'); + $table->dateTime('paytime')->nullable(); + $table->dateTime('sended')->nullable()->comment('发货时间'); + $table->dateTime('created')->nullable(); + $table->dateTime('modified')->nullable()->comment('修改时间(增量水位)'); + // 收货人(主单上冗余的部分,明细以 receiver 表为准) + $table->string('receiverstate', 64)->nullable(); + $table->string('receivercity', 64)->nullable(); + $table->string('receiverdistrict', 64)->nullable(); + $table->string('receivername', 128)->nullable(); + $table->string('receivermobile', 64)->nullable(); + $table->string('receiverphone', 64)->nullable(); + $table->longText('receiveraddress')->nullable(); + $table->decimal('weight', 12, 4)->nullable(); + $table->decimal('freight', 12, 2)->nullable(); + $table->longText('raw_json')->nullable()->comment('完整报文保真'); + $table->dateTime('synced_at', 6)->nullable(); + + $table->unique('source_id'); + $table->index('sourceno'); + $table->index('modified'); + $table->index('sended'); + }); + + // —— 平台商品明细 —— + if (! $schema->hasTable('jst_sctrade_items')) $schema->create('jst_sctrade_items', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->unsignedBigInteger('source_id')->comment('明细 id'); + $table->unsignedBigInteger('hid')->comment('主单 source_id'); + $table->string('oid', 64)->nullable()->comment('平台子订单号'); + $table->string('shopproid', 64)->nullable(); + $table->string('shoprocode', 128)->nullable(); + $table->string('shopskucode', 128)->nullable(); + $table->string('shoproname', 512)->nullable(); + $table->integer('qty')->nullable(); + $table->longText('raw_json')->nullable(); + $table->dateTime('synced_at', 6)->nullable(); + + $table->unique('source_id'); + $table->index('hid'); + }); + + // —— SKU 明细 —— + if (! $schema->hasTable('jst_sctrade_skus')) $schema->create('jst_sctrade_skus', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->unsignedBigInteger('source_id')->comment('SKU 明细 id'); + $table->unsignedBigInteger('hid')->comment('主单 source_id'); + $table->string('procode', 128)->nullable()->comment('商品编码/货号'); + $table->string('sku_id', 128)->nullable(); + $table->string('proname', 512)->nullable(); + $table->string('scmname', 512)->nullable()->comment('成品名'); + $table->string('postcode', 64)->nullable()->comment('快递单号'); + $table->string('logistics_company', 128)->nullable()->comment('快递公司'); + $table->integer('qty')->nullable(); + $table->dateTime('sended')->nullable(); + $table->longText('raw_json')->nullable(); + $table->dateTime('synced_at', 6)->nullable(); + + $table->unique('source_id'); + $table->index('hid'); + $table->index('postcode'); + }); + + // —— 收货人明细 —— + if (! $schema->hasTable('jst_sctrade_receiver')) $schema->create('jst_sctrade_receiver', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->unsignedBigInteger('hid')->comment('主单 source_id'); + $table->string('receivername', 128)->nullable(); + $table->string('receiverstate', 64)->nullable(); + $table->string('receivercity', 64)->nullable(); + $table->string('receiverdistrict', 64)->nullable(); + $table->longText('receiveraddress')->nullable(); + $table->string('receivermobile', 64)->nullable(); + $table->string('receiverphone', 64)->nullable(); + $table->string('receiverzip', 32)->nullable(); + $table->longText('raw_json')->nullable(); + $table->dateTime('synced_at', 6)->nullable(); + + $table->unique('hid'); + }); + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('jst_sctrade_receiver'); + $schema->dropIfExists('jst_sctrade_skus'); + $schema->dropIfExists('jst_sctrade_items'); + $schema->dropIfExists('jst_sctrade'); + } +}; diff --git a/modules/EcommerceFinance/Database/Migrations/2026_09_15_100002_create_jst_sync_state_table.php b/modules/EcommerceFinance/Database/Migrations/2026_09_15_100002_create_jst_sync_state_table.php new file mode 100644 index 00000000..547cc346 --- /dev/null +++ b/modules/EcommerceFinance/Database/Migrations/2026_09_15_100002_create_jst_sync_state_table.php @@ -0,0 +1,36 @@ +connection())->hasTable('jst_sync_state')) return; + Schema::connection($this->connection())->create('jst_sync_state', function (Blueprint $table) { + $table->string('dataset_key', 128)->primary(); // 如 jst.sctrade + $table->dateTime('watermark')->nullable(); // 已同步到的 modified 时间 + $table->string('status', 20)->default('pending'); // pending/running/succeeded/failed + $table->dateTime('last_started_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->text('last_error')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::connection($this->connection())->dropIfExists('jst_sync_state'); + } +}; diff --git a/modules/EcommerceFinance/Database/Migrations/2026_09_15_110001_create_jst_oms_shipping_table.php b/modules/EcommerceFinance/Database/Migrations/2026_09_15_110001_create_jst_oms_shipping_table.php new file mode 100644 index 00000000..c4bd82c0 --- /dev/null +++ b/modules/EcommerceFinance/Database/Migrations/2026_09_15_110001_create_jst_oms_shipping_table.php @@ -0,0 +1,89 @@ +conn()); + if ($schema->hasTable('jst_oms_shipping')) return; + + $schema->create('jst_oms_shipping', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->unsignedBigInteger('source_id')->nullable()->comment('聚水潭单据 id'); + $table->unsignedBigInteger('sku_source_id')->nullable()->comment('聚水潭 SKU 明细 id'); + + // —— 按界面顺序的 47 列 —— + $table->string('express_no', 64)->nullable()->comment('1 快递单号'); + $table->string('trade_no', 64)->nullable()->comment('2 交易单号'); + $table->string('item_id', 64)->nullable()->comment('3 商品ID'); + $table->string('barcode', 128)->nullable()->comment('4 条形码'); + $table->string('product_name', 512)->nullable()->comment('5 商品名称'); + $table->integer('qty')->nullable()->comment('6 数量'); + $table->string('receiver_state', 64)->nullable()->comment('7 省'); + $table->string('buyer_nick', 128)->nullable()->comment('8 买家昵称'); + $table->string('receiver_name', 128)->nullable()->comment('9 收货姓名'); + $table->string('shop_name', 255)->nullable()->comment('10 店铺名称'); + $table->string('express_name1', 128)->nullable()->comment('11 快递名称1'); + $table->string('warehouse_name', 128)->nullable()->comment('12 仓库'); + $table->dateTime('ship_time')->nullable()->comment('13 发货时间'); + $table->decimal('freight', 18, 2)->nullable()->comment('14 运费'); + $table->decimal('online_weight', 18, 4)->nullable()->comment('15 线上重量'); + $table->decimal('actual_weight', 18, 4)->nullable()->comment('16 实称重量'); + $table->decimal('length_cm', 18, 2)->nullable()->comment('17 长'); + $table->decimal('width_cm', 18, 2)->nullable()->comment('18 宽'); + $table->decimal('height_cm', 18, 2)->nullable()->comment('19 高'); + $table->decimal('volume_cm3', 18, 4)->nullable()->comment('20 体积'); + $table->string('receiver_city', 64)->nullable()->comment('21 市'); + $table->string('receiver_district', 64)->nullable()->comment('22 区'); + $table->string('supplier_name', 128)->nullable()->comment('23 供应商'); + $table->longText('receiver_address')->nullable()->comment('24 收货详细地址'); + $table->string('receiver_mobile', 64)->nullable()->comment('25 手机号码'); + $table->string('receiver_phone', 64)->nullable()->comment('26 座机号码'); + $table->string('express_name2', 128)->nullable()->comment('27 快递名称2'); + $table->string('platform', 64)->nullable()->comment('28 平台'); + $table->longText('buyer_memo')->nullable()->comment('29 买家留言'); + $table->longText('seller_memo')->nullable()->comment('30 卖家备注'); + $table->string('package_no', 64)->nullable()->comment('31 配货单号'); + $table->decimal('amount', 18, 2)->nullable()->comment('32 金额'); + $table->string('product_code', 128)->nullable()->comment('33 货号'); + $table->dateTime('download_time')->nullable()->comment('34 下载时间'); + $table->dateTime('pay_time')->nullable()->comment('35 付款时间'); + $table->decimal('freight_rate', 18, 4)->nullable()->comment('36 费率'); + $table->string('freight_formula', 255)->nullable()->comment('37 公式'); + $table->decimal('weight_kg', 18, 4)->nullable()->comment('38 重量'); + $table->decimal('settle_weight_kg', 18, 4)->nullable()->comment('39 结算重量'); + $table->decimal('settle_volume_cm3', 18, 4)->nullable()->comment('40 结算体积'); + $table->decimal('recon_weight_kg', 18, 4)->nullable()->comment('41 对账重量'); + $table->decimal('recon_volume_cm3', 18, 4)->nullable()->comment('42 对账体积'); + $table->string('finished_barcode', 128)->nullable()->comment('43 成品条码'); + $table->string('finished_name', 512)->nullable()->comment('44 成品名称'); + $table->string('finished_supplier', 128)->nullable()->comment('45 成品供应商'); + $table->decimal('settle_freight', 18, 2)->nullable()->comment('46 结算运费'); + $table->string('front_no', 64)->nullable()->comment('47 换单前单号'); + + $table->dateTime('modified')->nullable()->comment('增量水位'); + $table->dateTime('synced_at', 6)->nullable(); + + $table->index('express_no'); + $table->index('trade_no'); + $table->index('ship_time'); + $table->unique(['source_id', 'sku_source_id'], 'jst_oms_uniq'); + }); + } + + public function down(): void + { + Schema::connection($this->conn())->dropIfExists('jst_oms_shipping'); + } +}; diff --git a/modules/EcommerceFinance/Providers/Main.php b/modules/EcommerceFinance/Providers/Main.php index d3f51ced..c2564bd6 100644 --- a/modules/EcommerceFinance/Providers/Main.php +++ b/modules/EcommerceFinance/Providers/Main.php @@ -3,6 +3,7 @@ namespace Modules\EcommerceFinance\Providers; use Illuminate\Support\ServiceProvider as Provider; +use Modules\EcommerceFinance\Console\SyncJushuitanShipping; use Modules\EcommerceFinance\Services\JianSunSnapshotRefresher; use Modules\EcommerceFinance\Services\OperationsReplicaSnapshotRefresher; use Modules\EcommerceFinance\Services\UpstreamSnapshotRefresherRegistry; @@ -14,6 +15,12 @@ class Main extends Provider { $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'ecommerce-finance'); $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations'); + + if ($this->app->runningInConsole()) { + $this->commands([ + SyncJushuitanShipping::class, + ]); + } } public function register(): void diff --git a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php new file mode 100644 index 00000000..d2cb5af6 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php @@ -0,0 +1,73 @@ +db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local')); + } + + /** + * @param array $filters express_no / sourceno / ship_from / ship_to + * @return array{data:array,total:int} + */ + public function paginate(array $filters, int $page, int $perPage): array + { + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + + $q = $this->db->table('jst_oms_shipping'); + if (($filters['express_no'] ?? '') !== '') { + $q->where('express_no', '=', trim((string) $filters['express_no'])); + } + if (($filters['sourceno'] ?? '') !== '') { + $q->where('trade_no', '=', trim((string) $filters['sourceno'])); + } + if (($filters['ship_from'] ?? '') !== '') { + $q->where('ship_time', '>=', $filters['ship_from'] . ' 00:00:00'); + } + if (($filters['ship_to'] ?? '') !== '') { + $q->where('ship_time', '<', date('Y-m-d 00:00:00', strtotime($filters['ship_to'] . ' +1 day'))); + } + + $total = (clone $q)->count(); + $rows = (clone $q) + ->orderByDesc('ship_time') + ->orderByDesc('id') + ->forPage($page, $perPage) + ->get() + ->map(fn ($r) => (array) $r) + ->all(); + + return ['data' => $rows, 'total' => $total]; + } + + /** 同步状态(供页面显示同步中/最近完成)。 */ + public function syncStatus(): array + { + try { + $row = $this->db->table('jst_sync_state')->where('dataset_key', 'jst.sctrade')->first(); + if (! $row) { + return ['code' => 'unavailable', 'last_succeeded_at' => null]; + } + + return [ + 'code' => (string) ($row->status ?? 'unavailable'), + 'last_succeeded_at' => $row->last_succeeded_at ?? null, + ]; + } catch (\Throwable) { + return ['code' => 'unavailable', 'last_succeeded_at' => null]; + } + } +} diff --git a/modules/EcommerceFinance/Services/Jushuitan/QimenClient.php b/modules/EcommerceFinance/Services/Jushuitan/QimenClient.php new file mode 100644 index 00000000..40a26167 --- /dev/null +++ b/modules/EcommerceFinance/Services/Jushuitan/QimenClient.php @@ -0,0 +1,130 @@ +assertConfigured(); + + $bodyJson = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + if ($bodyJson === false) { + throw new RuntimeException('聚水潭请求体序列化失败。'); + } + + $baseParams = $this->baseParams($method); + $baseParams['sign'] = $this->sign($baseParams, $bodyJson); + + $sync = $this->config['sync'] ?? []; + $timeout = (int) ($sync['request_timeout'] ?? 30); + $retries = max((int) ($sync['retry_times'] ?? 5), 1); + $retrySleep = (int) ($sync['retry_sleep_ms'] ?? 1000); + + $response = Http::withOptions(['query' => $baseParams]) + ->withHeaders(['Content-Type' => 'application/json']) + ->timeout($timeout) + ->retry($retries, $retrySleep) + ->withBody($bodyJson, 'application/json') + ->post($this->gatewayUrl()); + + if ($response->failed()) { + Log::warning('聚水潭奇门接口 HTTP 失败。', ['method' => $method, 'status' => $response->status()]); + throw new RuntimeException("聚水潭接口 {$method} 请求失败:HTTP {$response->status()}"); + } + + $data = $response->json(); + if (! is_array($data)) { + throw new RuntimeException("聚水潭接口 {$method} 返回非 JSON。"); + } + + // 奇门通常以 code=0 / issuccess 标识成功,具体字段以实际返回为准,此处仅做基础校验。 + return $data; + } + + /** @return array */ + private function baseParams(string $method): array + { + return [ + 'app_key' => (string) ($this->config['app_key'] ?? ''), + 'customerId' => (string) ($this->config['customer_id'] ?? ''), + 'format' => (string) ($this->config['format'] ?? 'json'), + 'method' => $method, + 'simplify' => (string) ($this->config['simplify'] ?? 'true'), + 'timestamp' => now()->format('Y-m-d H:i:s'), + 'v' => (string) ($this->config['version'] ?? '2'), + ]; + } + + /** + * 奇门 MD5 签名。等价于工作平台 ErpApiHelper.SignTopRequest: + * raw = secret + Σ(key+value,按固定顺序,跳过 sign) + body + secret + */ + private function sign(array $baseParams, string $bodyJson): string + { + $secret = (string) ($this->config['app_secret'] ?? ''); + $raw = $secret; + foreach (self::SIGN_ORDER as $key) { + $value = $baseParams[$key] ?? null; + if ($value !== null && $value !== '') { + $raw .= $key . $value; + } + } + $raw .= $bodyJson . $secret; + + return strtoupper(md5($raw)); + } + + private function gatewayUrl(): string + { + $url = trim((string) ($this->config['gateway_url'] ?? '')); + if ($url === '') { + throw new RuntimeException('未配置聚水潭奇门网关地址(JST_QIMEN_URL)。'); + } + + return $url; + } + + private function assertConfigured(): void + { + foreach (['app_key' => 'JST_APP_KEY', 'app_secret' => 'JST_APP_SECRET', 'customer_id' => 'JST_CUSTOMER_ID'] as $key => $env) { + if (trim((string) ($this->config[$key] ?? '')) === '') { + throw new RuntimeException("未配置聚水潭凭证 {$env},已拒绝请求(不会同步任何数据)。"); + } + } + } +} diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingDataSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingDataSynchronizer.php new file mode 100644 index 00000000..4b18ec49 --- /dev/null +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingDataSynchronizer.php @@ -0,0 +1,278 @@ + 得到每单 id / modified + * 2) erp.sradesku.query 按 tradeId 拉单据完整明细 -> 主单 + items + skus + receiver + * 增量以 modified 为水位,带重叠窗口;按 source_id upsert 去重。 + * + * 注意:奇门返回的 JSON 字段路径以聚水潭实际返回为准,本骨架的取值点已用 + * pluck() 集中,联调时按真实返回调整即可,不影响主流程结构。 + */ +class ShippingDataSynchronizer +{ + private const DATASET = 'jst.sctrade'; + + private readonly ConnectionInterface $db; + + public function __construct( + private readonly QimenClient $client, + private readonly array $config, + ) { + $this->db = DB::connection($config['connection'] ?? 'business_mirror'); + } + + public static function make(): self + { + return new self(QimenClient::fromConfig(), (array) config('jushuitan')); + } + + /** + * 执行一次增量同步。 + * + * @param ?Carbon $from 起始修改时间;默认取水位 - overlap + * @param ?Carbon $to 截止修改时间;默认 now + */ + public function syncIncremental(?Carbon $from = null, ?Carbon $to = null): array + { + $sync = $this->config['sync'] ?? []; + $overlap = max((int) ($sync['overlap_hours'] ?? 48), 0); + $limit = max((int) ($sync['page_limit'] ?? 100), 1); + $maxPages = (int) ($sync['max_pages'] ?? 0); + + $state = $this->state(); + $from ??= isset($state['watermark']) && $state['watermark'] + ? Carbon::parse($state['watermark'])->subHours($overlap) + : now()->subHours(max((int) ($sync['window_hours'] ?? 24), 1)); + $to ??= now(); + + $this->markRunning(); + $processed = 0; + $maxModified = $from; + + try { + $page = 1; + do { + $list = $this->client->call($this->method('sctrade_list'), [ + 'updateSt' => $from->format('Y-m-d H:i:s'), + 'updateEt' => $to->format('Y-m-d H:i:s'), + 'limit' => $limit, + 'page' => $page, + ]); + + $orders = $this->pluckOrders($list); + foreach ($orders as $order) { + $id = $this->pluckId($order); + if ($id === null) { + continue; + } + $detail = $this->client->call($this->method('sctrade_detail'), ['tradeId' => $id]); + $data = $detail['data'] ?? $detail; + $this->upsertOrder($data); + $processed++; + + $modified = $this->pluckModified($data); + if ($modified && (! $maxModified || $modified->gt($maxModified))) { + $maxModified = $modified; + } + } + + $hasNext = count($orders) >= $limit && ($maxPages === 0 || $page < $maxPages); + $page++; + } while ($hasNext); + + $this->markSucceeded($maxModified); + } catch (Throwable $e) { + $this->markFailed($e->getMessage()); + report($e); + throw $e; + } + + return ['processed' => $processed, 'watermark' => optional($maxModified)->toDateTimeString()]; + } + + /* ---------------- upsert(按 source_id 去重) ---------------- */ + + private function upsertOrder(array $data): void + { + $sourceId = $this->pluckId($data); + if ($sourceId === null) { + return; + } + $now = now(); + + $this->db->table('jst_sctrade')->updateOrInsert( + ['source_id' => $sourceId], + [ + 'sourceno' => $data['so_id'] ?? ($data['sourceno'] ?? null), + 'io_id' => $data['io_id'] ?? null, + 'shop_id' => $data['shop_id'] ?? null, + 'shopcode' => $data['shopcode'] ?? null, + 'wms_co_id' => $data['wms_co_id'] ?? null, + 'platform' => $data['platform'] ?? null, + 'status' => $data['status'] ?? null, + 'paytime' => $this->ts($data['pay_date'] ?? ($data['paytime'] ?? null)), + 'sended' => $this->ts($data['sended'] ?? null), + 'created' => $this->ts($data['created'] ?? null), + 'modified' => $this->ts($data['modified'] ?? null), + 'receiverstate' => $data['receiver_state'] ?? ($data['receiverstate'] ?? null), + 'receivercity' => $data['receiver_city'] ?? ($data['receivercity'] ?? null), + 'receiverdistrict' => $data['receiver_district'] ?? ($data['receiverdistrict'] ?? null), + 'receivername' => $data['receiver_name'] ?? ($data['receivername'] ?? null), + 'receivermobile' => $data['receiver_mobile'] ?? ($data['receivermobile'] ?? null), + 'receiverphone' => $data['receiver_phone'] ?? ($data['receiverphone'] ?? null), + 'receiveraddress' => $data['receiver_address'] ?? ($data['receiveraddress'] ?? null), + 'weight' => $data['weight'] ?? null, + 'freight' => $data['freight'] ?? null, + 'raw_json' => json_encode($data, JSON_UNESCAPED_UNICODE), + 'synced_at' => $now, + ] + ); + + foreach (($data['items'] ?? []) as $item) { + $iid = $item['id'] ?? null; + if ($iid === null) { + continue; + } + $this->db->table('jst_sctrade_items')->updateOrInsert( + ['source_id' => $iid], + [ + 'hid' => $sourceId, + 'oid' => $item['oid'] ?? null, + 'shopproid' => $item['shop_i_id'] ?? ($item['shopproid'] ?? null), + 'shoprocode' => $item['sku_id'] ?? ($item['shoprocode'] ?? null), + 'shopskucode' => $item['shopskucode'] ?? null, + 'shoproname' => $item['name'] ?? ($item['shoproname'] ?? null), + 'qty' => $item['qty'] ?? null, + 'raw_json' => json_encode($item, JSON_UNESCAPED_UNICODE), + 'synced_at' => $now, + ] + ); + } + + foreach (($data['tradeskus'] ?? ($data['skus'] ?? [])) as $sku) { + $sid = $sku['id'] ?? null; + if ($sid === null) { + continue; + } + $this->db->table('jst_sctrade_skus')->updateOrInsert( + ['source_id' => $sid], + [ + 'hid' => $sourceId, + 'procode' => $sku['sku_id'] ?? ($sku['procode'] ?? null), + 'sku_id' => $sku['sku_id'] ?? null, + 'proname' => $sku['name'] ?? ($sku['proname'] ?? null), + 'scmname' => $sku['scmname'] ?? null, + 'postcode' => $sku['postcode'] ?? ($sku['l_id'] ?? null), + 'logistics_company' => $sku['logistics_company'] ?? null, + 'qty' => $sku['qty'] ?? null, + 'sended' => $this->ts($sku['sended'] ?? null), + 'raw_json' => json_encode($sku, JSON_UNESCAPED_UNICODE), + 'synced_at' => $now, + ] + ); + } + + $receiver = $data['tradeReceiver'] ?? ($data['receiver'] ?? null); + if (is_array($receiver)) { + $this->db->table('jst_sctrade_receiver')->updateOrInsert( + ['hid' => $sourceId], + [ + 'receivername' => $receiver['receivername'] ?? ($receiver['name'] ?? null), + 'receiverstate' => $receiver['receiverstate'] ?? null, + 'receivercity' => $receiver['receivercity'] ?? null, + 'receiverdistrict' => $receiver['receiverdistrict'] ?? null, + 'receiveraddress' => $receiver['receiveraddress'] ?? null, + 'receivermobile' => $receiver['receivermobile'] ?? null, + 'receiverphone' => $receiver['receiverphone'] ?? null, + 'receiverzip' => $receiver['receiverzip'] ?? null, + 'raw_json' => json_encode($receiver, JSON_UNESCAPED_UNICODE), + 'synced_at' => $now, + ] + ); + } + } + + /* ---------------- 返回体取值点(按聚水潭实际返回调整) ---------------- */ + + /** @return array */ + private function pluckOrders(array $list): array + { + $data = $list['data'] ?? $list; + return $data['datas'] ?? ($data['orders'] ?? ($data['list'] ?? [])); + } + + private function pluckId(array $order): ?int + { + $id = $order['id'] ?? ($order['io_id'] ?? null); + return $id === null ? null : (int) $id; + } + + private function pluckModified(array $data): ?Carbon + { + return $this->ts($data['modified'] ?? null); + } + + private function ts(mixed $value): ?Carbon + { + if ($value === null || $value === '' ) { + return null; + } + try { + if (is_numeric($value)) { + $v = (int) $value; + return Carbon::createFromTimestamp($v > 9999999999 ? intdiv($v, 1000) : $v); + } + return Carbon::parse((string) $value); + } catch (Throwable) { + return null; + } + } + + /* ---------------- 同步状态 ---------------- */ + + private function state(): array + { + $row = $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->first(); + return $row ? (array) $row : []; + } + + private function markRunning(): void + { + $this->db->table('jst_sync_state')->updateOrInsert( + ['dataset_key' => self::DATASET], + ['status' => 'running', 'last_started_at' => now(), 'updated_at' => now(), 'created_at' => now()] + ); + } + + private function markSucceeded(?Carbon $watermark): void + { + $update = ['status' => 'succeeded', 'last_succeeded_at' => now(), 'last_error' => null, 'updated_at' => now()]; + if ($watermark) { + $update['watermark'] = $watermark; + } + $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->update($update); + } + + private function markFailed(string $error): void + { + $this->db->table('jst_sync_state')->where('dataset_key', self::DATASET)->update([ + 'status' => 'failed', 'last_error' => mb_substr($error, 0, 1000), 'updated_at' => now(), + ]); + } + + private function method(string $key): string + { + return $this->config['methods'][$key] ?? ''; + } +} diff --git a/resources/views/business/pages/courier-payables/shipping-data.blade.php b/resources/views/business/pages/courier-payables/shipping-data.blade.php new file mode 100644 index 00000000..e7ad2b9d --- /dev/null +++ b/resources/views/business/pages/courier-payables/shipping-data.blade.php @@ -0,0 +1,134 @@ +@php + $filters = $shippingFilters ?? []; + $sync = $shippingSync ?? ['code' => 'unavailable', 'last_succeeded_at' => null]; + $statusLabels = ['succeeded' => '数据新鲜', 'running' => '同步中', 'pending' => '等待同步', 'failed' => '同步失败', 'unavailable' => '尚未同步']; + + // 按工作平台发货数据界面顺序的 47 列: [列key, 表头, 对齐, 类型] + $columns = [ + ['express_no','快递单号','left','mono'], + ['trade_no','交易单号','left','mono'], + ['item_id','商品ID','left','mono'], + ['barcode','条形码','left','text'], + ['product_name','商品名称','left','text'], + ['qty','数量','right','int'], + ['receiver_state','省','left','text'], + ['buyer_nick','买家昵称','left','text'], + ['receiver_name','收货姓名','left','text'], + ['shop_name','店铺名称','left','text'], + ['express_name1','快递名称1','left','text'], + ['warehouse_name','仓库','left','text'], + ['ship_time','发货时间','left','text'], + ['freight','运费','right','money'], + ['online_weight','线上重量','right','num'], + ['actual_weight','实称重量','right','num'], + ['length_cm','长(cm)','right','num'], + ['width_cm','宽(cm)','right','num'], + ['height_cm','高(cm)','right','num'], + ['volume_cm3','体积(cm³)','right','num'], + ['receiver_city','市','left','text'], + ['receiver_district','区','left','text'], + ['supplier_name','供应商','left','text'], + ['receiver_address','收货详细地址','left','text'], + ['receiver_mobile','手机号码','left','text'], + ['receiver_phone','座机号码','left','text'], + ['express_name2','快递名称2','left','text'], + ['platform','平台','left','text'], + ['buyer_memo','买家留言','left','text'], + ['seller_memo','卖家备注','left','text'], + ['package_no','配货单号','left','mono'], + ['amount','金额','right','money'], + ['product_code','货号','left','text'], + ['download_time','下载时间','left','text'], + ['pay_time','付款时间','left','text'], + ['freight_rate','费率','right','num'], + ['freight_formula','公式','left','text'], + ['weight_kg','重量(kg)','right','num'], + ['settle_weight_kg','结算重量(kg)','right','num'], + ['settle_volume_cm3','结算体积(cm³)','right','num'], + ['recon_weight_kg','对账重量(kg)','right','num'], + ['recon_volume_cm3','对账体积(cm³)','right','num'], + ['finished_barcode','成品条码','left','text'], + ['finished_name','成品名称','left','text'], + ['finished_supplier','成品供应商','left','text'], + ['settle_freight','结算运费','right','money'], + ['front_no','换单前单号','left','mono'], + ]; + + $fmt = function ($v, $type) { + if ($v === null || $v === '') return ''; + return match ($type) { + 'money' => number_format((float) $v, 2), + 'num' => rtrim(rtrim(number_format((float) $v, 4, '.', ''), '0'), '.'), + 'int' => (string) (int) $v, + default => (string) $v, + }; + }; +@endphp + +
+ + +
+
+

{{ $page['title'] ?? '发货数据' }}

+

数据来源:聚水潭(聚石塔/奇门)· 销售出库单 · caiwu 直连拉取 · 用于快递运费核算

+
+
+ {{ $statusLabels[$sync['code'] ?? 'unavailable'] ?? '状态未知' }} + @if (!empty($sync['last_succeeded_at'])) 最近同步 {{ $sync['last_succeeded_at'] }} @endif +
+
+ + @if (!empty($shippingError)) +
{{ $shippingError }}
+ @endif + +
+
+ + + + +
重置
+
+
+ +
+
+ + + @foreach ($columns as $c) + + @endforeach + + + @forelse ($shippingRows ?? [] as $row) + + @foreach ($columns as $c) + @php $val = $fmt($row[$c[0]] ?? null, $c[3]); @endphp + + @endforeach + + @empty + + @endforelse + +
{{ $c[1] }}
{{ $val === '' ? '-' : $val }}
暂无发货数据(填好聚水潭凭证并运行同步后显示;或先运行演示数据 Seeder 查看界面)
+
+ @if (($shippingRows ?? null) instanceof \Illuminate\Contracts\Pagination\LengthAwarePaginator && $shippingRows->hasPages()) +
共 {{ $shippingRows->total() }} 条记录
{{ $shippingRows->onEachSide(1)->links() }}
+ @endif +
+
From f580807097de3311769b56b31288dfcef932bde9 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Wed, 16 Sep 2026 10:55:27 +0800 Subject: [PATCH 02/11] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=8F=91?= =?UTF-8?q?=E8=B4=A7=E6=95=B0=E6=8D=AE=E7=AD=9B=E9=80=89=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E9=80=89=E6=8B=A9=E4=B8=8E=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Http/Controllers/Business/Pages.php | 126 ++++++++++++++++-- .../Repositories/ShippingOrderRepository.php | 89 +++++++++++-- .../courier-payables/shipping-data.blade.php | 51 +++++-- routes/admin.php | 4 + .../Feature/Business/ShippingDataPageTest.php | 115 ++++++++++++++++ 5 files changed, 352 insertions(+), 33 deletions(-) create mode 100644 tests/Feature/Business/ShippingDataPageTest.php diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index ccec6236..8b94b681 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -756,16 +756,7 @@ class Pages extends Controller protected function contentForShippingData(): array { $request = request(); - $date = static function (mixed $value): string { - $value = trim((string) $value); - return preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $value) === 1 ? $value : ''; - }; - $filters = [ - 'express_no' => mb_substr(trim((string) $request->query('express_no', '')), 0, 80), - 'sourceno' => mb_substr(trim((string) $request->query('sourceno', '')), 0, 80), - 'ship_from' => $date($request->query('ship_from', '')), - 'ship_to' => $date($request->query('ship_to', '')), - ]; + $filters = $this->shippingDataFilters($request); $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, [ @@ -796,6 +787,121 @@ class Pages extends Controller 'shippingFilters' => $filters, 'shippingSync' => $sync, 'shippingError' => $error, + 'shippingExportUrl' => route('business.courier-payables.shipping-data.export'), + ]; + } + + public function exportShippingData(Request $request): StreamedResponse + { + $filters = $this->shippingDataFilters($request); + $columns = $this->shippingDataColumns(); + + return response()->streamDownload(function () use ($filters, $columns): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new \RuntimeException('无法创建发货数据导出流。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, array_column($columns, 'label')); + + foreach ($this->shippingOrders->exportRows($filters) as $row) { + fputcsv($csv, array_map(function (array $column) use ($row): mixed { + $value = data_get($row, $column['field']); + + return match ($column['type']) { + 'identifier' => $this->csvIdentifier($value), + 'number' => $value === null || $value === '' ? '' : $value, + default => $this->csvText($value), + }; + }, $columns)); + } + + fclose($csv); + }, '发货数据_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** @return array */ + private function shippingDataFilters(Request $request): array + { + $text = static fn (string $key, int $length = 128): string => mb_substr( + trim((string) $request->query($key, '')), + 0, + $length, + ); + $date = static function (mixed $value): string { + $value = trim((string) $value); + + return preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $value) === 1 ? $value : ''; + }; + + return [ + 'express_no' => $text('express_no', 80), + 'sourceno' => $text('sourceno', 80), + 'barcode' => $text('barcode'), + 'supplier_name' => $text('supplier_name'), + 'shop_name' => $text('shop_name', 255), + 'warehouse_name' => $text('warehouse_name'), + 'express_company' => $text('express_company'), + 'ship_from' => $date($request->query('ship_from', '')), + 'ship_to' => $date($request->query('ship_to', '')), + ]; + } + + /** @return list */ + private function shippingDataColumns(): array + { + return [ + ['field' => 'express_no', 'label' => '快递单号', 'type' => 'identifier'], + ['field' => 'trade_no', 'label' => '交易单号', 'type' => 'identifier'], + ['field' => 'item_id', 'label' => '商品ID', 'type' => 'identifier'], + ['field' => 'barcode', 'label' => '条形码', 'type' => 'identifier'], + ['field' => 'product_name', 'label' => '商品名称', 'type' => 'text'], + ['field' => 'qty', 'label' => '数量', 'type' => 'number'], + ['field' => 'receiver_state', 'label' => '省', 'type' => 'text'], + ['field' => 'buyer_nick', 'label' => '买家昵称', 'type' => 'text'], + ['field' => 'receiver_name', 'label' => '收货姓名', 'type' => 'text'], + ['field' => 'shop_name', 'label' => '店铺名称', 'type' => 'text'], + ['field' => 'express_name1', 'label' => '快递名称1', 'type' => 'text'], + ['field' => 'warehouse_name', 'label' => '仓库', 'type' => 'text'], + ['field' => 'ship_time', 'label' => '发货时间', 'type' => 'text'], + ['field' => 'freight', 'label' => '运费', 'type' => 'number'], + ['field' => 'online_weight', 'label' => '线上重量', 'type' => 'number'], + ['field' => 'actual_weight', 'label' => '实称重量', 'type' => 'number'], + ['field' => 'length_cm', 'label' => '长(cm)', 'type' => 'number'], + ['field' => 'width_cm', 'label' => '宽(cm)', 'type' => 'number'], + ['field' => 'height_cm', 'label' => '高(cm)', 'type' => 'number'], + ['field' => 'volume_cm3', 'label' => '体积(cm³)', 'type' => 'number'], + ['field' => 'receiver_city', 'label' => '市', 'type' => 'text'], + ['field' => 'receiver_district', 'label' => '区', 'type' => 'text'], + ['field' => 'supplier_name', 'label' => '供应商', 'type' => 'text'], + ['field' => 'receiver_address', 'label' => '收货详细地址', 'type' => 'text'], + ['field' => 'receiver_mobile', 'label' => '手机号码', 'type' => 'identifier'], + ['field' => 'receiver_phone', 'label' => '座机号码', 'type' => 'identifier'], + ['field' => 'express_name2', 'label' => '快递名称2', 'type' => 'text'], + ['field' => 'platform', 'label' => '平台', 'type' => 'text'], + ['field' => 'buyer_memo', 'label' => '买家留言', 'type' => 'text'], + ['field' => 'seller_memo', 'label' => '卖家备注', 'type' => 'text'], + ['field' => 'package_no', 'label' => '配货单号', 'type' => 'identifier'], + ['field' => 'amount', 'label' => '金额', 'type' => 'number'], + ['field' => 'product_code', 'label' => '货号', 'type' => 'identifier'], + ['field' => 'download_time', 'label' => '下载时间', 'type' => 'text'], + ['field' => 'pay_time', 'label' => '付款时间', 'type' => 'text'], + ['field' => 'freight_rate', 'label' => '费率', 'type' => 'number'], + ['field' => 'freight_formula', 'label' => '公式', 'type' => 'text'], + ['field' => 'weight_kg', 'label' => '重量(kg)', 'type' => 'number'], + ['field' => 'settle_weight_kg', 'label' => '结算重量(kg)', 'type' => 'number'], + ['field' => 'settle_volume_cm3', 'label' => '结算体积(cm³)', 'type' => 'number'], + ['field' => 'recon_weight_kg', 'label' => '对账重量(kg)', 'type' => 'number'], + ['field' => 'recon_volume_cm3', 'label' => '对账体积(cm³)', 'type' => 'number'], + ['field' => 'finished_barcode', 'label' => '成品条码', 'type' => 'identifier'], + ['field' => 'finished_name', 'label' => '成品名称', 'type' => 'text'], + ['field' => 'finished_supplier', 'label' => '成品供应商', 'type' => 'text'], + ['field' => 'settle_freight', 'label' => '结算运费', 'type' => 'number'], + ['field' => 'front_no', 'label' => '换单前单号', 'type' => 'identifier'], ]; } diff --git a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php index d2cb5af6..e2605f67 100644 --- a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php +++ b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php @@ -3,6 +3,7 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\ConnectionInterface; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\DB; /** @@ -19,7 +20,7 @@ class ShippingOrderRepository } /** - * @param array $filters express_no / sourceno / ship_from / ship_to + * @param array $filters * @return array{data:array,total:int} */ public function paginate(array $filters, int $page, int $perPage): array @@ -27,19 +28,7 @@ class ShippingOrderRepository $page = max($page, 1); $perPage = min(max($perPage, 1), 100); - $q = $this->db->table('jst_oms_shipping'); - if (($filters['express_no'] ?? '') !== '') { - $q->where('express_no', '=', trim((string) $filters['express_no'])); - } - if (($filters['sourceno'] ?? '') !== '') { - $q->where('trade_no', '=', trim((string) $filters['sourceno'])); - } - if (($filters['ship_from'] ?? '') !== '') { - $q->where('ship_time', '>=', $filters['ship_from'] . ' 00:00:00'); - } - if (($filters['ship_to'] ?? '') !== '') { - $q->where('ship_time', '<', date('Y-m-d 00:00:00', strtotime($filters['ship_to'] . ' +1 day'))); - } + $q = $this->filteredQuery($filters); $total = (clone $q)->count(); $rows = (clone $q) @@ -53,6 +42,78 @@ class ShippingOrderRepository return ['data' => $rows, 'total' => $total]; } + /** + * @param array $filters + * @return \Generator> + */ + public function exportRows(array $filters, int $batchSize = 1000): \Generator + { + $batchSize = min(max($batchSize, 1), 5000); + $lastId = null; + + while (true) { + $query = $this->filteredQuery($filters); + if ($lastId !== null) { + $query->where('id', '>', $lastId); + } + + $rows = $query->orderBy('id')->limit($batchSize)->get()->all(); + if ($rows === []) { + return; + } + + foreach ($rows as $row) { + yield (array) $row; + } + + $lastId = (int) $rows[array_key_last($rows)]->id; + if (count($rows) < $batchSize) { + return; + } + } + } + + /** @param array $filters */ + private function filteredQuery(array $filters): Builder + { + $query = $this->db->table('jst_oms_shipping'); + + if (($filters['express_no'] ?? '') !== '') { + $query->where('express_no', '=', trim((string) $filters['express_no'])); + } + if (($filters['sourceno'] ?? '') !== '') { + $query->where('trade_no', '=', trim((string) $filters['sourceno'])); + } + + foreach (['barcode', 'supplier_name', 'shop_name', 'warehouse_name'] as $column) { + if (($filters[$column] ?? '') !== '') { + $query->whereRaw($column . " LIKE ? ESCAPE '!'", [$this->contains((string) $filters[$column])]); + } + } + + if (($filters['express_company'] ?? '') !== '') { + $value = $this->contains((string) $filters['express_company']); + $query->where(static function (Builder $courier) use ($value): void { + $courier->whereRaw("express_name1 LIKE ? ESCAPE '!'", [$value]) + ->orWhereRaw("express_name2 LIKE ? ESCAPE '!'", [$value]); + }); + } + + if (($filters['ship_from'] ?? '') !== '') { + $query->where('ship_time', '>=', $filters['ship_from'] . ' 00:00:00'); + } + if (($filters['ship_to'] ?? '') !== '') { + $query->where('ship_time', '<', date('Y-m-d 00:00:00', strtotime($filters['ship_to'] . ' +1 day'))); + } + + return $query; + } + + private function contains(string $value): string + { + return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($value)) . '%'; + } + /** 同步状态(供页面显示同步中/最近完成)。 */ public function syncStatus(): array { diff --git a/resources/views/business/pages/courier-payables/shipping-data.blade.php b/resources/views/business/pages/courier-payables/shipping-data.blade.php index e7ad2b9d..75344ff6 100644 --- a/resources/views/business/pages/courier-payables/shipping-data.blade.php +++ b/resources/views/business/pages/courier-payables/shipping-data.blade.php @@ -68,11 +68,18 @@
@@ -103,14 +108,14 @@ @endif
-
+ - - - - + + + +
@@ -163,5 +168,72 @@ else input.click(); }); }); + + // 筛选框自动补全:输入关键词弹下拉,点选或键盘选择填入。 + (() => { + const form = document.querySelector('.shipping-data-page form[aria-label="发货数据筛选"]'); + const url = form ? form.dataset.suggestUrl : ''; + if (!form || !url) return; + + form.querySelectorAll('input[data-suggest]').forEach((input) => { + const label = input.closest('label'); + if (!label) return; + label.classList.add('sd-ac-field'); + + const list = document.createElement('ul'); + list.className = 'sd-ac-list'; + list.hidden = true; + label.appendChild(list); + + let timer = null; + let active = -1; + let seq = 0; + + const hide = () => { list.hidden = true; list.innerHTML = ''; active = -1; }; + + const render = (items) => { + list.innerHTML = ''; + active = -1; + if (!items.length) { hide(); return; } + items.forEach((it) => { + const li = document.createElement('li'); + li.className = 'sd-ac-item'; + li.textContent = it; + li.title = it; + li.addEventListener('mousedown', (e) => { e.preventDefault(); input.value = it; hide(); }); + list.appendChild(li); + }); + list.hidden = false; + }; + + const load = () => { + const my = ++seq; + const q = input.value.trim(); + const u = url + '?field=' + encodeURIComponent(input.dataset.suggest) + '&q=' + encodeURIComponent(q); + fetch(u, { headers: { 'X-Requested-With': 'XMLHttpRequest' }, credentials: 'same-origin' }) + .then((r) => r.ok ? r.json() : { items: [] }) + .then((d) => { if (my === seq) render(Array.isArray(d.items) ? d.items : []); }) + .catch(() => { if (my === seq) hide(); }); + }; + + const schedule = (delay) => { clearTimeout(timer); timer = setTimeout(load, delay); }; + + input.addEventListener('input', () => schedule(200)); + input.addEventListener('focus', () => schedule(120)); + input.addEventListener('blur', () => setTimeout(hide, 150)); + input.addEventListener('keydown', (e) => { + if (list.hidden) return; + const items = list.querySelectorAll('.sd-ac-item'); + if (!items.length) return; + if (e.key === 'ArrowDown') { e.preventDefault(); active = Math.min(active + 1, items.length - 1); } + else if (e.key === 'ArrowUp') { e.preventDefault(); active = Math.max(active - 1, 0); } + else if (e.key === 'Enter') { if (active >= 0) { e.preventDefault(); input.value = items[active].textContent; hide(); } return; } + else if (e.key === 'Escape') { hide(); return; } + else return; + items.forEach((li, i) => li.classList.toggle('is-active', i === active)); + items[active].scrollIntoView({ block: 'nearest' }); + }); + }); + })(); })(); diff --git a/routes/admin.php b/routes/admin.php index 69e90c4f..99151e5d 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -147,6 +147,10 @@ Route::get('workspace/courier-payables/shipping-data/export', 'Business\Pages@ex ->middleware('business.page:courier-payables,shipping-data') ->name('business.courier-payables.shipping-data.export'); +Route::get('workspace/courier-payables/shipping-data/suggest', 'Business\\Pages@suggestShippingData') + ->middleware('business.page:courier-payables,shipping-data') + ->name('business.courier-payables.shipping-data.suggest'); + Route::get('workspace/courier-payables/third-party-warehouse-storage/export', 'Business\Pages@exportThirdPartyWarehouseStorage') ->middleware('business.page:courier-payables,third-party-warehouse-storage') ->name('business.courier-payables.third-party-warehouse-storage.export'); From 440f06079fb051da46b8e31e2ef9feea2c42c7a1 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Mon, 21 Sep 2026 03:54:48 +0000 Subject: [PATCH 06/11] =?UTF-8?q?feat(=E5=8F=91=E8=B4=A7=E6=95=B0=E6=8D=AE?= =?UTF-8?q?):=20=E4=BE=9B=E5=BA=94=E5=95=86/=E5=BA=97=E9=93=BA/=E4=BB=93?= =?UTF-8?q?=E5=BA=93/=E5=BF=AB=E9=80=92=E5=85=AC=E5=8F=B8=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=8B=BE=E9=80=89=E5=BC=8F=E5=A4=9A=E9=80=89=E4=B8=8B?= =?UTF-8?q?=E6=8B=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 下拉面板:回车检索 + 清除 + 表头全选 + 复选框列表,勾选多个即可 - 后端多选精确匹配:仓库/店铺/供应商 whereIn;快递公司匹配快递名称1/2 任一 - suggest 接口支持 limit(≤500),过滤空值与占位脏值"0" - 查询与导出均按所选多个值生效 Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf --- app/Http/Controllers/Business/Pages.php | 35 +++- .../Repositories/ShippingOrderRepository.php | 52 ++++- .../courier-payables/shipping-data.blade.php | 195 ++++++++++++------ 3 files changed, 198 insertions(+), 84 deletions(-) diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 7b1f00c0..f395bb15 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -832,9 +832,10 @@ class Pages extends Controller return response()->json(['items' => []]); } $keyword = mb_substr(trim((string) $request->query('q', '')), 0, 64); + $limit = min(max((int) $request->query('limit', 20), 1), 500); try { - $items = $this->shippingOrders->distinctValues($field, $keyword, 20); + $items = $this->shippingOrders->distinctValues($field, $keyword, $limit); } catch (Throwable $exception) { report($exception); $items = []; @@ -843,7 +844,7 @@ class Pages extends Controller return response()->json(['items' => array_values($items)]); } - /** @return array */ + /** @return array */ private function shippingDataFilters(Request $request): array { $text = static fn (string $key, int $length = 128): string => mb_substr( @@ -851,6 +852,28 @@ class Pages extends Controller 0, $length, ); + // 多选字段:接收 name[] 数组(也兼容单个字符串),去重、限长、限个数。 + $multi = static function (string $key, int $length = 191, int $max = 50) use ($request): array { + $raw = $request->query($key, []); + if (is_string($raw)) { + $raw = $raw === '' ? [] : [$raw]; + } + if (! is_array($raw)) { + $raw = []; + } + $out = []; + foreach ($raw as $value) { + $value = mb_substr(trim((string) $value), 0, $length); + if ($value !== '' && ! in_array($value, $out, true)) { + $out[] = $value; + } + if (count($out) >= $max) { + break; + } + } + + return $out; + }; $date = static function (mixed $value): string { $value = trim((string) $value); @@ -861,10 +884,10 @@ class Pages extends Controller 'express_no' => $text('express_no', 80), 'sourceno' => $text('sourceno', 80), 'barcode' => $text('barcode'), - 'supplier_name' => $text('supplier_name'), - 'shop_name' => $text('shop_name', 255), - 'warehouse_name' => $text('warehouse_name'), - 'express_company' => $text('express_company'), + 'supplier_name' => $multi('supplier_name'), + 'shop_name' => $multi('shop_name', 255), + 'warehouse_name' => $multi('warehouse_name'), + 'express_company' => $multi('express_company'), 'ship_from' => $date($request->query('ship_from', '')), 'ship_to' => $date($request->query('ship_to', '')), ]; diff --git a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php index 78495956..68a9f749 100644 --- a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php +++ b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php @@ -85,17 +85,25 @@ class ShippingOrderRepository $query->where('trade_no', '=', trim((string) $filters['sourceno'])); } - foreach (['barcode', 'supplier_name', 'shop_name', 'warehouse_name'] as $column) { - if (($filters[$column] ?? '') !== '') { - $query->whereRaw($column . " LIKE ? ESCAPE '!'", [$this->contains((string) $filters[$column])]); + // 条形码:单值关键词 + if (($filters['barcode'] ?? '') !== '') { + $query->whereRaw("barcode LIKE ? ESCAPE '!'", [$this->contains((string) $filters['barcode'])]); + } + + // 供应商/店铺/仓库:多选,精确匹配所选的任意一个 + foreach (['supplier_name', 'shop_name', 'warehouse_name'] as $column) { + $values = $this->multi($filters[$column] ?? null); + if ($values !== []) { + $query->whereIn($column, $values); } } - if (($filters['express_company'] ?? '') !== '') { - $value = $this->contains((string) $filters['express_company']); - $query->where(static function (Builder $courier) use ($value): void { - $courier->whereRaw("express_name1 LIKE ? ESCAPE '!'", [$value]) - ->orWhereRaw("express_name2 LIKE ? ESCAPE '!'", [$value]); + // 快递公司:多选,匹配快递名称1/2 任意一个 + $couriers = $this->multi($filters['express_company'] ?? null); + if ($couriers !== []) { + $query->where(function (Builder $group) use ($couriers): void { + $group->whereIn('express_name1', $couriers) + ->orWhereIn('express_name2', $couriers); }); } @@ -114,6 +122,29 @@ class ShippingOrderRepository return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($value)) . '%'; } + /** + * 归一多选筛选值为字符串数组(兼容单个字符串)。 + * @return array + */ + private function multi(mixed $value): array + { + if (is_string($value)) { + $value = $value === '' ? [] : [$value]; + } + if (! is_array($value)) { + return []; + } + $out = []; + foreach ($value as $item) { + $item = trim((string) $item); + if ($item !== '' && ! in_array($item, $out, true)) { + $out[] = $item; + } + } + + return array_slice($out, 0, 50); + } + /** * 取某字段去重候选值(供筛选框自动补全)。 * @return array @@ -129,7 +160,7 @@ class ShippingOrderRepository if (! isset($map[$field])) { return []; } - $limit = min(max($limit, 1), 50); + $limit = min(max($limit, 1), 500); $like = $this->contains($keyword); $values = []; foreach ($map[$field] as $col) { @@ -144,7 +175,8 @@ class ShippingOrderRepository ->pluck('v'); foreach ($rows as $v) { $v = trim((string) $v); - if ($v !== '') { + // 过滤空值与占位脏值(如自动发货仓 send_warehouse 为 "0") + if ($v !== '' && $v !== '0') { $values[$v] = true; } } diff --git a/resources/views/business/pages/courier-payables/shipping-data.blade.php b/resources/views/business/pages/courier-payables/shipping-data.blade.php index 66744cd0..762e692d 100644 --- a/resources/views/business/pages/courier-payables/shipping-data.blade.php +++ b/resources/views/business/pages/courier-payables/shipping-data.blade.php @@ -90,6 +90,24 @@ .shipping-data-page .sd-ac-item { padding: .35rem .5rem; font-size: .8rem; border-radius: .375rem; cursor: pointer; color: #29251f; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .shipping-data-page .sd-ac-item:hover, .shipping-data-page .sd-ac-item.is-active { background: #f3ece0; } .shipping-data-page .sd-ac-empty { padding: .35rem .5rem; font-size: .75rem; color: #9a9182; } + .shipping-data-page .sd-dd { position: relative; } + .shipping-data-page .sd-dd-toggle { display: flex; align-items: center; justify-content: space-between; gap: .25rem; width: 100%; height: 2.125rem; border: 1px solid #d8d2c7; border-radius: .5rem; padding: 0 .35rem 0 .625rem; background: #fff; color: #171717; font-size: .8125rem; cursor: pointer; text-align: left; } + .shipping-data-page .sd-dd.is-open .sd-dd-toggle, .shipping-data-page .sd-dd-toggle:focus { outline: none; border-color: #b18a4a; box-shadow: 0 0 0 2px rgba(177,138,74,.15); } + .shipping-data-page .sd-dd-summary { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .shipping-data-page .sd-dd-summary.is-empty { color: #9a9182; } + .shipping-data-page .sd-dd-caret { font-size: 1.1rem; color: #856632; flex: none; } + .shipping-data-page .sd-dd-panel { position: absolute; top: 100%; left: 0; z-index: 50; margin-top: 2px; min-width: 100%; width: max-content; max-width: 20rem; background: #fff; border: 1px solid #d8d2c7; border-radius: .5rem; box-shadow: 0 8px 24px rgba(0,0,0,.12); padding: 6px; } + .shipping-data-page .sd-dd-search { display: flex; gap: 4px; margin-bottom: 4px; } + .shipping-data-page .sd-dd-q { flex: 1; height: 1.9rem; border: 1px solid #d8d2c7; border-radius: .375rem; padding: 0 .5rem; font-size: .8rem; outline: none; } + .shipping-data-page .sd-dd-q:focus { border-color: #b18a4a; } + .shipping-data-page .sd-dd-clear { border: 1px solid #d8d2c7; border-radius: .375rem; background: #f7f3ec; color: #4b3a24; font-size: .75rem; padding: 0 .6rem; cursor: pointer; white-space: nowrap; } + .shipping-data-page .sd-dd-clear:hover { background: #efe7d8; } + .shipping-data-page .sd-dd-head { display: flex; align-items: center; gap: .4rem; padding: .3rem .4rem; border-bottom: 1px solid #eee8de; font-size: .78rem; font-weight: 600; color: #6f675c; cursor: pointer; } + .shipping-data-page .sd-dd-list { list-style: none; margin: 0; padding: 2px 0 0; max-height: 14rem; overflow-y: auto; } + .shipping-data-page .sd-dd-opt { display: flex; align-items: center; gap: .4rem; padding: .3rem .4rem; font-size: .8rem; color: #29251f; border-radius: .375rem; cursor: pointer; white-space: nowrap; } + .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; }
@@ -112,15 +130,41 @@ - - - - + @php + $msFields = [ + ['supplier_name', '供应商'], + ['shop_name', '店铺名称'], + ['warehouse_name', '仓库'], + ['express_company', '快递公司'], + ]; + $msVal = static function ($key) use ($filters) { + $v = $filters[$key] ?? []; + if (is_string($v)) { $v = $v === '' ? [] : [$v]; } + return array_values(array_filter(array_map('strval', (array) $v), static fn ($x) => $x !== '')); + }; + @endphp + @foreach ($msFields as [$msKey, $msLabel]) +
{{ $msLabel }} +
+ + + + @foreach ($msVal($msKey) as $chip) + + @endforeach + +
+
+ @endforeach @@ -156,11 +200,11 @@ From b9bbba31b7b824c7dc7034377781f716e680a357 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Mon, 21 Sep 2026 05:15:59 +0000 Subject: [PATCH 07/11] =?UTF-8?q?docs(=E5=8F=91=E8=B4=A7=E6=95=B0=E6=8D=AE?= =?UTF-8?q?):=20=E5=B7=A5=E4=BD=9C=E5=B9=B3=E5=8F=B0=E2=86=92caiwu=20100%?= =?UTF-8?q?=E8=BF=98=E5=8E=9F=E9=80=BB=E8=BE=91=E5=AF=B9=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 据 JSCrm OmsDataDayService 源码梳理:数据流、明细/合并(Expressno+Packageno)归并规则、 体积/件数(1/N)规则、派生字段(ExNameDto/SpName/ExpreBatch/换单前单号)、筛选口径、 暂缓的计泡+运费,及分阶段落地计划。 Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf --- docs/发货数据_工作平台还原_逻辑对照.md | 102 +++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 docs/发货数据_工作平台还原_逻辑对照.md diff --git a/docs/发货数据_工作平台还原_逻辑对照.md b/docs/发货数据_工作平台还原_逻辑对照.md new file mode 100644 index 00000000..52aedc18 --- /dev/null +++ b/docs/发货数据_工作平台还原_逻辑对照.md @@ -0,0 +1,102 @@ +# 发货数据:工作平台 → 财务系统(caiwu) 100% 还原逻辑对照 + +> 目的:让 caiwu「发货数据」界面与工作平台一致(含"导出/导出明细"两种口径),并把逻辑梳理清楚,脱离将停用的工作平台/ jiansun 库,改由经营分析副本库(operations_replica)直取。 + +## 一、总体数据流 + +**工作平台(现状,即将停用)** +1. 定时调聚水潭 `erp.dlv.query`(参数 `tradetype=1`=正常出库、`sendsgn=1`=已发货),按发货时间取发货单;`erp.dlv.getDlv` 取每单的商品明细。 +2. **逐件**写入 `fys_omsDataDayDetail`(明细表,一件商品一行)。 +3. 按 `Expressno, Packageno` **归并**成 `fys_omsDataDay`(合并表,一个快递单号/包裹一行)。 +4. 页面与导出:`导出明细`=查明细表;`导出`=查合并表;两者都再左连 店铺/仓库/快递/成品/运费/换单 维表。 + +**caiwu(目标)** +1. 副本库 `rpt.jst_order_express_details`(发货单 dlv 镜像)× `rpt.jst_OrderItem`(逐件)+ `rpt.jst_sku`(尺寸/重量/供应商)+ `rpt.fys_jstFreightCostDetail`(运费)。 +2. **逐件**写入 `jst_oms_shipping`(明细,一件一行;唯一键=包裹id+商品id)。 +3. 查询时按包裹**归并**出"合并"视图(不再单独建表,用 GROUP BY 实时归并)。 +4. 页面加「合并/明细」切换+两个导出,默认合并。 + +## 二、明细口径(对应"导出明细")——每件商品一行 + +一个发货单(包裹) × 其每件商品 = 一行。字段来源: + +| 列 | 工作平台字段 | caiwu 来源 | +|---|---|---| +| 快递单号 Expressno | dlv.postcode | express_details.logistic_id(空时回落 l_id/运费expressNo)| +| 交易单号 Sourceno | dlv.sourceno | express_details.so_id | +| 配货单号 Packageno | dlv.wmspackno | 待补(副本库对应字段确认中)| +| 商品ID shopproid | item.shopproid | OrderItem.shop_i_id | +| 条形码 Barcode | item.skuoid | OrderItem.sku_id | +| 货号 Productcode | item.procode | OrderItem.i_id | +| 商品名称 SkuName | item.skuname | OrderItem.name | +| 数量 Num | item.skucount | OrderItem.qty | +| 供应商 SupplierName | item.scmname / scsku | sku.supplier_name / dis_co_name | +| 长/宽/高 | 商品资料 | sku.l / w / h | +| 体积 Svolume | 见"体积规则" | 见"体积规则" | +| 实称重量 Weight | dlv 回传重量 | express_details.weight | +| 发货时间 Shiptime | dlv.sended | express_details.send_time(空回落 jst_Orders.send_date)| +| 付款时间 Paydate | dlv.paytime | express_details.pay_time | +| 省/市/区/地址/收货人/电话 | dlv.linker.* | express_details.receiver_* / 地址拆分 | +| 店铺/平台/仓库 | dlv.shopcode/pltmcode/whcode | express_details.shop_name/platform_name/warehouse_name | +| 件数 Count | '1/N' | 同 Packageno 商品件数 → '1/N' | + +**明细专有规则** +- **Count = '1/N'**:同一 Packageno 有 N 件商品,则每行显示 `1/N`。 +- **体积 Svolume**: + - 普通商品(货号不在配件表 ProCodeOfShipData、快递在 ExpressOfShipData、条码不含 `P-`):`Svolume = 数量 × 长 × 宽 × 高`。 + - 配件"一单多货"(同快递单号多件配件):只保留体积最大的一件,其余置 0(避免重复计泡)。 +- 去重:同 OmsId 重复的明细只留最小 Id 的一条。 + +## 三、合并口径(对应"导出")——按 `Expressno + Packageno` 归并 + +工作平台 `group by Expressno, Packageno`,各列归并规则(**照抄其 groupStr**): + +- **去重逗号拼接**:`条形码 Barcode`、`商品ID shopproid`(同包裹多件时拼成 `A,B,C`)。 +- **求和 sum**:`数量 Num`、`实称重量 Weight`、`体积 Svolume`、`对账重量 ReturnMinWeight`。 +- **取最大 max**:`长 Slength`、`宽 Swidth`、`高 Sheight`、`RuleWeight`、`RuleVolume`。 +- **取第一 min**:其余全部(交易单号、发货时间、省市区、地址、收货人、电话、商品名称 SkuName、店铺、买家昵称、买家/卖家留言、仓库、供应商、货号、平台、付款时间、成品编码/名称、备注 等)。 +- 分组键:`Expressno, Packageno`。 + +> 直白说:一个快递单号发了多件不同货 → 合并视图里"条形码/商品ID"逗号拼接、数量/重量/体积加总、长宽高取最大、其它取任一件的值;明细视图里则拆成多行、每行 `1/N`。 + +## 四、派生显示字段(两口径查询时左连/计算) + +- **快递名称 ExNameDto**:`fys_express.ExpressName` 去掉"一区""其他"后,取"-"前一段(无"-"则原值)。 +- **店铺名 SpName**:快递为"发票邮政"时=买家留言(去逗号),否则=店铺名。 +- **发货批次 ExpreBatch**:仅拼多多/京东——发货时间 0–12 点 → `日期_第一批`,12–24 点 → `日期_第二批`。 +- **换单前单号 FrontNum**:`fys_omsDataDay_ChangeOrder`(按 Sourceno+Packageno, chgsgn=2)。 +- 地区 Area、ABpackage、CommodityExpress 等由维表补充。 + +## 五、筛选条件(合并/明细一致)——已核对工作平台 searchStr + +| 条件 | 匹配方式 | caiwu 现状 | +|---|---|---| +| 发货时间起/止 | Shiptime 区间 | ✅ 已实现 | +| 交易单号 Sourceno | 精确 = | ✅ | +| 快递单号 Expressno | 精确 = | ✅ | +| 条形码 BarCode | 精确 = | ✅(现为模糊,可改精确)| +| 货号 ProCode | 精确 = | 待补 | +| 配货单号 Packageno | 精确 = | 待补 | +| 买家昵称 Buyernick | 精确 = | 待补 | +| 收货人 Receivername | 精确 = | 待补 | +| 电话 Receiverphone | 精确 = | 待补 | +| 快递公司 Express | **IN 多选** | ✅ 已做多选 | +| 店铺 Shop / 仓库 Warehouse / 供应商 Supplier | **IN 多选** | ✅ 已做多选 | +| 异常/加急/换单/快递标记 errsgn/jjsgn/chgsgn/kdsgn | = | 待补(可选)| + +> 工作平台快递/店铺/仓库/供应商本就是多选 IN —— 与刚做的勾选式多选一致。 + +## 六、暂缓项(依赖"计泡 + 报价规则",报价系统建好后再做) + +`NewWeight`(计泡后重量)、`NewVolue`(计泡体积)、`ReturnMinVolue`、`FreightNew`(运费)、`FreightRate`(费率)、`FreightFormula`(公式)、`JSFreight`(结算运费)。 +这些依赖各快递计泡规则(fys_DisExpressWeight 等)与报价,先留空,后续接。 + +## 七、落地计划(分阶段,均可脱离工作平台) + +1. **明细存储**:同步改成"发货单 × 每件商品"一行;补 Count='1/N'、体积规则(数量×长×宽×高 / 配件只留最大件)。 +2. **双口径**:仓储/页面支持 合并(默认) / 明细 切换;合并按 §三 规则 GROUP BY 实时归并;两个导出分别对应。 +3. **补齐筛选与派生**:货号/配货单号/买家昵称/收货人/电话 单值筛选;ExNameDto/SpName/ExpreBatch/换单前单号 派生列。 +4. **(后续)计泡 + 运费**:报价系统就绪后接 §六。 + +--- +_本文据 JSCrm 源码 `OmsDataDayService.cs`(getPageList / searchStr / searchDetailStr / DownLoadShipmentData 归并段)整理,作为 caiwu 发货数据还原的对照基准。_ From 2a1b663da23b2ec4b23cf560a2dd751d049f43f3 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Mon, 21 Sep 2026 07:49:26 +0000 Subject: [PATCH 08/11] =?UTF-8?q?feat(=E5=8F=91=E8=B4=A7=E6=95=B0=E6=8D=AE?= =?UTF-8?q?):=20=E5=90=88=E5=B9=B6/=E6=98=8E=E7=BB=86=E5=8F=8C=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=EF=BC=8C=E8=BF=98=E5=8E=9F=E5=B7=A5=E4=BD=9C=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=20=E5=AF=BC=E5=87=BA/=E5=AF=BC=E5=87=BA=E6=98=8E?= =?UTF-8?q?=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 同步改为"一个发货单×每件商品一行"(明细底座);新增 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 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf --- app/Console/Commands/JstCount.php | 28 +- app/Http/Controllers/Business/Pages.php | 109 +++- .../Console/SyncJushuitanShipping.php | 2 + ...0001_add_pkg_count_to_jst_oms_shipping.php | 36 ++ .../Repositories/ShippingOrderRepository.php | 98 +++- .../Jushuitan/ShippingReplicaSynchronizer.php | 491 +++++++++++------- .../courier-payables/shipping-data.blade.php | 16 +- 7 files changed, 556 insertions(+), 224 deletions(-) create mode 100644 modules/EcommerceFinance/Database/Migrations/2026_09_21_000001_add_pkg_count_to_jst_oms_shipping.php diff --git a/app/Console/Commands/JstCount.php b/app/Console/Commands/JstCount.php index 5deabeba..e36b4007 100644 --- a/app/Console/Commands/JstCount.php +++ b/app/Console/Commands/JstCount.php @@ -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; } } diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index f395bb15..d1b62321 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -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'], diff --git a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php index a6b4b95d..dfac2a96 100644 --- a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php +++ b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php @@ -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; diff --git a/modules/EcommerceFinance/Database/Migrations/2026_09_21_000001_add_pkg_count_to_jst_oms_shipping.php b/modules/EcommerceFinance/Database/Migrations/2026_09_21_000001_add_pkg_count_to_jst_oms_shipping.php new file mode 100644 index 00000000..78e71427 --- /dev/null +++ b/modules/EcommerceFinance/Database/Migrations/2026_09_21_000001_add_pkg_count_to_jst_oms_shipping.php @@ -0,0 +1,36 @@ +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'); + }); + } + } +}; diff --git a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php index 68a9f749..e6bfc714 100644 --- a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php +++ b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php @@ -23,50 +23,114 @@ class ShippingOrderRepository * @param array $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 $filters * @return \Generator> */ - 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; } diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php index 4085af3c..72fe2cc8 100644 --- a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php @@ -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 待批量写入缓冲 */ + /** @var 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,1: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 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 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 so_id|expressNo => 运费 (并含 so_id| 兜底键) */ + /** @return 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; } diff --git a/resources/views/business/pages/courier-payables/shipping-data.blade.php b/resources/views/business/pages/courier-payables/shipping-data.blade.php index 762e692d..3f1f6f6e 100644 --- a/resources/views/business/pages/courier-payables/shipping-data.blade.php +++ b/resources/views/business/pages/courier-payables/shipping-data.blade.php @@ -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; }
@@ -126,7 +129,16 @@ @endif
+@php $mode = $shippingMode ?? 'merged'; $modeQuery = array_merge(request()->query(), []); @endphp +
+ @@ -164,7 +176,9 @@
- 导出 + @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 + 导出 + 导出明细 重置
From 464f731d9e5426453a8a24b120aee1d44e360cb7 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Mon, 21 Sep 2026 07:55:03 +0000 Subject: [PATCH 09/11] =?UTF-8?q?fix(=E5=8F=91=E8=B4=A7=E6=95=B0=E6=8D=AE)?= =?UTF-8?q?:=20=E5=AF=BC=E5=87=BA=E5=8E=BB=E6=8E=89=E6=A0=87=E8=AF=86?= =?UTF-8?q?=E5=88=97=E7=9A=84=20'=20=E5=89=8D=E7=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 快递单号/交易单号/商品ID/条形码导出为原样文本,不再加 ' 前缀 (仅改发货数据导出;保留以 =+-@ 开头值的防注入引号;不影响其它导出) Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf --- app/Http/Controllers/Business/Pages.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index d1b62321..e06d3976 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -899,8 +899,8 @@ class Pages extends Controller fputcsv($csv, array_map(function (array $column) use ($row): mixed { $value = data_get($row, $column['field']); + // 发货数据导出:标识列(快递单号/交易单号/商品ID/条形码)按原样文本导出,不加 ' 前缀 return match ($column['type']) { - 'identifier' => $this->csvIdentifier($value), 'number' => $value === null || $value === '' ? '' : $value, default => $this->csvText($value), }; From a65604ddb9c311fbe0344efdefbe27d0e8b699d9 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Tue, 22 Sep 2026 01:08:40 +0000 Subject: [PATCH 10/11] =?UTF-8?q?fix(=E5=8F=91=E8=B4=A7=E6=95=B0=E6=8D=AE)?= =?UTF-8?q?:=20=E6=8E=92=E9=99=A4"=E7=BA=BF=E4=B8=8A=E5=8F=91=E8=B4=A7"(?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E4=BB=A3=E5=8F=91/=E4=BA=91=E4=BB=93)?= =?UTF-8?q?=E5=8D=95=EF=BC=8C=E5=AF=B9=E9=BD=90=E5=B7=A5=E4=BD=9C=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 工作平台调聚水潭 erp.dlv.query tradetype=1(卖家自出库单),不含平台代发/云仓的 "线上发货"单;副本库发货明细表却收录了它们,导致 caiwu 多出约5000包裹。 现按 order_labels/labels 含"线上发货"排除(主口径与自动发货仓并入均生效)。 实测:包裹 199602→194573(-5029),与差异样本 63/64 带该标签吻合。 Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf --- .../Jushuitan/ShippingReplicaSynchronizer.php | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php index 72fe2cc8..05aafdf0 100644 --- a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php @@ -81,7 +81,7 @@ class ShippingReplicaSynchronizer $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'; + . 'e.weight, e.f_weight, e.buyer_message, e.order_labels, jo.l_id AS jo_lid, jo.send_date AS jo_send'; $total = 0; $lastId = null; @@ -129,6 +129,9 @@ class ShippingReplicaSynchronizer if ($pkgId === 0) { continue; } + if ($this->excludedByLabel($r['order_labels'] ?? null)) { + continue; // 线上发货(平台代发/云仓):工作平台不拉,对齐排除 + } $so = (string) ($r['so_id'] ?? ''); $oid = (string) ($r['inner_order_id'] ?? ''); $items = $this->itemsFor($byOid, $bySo, $oid, $so); @@ -159,7 +162,7 @@ class ShippingReplicaSynchronizer { $batch = 400; $maxBatches = 600; - $cols = 'o.Id AS rid, o.o_id, o.so_id, o.l_id, o.logistics_company, o.order_from, ' + $cols = 'o.Id AS rid, o.o_id, o.so_id, o.l_id, o.logistics_company, o.order_from, o.labels, ' . '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'; @@ -204,6 +207,9 @@ class ShippingReplicaSynchronizer if ($oid === '') { continue; } + if ($this->excludedByLabel($r['labels'] ?? null)) { + continue; // 线上发货:对齐排除 + } $so = (string) ($r['so_id'] ?? ''); $items = $this->itemsFor($byOid, $bySo, $oid, $so); $tracking = $this->tracking((string) ($r['l_id'] ?? ''), '', $freight, $so); @@ -477,6 +483,16 @@ class ShippingReplicaSynchronizer return str_contains($name, '补收差价') || str_contains($name, '差价专用'); } + /** 线上发货(平台代发/云仓)标签:工作平台不拉取,caiwu 对齐排除。 */ + private function excludedByLabel(?string $labels): bool + { + if ($labels === null || $labels === '') { + return false; + } + + return str_contains($labels, '线上发货'); + } + /** @return array sku_id => 尺寸/重量/供应商 */ private function loadSkus(array $skuIds): array { From 067102ab155076bdd8417dab5b8b6fff2a212574 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Wed, 23 Sep 2026 17:02:53 +0800 Subject: [PATCH 11/11] =?UTF-8?q?feat(=E5=8F=91=E8=B4=A7=E6=95=B0=E6=8D=AE?= =?UTF-8?q?):=20=E5=95=86=E5=93=81=E6=9D=A5=E6=BA=90=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E5=87=BA=E5=BA=93=E5=AE=9E=E5=8F=91(=E5=8F=91=E8=B4=A7?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E8=A7=86=E5=9B=BE)=EF=BC=8C=E5=AF=B9?= =?UTF-8?q?=E9=BD=90=E5=B7=A5=E4=BD=9C=E5=B9=B3=E5=8F=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 商品来源从「下单商品 jst_OrderItem」改为「出库实发商品」:按出库单 io_id 关联发货数据视图 Jst_SendData_View_extension 取实发条码/数量,jst_OrderItem/dws 仅作兜底。消除组合/多规格包裹的多吐行与数量错误。 - 长宽高/体积/供应商/重量优先取自发货视图(体积=长×宽×高,整箱算一次)。 - 导出明细:多条码(逗号拼接)按条码拆条,数量/体积按条码数均摊,合并求和后与整行一致。 - 去除以 @ 开头、去@后已存在的重复单号(换单/重拉产生)。 - 发货单查询改为按主键翻页 + PHP 窗口过滤,避免 send_time 无索引全表扫。 - 逐天预载 dws,进度回调输出扫描/命中进度。 新增命令:jst:dump(导出对比CSV)、jst:row(抽查单号)、jst:dedup-at(去@重复)。 9.1-9.16 全量对比:共有 19.3 万包裹,数量/名称/条码/体积/供应商等字段一致率 99.9%; 导出明细件数结构 99.87% 一致。 Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhRy6EiUwf --- app/Console/Commands/DedupAt.php | 27 ++ app/Console/Commands/JstDump.php | 45 ++ app/Console/Commands/JstRow.php | 20 + .../Console/SyncJushuitanShipping.php | 8 +- .../Jushuitan/ShippingReplicaSynchronizer.php | 418 ++++++++++++++++-- 5 files changed, 482 insertions(+), 36 deletions(-) create mode 100644 app/Console/Commands/DedupAt.php create mode 100644 app/Console/Commands/JstDump.php create mode 100644 app/Console/Commands/JstRow.php diff --git a/app/Console/Commands/DedupAt.php b/app/Console/Commands/DedupAt.php new file mode 100644 index 00000000..6d2d6a11 --- /dev/null +++ b/app/Console/Commands/DedupAt.php @@ -0,0 +1,27 @@ +dedupAtPrefix(); + $this->info('去除@重复单号:' . $removed . ' 条'); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/JstDump.php b/app/Console/Commands/JstDump.php new file mode 100644 index 00000000..72b36b91 --- /dev/null +++ b/app/Console/Commands/JstDump.php @@ -0,0 +1,45 @@ +option('mode') === 'detail' ? 'detail' : 'merged'; + $filters = [ + 'ship_from' => (string) $this->option('from'), + 'ship_to' => (string) $this->option('to'), + ]; + $cols = [ + ['express_no', '快递单号'], ['trade_no', '交易单号'], ['item_id', '商品ID'], ['barcode', '条形码'], + ['product_name', '商品名称'], ['qty', '数量'], ['pkg_count', '件数'], ['warehouse_name', '仓库'], + ['supplier_name', '供应商'], ['platform', '平台'], ['shop_name', '店铺名称'], + ['volume_cm3', '体积'], ['length_cm', '长'], ['width_cm', '宽'], ['height_cm', '高'], + ['actual_weight', '实称重量'], ['online_weight', '线上重量'], ['freight', '运费'], + ['ship_time', '发货时间'], ['pay_time', '付款时间'], ['product_code', '货号'], + ['receiver_state', '省'], ['receiver_city', '市'], ['receiver_district', '区'], + ['package_no', '配货单号'], ['amount', '金额'], + ]; + $fh = fopen('php://output', 'w'); + fwrite($fh, chr(0xEF).chr(0xBB).chr(0xBF)); + fputcsv($fh, array_map(fn ($c) => $c[1], $cols)); + $n = 0; + foreach ($repo->exportRows($filters, 2000, $mode) as $row) { + fputcsv($fh, array_map(fn ($c) => (string) ($row[$c[0]] ?? ''), $cols)); + $n++; + } + fflush($fh); + fwrite(STDERR, 'wrote '.$n.' rows ('.$mode.')'.PHP_EOL); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/JstRow.php b/app/Console/Commands/JstRow.php new file mode 100644 index 00000000..7466e5e6 --- /dev/null +++ b/app/Console/Commands/JstRow.php @@ -0,0 +1,20 @@ +table('jst_oms_shipping')->where('trade_no', (string) $this->option('trade')) + ->get(['express_no', 'barcode', 'product_name', 'qty', 'pkg_count', 'supplier_name', 'length_cm', 'volume_cm3']); + $this->line('行数='.count($rows)); + foreach ($rows as $r) { + $this->line(' '.json_encode($r, JSON_UNESCAPED_UNICODE)); + } + return self::SUCCESS; + } +} diff --git a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php index dfac2a96..021124d4 100644 --- a/modules/EcommerceFinance/Console/SyncJushuitanShipping.php +++ b/modules/EcommerceFinance/Console/SyncJushuitanShipping.php @@ -39,8 +39,14 @@ class SyncJushuitanShipping extends Command $range = ($from && $to) ? $from->toDateString() . ' ~ ' . $to->toDateString() : '最近 ' . $limit . ' 条'; $this->info('开始从副本库同步发货明细(' . $range . ')...'); + $progress = function (string $msg): void { + $this->info(' ' . $msg); + if (function_exists('fflush')) { + @fflush(STDOUT); + } + }; try { - $result = ShippingReplicaSynchronizer::make()->sync($from, $to, $limit); + $result = ShippingReplicaSynchronizer::make()->sync($from, $to, $limit, $progress); } catch (\Throwable $e) { $this->error('同步失败:' . $e->getMessage()); return self::FAILURE; diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php index 05aafdf0..e1030f1a 100644 --- a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php @@ -26,12 +26,18 @@ class ShippingReplicaSynchronizer private const AUTOSHIP_OFFSET = 1000000000; private const FLUSH = 300; + private const VIEW = 'rpt.Jst_SendData_View_extension'; + private const OUTBOUND = 'rpt.jst_salesOutboundInfo'; + private readonly \Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery $up; private readonly \Illuminate\Database\ConnectionInterface $db; /** @var array */ private array $buffer = []; + /** @var array 窗口内 dws 销售全量商品缓存 sourceno=>items */ + private array $dwsCache = []; + public function __construct(UpstreamReadOnlyQueryFactory $factory) { $this->up = $factory->forSource(self::SOURCE); @@ -44,7 +50,7 @@ class ShippingReplicaSynchronizer return new self(app(UpstreamReadOnlyQueryFactory::class)); } - public function sync(?Carbon $from = null, ?Carbon $to = null, int $limit = 2000): array + public function sync(?Carbon $from = null, ?Carbon $to = null, int $limit = 2000, ?callable $progress = null): array { $this->markRunning(); try { @@ -60,10 +66,23 @@ class ShippingReplicaSynchronizer ->where('ship_time', '>=', $fromS)->where('ship_time', '<', $toS)->delete(); } - $total = $this->syncExpress($windowed, $fromS, $toS, $limit, $now); + $total = 0; $auto = 0; if ($windowed) { - $auto = $this->syncAutoShip($fromS, $toS, $now); + $this->preloadDws($from, $to); + if ($progress) { + $progress('dws 预载完成:' . count($this->dwsCache) . ' 个 sourceno'); + } + $total = $this->syncExpress(true, $fromS, $toS, $limit, $now, $progress); + $auto = $this->syncAutoShip($fromS, $toS, $now, $progress); + $this->dwsCache = []; + gc_collect_cycles(); + $removed = $this->dedupAtPrefix(); + if ($progress && $removed > 0) { + $progress('去除@重复单号:' . $removed . ' 条'); + } + } else { + $total = $this->syncExpress(false, $fromS, $toS, $limit, $now, $progress); } $this->markSucceeded(); @@ -74,26 +93,56 @@ class ShippingReplicaSynchronizer } } - /** 主口径:发货单(dlv 镜像) × 每件商品。 */ - private function syncExpress(bool $windowed, ?string $fromS, ?string $toS, int $limit, $now): int + /** 去除以 @ 开头、去@后已存在的重复单号(换单/重拉产生;工作平台只保留干净版)。 */ + public function dedupAtPrefix(): int { - $batch = 400; - $maxBatches = 3000; + $all = $this->db->table('jst_oms_shipping') + ->whereNotNull('express_no')->where('express_no', '!=', '') + ->distinct()->pluck('express_no')->all(); + $set = []; + foreach ($all as $e) { + $set[(string) $e] = true; + } + $toDel = []; + foreach (array_keys($set) as $e) { + $e = (string) $e; + if ($e !== '' && $e[0] === '@' && isset($set[substr($e, 1)])) { + $toDel[] = $e; + } + } + $removed = 0; + foreach (array_chunk($toDel, 500) as $chunk) { + if ($chunk === []) { + continue; + } + $removed += (int) $this->db->table('jst_oms_shipping')->whereIn('express_no', $chunk)->delete(); + } + + return $removed; + } + + /** 主口径:发货单(dlv 镜像) × 每件商品。 */ + private function syncExpress(bool $windowed, ?string $fromS, ?string $toS, int $limit, $now, ?callable $progress = null): int + { + $batch = 1500; + $maxBatches = 5000; $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, e.order_labels, jo.l_id AS jo_lid, jo.send_date AS jo_send'; + // 窗口模式:只按主键 e.id 翻页(有索引,毫秒级),send_time 窗口过滤放到 PHP, + // 避免每页都对无索引的 send_time 做全表扫描(那是"卡死"的真凶)。 + $fromTs = $fromS !== null ? strtotime($fromS) : null; + $toTs = $toS !== null ? strtotime($toS) : null; + $total = 0; + $scanned = 0; $lastId = null; + $entered = false; for ($b = 0; $b < $maxBatches; $b++) { - if ($windowed) { - $where = '((e.send_time >= ? AND e.send_time < ?) OR (e.send_time IS NULL AND jo.send_date >= ? AND jo.send_date < ?))'; - $bind = [$fromS, $toS, $fromS, $toS]; - } else { - $where = 'e.send_time IS NOT NULL'; - $bind = []; - } + $where = $windowed ? '1 = 1' : 'e.send_time IS NOT NULL'; + $bind = []; if ($lastId !== null) { $where .= ' AND e.id < ?'; $bind[] = $lastId; @@ -106,9 +155,37 @@ class ShippingReplicaSynchronizer break; } $cnt = count($rows); + $scanned += $cnt; + foreach ($rows as $r) { + $lastId = $r['id']; + } + + $pageNewest = null; + $pageHit = false; + if ($windowed) { + $kept = []; + foreach ($rows as $r) { + $st = $r['send_time'] ?? null; + $ts = ($st !== null && $st !== '') ? strtotime((string) $st) : null; + if ($ts === null) { + $jd = $r['jo_send'] ?? null; + $ts = ($jd !== null && $jd !== '') ? strtotime((string) $jd) : null; + } + if ($ts !== null && ($pageNewest === null || $ts > $pageNewest)) { + $pageNewest = $ts; + } + if ($ts !== null && $ts >= $fromTs && $ts < $toTs) { + $kept[] = $r; + $pageHit = true; + $entered = true; + } + } + $rows = $kept; + } $oids = []; $soIds = []; + $logs = []; foreach ($rows as $r) { $so = (string) ($r['so_id'] ?? ''); if ($so !== '') { @@ -118,10 +195,29 @@ class ShippingReplicaSynchronizer if ($oid !== '') { $oids[$oid] = true; } - $lastId = $r['id']; + $lg = (string) ($r['logistic_id'] ?? ''); + if ($lg !== '') { + $logs[$lg] = true; + } } [$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds)); - $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo)); + $dws = []; + foreach (array_keys($soIds) as $mso) { + if (empty($bySo[$mso]) && ! empty($this->dwsCache[$mso])) { + $dws[$mso] = $this->dwsCache[$mso]; + } + } + // 主口径:发货数据视图按出库单(io_id)取实发商品 + $ioMap = $this->loadIoMap(array_keys($logs), array_keys($oids)); + $ioIds = []; + foreach ($rows as $r) { + $io = $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), (string) ($r['inner_order_id'] ?? '')); + if ($io !== '') { + $ioIds[$io] = true; + } + } + $viewItems = $this->loadViewItems(array_keys($ioIds)); + $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo, $dws, $viewItems)); $freight = $this->loadFreight(array_keys($soIds)); foreach ($rows as $r) { @@ -134,17 +230,27 @@ class ShippingReplicaSynchronizer } $so = (string) ($r['so_id'] ?? ''); $oid = (string) ($r['inner_order_id'] ?? ''); - $items = $this->itemsFor($byOid, $bySo, $oid, $so); + $io = $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), $oid); + $items = ($io !== '' && ! empty($viewItems[$io])) + ? $viewItems[$io] + : $this->itemsFor($byOid, $bySo, $dws, $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); $pkg = $this->pkgFromExpress($r, $tracking, $shipTime); $total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now); } - unset($rows, $byOid, $bySo, $skus, $freight); - if ($b % 30 === 0) { + unset($rows, $byOid, $bySo, $dws, $skus, $freight); + if ($b % 20 === 0) { gc_collect_cycles(); } + if ($progress && $b % 20 === 0) { + $progress(sprintf('发货:已扫描 %d 行,命中窗口 %d 件', $scanned, $total)); + } + // 表远大于窗口时提前结束:已进入窗口,且本页整页都早于窗口(id≈时间倒序)。 + if ($windowed && $entered && ! $pageHit && $pageNewest !== null && $fromTs !== null && $pageNewest < $fromTs) { + break; + } if ($cnt < $batch) { break; } @@ -152,13 +258,16 @@ class ShippingReplicaSynchronizer break; } } + if ($progress) { + $progress(sprintf('发货完成:扫描 %d 行,写入 %d 件', $scanned, $total)); + } $this->flush(); return $total; } /** 并入自动发货仓:jst_Orders 已发货但不在发货明细表。 */ - private function syncAutoShip(string $fromS, string $toS, $now): int + private function syncAutoShip(string $fromS, string $toS, $now, ?callable $progress = null): int { $batch = 400; $maxBatches = 600; @@ -186,6 +295,7 @@ class ShippingReplicaSynchronizer $oids = []; $soIds = []; + $logs = []; foreach ($rows as $r) { $so = (string) ($r['so_id'] ?? ''); if ($so !== '') { @@ -195,10 +305,29 @@ class ShippingReplicaSynchronizer if ($oid !== '') { $oids[$oid] = true; } + $lg = (string) ($r['l_id'] ?? ''); + if ($lg !== '') { + $logs[$lg] = true; + } $lastRid = $r['rid']; } [$byOid, $bySo] = $this->loadAllItems(array_keys($oids), array_keys($soIds)); - $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo)); + $dws = []; + foreach (array_keys($soIds) as $mso) { + if (empty($bySo[$mso]) && ! empty($this->dwsCache[$mso])) { + $dws[$mso] = $this->dwsCache[$mso]; + } + } + $ioMap = $this->loadIoMap(array_keys($logs), array_keys($oids)); + $ioIds = []; + foreach ($rows as $r) { + $io = $this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), (string) ($r['o_id'] ?? '')); + if ($io !== '') { + $ioIds[$io] = true; + } + } + $viewItems = $this->loadViewItems(array_keys($ioIds)); + $skus = $this->loadSkus($this->collectSkuIds($byOid, $bySo, $dws, $viewItems)); $freight = $this->loadFreight(array_keys($soIds)); $cnt = count($rows); @@ -211,14 +340,17 @@ class ShippingReplicaSynchronizer continue; // 线上发货:对齐排除 } $so = (string) ($r['so_id'] ?? ''); - $items = $this->itemsFor($byOid, $bySo, $oid, $so); + $io = $this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), $oid); + $items = ($io !== '' && ! empty($viewItems[$io])) + ? $viewItems[$io] + : $this->itemsFor($byOid, $bySo, $dws, $oid, $so); $tracking = $this->tracking((string) ($r['l_id'] ?? ''), '', $freight, $so); $shipTime = $this->ts($r['send_date'] ?? null); $pkg = $this->pkgFromOrder($r, $tracking, $shipTime); $pkgId = self::AUTOSHIP_OFFSET + (int) $oid; $total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now, true); } - unset($rows, $byOid, $bySo, $skus, $freight); + unset($rows, $byOid, $bySo, $dws, $skus, $freight); if ($b % 30 === 0) { gc_collect_cycles(); } @@ -226,6 +358,9 @@ class ShippingReplicaSynchronizer break; } } + if ($progress) { + $progress(sprintf('代发仓完成:写入 %d 件', $total)); + } $this->flush(); return $total; @@ -263,12 +398,12 @@ class ShippingReplicaSynchronizer 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); + $skuW = (float) (($it['weight'] ?? null) ?: ($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; + $L = ($it['l'] ?? null) ?: ($sk['l'] ?? null); + $W = ($it['w'] ?? null) ?: ($sk['w'] ?? null); + $H = ($it['h'] ?? null) ?: ($sk['h'] ?? null); + $vol = ($it['vol'] ?? null) ? round((float) $it['vol'], 4) : (($L && $W && $H) ? round((float) $L * (float) $W * (float) $H, 4) : null); $pkgWeight = (float) ($pkg['weight'] ?? 0) ?: null; $freightW = (float) ($f['w'] ?? 0); @@ -279,17 +414,17 @@ class ShippingReplicaSynchronizer 'trade_no' => $pkg['so_id'], 'item_id' => $it['shopid'] ?? null, 'barcode' => $it['sku'] ?? null, - 'product_name' => $it['name'] ?? null, + 'product_name' => ($it['name'] ?? null) ?: ($sk['name'] ?? null), 'qty' => $it['qty'] ?? null, 'pkg_count' => $countStr, - 'product_code' => $it['iid'] ?? null, + 'product_code' => ($it['iid'] ?? null) ?: ($sk['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'], + 'supplier_name' => ($it['supplier'] ?? null) ?: (($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'], @@ -417,6 +552,73 @@ class ShippingReplicaSynchronizer return [$byOid, $bySo]; } + /** 开跑前按天预加载窗口内 dws 销售全量到内存,避免逐批扫表。 */ + private function preloadDws(\Illuminate\Support\Carbon $from, \Illuminate\Support\Carbon $to): void + { + $this->dwsCache = []; + $seen = []; + $day = $from->copy()->subDay()->startOfDay(); + $end = $to->copy(); + while ($day < $end) { + $d = $day->format('Y-m-d'); + $day = $day->addDay(); + try { + $rows = $this->up->select("SELECT sourceno, item_id, skuoid, goods_count, sales_amount FROM rpt.dws_sn_sales_full_info_di WHERE stat_date = ?", [$d]); + } catch (Throwable) { + continue; + } + foreach ($rows as $r) { + $so = (string) ($r['sourceno'] ?? ''); + $bc = (string) ($r['skuoid'] ?? ''); + if ($so === '' || $bc === '') { + continue; + } + $k = $so.'|'.$bc; + if (isset($seen[$k])) { + continue; + } + $seen[$k] = true; + $this->dwsCache[$so][] = [ + 'id' => null, 'sku' => $bc, 'iid' => null, 'shopid' => $r['item_id'] ?? null, + 'name' => null, 'qty' => $r['goods_count'] ?? null, 'amount' => $r['sales_amount'] ?? null, 'warehouse' => null, + ]; + } + unset($rows); + } + } + + /** jst_OrderItem 缺失时的兜底:dws 销售全量按 sourceno 取商品(条码/商品ID/数量/金额)。 */ + private function loadDwsItems(array $soIds): array + { + $out = []; + $seen = []; + foreach (array_chunk($soIds, 500) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + $sql = "SELECT sourceno, item_id, skuoid, goods_count, sales_amount FROM rpt.dws_sn_sales_full_info_di WHERE sourceno IN ({$ph})"; + foreach ($this->up->select($sql, $chunk) as $r) { + $so = (string) ($r['sourceno'] ?? ''); + $barcode = (string) ($r['skuoid'] ?? ''); + if ($so === '' || $barcode === '') { + continue; + } + $k = $so.'|'.$barcode; + if (isset($seen[$k])) { + continue; + } + $seen[$k] = true; + $out[$so][] = [ + 'id' => null, 'sku' => $barcode, 'iid' => null, 'shopid' => $r['item_id'] ?? null, + 'name' => null, 'qty' => $r['goods_count'] ?? null, 'amount' => $r['sales_amount'] ?? null, 'warehouse' => null, + ]; + } + } + + return $out; + } + private function itemArr(array $r): array { return [ @@ -427,7 +629,7 @@ class ShippingReplicaSynchronizer } /** 该包裹的商品:优先 o_id 精确,取不到回落 so_id。 */ - private function itemsFor(array $byOid, array $bySo, string $oid, string $so): array + private function itemsFor(array $byOid, array $bySo, array $dws, string $oid, string $so): array { if ($oid !== '' && ! empty($byOid[$oid])) { return $byOid[$oid]; @@ -435,14 +637,159 @@ class ShippingReplicaSynchronizer if ($so !== '' && ! empty($bySo[$so])) { return $bySo[$so]; } + if ($so !== '' && ! empty($dws[$so])) { + return $dws[$so]; // jst_OrderItem 取不到时,用 dws 销售全量兜底 + } return []; } - private function collectSkuIds(array $byOid, array $bySo): array + /** 快递单号/内部单号 -> 出库单 io_id(优先快递单号,精确到该次出库)。 */ + private function loadIoMap(array $logisticIds, array $oIds): array + { + $byL = []; + $byO = []; + foreach (array_chunk(array_values(array_unique(array_filter($logisticIds))), 800) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + foreach ($this->up->select('SELECT l_id, io_id FROM ' . self::OUTBOUND . " WHERE l_id IN ({$ph})", $chunk) as $r) { + $l = (string) ($r['l_id'] ?? ''); + if ($l !== '' && ! isset($byL[$l])) { + $byL[$l] = (string) ($r['io_id'] ?? ''); + } + } + } + foreach (array_chunk(array_values(array_unique(array_filter($oIds))), 800) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + foreach ($this->up->select('SELECT o_id, io_id FROM ' . self::OUTBOUND . " WHERE o_id IN ({$ph})", $chunk) as $r) { + $o = (string) ($r['o_id'] ?? ''); + if ($o !== '' && ! isset($byO[$o])) { + $byO[$o] = (string) ($r['io_id'] ?? ''); + } + } + } + + return ['byL' => $byL, 'byO' => $byO]; + } + + private function ioFor(array $ioMap, string $logisticId, string $oid): string + { + if ($logisticId !== '' && ! empty($ioMap['byL'][$logisticId])) { + return (string) $ioMap['byL'][$logisticId]; + } + if ($oid !== '' && ! empty($ioMap['byO'][$oid])) { + return (string) $ioMap['byO'][$oid]; + } + + return ''; + } + + /** io_id -> 实发商品[itemArr](发货数据视图,按(io_id,条码)去重,type=0 之和优先)。 */ + private function loadViewItems(array $ioIds): array + { + $agg = []; + foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 800) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + $sql = 'SELECT io_id, sku_ids, qty, type, sku_name, shop_i_id, wareHoursName, l, w, h, volume, weight, supplier_name FROM ' + . self::VIEW . " WHERE io_id IN ({$ph})"; + foreach ($this->up->select($sql, $chunk) as $r) { + $io = (string) ($r['io_id'] ?? ''); + $skuIds = (string) ($r['sku_ids'] ?? ''); + if ($io === '' || $skuIds === '') { + continue; + } + // 一行可能逗号拼接多个条码 —— 对齐工作平台导出明细:拆成每条码一件; + // 数量与体积按条码数均摊,保证合并求和后与整行值一致(工作平台合并体积"整箱算一次")。 + $bcs = array_values(array_filter(array_map('trim', explode(',', $skuIds)), fn ($x) => $x !== '')); + if ($bcs === []) { + continue; + } + $n = count($bcs); + $isT0 = ((string) ($r['type'] ?? '') === '0'); + $perQty = (float) ($r['qty'] ?? 0) / $n; + $rowVol = ($r['volume'] !== null && $r['volume'] !== '') ? (float) $r['volume'] : null; + $perVol = ($rowVol !== null) ? $rowVol / $n : null; + foreach ($bcs as $bc) { + $k = $io . '|' . mb_strtolower($bc); + if (! isset($agg[$k])) { + $agg[$k] = [ + 'io' => $io, 'sku' => $bc, 't0' => 0.0, 't0n' => 0, 'any' => 0.0, 'anyn' => 0, + 't0vol' => 0.0, 't0voln' => 0, 'anyvol' => 0.0, 'anyvoln' => 0, + 'shopid' => null, 'name' => null, 'wh' => null, + 'l' => null, 'w' => null, 'h' => null, + 'weight' => null, 'supplier' => null, + ]; + } + if ($isT0) { + $agg[$k]['t0'] += $perQty; + $agg[$k]['t0n']++; + if ($perVol !== null) { + $agg[$k]['t0vol'] += $perVol; + $agg[$k]['t0voln']++; + } + } + $agg[$k]['any'] += $perQty; + $agg[$k]['anyn']++; + if ($perVol !== null) { + $agg[$k]['anyvol'] += $perVol; + $agg[$k]['anyvoln']++; + } + // 名称/长宽高/供应商沿用整行值(共享):任意行回填一次 + if (empty($agg[$k]['name']) && ! empty($r['sku_name'])) { + $agg[$k]['name'] = $r['sku_name']; + } + if (empty($agg[$k]['shopid']) && ! empty($r['shop_i_id'])) { + $agg[$k]['shopid'] = $r['shop_i_id']; + } + if (empty($agg[$k]['wh']) && ! empty($r['wareHoursName'])) { + $agg[$k]['wh'] = $r['wareHoursName']; + } + foreach (['l', 'w', 'h', 'weight'] as $ff) { + if (empty($agg[$k][$ff]) && ! empty($r[$ff])) { + $agg[$k][$ff] = $r[$ff]; + } + } + if (empty($agg[$k]['supplier']) && ! empty($r['supplier_name'])) { + $agg[$k]['supplier'] = $r['supplier_name']; + } + } + } + } + $out = []; + foreach ($agg as $a) { + $qty = $a['t0n'] > 0 ? $a['t0'] : ($a['anyn'] > 0 ? $a['any'] / $a['anyn'] : 0); + $qty = (int) round($qty); + if ($qty < 1) { + $qty = 1; + } + // 体积:type=0 各条码分摊之和优先;否则取任一 type 的均值(去 type 重复) + $vol = $a['t0voln'] > 0 + ? round($a['t0vol'], 4) + : ($a['anyvoln'] > 0 ? round($a['anyvol'] / $a['anyvoln'], 4) : null); + $out[$a['io']][] = [ + 'id' => null, 'sku' => $a['sku'], 'iid' => null, + 'shopid' => $a['shopid'], 'name' => $a['name'], + 'qty' => $qty, 'amount' => null, 'warehouse' => $a['wh'], + 'l' => $a['l'], 'w' => $a['w'], 'h' => $a['h'], 'vol' => $vol, + 'weight' => $a['weight'], 'supplier' => $a['supplier'], + ]; + } + + return $out; + } + + private function collectSkuIds(array ...$maps): array { $ids = []; - foreach ([$byOid, $bySo] as $map) { + foreach ($maps as $map) { foreach ($map as $items) { foreach ($items as $it) { if (! empty($it['sku'])) { @@ -502,11 +849,12 @@ class ShippingReplicaSynchronizer continue; } $ph = implode(',', array_fill(0, count($chunk), '?')); - 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) { + foreach ($this->up->select("SELECT sku_id, l, w, h, pack_volume, weight, supplier_name, name, i_id 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, 'supplier' => $r['supplier_name'] ?? null, + 'name' => $r['name'] ?? null, 'iid' => $r['i_id'] ?? null, ]; } }