From a75b0ee1ac129302fb8d95373ac8aac227fb4fbe Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Thu, 3 Dec 2026 19:38:44 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=BF=AB=E9=80=92=E5=BA=94=E4=BB=98):=20?= =?UTF-8?q?=E9=80=80=E5=9B=9E=E4=BB=B6=E6=98=8E=E7=BB=86=E4=B8=8E=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E8=BF=9B=E4=BB=93=E5=90=8C=E6=AD=A5=20(#1717)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Console/Commands/SyncReturnedParcels.php | 52 +++++ app/Console/Kernel.php | 8 + app/Http/Controllers/Business/Pages.php | 1 + .../Business/ReturnedParcelController.php | 88 +++++++++ app/Utilities/SidebarPermissions.php | 4 + .../business_navigation_page_extensions.php | 3 + ..._create_courier_returned_parcel_mirror.php | 59 ++++++ deploy/activate-incremental-release.sh | 1 + deploy/activate-release.sh | 1 + deploy/run-finance-batch.sh | 13 +- docs/上游业务镜像清单.md | 4 + .../Services/ReturnedParcelSynchronizer.php | 137 +++++++++++++ .../returned-parcels.blade.php | 61 ++++++ routes/admin.php | 4 + .../Feature/Business/ReturnedParcelsTest.php | 186 ++++++++++++++++++ 15 files changed, 621 insertions(+), 1 deletion(-) create mode 100644 app/Console/Commands/SyncReturnedParcels.php create mode 100644 app/Http/Controllers/Business/ReturnedParcelController.php create mode 100644 database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php create mode 100644 modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php create mode 100644 resources/views/business/pages/courier-payables/returned-parcels.blade.php create mode 100644 tests/Feature/Business/ReturnedParcelsTest.php diff --git a/app/Console/Commands/SyncReturnedParcels.php b/app/Console/Commands/SyncReturnedParcels.php new file mode 100644 index 000000000..130407bdd --- /dev/null +++ b/app/Console/Commands/SyncReturnedParcels.php @@ -0,0 +1,52 @@ +option('from') ?: ReturnedParcelSynchronizer::START); + $to = (string) ($this->option('to') ?: now('Asia/Shanghai')->toDateString()); + foreach ([$from, $to] as $date) { + if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/D', $date, $parts) + || ! checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) { + $this->error('日期需要 YYYY-MM-DD。'); + return self::FAILURE; + } + } + if ($from < ReturnedParcelSynchronizer::START || $from > $to) { + $this->error('开始日期不得早于 2026-10-01,且不能晚于结束日期。'); + return self::FAILURE; + } + if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) { + $this->error('请通过服务器 run-finance-batch.sh 执行同步。'); + return self::FAILURE; + } + $lock = Cache::lock('courier-returned-parcels-sync', 2100); + if (! $lock->get()) { + $this->warn('退回件同步正在运行,本次跳过。'); + return self::SUCCESS; + } + try { + $result = $synchronizer->sync($from, $to, fn (int $n, int $total) => $this->line("已扫描 {$n} / {$total} 行")); + $this->info(sprintf('退回件同步完成:%s 至 %s,%d 条商品明细,耗时 %.2f 秒,PHP 峰值 %.2f MiB。', + $from, $to, $result['rows'], $result['seconds'], $result['peak_mb'])); + return self::SUCCESS; + } catch (Throwable $exception) { + report($exception); + $this->error('退回件同步失败,保留上次完整结果;使用相同日期可继续未完成批次。'); + return self::FAILURE; + } finally { + $lock->release(); + } + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index c12c49db4..4cb9877ec 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -71,6 +71,14 @@ class Kernel extends ConsoleKernel ->appendOutputTo(storage_path('logs/refund-pending-daily-sync.log')) ->runInBackground(); + // 使用生产批处理入口,避免在网页容器运行全量退回件同步。 + $schedule->exec('sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels') + ->cron('0 10,16 * * *') + ->timezone('Asia/Shanghai') + ->withoutOverlapping(60) + ->appendOutputTo(storage_path('logs/returned-parcels-sync.log')) + ->runInBackground(); + // 上游店铺档案每日刷新后留存一份完整基础信息,方便按日期复查负责人等字段。 $schedule->command('business-mirror:archive-store-information') ->dailyAt('07:00') diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index c24bee5ce..2c7ff816b 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -5972,6 +5972,7 @@ class Pages extends Controller 'courier-payable-summary' => app(\App\Http\Controllers\Business\CourierPayableSummaryController::class)->page(request()), 'shipping-data' => $this->contentForShippingData(), 'return-pickup-management' => $this->contentForReturnPickupManagement(), + 'returned-parcels' => app(ReturnedParcelController::class)->page(request()), 'withdrawal-management' => $this->contentForWithdrawalManagement(), 'fund-balance-monitor' => app(\Modules\EcommerceFinance\View\FundBalanceMonitorPageData::class)->page(), 'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(), diff --git a/app/Http/Controllers/Business/ReturnedParcelController.php b/app/Http/Controllers/Business/ReturnedParcelController.php new file mode 100644 index 000000000..39415995e --- /dev/null +++ b/app/Http/Controllers/Business/ReturnedParcelController.php @@ -0,0 +1,88 @@ + '进仓时间', 'after_sales_id' => '售后单号', 'online_after_sales_no' => '线上售后单号', + 'waybill' => '退回快递单号', 'courier' => '快递公司', 'shop' => '店铺', 'warehouse' => '收货仓库', + 'order_id' => '内部订单号', 'online_order_no' => '线上订单号', 'sku' => '商品编码', 'style_code' => '款式编码', + 'product_name' => '商品名称', 'properties' => '颜色规格', 'applied_qty' => '申请数量', + 'returned_qty' => '实退数量', 'price' => '商品单价', 'item_amount' => '明细金额', + 'status' => '售后状态', 'type' => '售后类型', 'goods_status' => '货物状态', 'reason' => '问题类型', + 'remark' => '备注', 'source_id' => '源明细编号', + ]; + + public function page(Request $request): array + { + $filters = $this->filters($request); + $data = ['view' => 'business.pages.courier-payables.returned-parcels', 'filters' => $filters, + 'columns' => self::COLUMNS, 'rows' => null, 'summary' => null, 'state' => null, 'error' => null]; + try { + $db = DB::connection(config('upstream_mirrors.connection', 'business_mirror')); + if (! Schema::connection($db->getName())->hasTable(Sync::TABLE)) { + $data['error'] = '退回件明细尚未完成首次同步,请稍后刷新。'; + return $data; + } + $query = $this->query($filters); + $data['summary'] = (clone $query)->selectRaw('COUNT(*) AS rows_count, COUNT(DISTINCT after_sales_id) AS orders_count, COALESCE(SUM(returned_qty),0) AS quantity')->first(); + $data['rows'] = $query->orderByDesc('received_at')->orderByDesc('source_id')->paginate(50)->withQueryString(); + $data['state'] = $db->table('business_mirror_table_states')->where('dataset_key', Sync::DATASET)->first(); + } catch (Throwable $exception) { + report($exception); + $data['error'] = '退回件明细暂时无法读取,请稍后重试。'; + } + return $data; + } + + public function export(Request $request) + { + $query = $this->query($this->filters($request)); + $selected = array_values(array_intersect(explode(',', (string) $request->query('columns', '')), array_keys(self::COLUMNS))); + $selected = $selected ?: array_keys(self::COLUMNS); + return response()->streamDownload(function () use ($query, $selected): void { + $file = fopen('php://output', 'w'); + fwrite($file, "\xEF\xBB\xBF"); + fputcsv($file, array_map(fn ($key) => self::COLUMNS[$key], $selected)); + foreach ($query->orderBy('source_id')->lazyById(1000, 'source_id') as $row) { + fputcsv($file, array_map(function ($key) use ($row) { + $value = (string) ($row->$key ?? ''); + if ($value !== '' && in_array($key, ['after_sales_id','online_after_sales_no','waybill','order_id','online_order_no','sku','style_code','source_id'], true)) return "'" . $value; + return preg_match('/^[=+@\-\t\r]/u', $value) ? "'" . $value : $value; + }, $selected)); + } + fclose($file); + }, '退回件明细.csv', ['Content-Type' => 'text/csv; charset=UTF-8']); + } + + private function filters(Request $request): array + { + return validator($request->query(), [ + 'from' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:2026-10-01'], + 'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'], + 'waybill' => ['nullable', 'string', 'max:255'], 'shop' => ['nullable', 'string', 'max:255'], + 'warehouse' => ['nullable', 'string', 'max:255'], 'sku' => ['nullable', 'string', 'max:255'], + ])->validate() + ['from' => Sync::START, 'to' => now('Asia/Shanghai')->toDateString(), + 'waybill' => '', 'shop' => '', 'warehouse' => '', 'sku' => '']; + } + + private function query(array $filters) + { + $query = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))->table(Sync::TABLE) + ->where('received_at', '>=', $filters['from'] ?: Sync::START); + if ($filters['to']) $query->where('received_at', '<', Carbon::parse($filters['to'])->addDay()->toDateString()); + foreach (['waybill', 'shop', 'warehouse', 'sku'] as $field) { + if (filled($filters[$field])) $query->where($field, trim($filters[$field])); + } + return $query; + } +} diff --git a/app/Utilities/SidebarPermissions.php b/app/Utilities/SidebarPermissions.php index defe87541..de5d9e850 100644 --- a/app/Utilities/SidebarPermissions.php +++ b/app/Utilities/SidebarPermissions.php @@ -127,6 +127,10 @@ class SidebarPermissions $allowed[] = 'process-data/invoice-data'; } + if (in_array('courier-payables/shipping-data', $allowed, true)) { + $allowed[] = 'courier-payables/returned-parcels'; + } + return array_values(array_unique($allowed)); } diff --git a/config/business_navigation_page_extensions.php b/config/business_navigation_page_extensions.php index 5eb00df6f..f4d1f8732 100644 --- a/config/business_navigation_page_extensions.php +++ b/config/business_navigation_page_extensions.php @@ -10,6 +10,9 @@ return [ | Entries are appended to an existing section in configuration order. | */ + 'courier-payables' => [ + ['slug' => 'returned-parcels', 'title' => '退回件明细', 'icon' => 'assignment_return'], + ], 'module_sections' => [ [ 'position_after' => 'inventory-management', diff --git a/database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php b/database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php new file mode 100644 index 000000000..a2723e0ea --- /dev/null +++ b/database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php @@ -0,0 +1,59 @@ +environment('testing') && config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + $schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror')); + foreach (['courier_returned_parcels', 'courier_returned_parcels_stage'] as $name) { + if ($schema->hasTable($name)) continue; + $schema->create($name, function (Blueprint $table): void { + $table->unsignedBigInteger('source_id')->primary(); + $table->unsignedBigInteger('after_sales_id')->nullable()->index(); + $table->unsignedBigInteger('item_id')->nullable(); + $table->dateTime('received_at', 6)->index(); + $table->string('online_after_sales_no', 255)->nullable(); + $table->string('order_id', 64)->nullable(); + $table->string('online_order_no', 255)->nullable(); + $table->string('waybill', 255)->nullable()->index(); + $table->string('courier', 255)->nullable(); + $table->string('shop', 255)->nullable(); + $table->string('warehouse', 255)->nullable(); + $table->string('sku', 255)->nullable()->index(); + $table->string('style_code', 255)->nullable(); + $table->text('product_name')->nullable(); + $table->text('properties')->nullable(); + $table->decimal('applied_qty', 20, 4)->nullable(); + $table->decimal('returned_qty', 20, 4)->nullable(); + $table->decimal('price', 20, 4)->nullable(); + $table->decimal('item_amount', 20, 4)->nullable(); + $table->decimal('order_refund', 20, 4)->nullable(); + $table->string('status', 64)->nullable(); + $table->string('type', 64)->nullable(); + $table->string('goods_status', 64)->nullable(); + $table->text('reason')->nullable(); + $table->text('remark')->nullable(); + $table->dateTime('source_updated_at', 6)->nullable(); + $table->uuid('generation')->index(); + $table->dateTime('synced_at', 6); + $table->index(['received_at', 'source_id'], 'returned_parcel_date_id_' . (str_ends_with($table->getTable(), '_stage') ? 'stage' : 'live')); + $table->index(['shop', 'received_at']); + $table->index(['warehouse', 'received_at']); + }); + } + } + + public function down(): void + { + $schema = Schema::connection(config('upstream_mirrors.connection', 'business_mirror')); + $schema->dropIfExists('courier_returned_parcels_stage'); + $schema->dropIfExists('courier_returned_parcels'); + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 8686795dd..28601b28b 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -248,6 +248,7 @@ CRON_TZ=Asia/Shanghai 15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1 # 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。 0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1 +0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 # 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。 */2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 0b797a22f..cda7bc201 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -252,6 +252,7 @@ CRON_TZ=Asia/Shanghai 15 10 * * * root /usr/bin/flock -n /run/caiwu-inventory-warehouse-alert.lock /usr/bin/docker exec -u www-data caiwu_app php artisan inventory:sync-warehouse-mapping-alert --quiet >/dev/null 2>&1 # 退款待确认四张副本库镜像每天 06:00 在独立批容器完整跑完一轮,确保 10:00 前完成。 0 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-tables --daily-only --max-batches=0 --quiet >/dev/null 2>&1 +0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels >>/opt/caiwuxitong/runtime/returned-parcels-sync.log 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 # 钉钉入驻审批通过后回传内部快递资料;与上游全量同步分开,单轮最多25单、115秒。 */2 * * * * root /usr/bin/flock -n /run/caiwu-courier-profile-sync.lock /usr/bin/timeout 115 /usr/bin/docker exec -u www-data caiwu_app php artisan courier-onboarding:sync-dingtalk-profiles --limit=25 --quiet >/dev/null 2>&1 diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index f13d5a3b5..3f1712455 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -11,7 +11,7 @@ case "${1:-}" in portal-freight:import-pending) is_import=1 ;; planting-reimbursement:auto-confirm) is_import=1 ;; jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; - jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;; + jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels) ;; jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;; esac @@ -125,4 +125,15 @@ if [ "$1" = 'account-mapping:refresh-coverage' ]; then --name "$container_name" batch "$@" exit $? fi +if [ "$1" = 'business-mirror:sync-returned-parcels' ]; then + container_name="caiwu_returned_parcels_$$" + cleanup_returned_parcels() { + docker rm --force "$container_name" >/dev/null 2>&1 || true + } + trap cleanup_returned_parcels EXIT INT TERM + /usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps \ + --name "$container_name" batch "$@" + exit $? +fi + docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@" diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 1dae45b77..1e995a6ca 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -20,6 +20,10 @@ ## 当前迁移状态 +“快递应付 → 退回件明细”按 `operations_replica/rpt.jst_returnAndRefundItem.receive_date`(进仓时间)读取 2026-10-01 起的商品明细,并按 `as_id` 关联 `rpt.jst_returnAndRefundInfo` 的售后、快递、店铺和仓库字段。结果写入共享镜像 `courier_returned_parcels`,源明细 `Id` 为稳定键;分批结果先写 `courier_returned_parcels_stage`,复用 `business_mirror_table_states` 保存游标。完整核对来源计数后在事务内替换指定进仓日期范围,失败保留上次完整结果,相同日期重跑可续传。页面只读此镜像,支持分页、精确筛选和流式 CSV 导出。首次指定 `--from=2026-10-01 --to=2026-12-02`(两端包含),日常从 2026-10-01 校准到当天,以覆盖退货明细无可靠更新时间造成的迟到与历史修订。 + +生产入口:`sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels`,北京时间每天 10:00、16:00 执行。沿用全局上游锁和独立批容器(1 CPU、3 GiB、PHP 512 MiB),单次容器执行上限 30 分钟、单条上游查询上限 60 秒;每批最多 2,000 条商品,按所选商品关联售后主表。命令不会写聚水潭或其他财务台账。 + | 状态 | 说明 | | --- | --- | | 本次修正 | “发票数据 → 发票明细”继续读取共享镜像 `ding_invoice_flow_mirror` 与 `ding_invoice_record_mirror`。钉钉附件抓取改为增量合并:已确认的台账发票不会被后续 OCR 失败或空附件覆盖,新识别附件只补充来源链接和缺失字段;同销售方同金额但发票号码不同的记录不下沉为同一张。识别支持 PDF 文本、图片 OCR(外部视觉接口或服务器 Tesseract)、XLSX 内嵌图片、ZIP/RAR/7Z 压缩包,XLS 通过 LibreOffice 转为 PDF 后识别。页面手动抓取仍可强制刷新;后台每 15 分钟自动选取最近一个待抓月份,每轮最多处理 20 个流程。 | diff --git a/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php b/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php new file mode 100644 index 000000000..5cf59a84a --- /dev/null +++ b/modules/EcommerceFinance/Services/ReturnedParcelSynchronizer.php @@ -0,0 +1,137 @@ +addDay()->toDateString(); + $state = $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->first(); + $cursor = $state ? json_decode($state->cursor ?? 'null', true) : null; + $resume = $state && in_array($state->status, ['running', 'failed'], true) + && is_array($cursor) && ($cursor['from'] ?? null) === $from && ($cursor['to'] ?? null) === $to; + $generation = $resume ? $state->generation : (string) Str::uuid(); + $last = $resume ? (int) $cursor['last_id'] : 0; + $batchSize = min(max($batchSize, 1), 2000); + $started = microtime(true); + $base = ['source_key' => 'operations_replica', 'source_object' => 'rpt.jst_returnAndRefundInfo + rpt.jst_returnAndRefundItem', + 'target_table' => self::TABLE, 'status' => 'running', 'run_mode' => 'full', 'generation' => $generation, + 'last_attempted_at' => now(), 'last_error_code' => null, 'updated_at' => now()]; + $db->table('business_mirror_table_states')->updateOrInsert(['dataset_key' => self::DATASET], $base + + ($state ? [] : ['created_at' => now()])); + + try { + if (! $resume) $db->table(self::STAGE)->delete(); + $expected = $this->sourceCount($from, $until); + while (true) { + $items = $this->items($from, $until, $last, $batchSize); + if ($items === []) break; + $headers = $this->headers(array_values(array_unique(array_column($items, 'as_id')))); + $rows = []; + foreach ($items as $item) { + $header = $headers[(string) $item['as_id']] ?? null; + if ($header === null) throw new RuntimeException('missing_after_sales_header'); + $rows[] = $this->row($item, $header, $generation); + } + $last = (int) end($items)['Id']; + $db->transaction(function () use ($db, $rows, $last, $generation, $from, $to): void { + foreach (array_chunk($rows, 400) as $part) { + $db->table(self::STAGE)->upsert($part, ['source_id'], array_keys($part[0])); + } + $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([ + 'cursor' => json_encode(['from' => $from, 'to' => $to, 'last_id' => $last]), + 'last_upserted_rows' => $db->table(self::STAGE)->where('generation', $generation)->count(), + 'updated_at' => now(), + ]); + }); + $progress && $progress($db->table(self::STAGE)->where('generation', $generation)->count(), $expected); + if (count($items) < $batchSize) break; + } + $count = $db->table(self::STAGE)->where('generation', $generation)->count(); + if ($count !== $expected || $count !== $this->sourceCount($from, $until)) { + $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update(['cursor' => null]); + throw new RuntimeException('source_count_changed_retry_required'); + } + // 同一事务替换范围,失败或中断不影响页面上一版;只操作派生镜像。 + $db->transaction(function () use ($db, $from, $until, $generation, $count): void { + $db->table(self::TABLE)->where('received_at', '>=', $from)->where('received_at', '<', $until)->delete(); + $columns = $db->getSchemaBuilder()->getColumnListing(self::TABLE); + $db->table(self::TABLE)->insertUsing($columns, $db->table(self::STAGE)->select($columns)->where('generation', $generation)); + $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([ + 'status' => 'succeeded', 'cursor' => null, 'initial_completed_at' => now(), + 'last_succeeded_at' => now(), 'last_full_succeeded_at' => now(), + 'window_started_at' => $from, 'window_ends_at' => $until, + 'last_upserted_rows' => $count, 'mirror_row_count' => $db->table(self::TABLE)->count(), + 'updated_at' => now(), + ]); + $db->table(self::STAGE)->where('generation', $generation)->delete(); + }); + return ['rows' => $count, 'from' => $from, 'to' => $to, 'seconds' => round(microtime(true) - $started, 2), + 'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 2)]; + } catch (Throwable $exception) { + $db->table('business_mirror_table_states')->where('dataset_key', self::DATASET)->update([ + 'status' => 'failed', 'last_error_code' => class_basename($exception), 'updated_at' => now(), + ]); + throw $exception; + } + } + + protected function sourceCount(string $from, string $until): int + { + return (int) $this->upstream()->scalar('SELECT COUNT_BIG(*) FROM rpt.jst_returnAndRefundItem WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime)', [$from, $until]); + } + + protected function items(string $from, string $until, int $last, int $limit): array + { + return $this->upstream()->select('SELECT TOP (' . $limit . ') Id,as_id,asi_id,CONVERT(varchar(27),receive_date,126) AS receive_date,' + . 'sku_id,i_id,name,properties_value,qty,r_qty,price,amount,remark FROM rpt.jst_returnAndRefundItem' + . ' WHERE receive_date >= CAST(? AS datetime) AND receive_date < CAST(? AS datetime) AND Id > ? ORDER BY Id', [$from, $until, $last]); + } + + protected function headers(array $ids): array + { + $rows = $this->upstream()->select('SELECT Id,as_id,outer_as_id,o_id,so_id,l_id,logistics_company,shop_name,warehouse,' + . 'status,type,good_status,question_type,refund,remark,CONVERT(varchar(27),updateTime,126) AS updateTime' + . ' FROM rpt.jst_returnAndRefundInfo WHERE as_id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')', $ids); + $headers = []; + foreach ($rows as $row) { + $key = (string) $row['as_id']; + if (! isset($headers[$key]) || (int) $row['Id'] > (int) $headers[$key]['Id']) $headers[$key] = $row; + } + return $headers; + } + + private function upstream(): UpstreamReadOnlyQuery + { + return $this->queries->forSourceWithTimeout('operations_replica', 60); + } + + private function row(array $i, array $h, string $generation): array + { + return ['source_id' => $i['Id'], 'after_sales_id' => $i['as_id'], 'item_id' => $i['asi_id'], + 'received_at' => $i['receive_date'], 'online_after_sales_no' => $h['outer_as_id'], + 'order_id' => $h['o_id'], 'online_order_no' => $h['so_id'], 'waybill' => $h['l_id'], + 'courier' => $h['logistics_company'], 'shop' => $h['shop_name'], 'warehouse' => $h['warehouse'], + 'sku' => $i['sku_id'], 'style_code' => $i['i_id'], 'product_name' => $i['name'], 'properties' => $i['properties_value'], + 'applied_qty' => $i['qty'], 'returned_qty' => $i['r_qty'], 'price' => $i['price'], 'item_amount' => $i['amount'], + 'order_refund' => $h['refund'], 'status' => $h['status'], 'type' => $h['type'], 'goods_status' => $h['good_status'], + 'reason' => $h['question_type'], 'remark' => trim(($h['remark'] ?? '') . "\n" . ($i['remark'] ?? '')), + 'source_updated_at' => $h['updateTime'], 'generation' => $generation, 'synced_at' => now()]; + } +} diff --git a/resources/views/business/pages/courier-payables/returned-parcels.blade.php b/resources/views/business/pages/courier-payables/returned-parcels.blade.php new file mode 100644 index 000000000..e29af1036 --- /dev/null +++ b/resources/views/business/pages/courier-payables/returned-parcels.blade.php @@ -0,0 +1,61 @@ +
+
+ @foreach (['from' => '进仓日期起', 'to' => '进仓日期止', 'waybill' => '退回快递单号', 'shop' => '店铺', 'warehouse' => '收货仓库', 'sku' => '商品编码'] as $key => $label) + + @endforeach + + 重置 + 导出筛选结果 + +
+
+ 每天 10:00、16:00 自动同步 · 最近完成:{{ $state->last_succeeded_at ?? '尚未完成' }} + @if(($state->status ?? '') === 'running') · 正在同步,当前显示上次完整结果@endif + @if(($state->status ?? '') === 'failed') · 最近同步失败,当前保留上次完整结果@endif +
+ @if($error)@endif + @if($summary) +

当前筛选:{{ number_format($summary->rows_count) }} 条商品明细 · {{ number_format($summary->orders_count) }} 个售后单 · 实退数量 {{ number_format($summary->quantity, 0) }}

+ @endif +
+
+ + @foreach($columns as $key => $label)@endforeach + + @forelse($rows ?? [] as $row) + @foreach($columns as $key => $label) + + @endforeach + @empty + + @endforelse + +
in_array($key,['applied_qty','returned_qty','price','item_amount'])])>{{ $label }}
in_array($key,['applied_qty','returned_qty','price','item_amount'])])> + @if(in_array($key,['price','item_amount'])){{ $row->$key === null ? '—' : number_format($row->$key, 2) }} + @elseif(in_array($key,['applied_qty','returned_qty'])){{ $row->$key === null ? '—' : rtrim(rtrim(number_format($row->$key, 4, '.', ''), '0'), '.') }} + @else{{ $row->$key ?? '—' }}@endif +
{{ $error ?: '当前进仓日期和筛选条件下没有退回件,请调整日期或清空筛选。' }}
+
+ @if($rows)@endif +

按聚水潭进仓时间展示商品明细;同一售后单有多件商品或分批退回时可出现多行。筛选日期包含起止当天。

+
+ +@push('body_end') + +@endpush diff --git a/routes/admin.php b/routes/admin.php index b24ab0233..b4e853d26 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -771,6 +771,10 @@ Route::get('workspace/courier-payables/shipping-data/suggest', 'Business\\Pages@ ->middleware('business.page:courier-payables,shipping-data') ->name('business.courier-payables.shipping-data.suggest'); +Route::get('workspace/courier-payables/returned-parcels/export', [\App\Http\Controllers\Business\ReturnedParcelController::class, 'export']) + ->middleware('business.page:courier-payables,returned-parcels') + ->name('business.courier-payables.returned-parcels.export'); + foreach (['courier-payables', 'courier-payables-final'] as $unshippedSection) { Route::prefix('workspace/'.$unshippedSection.'/unshipped-waybills') ->middleware('business.page:'.$unshippedSection.',unshipped-waybills') diff --git a/tests/Feature/Business/ReturnedParcelsTest.php b/tests/Feature/Business/ReturnedParcelsTest.php new file mode 100644 index 000000000..22be3bac2 --- /dev/null +++ b/tests/Feature/Business/ReturnedParcelsTest.php @@ -0,0 +1,186 @@ +hasTable('business_mirror_table_states')) { + $schema->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key')->primary(); + foreach (['source_key','source_object','target_table','status','run_mode','generation','last_error_code'] as $key) $table->string($key)->nullable(); + $table->text('cursor')->nullable(); + foreach (['window_started_at','window_ends_at','initial_completed_at','last_full_succeeded_at','last_attempted_at','last_succeeded_at'] as $key) $table->dateTime($key)->nullable(); + $table->integer('last_upserted_rows')->default(0); + $table->integer('mirror_row_count')->default(0); + $table->timestamps(); + }); + } + if (! $schema->hasTable(ReturnedParcelSynchronizer::TABLE)) { + (require base_path('database/migrations/2026_12_03_200000_create_courier_returned_parcel_mirror.php'))->up(); + } + } + + private function synchronizer(array $items): ReturnedParcelFakeSynchronizer + { + return new ReturnedParcelFakeSynchronizer($items); + } + + private function item(int $id, string $received = '2026-11-02 12:00:00'): array + { + return ['Id'=>$id,'as_id'=>100,'asi_id'=>$id+1000,'receive_date'=>$received,'sku_id'=>'SKU-'.$id, + 'i_id'=>'STYLE','name'=>'测试商品','properties_value'=>'白色','qty'=>2,'r_qty'=>1, + 'price'=>'12.3400','amount'=>'24.6800','remark'=>'明细备注']; + } + + public function test_sync_preserves_item_grain_boundaries_and_is_idempotent(): void + { + $items = [$this->item(1, '2026-09-30 23:59:59'), $this->item(2, '2026-10-01 00:00:00'), + $this->item(3, '2026-12-02 23:59:59'), $this->item(4, '2026-12-03 00:00:00')]; + $sync = $this->synchronizer($items); + $this->assertSame(2, $sync->sync('2026-10-01','2026-12-02', null, 1)['rows']); + $sync->sync('2026-10-01','2026-12-02', null, 1); + $rows=DB::connection('business_mirror')->table(ReturnedParcelSynchronizer::TABLE)->orderBy('source_id')->get(); + $this->assertSame([2,3], $rows->pluck('source_id')->all()); + $this->assertSame([100,100], $rows->pluck('after_sales_id')->all()); + $this->assertEquals(1, $rows[0]->returned_qty); + $this->assertEquals(12.34, $rows[0]->price); + $this->assertSame('TEST-RETURN', $rows[0]->waybill); + } + + public function test_failed_sync_keeps_live_rows_and_resumes_from_committed_batch(): void + { + $sync=$this->synchronizer([$this->item(10)]); + $sync->sync('2026-10-01','2026-12-02'); + $sync=$this->synchronizer([$this->item(20),$this->item(21),$this->item(22)]); + $sync->failAfter=1; + try {$sync->sync('2026-10-01','2026-12-02', null, 1); $this->fail('Expected upstream failure');} + catch (RuntimeException $e) {$this->assertSame('upstream_failed', $e->getMessage());} + $db=DB::connection('business_mirror'); + $this->assertSame([10], $db->table(ReturnedParcelSynchronizer::TABLE)->pluck('source_id')->all()); + $this->assertSame('failed', $db->table('business_mirror_table_states')->value('status')); + $sync->failAfter=null; + $sync->readCursors=[]; + $sync->sync('2026-10-01','2026-12-02', null, 1); + $this->assertSame(20, $sync->readCursors[0]); + $this->assertSame([20,21,22], $db->table(ReturnedParcelSynchronizer::TABLE)->orderBy('source_id')->pluck('source_id')->all()); + } + + public function test_count_mismatch_keeps_previous_snapshot_and_resets_checkpoint(): void + { + $sync=$this->synchronizer([$this->item(1)]); + $sync->sync('2026-10-01','2026-12-02'); + $sync=$this->synchronizer([$this->item(2)]); + $sync->countOffset=1; + try {$sync->sync('2026-10-01','2026-12-02'); $this->fail('Expected count mismatch');} + catch (RuntimeException $e) {$this->assertSame('source_count_changed_retry_required', $e->getMessage());} + $db=DB::connection('business_mirror'); + $this->assertSame([1], $db->table(ReturnedParcelSynchronizer::TABLE)->pluck('source_id')->all()); + $this->assertNull($db->table('business_mirror_table_states')->value('cursor')); + } + + public function test_page_reads_mirror_filters_received_date_and_paginates(): void + { + $items=[]; + for($id=1;$id<=55;$id++) $items[]=$this->item($id); + $items[]=$this->item(90,'2026-12-03 12:00:00'); + $this->synchronizer($items)->sync('2026-10-01','2026-12-03'); + $controller=app(ReturnedParcelController::class); + $request=Request::create('/?from=2026-11-01&to=2026-11-30'); + $data=$controller->page($request); + $this->assertSame(55,$data['rows']->total()); + $this->assertCount(50,$data['rows']->items()); + $this->assertEquals(55,$data['summary']->quantity); + $this->assertSame(1,(int)$data['summary']->orders_count); + $filtered=$controller->page(Request::create('/?from=2026-11-01&to=2026-11-30&sku=SKU-2')); + $this->assertSame(1,$filtered['rows']->total()); + $this->assertSame(2,$filtered['rows']->first()->source_id); + $section=collect(BusinessNavigation::all())->firstWhere('slug','courier-payables'); + $this->assertSame('退回件明细',collect($section['pages'])->firstWhere('slug','returned-parcels')['title']); + $this->user->attachPermission(Permission::where('name','read-admin-panel')->firstOrFail()); + $this->loginAs()->get(route('business.pages.show',['section'=>'courier-payables','page'=>'returned-parcels','from'=>'2026-11-01','to'=>'2026-11-30'])) + ->assertOk()->assertSeeText('进仓时间')->assertSeeText('测试商品')->assertSeeText('55 条商品明细')->assertSeeText('10:00、16:00'); + } + + public function test_schedule_uses_managed_batch_at_both_requested_times(): void + { + foreach (['activate-release.sh','activate-incremental-release.sh'] as $file) { + $text=file_get_contents(base_path('deploy/'.$file)); + $this->assertStringContainsString('0 10,16 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-returned-parcels', $text); + } + $this->assertStringContainsString('/usr/bin/timeout 1800', file_get_contents(base_path('deploy/run-finance-batch.sh'))); + } + + public function test_returned_page_inherits_existing_shipping_visibility_only(): void + { + $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]); + $subject = 'user_' . $this->user->id; + setting()->set('system.sidebar_permissions', ['configured' => [$subject], 'subjects' => [$subject => ['courier-payables/shipping-data']]]); + setting()->save(); + $this->assertContains('courier-payables/returned-parcels', SidebarPermissions::effectiveAllowedKeys($this->user)); + $this->assertNotContains('courier-payables/courier-information', SidebarPermissions::effectiveAllowedKeys($this->user)); + } + + public function test_export_contains_every_filtered_row_and_preserves_long_identifiers(): void + { + $items=[]; + for($id=1;$id<=55;$id++)$items[]=$this->item($id); + $this->synchronizer($items)->sync('2026-10-01','2026-12-02'); + $this->user->attachPermission(Permission::where('name','read-admin-panel')->firstOrFail()); + $response=$this->loginAs()->get(route('business.courier-payables.returned-parcels.export',[ + 'from'=>'2026-11-01','to'=>'2026-11-30','columns'=>'online_order_no,sku', + ]))->assertOk(); + $csv=$response->streamedContent(); + $this->assertSame(56, count(array_filter(explode("\n",$csv)))); + $this->assertStringContainsString("'00001234567890123456", $csv); + $this->assertStringContainsString("'SKU-55", $csv); + $this->assertStringNotContainsString('明细金额', $csv); + } + + public function test_command_rejects_invalid_dates_before_querying_source(): void + { + $this->artisan('business-mirror:sync-returned-parcels', ['--from'=>'2026-02-30','--to'=>'2026-12-02'])->assertFailed(); + $this->artisan('business-mirror:sync-returned-parcels', ['--from'=>'2026-11-01','--to'=>'2026-10-01'])->assertFailed(); + } +} + +class ReturnedParcelFakeSynchronizer extends ReturnedParcelSynchronizer +{ + public ?int $failAfter=null; + public int $countOffset=0; + public array $readCursors=[]; + public function __construct(public array $source) {} + protected function sourceCount(string $from,string $until): int + { + return count(array_filter($this->source,fn($row)=>$row['receive_date'] >= $from && $row['receive_date'] < $until))+$this->countOffset; + } + protected function items(string $from,string $until,int $last,int $limit): array + { + $this->readCursors[]=$last; + if($this->failAfter!==null && count($this->readCursors)>$this->failAfter)throw new RuntimeException('upstream_failed'); + return array_slice(array_values(array_filter($this->source,fn($row)=>$row['Id']>$last && $row['receive_date'] >= $from && $row['receive_date'] < $until)),0,$limit); + } + protected function headers(array $ids): array + { + $h=['Id'=>10,'as_id'=>100,'outer_as_id'=>'ONLINE-AS','o_id'=>99,'so_id'=>'00001234567890123456','l_id'=>'TEST-RETURN', + 'logistics_company'=>'测试快递','shop_name'=>'测试店铺','warehouse'=>'测试仓库','status'=>'Confirmed','type'=>'退货退款', + 'good_status'=>'已收货','question_type'=>'测试原因','refund'=>'24.6800','remark'=>'售后备注','updateTime'=>'2026-12-03 10:00:00']; + return [100=>$h]; + } +}