From 46107e196fc60cc37935086f81b34966d727a8ed Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 9 Sep 2026 10:46:17 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E5=8F=91=E5=B8=83=E5=B0=8F=E9=A2=9D?= =?UTF-8?q?=E6=89=93=E6=AC=BE=E7=B4=A2=E5=BC=95=E4=BF=AE=E5=A4=8D=E4=B8=8E?= =?UTF-8?q?=E7=BA=BF=E4=B8=8A=E4=BB=A3=E5=8F=91=E4=BB=B7=E6=A0=BC=20(#134)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Console/Commands/SyncBusinessMirrors.php | 24 ++ .../Commands/SyncDingOnlineDaifaPrice.php | 49 +++ app/Console/Kernel.php | 8 + app/Http/Controllers/Business/Pages.php | 58 +++ config/business_navigation.php | 1 + config/upstream_mirrors.php | 53 +++ ..._ding_online_daifa_price_mirror_tables.php | 61 +++ ...dd_daifa_product_name_and_skumap_index.php | 80 ++++ ...2026_09_08_000200_add_daifa_payee_name.php | 50 +++ .../DingOnlineDaifaPriceMirrorRepository.php | 176 +++++++++ .../Services/BusinessMirrorSchemaManager.php | 36 +- .../DingPayableWorkflowMirrorSynchronizer.php | 348 +++++++++++++++++- .../online-daifa-price.blade.php | 157 ++++++++ .../Business/OnlineDaifaPricePageTest.php | 131 +++++++ .../BusinessMirrorSynchronizerTest.php | 71 ++++ ...gPayableWorkflowMirrorSynchronizerTest.php | 48 +++ 16 files changed, 1327 insertions(+), 24 deletions(-) create mode 100644 app/Console/Commands/SyncDingOnlineDaifaPrice.php create mode 100644 database/migrations/2026_09_08_000000_create_ding_online_daifa_price_mirror_tables.php create mode 100644 database/migrations/2026_09_08_000100_add_daifa_product_name_and_skumap_index.php create mode 100644 database/migrations/2026_09_08_000200_add_daifa_payee_name.php create mode 100644 modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php create mode 100644 resources/views/business/pages/product-inventory/online-daifa-price.blade.php create mode 100644 tests/Feature/Business/OnlineDaifaPricePageTest.php diff --git a/app/Console/Commands/SyncBusinessMirrors.php b/app/Console/Commands/SyncBusinessMirrors.php index 7c3bb48c..e894feff 100644 --- a/app/Console/Commands/SyncBusinessMirrors.php +++ b/app/Console/Commands/SyncBusinessMirrors.php @@ -104,6 +104,30 @@ class SyncBusinessMirrors extends Command Log::error('钉钉应付流程镜像同步失败。', ['exception' => $exception::class]); $this->error('operations_replica.rpt.ding_payable_workflows:同步失败,已保留上一版共享数据。'); } + + // 线上代发业务报销流程复用同一套钉钉流程镜像同步链路,接入此处后 + // 由现有生产 cron 自动断点续传,不额外维护调度脚本。 + try { + $daifaResult = $dingPayableWorkflows + ->forConfigKey('ding_online_daifa_price') + ->sync( + (bool) $this->option('full'), + $this->option('batch') === null ? null : (int) $this->option('batch'), + $this->option('max-batches') === null ? null : (int) $this->option('max-batches'), + ); + if ($daifaResult['status'] !== 'requires_full_sync') { + $this->info(sprintf( + 'operations_replica.rpt.ding_online_daifa_price:%s,本轮 %d 批,累计处理 %d 条明细。', + $daifaResult['status'] === 'succeeded' ? '同步完成' : '同步进行中', + $daifaResult['batches'], + $daifaResult['rows'], + )); + } + } catch (Throwable $exception) { + $failed = true; + Log::error('钉钉线上代发价格流程镜像同步失败。', ['exception' => $exception::class]); + $this->error('operations_replica.rpt.ding_online_daifa_price:同步失败,已保留上一版共享数据。'); + } } return $failed ? self::FAILURE : self::SUCCESS; diff --git a/app/Console/Commands/SyncDingOnlineDaifaPrice.php b/app/Console/Commands/SyncDingOnlineDaifaPrice.php new file mode 100644 index 00000000..b33cc6a0 --- /dev/null +++ b/app/Console/Commands/SyncDingOnlineDaifaPrice.php @@ -0,0 +1,49 @@ +option('full')) { + return self::SUCCESS; + } + + try { + $result = $synchronizer + ->forConfigKey('ding_online_daifa_price') + ->sync( + (bool) $this->option('full'), + $this->option('batch') === null ? null : (int) $this->option('batch'), + $this->option('max-batches') === null ? null : (int) $this->option('max-batches'), + ); + } catch (Throwable $exception) { + Log::error('钉钉线上代发价格流程镜像同步失败。', ['exception' => $exception::class]); + $this->error('钉钉线上代发价格流程同步失败,已保留上一版共享数据。'); + + return self::FAILURE; + } + + $this->info(sprintf( + '%s:本轮 %d 批,累计处理 %d 条明细。', + $result['status'] === 'succeeded' ? '同步完成' : '同步进行中', + $result['batches'], + $result['rows'], + )); + + return self::SUCCESS; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 09f0d5ad..c403c1e1 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -35,6 +35,14 @@ class Kernel extends ConsoleKernel $schedule->command('storage-temp:clear')->dailyAt('17:00'); $schedule->command('model:prune')->dailyAt('17:00'); + // 线上代发价格:每天凌晨 00:00 全量/增量同步一次钉钉线上代发业务报销流程。 + // 生产环境由 business-mirror:sync-tables 的 cron 持续增量覆盖,此处保证 + // 一个固定的每日零点刷新入口;命令本身在非刷新环境会安全跳过。 + $schedule->command('business-mirror:sync-ding-online-daifa-price') + ->dailyAt('00:00') + ->withoutOverlapping(60) + ->runInBackground(); + if ((bool) config('services.esign.polling_enabled', false)) { $schedule->command('esign:poll-signatures --quiet') ->cron('*/2 * * * *') diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 0b142a08..712c8e08 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -38,6 +38,7 @@ use Modules\EcommerceFinance\Repositories\ProductCatalogMirrorRepository; use Modules\EcommerceFinance\Repositories\ProductPriceMirrorRepository; use Modules\EcommerceFinance\Repositories\RawBoardPayablesRepository; use Modules\EcommerceFinance\Repositories\DingPayableWorkflowMirrorRepository; +use Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository; use Modules\EcommerceFinance\Repositories\SmallPaymentWorkOrderMirrorRepository; use Modules\EcommerceFinance\Repositories\SupplierPayableReportRepository; use Modules\EcommerceFinance\Repositories\TmallTaobaoSpreadBillRepository; @@ -78,6 +79,7 @@ class Pages extends Controller private readonly CourierFreightReconciliationMirrorRepository $courierFreightReconciliations, private readonly RawBoardPayablesRepository $rawBoardPayables, private readonly DingPayableWorkflowMirrorRepository $dingPayableWorkflows, + private readonly DingOnlineDaifaPriceMirrorRepository $onlineDaifaPrices, private readonly SupplierPayableReportRepository $supplierPayableReports, private readonly UpstreamQueryCacheFactory $upstreamCaches, private readonly CourierSurchargeQuoteRepository $courierSurchargeQuotes, @@ -579,6 +581,7 @@ class Pages extends Controller 'board-deductions' => $this->contentForBoardDeductions(), 'supplier-payables-report' => $this->contentForSupplierPayablesReport(), 'payable-cloud-warehouse-vehicle-fee' => $this->contentForDingPayableWorkflows(), + 'online-daifa-price' => $this->contentForOnlineDaifaPrice(), 'courier-surcharge' => $this->contentForCourierSurcharge(), 'bill-offset' => app(\Modules\EcommerceFinance\View\BillOffsetPageData::class)->page(), default => null, @@ -737,6 +740,61 @@ class Pages extends Controller } } + protected function contentForOnlineDaifaPrice(): array + { + $clean = static fn (mixed $value, int $length = 80): string => mb_substr(trim((string) $value), 0, $length); + $date = static function (mixed $value): string { + $value = trim((string) $value); + return preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1 ? $value : ''; + }; + $status = strtoupper(mb_substr(trim((string) request('status', '')), 0, 30)); + $filters = [ + 'keyword' => $clean(request('keyword', ''), 80), + 'product_id' => $clean(request('product_id', ''), 64), + 'shop_name' => $clean(request('shop_name', ''), 120), + 'status' => preg_match('/^[A-Z_]+$/', $status) === 1 ? $status : '', + 'created_from' => $date(request('created_from', '')), + 'created_to' => $date(request('created_to', '')), + ]; + $page = max((int) request('page', 1), 1); + $limit = min(max((int) setting('default.list_limit', 25), 1), 100); + + try { + $result = $this->onlineDaifaPrices->paginate($filters, $page, $limit); + $rows = new LengthAwarePaginator( + Collection::make($result['data'] ?? []), + (int) ($result['total'] ?? 0), + $limit, + $page, + ['path' => request()->url(), 'query' => request()->except('page')], + ); + + return [ + 'view' => 'business.pages.product-inventory.online-daifa-price', + 'onlineDaifaRows' => $rows, + 'onlineDaifaFilters' => $filters, + 'onlineDaifaStatus' => $result['status'] ?? 'unknown', + 'onlineDaifaSyncedAt' => $result['last_synced_at'] ?? null, + 'onlineDaifaSummary' => $result['summary'] ?? [], + 'onlineDaifaError' => null, + ]; + } catch (Throwable $exception) { + report($exception); + + return [ + 'view' => 'business.pages.product-inventory.online-daifa-price', + 'onlineDaifaRows' => new LengthAwarePaginator([], 0, $limit, $page, [ + 'path' => request()->url(), 'query' => request()->except('page'), + ]), + 'onlineDaifaFilters' => $filters, + 'onlineDaifaStatus' => 'unavailable', + 'onlineDaifaSyncedAt' => null, + 'onlineDaifaSummary' => [], + 'onlineDaifaError' => '线上代发价格镜像尚未完成同步,请稍后重试。', + ]; + } + } + protected function contentForJingxiRefundData(): array { return [ diff --git a/config/business_navigation.php b/config/business_navigation.php index fea78ef6..1f4afbe8 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -295,6 +295,7 @@ return [ 'icon' => 'inventory_2', 'pages' => [ ['slug' => 'normal-products', 'title' => '普通商品资料'], + ['slug' => 'online-daifa-price', 'title' => '线上代发价格'], ], ], [ diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index ad37961a..e286e124 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -14,6 +14,59 @@ return [ 'max_batches_per_run' => (int) env('DING_PAYABLE_WORKFLOW_MIRROR_MAX_BATCHES', 2), ], + // 线上代发业务报销流程(钉钉 OA 审批):数据源为 operations_replica 的 + // rpt.ding_Workflow 中固定流程编码。明细按“商品ID”关联到共享业务镜像的 + // 商品目录(ops_jst_sku_map / ops_jst_sku)做匹配。页面从共享镜像读取, + // 不在 HTTP 请求中直连上游。process_code 由环境变量注入,避免在代码中 + // 硬编码审批模板编码;填入前不会同步任何数据。 + 'ding_online_daifa_price' => [ + 'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price', + 'source_key' => 'operations_replica', + 'process_code' => env('DING_ONLINE_DAIFA_PRICE_PROCESS_CODE', ''), + 'target_table' => 'ding_online_daifa_price_mirror', + 'extend_columns' => true, + // 同步阶段按商品ID(钉钉表单“商品ID”即 shop_i_id)关联商品目录并写入 + // product_name 列,页面只读镜像、不临时 JOIN 2500 万行的 ops_jst_sku_map。 + 'resolve_product_name' => true, + // 钉钉表单字段名 -> 镜像宽表列。下方列名依据用户提供的演示数据校验, + // 若实际审批模板字段名不同,仅需调整此映射即可,无需改动同步与页面代码。 + 'column_map' => [ + 'payee_name' => '收款人全称', + 'product_id' => '商品ID', + 'daifa_trade_no' => '代发交易单号', + 'shop_trade_no' => '店铺交易单号', + 'shop_name' => '店铺名称', + 'supplier_name' => '供应商名称', + 'material_no' => '料号', + 'ship_qty' => '订单发货数量', + 'paid_amount' => '订单实付金额', + 'daifa_amount' => '代发订单金额', + 'price_diff' => '差价', + ], + // 宽表列类型,决定抽取时的强制转换;字符串列留空即可。 + 'column_types' => [ + 'ship_qty' => 'int', + 'paid_amount' => 'decimal', + 'daifa_amount' => 'decimal', + 'price_diff' => 'decimal', + ], + // 若审批模板把“一个商品一行”放在明细表格里,填写该表格的字段名, + // 同步器会按明细行展开为多条镜像记录;留空则整张表单视为单行。 + 'detail_table' => env('DING_ONLINE_DAIFA_PRICE_DETAIL_TABLE', ''), + // 仅保留“收款人全称”为指定公司的报销明细。收款人全称在钉钉表单中是 + // 顶层字段,同步器会把它并入每条明细行;此处按值精确匹配(去首尾空白), + // 不匹配的明细行不写入镜像。默认限定“宁波顾家望业家居有限公司”,切换 + // 收款人只需调整 env,无需改动同步与页面代码;置空该值即不过滤。 + 'row_filters' => [ + 'payee_name' => env('DING_ONLINE_DAIFA_PRICE_PAYEE', '宁波顾家望业家居有限公司'), + ], + // 只同步指定审批状态的单据(默认只要“已完成/已通过”,与页面状态口径一致); + // 未通过/已拒绝/撤回等整单暂不写入镜像。置空则不限状态。 + 'only_status' => env('DING_ONLINE_DAIFA_PRICE_ONLY_STATUS', 'COMPLETED'), + 'batch_size' => (int) env('DING_ONLINE_DAIFA_PRICE_MIRROR_BATCH_SIZE', 100), + 'max_batches_per_run' => (int) env('DING_ONLINE_DAIFA_PRICE_MIRROR_MAX_BATCHES', 2), + ], + // 只有生产刷新节点写镜像;开发环境和网页请求只读共享结果。 'refresh_enabled' => env( 'BUSINESS_MIRROR_REFRESH_ENABLED', diff --git a/database/migrations/2026_09_08_000000_create_ding_online_daifa_price_mirror_tables.php b/database/migrations/2026_09_08_000000_create_ding_online_daifa_price_mirror_tables.php new file mode 100644 index 00000000..81deeafa --- /dev/null +++ b/database/migrations/2026_09_08_000000_create_ding_online_daifa_price_mirror_tables.php @@ -0,0 +1,61 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('ding_online_daifa_price_mirror')) { + $schema->create('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->string('process_instance_id', 100); + $table->unsignedTinyInteger('detail_index')->default(0); + // 宽表列:按钉钉表单字段抽取,建立索引供页面筛选与按商品ID关联。 + $table->string('product_id', 64)->nullable()->index(); + $table->string('daifa_trade_no', 64)->nullable()->index(); + $table->string('shop_trade_no', 64)->nullable()->index(); + $table->string('shop_name', 120)->nullable()->index(); + $table->string('payee_name', 120)->nullable()->index(); + $table->string('supplier_name', 120)->nullable(); + $table->string('material_no', 120)->nullable(); + $table->unsignedInteger('ship_qty')->nullable(); + $table->decimal('paid_amount', 14, 2)->nullable(); + $table->decimal('daifa_amount', 14, 2)->nullable(); + $table->decimal('price_diff', 14, 2)->nullable(); + // 原始载荷保留,页面可展开核对原始表单,避免因模板改版丢数据。 + $table->json('workflow_payload'); + $table->json('scheme_payload'); + $table->json('task_payload')->nullable(); + $table->string('workflow_created_at', 32)->nullable()->index(); + $table->uuid('sync_generation')->nullable()->index(); + $table->dateTime('synced_at', 6); + + $table->primary(['process_instance_id', 'detail_index']); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + Schema::connection($this->connection())->dropIfExists('ding_online_daifa_price_mirror'); + } +}; diff --git a/database/migrations/2026_09_08_000100_add_daifa_product_name_and_skumap_index.php b/database/migrations/2026_09_08_000100_add_daifa_product_name_and_skumap_index.php new file mode 100644 index 00000000..0127519b --- /dev/null +++ b/database/migrations/2026_09_08_000100_add_daifa_product_name_and_skumap_index.php @@ -0,0 +1,80 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->mirrorConnection()); + + // 1) 线上代发价格镜像宽表增加“已匹配商品名称”列。 + // 商品名称在同步阶段按商品ID关联商品目录后写入,页面只读镜像, + // 不在此处临时 JOIN 2500 万行的 ops_jst_sku_map,避免页面查询超时。 + if ($schema->hasTable('ding_online_daifa_price_mirror') + && ! $schema->hasColumn('ding_online_daifa_price_mirror', 'product_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->string('product_name', 255)->nullable()->comment('按商品ID关联商品目录得到的名称'); + }); + } + + // 2) ops_jst_sku_map 是 2500 万行的共享镜像,原来没有 shop_i_id 单列索引, + // 按商品ID(钉钉表单“商品ID”即 shop_i_id)匹配只能全表扫描。这里补建 + // 单列索引,使按商品ID的关联在同步阶段可秒级完成。 + $this->ensureShopIIdIndex(); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->mirrorConnection()); + + if ($schema->hasTable('ding_online_daifa_price_mirror') + && $schema->hasColumn('ding_online_daifa_price_mirror', 'product_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->dropColumn('product_name'); + }); + } + + if ($this->hasIndex('ops_jst_sku_map', 'idx_shop_i_id')) { + $schema->table('ops_jst_sku_map', function (Blueprint $table): void { + $table->dropIndex('idx_shop_i_id'); + }); + } + } + + private function hasIndex(string $table, string $index): bool + { + $rows = DB::connection($this->mirrorConnection()) + ->select("SELECT 1 FROM information_schema.statistics WHERE TABLE_SCHEMA='caiwu_business_mirror' AND TABLE_NAME=? AND INDEX_NAME=? LIMIT 1", [$table, $index]); + + return count($rows) > 0; + } + + private function ensureShopIIdIndex(): void + { + if (! $this->hasIndex('ops_jst_sku_map', 'idx_shop_i_id')) { + Schema::connection($this->mirrorConnection()) + ->table('ops_jst_sku_map', function (Blueprint $table): void { + $table->index('shop_i_id', 'idx_shop_i_id'); + }); + } + } +}; diff --git a/database/migrations/2026_09_08_000200_add_daifa_payee_name.php b/database/migrations/2026_09_08_000200_add_daifa_payee_name.php new file mode 100644 index 00000000..0cb4dac7 --- /dev/null +++ b/database/migrations/2026_09_08_000200_add_daifa_payee_name.php @@ -0,0 +1,50 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + // 线上代发价格镜像宽表增加“收款人全称”列。同步阶段按钉钉表单“收款人全称” + // 抽取该列,并据此把镜像限定到指定收款人(默认宁波顾家望业家居有限公司)。 + // 已建表但缺列时补列;建表迁移已含该列则跳过,保证幂等。 + if ($schema->hasTable('ding_online_daifa_price_mirror') + && ! $schema->hasColumn('ding_online_daifa_price_mirror', 'payee_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->string('payee_name', 120)->nullable()->index()->after('shop_name'); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if ($schema->hasTable('ding_online_daifa_price_mirror') + && $schema->hasColumn('ding_online_daifa_price_mirror', 'payee_name')) { + $schema->table('ding_online_daifa_price_mirror', function (Blueprint $table): void { + $table->dropColumn('payee_name'); + }); + } + } +}; diff --git a/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php new file mode 100644 index 00000000..301c24b8 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php @@ -0,0 +1,176 @@ +connection = $mirror->connection(); + } + + public function ready(): bool + { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable(self::TARGET_TABLE) || ! $schema->hasTable('business_mirror_table_states')) { + return false; + } + + $state = $this->connection->table('business_mirror_table_states') + ->where('dataset_key', self::DATASET_KEY)->first(); + + return $state !== null && $state->initial_completed_at !== null; + } + + /** @return array{data:list>,total:int,status:string,last_synced_at:?string,summary:array} */ + public function paginate(array $filters, int $page, int $perPage): array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + $state = $this->connection->table('business_mirror_table_states')->where('dataset_key', self::DATASET_KEY)->first(); + + $query = $this->connection->table(self::TARGET_TABLE); + + if (($filters['product_id'] ?? '') !== '') { + $query->where('product_id', (string) $filters['product_id']); + } + if (($filters['shop_name'] ?? '') !== '') { + $query->where('shop_name', (string) $filters['shop_name']); + } + if (($filters['keyword'] ?? '') !== '') { + $keyword = (string) $filters['keyword']; + $query->where(function ($q) use ($keyword): void { + $q->where('process_instance_id', 'like', '%' . $keyword . '%') + ->orWhere('daifa_trade_no', 'like', '%' . $keyword . '%') + ->orWhere('shop_trade_no', 'like', '%' . $keyword . '%'); + }); + } + if (($filters['created_from'] ?? '') !== '') { + $query->where('workflow_created_at', '>=', (string) $filters['created_from']); + } + if (($filters['created_to'] ?? '') !== '') { + $query->where('workflow_created_at', '<', \Illuminate\Support\Carbon::parse((string) $filters['created_to'])->addDay()->startOfDay()->format('Y-m-d H:i:s')); + } + + $rows = $query->orderByDesc('workflow_created_at')->orderByDesc('process_instance_id')->orderByDesc('detail_index')->get(); + + $statusFilter = strtoupper(trim((string) ($filters['status'] ?? ''))); + $matched = []; + foreach ($rows as $row) { + $workflow = $this->decode((string) $row->workflow_payload, []); + if ($statusFilter !== '' && DingPayableWorkflowStatus::key($workflow) !== $statusFilter) { + continue; + } + $matched[] = $row; + } + + $total = count($matched); + $pageRows = array_slice($matched, ($page - 1) * $perPage, $perPage); + + $data = []; + foreach ($pageRows as $row) { + $workflow = $this->decode((string) $row->workflow_payload, []); + $productId = (string) ($row->product_id ?? ''); + // 商品名称已在同步阶段按 商品ID 关联商品目录并写入镜像宽表 product_name 列, + // 页面直接读取,避免对 2500 万行的 ops_jst_sku_map 做临时 JOIN 导致超时。 + $resolvedName = $this->cleanName($row->product_name ?? null); + $product = $productId !== '' && $resolvedName !== null + ? ['matched' => true, 'name' => $resolvedName, 'sku_id' => null, 'i_id' => null] + : ['matched' => false, 'name' => null, 'sku_id' => null, 'i_id' => null]; + $data[] = [ + 'process_instance_id' => (string) $row->process_instance_id, + 'detail_index' => (int) $row->detail_index, + 'product_id' => $productId, + 'daifa_trade_no' => (string) ($row->daifa_trade_no ?? ''), + 'shop_trade_no' => (string) ($row->shop_trade_no ?? ''), + 'shop_name' => (string) ($row->shop_name ?? ''), + 'payee_name' => (string) ($row->payee_name ?? ''), + 'supplier_name' => (string) ($row->supplier_name ?? ''), + 'material_no' => (string) ($row->material_no ?? ''), + 'ship_qty' => $row->ship_qty === null ? null : (int) $row->ship_qty, + 'paid_amount' => $row->paid_amount === null ? null : (float) $row->paid_amount, + 'daifa_amount' => $row->daifa_amount === null ? null : (float) $row->daifa_amount, + 'price_diff' => $row->price_diff === null ? null : (float) $row->price_diff, + 'workflow' => $workflow, + 'scheme' => $this->decode((string) ($row->scheme_payload ?? '[]'), []), + 'tasks' => $this->decode((string) ($row->task_payload ?? '[]'), []), + 'status_key' => DingPayableWorkflowStatus::key($workflow), + 'status_label' => DingPayableWorkflowStatus::label($workflow), + 'matched_product' => $product, + 'workflow_created_at' => (string) ($row->workflow_created_at ?? ''), + ]; + } + + return [ + 'data' => $data, + 'total' => $total, + 'status' => (string) ($state->status ?? 'unknown'), + 'last_synced_at' => $state->last_succeeded_at ? (string) $state->last_succeeded_at : null, + 'summary' => $this->summary($matched), + ]; + } + + /** @param list $rows */ + private function summary(array $rows): array + { + $daifa = 0.0; + $paid = 0.0; + $diff = 0.0; + $matched = 0; + foreach ($rows as $row) { + $daifa += (float) ($row->daifa_amount ?? 0); + $paid += (float) ($row->paid_amount ?? 0); + $diff += (float) ($row->price_diff ?? 0); + if (! empty($row->product_id) && $this->cleanName($row->product_name ?? null) !== null) { + $matched++; + } + } + return [ + 'count' => count($rows), + 'matched_count' => $matched, + 'daifa_amount' => round($daifa, 2), + 'paid_amount' => round($paid, 2), + 'price_diff' => round($diff, 2), + ]; + } + + private function cleanName(mixed $value): ?string + { + if ($value === null) { + return null; + } + $name = trim((string) $value); + return $name === '' ? null : $name; + } + + private function decode(string $json, mixed $fallback): mixed + { + if ($json === '') { + return $fallback; + } + $decoded = json_decode($json, true); + return is_array($decoded) ? $decoded : $fallback; + } +} diff --git a/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php b/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php index 7f011d71..79ceec29 100644 --- a/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php +++ b/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php @@ -23,7 +23,7 @@ class BusinessMirrorSchemaManager $table->char('_mirror_key', 64)->primary(); foreach ($columns as $column) { - $this->addColumn($table, $column); + $this->addColumn($table, $column, $dataset); } $table->uuid('_mirror_generation')->nullable()->index(); @@ -49,9 +49,9 @@ class BusinessMirrorSchemaManager )); if ($missing !== []) { - $schema->table($dataset->targetTable(), function (Blueprint $table) use ($missing): void { + $schema->table($dataset->targetTable(), function (Blueprint $table) use ($missing, $dataset): void { foreach ($missing as $column) { - $this->addColumn($table, $column); + $this->addColumn($table, $column, $dataset); } }); } @@ -120,7 +120,7 @@ class BusinessMirrorSchemaManager return $rows; } - private function addColumn(Blueprint $table, array $column): void + private function addColumn(Blueprint $table, array $column, BusinessMirrorDataset $dataset): void { $name = (string) $column['column_name']; $type = strtolower((string) $column['data_type']); @@ -144,9 +144,11 @@ class BusinessMirrorSchemaManager // MariaDB counts every inline varchar column towards the 65,535-byte // row limit. Wide legacy SQL Server tables can contain dozens of // nvarchar columns even though each individual column looks small. - // Keep only genuinely short values inline; TEXT is stored off-page - // and lets the mirror preserve the complete source schema. - 'char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying' => $length > 0 && $length <= 64 + // Keep only genuinely short values inline. A declared lookup index + // may opt a bounded legacy identifier into VARCHAR; every other + // wide string remains TEXT and is stored off-page. + 'char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying' => $length > 0 + && ($length <= 64 || ($length <= 191 && $this->isConfiguredIndexColumn($dataset, $name))) ? $table->string($name, $length) : $table->longText($name), default => $table->longText($name), @@ -155,7 +157,7 @@ class BusinessMirrorSchemaManager $definition->nullable(); } - private function isIndexable(array $columns, string $name): bool + private function isIndexable(array $columns, string $name, ?BusinessMirrorDataset $dataset = null): bool { foreach ($columns as $column) { if (strcasecmp((string) $column['column_name'], $name) !== 0) { @@ -166,7 +168,8 @@ class BusinessMirrorSchemaManager $length = (int) ($column['max_length'] ?? 0); return ! in_array($type, ['text', 'ntext', 'xml', 'image', 'binary', 'varbinary', 'bytea', 'json', 'jsonb', 'array', 'user-defined'], true) - && (! in_array($type, ['char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying'], true) || ($length > 0 && $length <= 64)); + && (! in_array($type, ['char', 'nchar', 'varchar', 'nvarchar', 'character', 'character varying'], true) + || ($length > 0 && ($length <= 64 || ($length <= 191 && $dataset !== null && $this->isConfiguredIndexColumn($dataset, $name))))); } return false; @@ -188,7 +191,7 @@ class BusinessMirrorSchemaManager foreach ($dataset->indexDefinitions() as $index) { foreach ($index as $column) { if (! in_array(strtolower($column), $columnNames, true) - || ! $this->isIndexable($columns, $column)) { + || ! $this->isIndexable($columns, $column, $dataset)) { throw new RuntimeException('business_mirror_index_column_unsupported:' . $dataset->key()); } } @@ -197,6 +200,19 @@ class BusinessMirrorSchemaManager return $dataset->indexDefinitions(); } + private function isConfiguredIndexColumn(BusinessMirrorDataset $dataset, string $column): bool + { + foreach ($dataset->indexDefinitions() as $index) { + foreach ($index as $indexedColumn) { + if (strcasecmp((string) $indexedColumn, $column) === 0) { + return true; + } + } + } + + return false; + } + private function configuredIndexName(string $table, array $columns, int $position): string { $signature = implode('_', $columns) . '_' . $position; diff --git a/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php b/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php index 167b2894..233e88de 100644 --- a/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php @@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\Services; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Schema\Blueprint; +use Illuminate\Database\Schema\Builder; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Carbon; use Illuminate\Support\Str; @@ -11,15 +12,23 @@ use RuntimeException; use Throwable; /** - * 将钉钉应付申请流程的固定流程编码同步为按流程聚合的共享镜像。 + * 将钉钉审批流程(按固定流程编码)同步为按流程聚合的共享镜像。 * * 钉钉表单字段存放在 JSON 中,且历史版本字段不完全一致;镜像保留原始 * 主表、表单和审批任务 payload,页面只在镜像库中解析和筛选。 + * + * 同一套同步逻辑通过 configKey 支持多个钉钉流程:默认处理“应付申请流程”, + * 配置 ding_online_daifa_price 时按列映射抽取宽表列并(可选)按明细表格 + * 展开为多行,便于按商品ID关联商品目录。新增流程只需在 + * config/upstream_mirrors.php 增加一项,无需另造同步链路。 */ class DingPayableWorkflowMirrorSynchronizer { private readonly ConnectionInterface $connection; + /** 当前同步的钉钉流程配置键,默认“应付申请流程”。 */ + private string $configKey = 'ding_payable_workflows'; + public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) { $this->connection = app('db')->connection( @@ -27,10 +36,18 @@ class DingPayableWorkflowMirrorSynchronizer ); } + /** 切换要同步的钉钉流程配置键(复用同一套同步链路)。 */ + public function forConfigKey(string $configKey): self + { + $this->configKey = $configKey; + + return $this; + } + /** @return array{status:string,mode:string,batches:int,rows:int,dataset:string} */ public function sync(bool $full = false, ?int $batchSize = null, ?int $maxBatches = null): array { - $config = (array) config('upstream_mirrors.ding_payable_workflows', []); + $config = (array) config('upstream_mirrors.' . $this->configKey, []); $dataset = (string) ($config['dataset_key'] ?? 'operations_replica.rpt.ding_payable_workflows'); $target = (string) ($config['target_table'] ?? 'ding_payable_workflow_mirror'); $source = (string) ($config['source_key'] ?? 'operations_replica'); @@ -92,12 +109,24 @@ class DingPayableWorkflowMirrorSynchronizer $taskById = $this->groupBy($tasks, 'processInstanceId'); $now = now(); $payloads = []; + $extendColumns = ! empty($config['extend_columns']); + $columnMap = $extendColumns ? (array) ($config['column_map'] ?? []) : []; + $columnTypes = $extendColumns ? (array) ($config['column_types'] ?? []) : []; + $detailTable = $extendColumns ? trim((string) ($config['detail_table'] ?? '')) : ''; + $resolveProductName = $extendColumns && ! empty($config['resolve_product_name']); + $rowFilters = $extendColumns ? (array) ($config['row_filters'] ?? []) : []; + $onlyStatus = strtoupper(trim((string) ($config['only_status'] ?? ''))); foreach ($workflows as $workflow) { $id = (string) ($workflow['processInstanceId'] ?? ''); if ($id === '') { continue; } + // 工作流级状态过滤:只保留指定审批状态(默认只要“已完成/已通过”), + // 未通过/已拒绝/撤回等整单不写入镜像。置空 only_status 则不限状态。 + if ($onlyStatus !== '' && DingPayableWorkflowStatus::key($workflow) !== $onlyStatus) { + continue; + } $originatorId = trim((string) ($workflow['originatorUserId'] ?? '')); $originatorName = trim((string) ($originatorNames[$originatorId] ?? '')); if ($originatorName !== '') { @@ -105,15 +134,38 @@ class DingPayableWorkflowMirrorSynchronizer // 页面无需在请求期间再次直连上游或猜测标题内容。 $workflow['originatorUserName'] = $originatorName; } - $payloads[] = [ - 'process_instance_id' => $id, - 'workflow_payload' => json_encode($workflow, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), - 'scheme_payload' => json_encode($schemeById[$id] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), - 'task_payload' => json_encode($taskById[$id] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), - 'workflow_created_at' => isset($workflow['createAt']) ? (string) $workflow['createAt'] : null, - 'sync_generation' => $generation, - 'synced_at' => $now, - ]; + $schemeRows = $schemeById[$id] ?? []; + $detailFieldsList = $this->buildDetailRowFields($schemeRows, $detailTable); + $detailIndex = 0; + foreach ($detailFieldsList as $fields) { + $payload = [ + 'process_instance_id' => $id, + 'workflow_payload' => json_encode($workflow, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + 'scheme_payload' => json_encode($schemeRows, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + 'task_payload' => json_encode($taskById[$id] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + 'workflow_created_at' => isset($workflow['createAt']) ? (string) $workflow['createAt'] : null, + 'sync_generation' => $generation, + 'synced_at' => $now, + ]; + if ($extendColumns) { + foreach ($columnMap as $column => $label) { + $payload[$column] = $this->castColumn($fields[$label] ?? null, (string) ($columnTypes[$column] ?? 'string')); + } + // 行级过滤(如“收款人全称”限定):不匹配的明细行直接跳过, + // 不写入镜像,也不占用 detail_index,保证保留行编号连续。 + if ($rowFilters !== [] && ! $this->matchesRowFilters($payload, $rowFilters)) { + continue; + } + $payload['detail_index'] = $detailIndex; + } + $payloads[] = $payload; + $detailIndex++; + } + + } + + if ($resolveProductName && $payloads !== []) { + $this->resolveProductNames($payloads); } $nextCursor = $this->cursorFromWorkflow($workflows[array_key_last($workflows)]); @@ -123,12 +175,25 @@ class DingPayableWorkflowMirrorSynchronizer $cursor = $nextCursor; $rows += count($payloads); $batches++; - $this->connection->transaction(function () use ($dataset, $target, $payloads, $cursor, $generation, $rows, $now): void { + $upsertKeys = $extendColumns ? ['process_instance_id', 'detail_index'] : ['process_instance_id']; + $updateColumns = ['workflow_payload', 'scheme_payload', 'task_payload', 'workflow_created_at', 'sync_generation', 'synced_at']; + if ($extendColumns) { + $updateColumns = array_merge($updateColumns, array_keys($columnMap)); + if ($resolveProductName) { + $updateColumns[] = 'product_name'; + } + } + $this->connection->transaction(function () use ($dataset, $target, $payloads, $cursor, $generation, $rows, $now, $upsertKeys, $updateColumns, $extendColumns, $ids): void { + // A changed workflow may have fewer details or no longer match + // the approved status/payee. Replace its rows atomically. + if ($extendColumns && $ids !== []) { + $this->connection->table($target)->whereIn('process_instance_id', $ids)->delete(); + } if ($payloads !== []) { $this->connection->table($target)->upsert( $payloads, - ['process_instance_id'], - ['workflow_payload', 'scheme_payload', 'task_payload', 'workflow_created_at', 'sync_generation', 'synced_at'], + $upsertKeys, + $updateColumns, ); } $this->connection->table('business_mirror_table_states') @@ -166,6 +231,12 @@ class DingPayableWorkflowMirrorSynchronizer if ($schema->hasTable($target)) { return; } + $config = (array) config('upstream_mirrors.' . $this->configKey, []); + if (! empty($config['extend_columns'])) { + $this->createExtendedMirrorTable($schema, $target); + + return; + } $schema->create($target, function (Blueprint $table): void { $table->string('process_instance_id', 100)->primary(); $table->json('workflow_payload'); @@ -177,6 +248,37 @@ class DingPayableWorkflowMirrorSynchronizer }); } + /** + * 扩展镜像表:在原始 JSON 载荷之外抽取宽表列并建立索引,便于按商品ID + * 关联商品目录、按单据号/店铺筛选。结构与对应迁移保持一致。 + */ + private function createExtendedMirrorTable(Builder $schema, string $target): void + { + $schema->create($target, function (Blueprint $table): void { + $table->string('process_instance_id', 100); + $table->unsignedTinyInteger('detail_index')->default(0); + $table->string('product_id', 64)->nullable()->index(); + $table->string('daifa_trade_no', 64)->nullable()->index(); + $table->string('shop_trade_no', 64)->nullable()->index(); + $table->string('shop_name', 120)->nullable()->index(); + $table->string('payee_name', 120)->nullable()->index(); + $table->string('supplier_name', 120)->nullable(); + $table->string('material_no', 120)->nullable(); + $table->string('product_name', 255)->nullable()->comment('按商品ID关联商品目录得到的名称'); + $table->unsignedInteger('ship_qty')->nullable(); + $table->decimal('paid_amount', 14, 2)->nullable(); + $table->decimal('daifa_amount', 14, 2)->nullable(); + $table->decimal('price_diff', 14, 2)->nullable(); + $table->json('workflow_payload'); + $table->json('scheme_payload'); + $table->json('task_payload')->nullable(); + $table->string('workflow_created_at', 32)->nullable()->index(); + $table->uuid('sync_generation')->nullable()->index(); + $table->dateTime('synced_at', 6); + $table->primary(['process_instance_id', 'detail_index']); + }); + } + /** @return array|null */ private function state(string $dataset): ?array { @@ -438,4 +540,222 @@ class DingPayableWorkflowMirrorSynchronizer } return $grouped; } + + /** + * 从表单 scheme 解析每一行的“字段名 -> 值”映射。 + * + * 若配置了明细表格字段名,则按该表格的每一行展开(并合并顶层字段, + * 如店铺名称),否则整张表单视为单行。返回数组长度即镜像明细行数。 + * + * @param array> $schemeRows + * @return list> + */ + private function buildDetailRowFields(array $schemeRows, string $detailTable): array + { + $topLevel = $this->formFieldLookup($schemeRows); + if ($detailTable === '') { + return [$topLevel]; + } + + $grid = null; + foreach ($schemeRows as $row) { + if (! is_array($row)) { + continue; + } + if (trim((string) ($row['name'] ?? '')) === $detailTable) { + $value = $row['value'] ?? null; + // 钉钉明细表格在上游/镜像中以 JSON 字符串存储,需先解码为数组再按行展开。 + if (is_string($value)) { + $decoded = json_decode($value, true); + $value = is_array($decoded) ? $decoded : null; + } + $grid = is_array($value) ? $value : null; + break; + } + } + + if ($grid === null) { + return [$topLevel]; + } + + $rows = []; + foreach ($grid as $gridRow) { + if (! is_array($gridRow) || ! isset($gridRow['rowValue']) || ! is_array($gridRow['rowValue'])) { + continue; + } + $cellLookup = []; + foreach ($gridRow['rowValue'] as $cell) { + if (! is_array($cell) || ! isset($cell['label'])) { + continue; + } + $cellLookup[(string) $cell['label']] = $this->scalarValue($cell['value'] ?? null); + } + $rows[] = array_merge($topLevel, $cellLookup); + } + + return $rows === [] ? [$topLevel] : $rows; + } + + /** @param array> $schemeRows @return array */ + private function formFieldLookup(array $schemeRows): array + { + $lookup = []; + foreach ($schemeRows as $row) { + if (! is_array($row)) { + continue; + } + $name = trim((string) ($row['name'] ?? '')); + if ($name === '') { + continue; + } + $lookup[$name] = $this->scalarValue($row['value'] ?? null); + } + return $lookup; + } + + private function scalarValue(mixed $value): mixed + { + if (is_scalar($value) || $value === null) { + return $value; + } + return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } + + /** + * 行级过滤:按“镜像列 => 目标值”精确匹配(去首尾空白)。任一条件不满足即 + * 返回 false,该明细行不写入镜像。目标值为空表示不对该列过滤;过滤集合为 + * 空则全部通过。用于把“线上代发业务报销”限定到指定收款人全称等场景。 + * + * @param array $payload + * @param array $filters + */ + private function matchesRowFilters(array $payload, array $filters): bool + { + foreach ($filters as $column => $expected) { + $expected = trim((string) $expected); + if ($expected === '') { + continue; + } + if (trim((string) ($payload[$column] ?? '')) !== $expected) { + return false; + } + } + + return true; + } + + private function castColumn(mixed $value, string $type): mixed + { + if ($value === null || $value === '') { + return null; + } + return match ($type) { + 'int' => is_numeric($value) ? (int) $value : null, + 'decimal' => is_numeric($value) ? (float) $value : null, + default => is_scalar($value) ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + }; + } + + /** + * 同步阶段按商品ID(钉钉表单“商品ID”即 ops_jst_sku_map.shop_i_id)关联商品目录, + * 将已匹配的商品名称写入镜像宽表的 product_name 列。页面只读镜像,不在此处临时 + * JOIN 2500 万行的商品映射表,避免页面查询超时。所有商品ID一次性批量关联, + * 未命中的再回退到 ops_jst_sku 的 i_id/sku_id。 + * + * @param list> $payloads + */ + private function resolveProductNames(array &$payloads): void + { + $ids = []; + foreach ($payloads as $payload) { + $id = trim((string) ($payload['product_id'] ?? '')); + if ($id !== '' && ! isset($ids[$id])) { + $ids[$id] = true; + } + } + if ($ids === []) { + return; + } + $idList = array_keys($ids); + + $names = []; + if ($this->connection->getSchemaBuilder()->hasTable('ops_jst_sku_map')) { + $rows = $this->guardedQuery(4000, fn () => $this->connection->table('ops_jst_sku_map') + ->whereIn('shop_i_id', $idList) + ->select(['shop_i_id', 'sku_id', 'i_id', 'name']) + ->limit(5000) + ->get()); + foreach ($rows as $row) { + $id = (string) $row->shop_i_id; + if (! isset($names[$id])) { + $name = $this->cleanProductName($row->name ?? null); + if ($name !== null) { + $names[$id] = $name; + } + } + } + } + + $missing = array_values(array_filter($idList, static fn (string $id): bool => ! isset($names[$id]))); + if ($missing !== [] && $this->connection->getSchemaBuilder()->hasTable('ops_jst_sku')) { + $rows = $this->guardedQuery(4000, fn () => $this->connection->table('ops_jst_sku') + ->whereIn('i_id', $missing) + ->orWhereIn('sku_id', $missing) + ->select(['i_id', 'sku_id', 'name']) + ->limit(5000) + ->get()); + foreach ($rows as $row) { + foreach ([(string) $row->i_id, (string) $row->sku_id] as $candidate) { + if ($candidate !== '' && isset($names[$candidate]) === false) { + $name = $this->cleanProductName($row->name ?? null); + if ($name !== null) { + $names[$candidate] = $name; + } + } + } + } + } + + foreach ($payloads as &$payload) { + $id = trim((string) ($payload['product_id'] ?? '')); + $payload['product_name'] = $id !== '' && isset($names[$id]) ? $names[$id] : null; + } + unset($payload); + } + + private function cleanProductName(mixed $value): ?string + { + if ($value === null) { + return null; + } + $name = trim((string) $value); + return $name === '' ? null : $name; + } + + /** + * 对可能命中大表的查询加会话级超时,避免索引缺失时整批同步被拖垮。 + * 超时后该批商品名称留空,页面仍可正常展示(仅缺失匹配名),不影响同步完成。 + * + * @template T + * @param callable():T $callback + * @return T + */ + private function guardedQuery(int $milliseconds, callable $callback) + { + $conn = $this->connection; + try { + $conn->statement('SET SESSION MAX_EXECUTION_TIME=' . $milliseconds); + return $callback(); + } catch (Throwable $exception) { + // 超时(SQLSTATE HY000/3024)或其它只读异常:放弃匹配该批商品名称, + // 不让同步链路中断。 + return []; + } finally { + try { + $conn->statement('SET SESSION MAX_EXECUTION_TIME=0'); + } catch (Throwable) { + // 忽略重置失败。 + } + } + } } diff --git a/resources/views/business/pages/product-inventory/online-daifa-price.blade.php b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php new file mode 100644 index 00000000..d7abafdc --- /dev/null +++ b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php @@ -0,0 +1,157 @@ +@php + $rows = $onlineDaifaRows ?? null; + $filters = $onlineDaifaFilters ?? []; + $status = (string) ($onlineDaifaStatus ?? 'unknown'); + $syncedAt = $onlineDaifaSyncedAt ?? null; + $summary = $onlineDaifaSummary ?? []; + $error = $onlineDaifaError ?? null; + $json = static fn (mixed $value): string => is_array($value) + ? (json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) ?: '-') + : (string) ($value ?? '-'); + $statusOptions = \Modules\EcommerceFinance\Services\DingPayableWorkflowStatus::filterOptions(); + $num = static fn (mixed $value): string => $value === null || $value === '' ? '-' : (string) $value; + $money = static fn (mixed $value): string => $value === null ? '-' : number_format((float) $value, 2); + $productName = static fn (array $row): string => $row['matched_product']['matched'] ?? false + ? (string) ($row['matched_product']['name'] ?? '-') + : '(未匹配)'; + $payeeScope = trim((string) config('upstream_mirrors.ding_online_daifa_price.row_filters.payee_name', '')); +@endphp + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + + +
+
+
+ + 重置 +
+
+ + @if ($error) + + @endif + +
+ 固定流程:线上代发业务报销流程(钉钉 OA 审批) + @if ($payeeScope !== '') 固定收款人:{{ $payeeScope }} @endif + 镜像状态:{{ $status }} + @if ($syncedAt) 最近同步:{{ $syncedAt }} @endif + 共 {{ $rows?->total() ?? 0 }} 条 +
+ +
+
代发订单金额合计{{ $money($summary['daifa_amount'] ?? null) }}
+
订单实付金额合计{{ $money($summary['paid_amount'] ?? null) }}
+
差价合计{{ $money($summary['price_diff'] ?? null) }}
+
已匹配商品目录{{ (int) ($summary['matched_count'] ?? 0) }} / {{ (int) ($summary['count'] ?? 0) }}
+
+ +
+ + + + + + + + + + @forelse ($rows ?? [] as $row) + @php($workflow = $row['workflow'] ?? []) + @php($approvalNumber = trim((string) ($workflow['businessId'] ?? '')) ?: (string) ($row['process_instance_id'] ?? '-')) + @php($originator = trim((string) ($workflow['originatorUserName'] ?? '')) ?: trim((string) ($workflow['originatorUserId'] ?? '-'))) + + + + + + + + + + + + + + + + + + + + + @empty + + @endforelse + +
审批编号标题状态申请人收款人全称商品ID商品名称(匹配)店铺名称代发交易单号店铺交易单号发货数量订单实付金额代发订单金额差价供应商名称料号创建时间原始表单
{{ $approvalNumber }}{{ $workflow['title'] ?? '-' }}{{ $row['status_label'] ?? '-' }}{{ $originator }}{{ $num($row['payee_name']) }}{{ $num($row['product_id']) }}{{ $productName($row) }}{{ $num($row['shop_name']) }}{{ $num($row['daifa_trade_no']) }}{{ $num($row['shop_trade_no']) }}{{ $num($row['ship_qty']) }}{{ $money($row['paid_amount']) }}{{ $money($row['daifa_amount']) }}{{ $money($row['price_diff']) }}{{ $num($row['supplier_name']) }}{{ $num($row['material_no']) }}{{ $row['workflow_created_at'] ?? '-' }}
展开表单({{ count($row['scheme'] ?? []) }} 项)
{{ $json($row['scheme'] ?? []) }}
{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的线上代发价格数据;同步完成后会自动显示。' }}
+
+ 当前页 {{ $rows?->count() ?? 0 }} 条 · 第 {{ $rows?->currentPage() ?? 1 }} 页 + + @if ($rows && !$rows->onFirstPage())上一页@endif + @if ($rows && $rows->hasMorePages())下一页@endif + +
+
+
diff --git a/tests/Feature/Business/OnlineDaifaPricePageTest.php b/tests/Feature/Business/OnlineDaifaPricePageTest.php new file mode 100644 index 00000000..ff5e0979 --- /dev/null +++ b/tests/Feature/Business/OnlineDaifaPricePageTest.php @@ -0,0 +1,131 @@ +user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class); + $repository->shouldReceive('paginate')->once()->andReturn([ + 'data' => [[ + 'process_instance_id' => 'DEMO-6927049845766979458', + 'detail_index' => 0, + 'product_id' => '3821829253650055444', + 'daifa_trade_no' => '6927049845766979458', + 'shop_trade_no' => '6927049845766979458', + 'shop_name' => '抖音-HX旗舰店101', + 'payee_name' => '宁波顾家望业家居有限公司', + 'supplier_name' => '', + 'material_no' => '', + 'ship_qty' => 1, + 'paid_amount' => 616.61, + 'daifa_amount' => 375.0, + 'price_diff' => 241.61, + 'workflow' => [ + 'businessId' => '20260901001', + 'title' => '线上代发业务报销', + 'status' => 'COMPLETED', + 'result' => 'agree', + 'originatorUserName' => '扬灵', + 'createAt' => '2026-09-01 10:00:00', + ], + 'scheme' => [['name' => '商品ID', 'value' => '3821829253650055444']], + 'tasks' => [], + 'status_key' => 'COMPLETED', + 'status_label' => '已完成', + 'matched_product' => ['matched' => true, 'name' => '演示商品', 'sku_id' => null, 'i_id' => null], + 'workflow_created_at' => '2026-09-01 10:00:00', + ]], + 'total' => 1, + 'status' => 'succeeded', + 'last_synced_at' => '2026-09-08 00:00:05', + 'summary' => [ + 'count' => 1, + 'matched_count' => 1, + 'daifa_amount' => 375.0, + 'paid_amount' => 616.61, + 'price_diff' => 241.61, + ], + ]); + $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', + 'page' => 'online-daifa-price', + ]))->assertOk() + ->assertSee('线上代发价格') + ->assertSee('固定流程:线上代发业务报销流程(钉钉 OA 审批)') + ->assertSee('固定收款人:') + ->assertSee('宁波顾家望业家居有限公司') + ->assertSee('镜像状态:succeeded') + ->assertSee('3821829253650055444') + ->assertSee('演示商品') + ->assertSee('抖音-HX旗舰店101') + ->assertSee('6927049845766979458') + ->assertSee('已完成') + ->assertSee('扬灵') + ->assertSee('已匹配商品目录') + ->assertSee('展开表单(1 项)'); + } + + public function test_online_daifa_price_page_keeps_an_unavailable_mirror_readable(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class); + $repository->shouldReceive('paginate')->andThrow(new \RuntimeException('not ready')); + $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', + 'page' => 'online-daifa-price', + ]))->assertOk() + ->assertSee('线上代发价格镜像尚未完成同步,请稍后重试。') + ->assertSee('镜像读取失败,请稍后重试。'); + } + + public function test_online_daifa_price_page_passes_filters_to_repository(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class); + $repository->shouldReceive('paginate')->once()->with( + [ + 'keyword' => '6927049845766979458', + 'product_id' => '3821829253650055444', + 'shop_name' => '抖音-HX旗舰店101', + 'status' => '', + 'created_from' => '2026-09-01', + 'created_to' => '2026-09-07', + ], + 1, + Mockery::type('int'), + )->andReturn([ + 'data' => [], + 'total' => 0, + 'status' => 'succeeded', + 'last_synced_at' => '2026-09-08 00:00:05', + 'summary' => [], + ]); + $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', + 'page' => 'online-daifa-price', + 'keyword' => '6927049845766979458', + 'product_id' => '3821829253650055444', + 'shop_name' => '抖音-HX旗舰店101', + 'created_from' => '2026-09-01', + 'created_to' => '2026-09-07', + ]))->assertOk() + ->assertSee('商品ID') + ->assertSee('店铺名称') + ->assertSee('2026-09-01') + ->assertSee('2026-09-07'); + } +} diff --git a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php index a601244b..24cc92ec 100644 --- a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php @@ -246,6 +246,77 @@ class BusinessMirrorSynchronizerTest extends TestCase $this->assertSame('text', $types['longLabel']); } + public function test_small_payment_work_order_dataset_accepts_only_supported_indexes(): void + { + $datasets = (array) config('upstream_mirrors.datasets', []); + $datasets['jiansun.dbo.jst_workOrderInfo'] = [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'jst_workOrderInfo', + 'target' => 'test_small_payment_work_orders', + 'keys' => ['Id'], + 'watermark' => 'updateTime', + 'columns' => [ + 'Id', 'woNo', 'woTypeId', 'title', 'content', 'status', 'grade', + 'urging', 'createby', 'executors', 'beginTime', 'endTime', + 'completer', 'completeTime', 'updated', 'created', + 'businessFieldList', 'createTime', 'updateTime', + ], + 'indexes' => [ + ['woTypeId', 'woNo', 'Id'], + ['created', 'Id'], + ], + ]; + config(['upstream_mirrors.datasets' => $datasets]); + + $columns = [ + ['name' => 'Id', 'type' => 'int', 'length' => null], + ['name' => 'woNo', 'type' => 'nvarchar', 'length' => 100], + ['name' => 'woTypeId', 'type' => 'nvarchar', 'length' => 100], + ['name' => 'urging', 'type' => 'int', 'length' => null], + ['name' => 'created', 'type' => 'datetime2', 'length' => null], + ['name' => 'updateTime', 'type' => 'datetime2', 'length' => null], + ]; + $selected = $datasets['jiansun.dbo.jst_workOrderInfo']['columns']; + foreach ($selected as $position => $name) { + $definition = collect($columns)->firstWhere('name', $name) ?? [ + 'name' => $name, + 'type' => 'nvarchar', + 'length' => 120, + ]; + DB::table('upstream_schema_columns')->insert(array_replace($this->column( + $definition['name'], + $position + 1, + $definition['type'], + $definition['length'], + ), [ + 'source_key' => 'jiansun', + 'schema_name' => 'dbo', + 'object_name' => 'jst_workOrderInfo', + ])); + } + + $dataset = (new BusinessMirrorDatasetRegistry())->get('jiansun.dbo.jst_workOrderInfo'); + $this->assertSame([ + ['woTypeId', 'woNo', 'Id'], + ['created', 'Id'], + ], $dataset->indexDefinitions()); + + (new BusinessMirrorSchemaManager())->ensure($dataset); + + $indexes = collect(Schema::connection('business_mirror')->getIndexes($dataset->targetTable())) + ->map(static fn (array $index): array => array_map('strtolower', (array) ($index['columns'] ?? []))) + ->all(); + $types = collect(DB::connection('business_mirror')->select('PRAGMA table_info(test_small_payment_work_orders)')) + ->pluck('type', 'name') + ->map(static fn (string $type): string => strtolower($type)); + $this->assertSame('varchar', $types['woNo']); + $this->assertSame('varchar', $types['woTypeId']); + $this->assertSame('text', $types['businessFieldList']); + $this->assertContains(['wotypeid', 'wono', 'id'], $indexes); + $this->assertContains(['created', 'id'], $indexes); + } + public function test_empty_full_read_does_not_delete_previous_mirror_rows(): void { $this->query->batches = [[ diff --git a/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php index 0018d5d6..1badf847 100644 --- a/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php @@ -159,6 +159,54 @@ class DingPayableWorkflowMirrorSynchronizerTest extends TestCase $this->assertSame(2, DB::connection('business_mirror')->table('ding_payable_workflow_mirror')->count()); } + public function test_extended_workflow_update_removes_rows_that_no_longer_match(): void + { + config(['upstream_mirrors.ding_online_daifa_price' => [ + 'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price', + 'target_table' => 'ding_online_daifa_price_mirror', + 'source_key' => 'operations_replica', 'process_code' => 'PROC-TEST', + 'extend_columns' => true, 'only_status' => 'COMPLETED', + 'column_map' => ['product_id' => '商品ID'], + ]]); + $sync = $this->synchronizer->forConfigKey('ding_online_daifa_price'); + $this->query->workflowBatches = [[$this->workflow('changed', now()->subHour()->format('Y-m-d H:i:s.u'))]]; + $sync->sync(true, 10, 0); + $table = DB::connection('business_mirror')->table('ding_online_daifa_price_mirror'); + $this->assertSame(1, $table->count()); + $this->query->workflowBatches = [[$this->workflow('changed', now()->format('Y-m-d H:i:s.u'), 'RUNNING')]]; + $sync->sync(false, 10, 0); + $this->assertSame(0, $table->count()); + } + + public function test_daifa_repository_includes_end_date_and_counts_only_resolved_products(): void + { + config(['upstream_mirrors.ding_online_daifa_price' => [ + 'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price', + 'target_table' => 'ding_online_daifa_price_mirror', + 'source_key' => 'operations_replica', 'process_code' => 'PROC-TEST', + 'extend_columns' => true, 'column_map' => ['product_id' => '商品ID'], + ]]); + $this->query->workflowBatches = [[ + $this->workflow('A', '2026-08-01 00:00:00'), + $this->workflow('B', '2026-08-01 23:59:59'), + $this->workflow('C', '2026-08-02 00:00:00'), + ]]; + $this->synchronizer->forConfigKey('ding_online_daifa_price')->sync(true, 10, 0); + $db = DB::connection('business_mirror'); + $db->table('ding_online_daifa_price_mirror')->where('process_instance_id', 'A') + ->update(['product_id' => 'fixture-a', 'product_name' => '已匹配示例']); + $db->table('ding_online_daifa_price_mirror')->where('process_instance_id', 'B') + ->update(['product_id' => 'fixture-b', 'product_name' => null]); + $db->enableQueryLog(); + $result = app(\Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository::class) + ->paginate(['created_from' => '2026-08-01', 'created_to' => '2026-08-01'], 1, 25); + $this->assertSame(2, $result['total']); + $this->assertSame(1, $result['summary']['matched_count']); + $this->assertSame(['B', 'A'], array_column($result['data'], 'process_instance_id')); + $queries = array_filter($db->getQueryLog(), fn ($q) => str_contains($q['query'], 'workflow_created_at')); + $this->assertContains('2026-08-02 00:00:00', array_values($queries)[0]['bindings']); + } + /** @return array */ private function workflow(string $id, string $updateAt, string $status = 'COMPLETED'): array { From a50b7596e8b9486a0125d78cf2be5e3e0da3ebe2 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 9 Sep 2026 10:53:53 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=B0=8F=E9=A2=9D?= =?UTF-8?q?=E6=89=93=E6=AC=BE=E5=B7=A5=E5=8D=95=E5=85=B3=E8=81=94=E6=9C=AA?= =?UTF-8?q?=E5=91=BD=E4=B8=AD=E7=BB=84=E5=90=88=E7=B4=A2=E5=BC=95=20(#135)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Repositories/SmallPaymentWorkOrderMirrorRepository.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php b/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php index f5b6e80c..27e307ed 100644 --- a/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/SmallPaymentWorkOrderMirrorRepository.php @@ -211,6 +211,9 @@ class SmallPaymentWorkOrderMirrorRepository $join->on('work_order_versions.woNo', '=', 'p.woNo'); }) ->join($workOrders . ' AS w', 'w.Id', '=', 'work_order_versions.Id') + // Match the leading columns of (woTypeId, woNo, Id), rather than + // rescanning all orders of this type for every payment-map row. + ->whereColumn('w.woNo', 'p.woNo') ->where('p.woTypeId', self::SMALL_PAYMENT_WORK_TYPE_ID) ->where('w.woTypeId', self::SMALL_PAYMENT_WORK_TYPE_ID); } From 914a3fe352375c4e088dfa4c0e8074b9a5e9b8b5 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 9 Sep 2026 11:40:00 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E5=8F=96=E6=B6=88=E6=99=AE=E9=80=9A?= =?UTF-8?q?=E7=94=9F=E4=BA=A7=E5=8F=91=E5=B8=83=E7=9A=84=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E6=8E=88=E6=9D=83=E8=A6=81=E6=B1=82=20(#136)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 4 ++-- docs/team-collaboration.md | 2 +- docs/开发与部署SOP.md | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1883d235..44f5a02a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ - 提交前检查 `git status`、实际 diff 和暂存区,只提交当前任务文件;不得带入 `.env`、凭据、日志、构建产物或他人的改动。 - PR 说明做了什么、修改文件、验证结果,以及是否涉及金额、权限、数据库或配置。小型低风险任务不要求冗长模板说明。 - 任务 Codex 在需求满足、相关测试通过且完整 diff 自审无误后,可直接执行 Squash merge、验证远程 `main` 并清理已合并分支,不需要另一位开发者或负责人再次操作。 -- 生产部署、生产迁移、数据修复、删除或覆盖配置仍需单独明确授权,不能因为代码已合并而自动执行。 +- 普通代码发布在相关验证通过、完整 diff 自审并合并到最新 `main` 后,由任务 Codex 直接部署和验收,无需另行取得部署授权。生产迁移、数据修复、删除或覆盖配置仍需单独明确授权,不能因为代码已合并而自动执行。 ## 4. 验证要求 @@ -64,7 +64,7 @@ ## 8. 构建与生产部署 -- 只有用户明确要求“部署、上线”时才执行生产发布;正式发布只使用已合并的最新 `main`。 +- 普通代码发布由任务 Codex 在完成验证与合并后直接执行,不要求用户再次说“部署、上线”;用户明确要求仅本地开发、仅审查或暂不上线时遵循其范围。正式发布只使用已合并的最新 `main`。 - Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`。服务器只运行开发机已构建的 `caiwu_akaunting:` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。 - 当前生产入口为 `https://caiwu.jiansuntuzhi.cn:8442`;公网仍只使用 `8442`,日常发布不得改成无端口地址。 - 发布脚本检测到新增数据库迁移时必须停止,取得负责人明确授权并完成备份后才能使用迁移开关。 diff --git a/docs/team-collaboration.md b/docs/team-collaboration.md index 3f97d2b3..e4ef257f 100644 --- a/docs/team-collaboration.md +++ b/docs/team-collaboration.md @@ -118,7 +118,7 @@ Codex 在合并前必须进入一次独立自审,不得直接沿用开发阶 请进入独立的合并前自审,不要直接沿用开发阶段的完成结论。重新 fetch、读取原始需求和验收标准,并以 origin/main...当前任务分支的完整 diff 为准逐文件审核。检查工作区、WIP 状态、修改边界、公共契约、远程支线重叠、敏感内容、测试证据和目标 main。条件全部满足后,使用 Squash merge 合并到 main,核对远程 main 已包含目标改动,再验证实际页面或接口并删除已合并任务分支。禁止强推;如有冲突、测试失败、自审不通过或涉及尚未授权的生产迁移/数据操作,立即停止并报告。 ``` -日常 PR 自审、合并、主线验证和分支清理由任务开发者的 Codex 完成,不需要另一位开发者或项目负责人参与。开发者不手工执行 Git 合并命令,也不能绕过 PR。涉及生产迁移、数据修复、删除、覆盖配置或部署时,继续执行仓库现有高风险授权规则。 +日常 PR 自审、合并、主线验证、普通代码部署与验收和分支清理由任务开发者的 Codex 完成,不需要另一位开发者或项目负责人参与,也无需另行取得普通部署授权。开发者不手工执行 Git 合并命令,也不能绕过 PR;用户明确要求暂不上线时遵循其范围。涉及生产迁移、数据修复、删除或覆盖配置时,继续执行仓库现有高风险授权规则。 ## PR 落后或发生冲突 diff --git a/docs/开发与部署SOP.md b/docs/开发与部署SOP.md index cb0b8d15..c9b25ee4 100644 --- a/docs/开发与部署SOP.md +++ b/docs/开发与部署SOP.md @@ -29,6 +29,8 @@ 服务器永远不构建源码。 +普通代码发布在相关验证通过、自审并合并到最新 `main` 后,由任务 Codex 按本 SOP 直接部署并验收,无需用户再次授权部署;用户明确要求暂不上线时遵循其范围。数据库迁移、数据修复、删除和覆盖配置仍按 `AGENTS.md` 的授权边界执行。 + ## 2. 每台开发机只做一次的设置 新人只负责启动 Docker Desktop、在网页中登录,以及输入一次系统数据库密码。下面涉及仓库、脚本、构建、迁移、缓存、容器、数据库验证和排错的动作均由 Codex 执行,不能把命令转交给新人。 From 784e82b0a22090295dfee75d8dc665b0c62d2498 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 9 Sep 2026 11:54:21 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E6=94=AF=E6=8C=81=E7=9B=B4=E6=8E=A5?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=AF=86=E7=A0=81=E9=83=A8=E7=BD=B2=E5=B9=B6?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=A4=8D=E7=94=A8=E6=9C=AC=E6=9C=BA=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E4=BF=A1=E6=81=AF=20(#137)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 1 + docs/开发与部署SOP.md | 10 +-- scripts/deploy-auth.ps1 | 54 ++++++++++++ scripts/deploy-from-workstation.ps1 | 117 +++++++++++++------------ scripts/deploy-password-prompt.cmd | 2 + scripts/deploy-password-prompt.ps1 | 47 ++++++++++ tests/scripts/deploy-auth-server.py | 86 ++++++++++++++++++ tests/scripts/deploy-password-auth.ps1 | 73 +++++++++++++++ 8 files changed, 330 insertions(+), 60 deletions(-) create mode 100644 scripts/deploy-auth.ps1 create mode 100644 scripts/deploy-password-prompt.cmd create mode 100644 scripts/deploy-password-prompt.ps1 create mode 100644 tests/scripts/deploy-auth-server.py create mode 100644 tests/scripts/deploy-password-auth.ps1 diff --git a/AGENTS.md b/AGENTS.md index 44f5a02a..710b99dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,6 +66,7 @@ - 普通代码发布由任务 Codex 在完成验证与合并后直接执行,不要求用户再次说“部署、上线”;用户明确要求仅本地开发、仅审查或暂不上线时遵循其范围。正式发布只使用已合并的最新 `main`。 - Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`。服务器只运行开发机已构建的 `caiwu_akaunting:` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。 +- 新人只需表达部署需求;Codex 使用默认生产入口运行脚本。首次通过本机窗口提供一次服务器密码后,加密保存在本人电脑供后续自动使用,不要求新人准备私钥、执行命令或每次重输密码。已有私钥认证仍兼容。 - 当前生产入口为 `https://caiwu.jiansuntuzhi.cn:8442`;公网仍只使用 `8442`,日常发布不得改成无端口地址。 - 发布脚本检测到新增数据库迁移时必须停止,取得负责人明确授权并完成备份后才能使用迁移开关。 - 容器内 Laravel 命令使用 `www-data`。发布后只需确认部署 SHA、应用容器健康、受影响的真实页面/接口、迁移是否执行,以及当前和上一版镜像可回滚。 diff --git a/docs/开发与部署SOP.md b/docs/开发与部署SOP.md index c9b25ee4..7ad7db0c 100644 --- a/docs/开发与部署SOP.md +++ b/docs/开发与部署SOP.md @@ -39,9 +39,11 @@ 2. 在 Docker Desktop 的 `Settings -> Resources -> Advanced` 中: - Docker 虚拟磁盘上限建议 60GB; - Windows 磁盘至少保留 15GB 可用空间。 -3. SSH 私钥放到个人目录,例如 `C:\Users\你的用户名\.ssh\caiwu.pem`,不要放进 Git。 +3. 首次部署仅需在本机密码窗口输入一次服务器密码,之后 Codex 自动复用本机加密保存的登录信息;不要求新人生成、配置或管理私钥。密码使用 Windows 当前用户绑定的 DPAPI 加密,保存在 `%LOCALAPPDATA%\CaiWuXiTong\deploy-credentials`,不进入仓库或日志。已有私钥的机器仍可选传 `-KeyPath`。 4. 只使用仓库里的发布脚本。不要自行执行 `docker system prune -a`,也不要重置 Docker Desktop。 +Codex 已有用户提供的密码时可通过 `-Password` 的 `SecureString` 参数直接使用并保存,无需用户再输入;不要把明文写进命令参数或日志。密码变更时由 Codex 使用 `-UpdatePassword` 更新本机登录信息。部署结束保留加密凭据,下次自动使用。 + 说明:Docker 虚拟磁盘清理后,Windows 上看到的 `.vhdx` 文件可能不会立刻变小,但内部可用空间已经释放。不要为了让文件数字变小而删除虚拟磁盘。 ## 3. 为什么后续不会反复全量下载和上传 @@ -71,7 +73,6 @@ ```powershell .\scripts\deploy-from-workstation.ps1 ` -Server 218.93.190.75 ` - -KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem" ` -BootstrapServer ``` @@ -98,9 +99,7 @@ git switch main git pull --ff-only -.\scripts\deploy-from-workstation.ps1 ` - -Server 218.93.190.75 ` - -KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem" +.\scripts\deploy-from-workstation.ps1 ``` 脚本自动完成: @@ -138,7 +137,6 @@ git pull --ff-only ```powershell .\scripts\deploy-from-workstation.ps1 ` -Server 218.93.190.75 ` - -KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem" ` -AllowMigrations ``` diff --git a/scripts/deploy-auth.ps1 b/scripts/deploy-auth.ps1 new file mode 100644 index 00000000..cac90c74 --- /dev/null +++ b/scripts/deploy-auth.ps1 @@ -0,0 +1,54 @@ +function Start-CaiwuDeploymentAuth { + param([string]$Server, [string]$SshUser, [string]$KeyPath, [Security.SecureString]$Password, [switch]$UpdatePassword) + if ($Server -notmatch '^[A-Za-z0-9][A-Za-z0-9.-]*$' -or $SshUser -notmatch '^[A-Za-z_][A-Za-z0-9_-]*$') { + throw '服务器地址或登录用户名格式无效。' + } + $options = @('-o', 'StrictHostKeyChecking=accept-new', '-o', 'ConnectTimeout=10') + if (-not [string]::IsNullOrWhiteSpace($KeyPath)) { + return @{ Options = $options + @('-i', (Resolve-Path -LiteralPath $KeyPath).Path, '-o', 'BatchMode=yes'); Directory = $null; Saved = @{} } + } + $directory = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) "CaiWuXiTong/deploy-credentials/${SshUser}@${Server}" + [IO.Directory]::CreateDirectory($directory) | Out-Null + $session = @{ Directory = $directory; Saved = @{}; Options = $options + @('-o', 'BatchMode=no', '-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no', '-o', 'NumberOfPasswordPrompts=1') } + try { + $acl = [Security.AccessControl.DirectorySecurity]::new() + $acl.SetAccessRuleProtection($true, $false) + $owner = [Security.Principal.WindowsIdentity]::GetCurrent().User + $acl.SetOwner($owner) + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($owner, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) + [IO.FileSystemAclExtensions]::SetAccessControl([IO.DirectoryInfo]::new($directory), $acl) + $values = @{ + SSH_ASKPASS = (Join-Path $PSScriptRoot 'deploy-password-prompt.cmd') + SSH_ASKPASS_REQUIRE = 'force' + DISPLAY = 'caiwu-deploy' + CAIWU_DEPLOY_LOGIN = "${SshUser}@${Server}" + CAIWU_DEPLOY_PASSWORD_CACHE = (Join-Path $directory 'password.dpapi') + CAIWU_DEPLOY_PASSWORD_UPDATE = $(if ($UpdatePassword) { '1' } else { $null }) + } + foreach ($name in $values.Keys) { + $session.Saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') + [Environment]::SetEnvironmentVariable($name, $values[$name], 'Process') + } + if ($Password) { + $Password | ConvertFrom-SecureString | Set-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Encoding ASCII + $env:CAIWU_DEPLOY_PASSWORD_UPDATE = $null + } + if (Test-Path -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE) { + Write-Host '正在使用本机已保存的部署登录信息。' + } else { + Write-Host '首次部署:请在本机窗口输入服务器密码。此后自动使用已保存的登录信息。' + } + return $session + } catch { + Stop-CaiwuDeploymentAuth $session + throw + } +} + +function Stop-CaiwuDeploymentAuth { + param($Session) + if (-not $Session) { return } + foreach ($name in $Session.Saved.Keys) { + [Environment]::SetEnvironmentVariable($name, $Session.Saved[$name], 'Process') + } +} diff --git a/scripts/deploy-from-workstation.ps1 b/scripts/deploy-from-workstation.ps1 index fcf9f2eb..d1ef5467 100644 --- a/scripts/deploy-from-workstation.ps1 +++ b/scripts/deploy-from-workstation.ps1 @@ -1,10 +1,10 @@ [CmdletBinding()] param( - [Parameter(Mandatory = $true)] - [string]$Server, + [string]$Server = '218.93.190.75', - [Parameter(Mandatory = $true)] [string]$KeyPath, + [Security.SecureString]$Password, + [switch]$UpdatePassword, [string]$SshUser = 'root', [string]$RemotePath = '/opt/caiwuxitong', @@ -26,7 +26,9 @@ param( $ErrorActionPreference = 'Stop' $repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path -$keyFullPath = (Resolve-Path $KeyPath).Path +. (Join-Path $PSScriptRoot 'deploy-auth.ps1') +$authSession = $null +$sshOptions = @() $sshTarget = "${SshUser}@${Server}" $imageName = 'caiwu_akaunting' $tempRoot = Join-Path ([IO.Path]::GetTempPath()) ("caiwu-deploy-" + [Guid]::NewGuid().ToString('N')) @@ -114,7 +116,7 @@ function Ensure-QiniuBusinessStorageRuntime { "grep -q '^QINIU_SECRET_KEY=.' '$remoteEnvironment'" ) -join ' && ' - & ssh -i $keyFullPath -o BatchMode=yes $sshTarget $remoteReadyCommand + & ssh @sshOptions $sshTarget $remoteReadyCommand $remoteReady = $LASTEXITCODE -eq 0 if ($remoteReady) { @@ -136,8 +138,7 @@ function Ensure-QiniuBusinessStorageRuntime { $pendingEnvironment = "$remoteEnvironment.pending" $environmentContent | & ssh ` - -i $keyFullPath ` - -o BatchMode=yes ` + @sshOptions ` $sshTarget ` "umask 077; cat > '$pendingEnvironment'; chmod 600 '$pendingEnvironment'; mv '$pendingEnvironment' '$remoteEnvironment'" if ($LASTEXITCODE -ne 0) { @@ -249,17 +250,15 @@ function Start-RegistryTunnel { $startInfo.FileName = $sshPath $startInfo.UseShellExecute = $false $startInfo.CreateNoWindow = $true - foreach ($argument in @( + foreach ($argument in ($sshOptions + @( '-N', - '-i', $keyFullPath, - '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'ExitOnForwardFailure=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=20', '-L', "127.0.0.1:${LocalPort}:127.0.0.1:5000", $sshTarget - )) { + ))) { $startInfo.ArgumentList.Add($argument) } @@ -303,7 +302,6 @@ try { $deploySha = (git rev-parse HEAD).Trim() $imageTag = $deploySha.Substring(0, 12) $fullImage = "${imageName}:$imageTag" - $remoteArchive = "$RemotePath/image-$imageTag.tar.gz" $buildDate = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') if (-not $AppUrl) { @@ -317,6 +315,13 @@ try { Invoke-Native { docker version | Out-Null } 'Docker Desktop 未启动或不可用。' + $authSession = Start-CaiwuDeploymentAuth -Server $Server -SshUser $SshUser -KeyPath $KeyPath -Password $Password -UpdatePassword:$UpdatePassword + $sshOptions = $authSession.Options + & ssh @sshOptions $sshTarget true + if ($LASTEXITCODE -ne 0) { throw '服务器登录失败或已取消,已停止部署。若密码已变更,由 Codex 使用 -UpdatePassword 重新打开本机密码窗口。' } + if ($authSession.Directory) { $env:CAIWU_DEPLOY_PASSWORD_UPDATE = $null } + $remoteArchive = "$RemotePath/image-$imageTag.tar.gz" + & (Join-Path $PSScriptRoot 'build-frontend.ps1') docker buildx inspect $BuilderName 2>$null | Out-Null @@ -351,7 +356,7 @@ try { docker run --rm --network none --user www-data --entrypoint php $fullImage artisan --version } '发布镜像无法引导 Laravel。服务器未发生任何变更。' - $previousShaOutput = @(& ssh -i $keyFullPath -o BatchMode=yes -o StrictHostKeyChecking=accept-new $sshTarget "cat '$RemotePath/.deployed-sha' 2>/dev/null || true") + $previousShaOutput = @(& ssh @sshOptions -o StrictHostKeyChecking=accept-new $sshTarget "cat '$RemotePath/.deployed-sha' 2>/dev/null || true") $previousSha = ($previousShaOutput -join "`n").Trim() if ($LASTEXITCODE -ne 0) { throw '无法连接服务器。' @@ -381,22 +386,22 @@ try { if ($BootstrapServer) { $bootstrapRemote = "/tmp/caiwu-bootstrap-$imageTag.sh" Invoke-Native { - scp -i $keyFullPath -o BatchMode=yes deploy/bootstrap-server.sh "${sshTarget}:$bootstrapRemote" + scp @sshOptions deploy/bootstrap-server.sh "${sshTarget}:$bootstrapRemote" } '上传服务器初始化脚本失败。' Invoke-Native { - ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$bootstrapRemote' && '$bootstrapRemote' '$AppUrl' '$RemotePath' && rm -f '$bootstrapRemote'" + ssh @sshOptions $sshTarget "chmod 700 '$bootstrapRemote' && '$bootstrapRemote' '$AppUrl' '$RemotePath' && rm -f '$bootstrapRemote'" } '服务器初始化失败。' } Invoke-Native { - ssh -i $keyFullPath -o BatchMode=yes $sshTarget "docker version >/dev/null && docker compose version >/dev/null && install -d -m 700 '$RemotePath'" + ssh @sshOptions $sshTarget "docker version >/dev/null && docker compose version >/dev/null && install -d -m 700 '$RemotePath'" } '服务器 Docker 未就绪;首次发布请添加 -BootstrapServer。' Ensure-QiniuBusinessStorageRuntime $migrationFlag = if ($AllowMigrations) { '1' } else { '0' } Invoke-Native { - scp -i $keyFullPath -o BatchMode=yes ` + scp @sshOptions ` compose.jiangling.yml ` deploy/activate-release.sh ` deploy/activate-incremental-release.sh ` @@ -410,7 +415,7 @@ try { } '上传运行配置失败。' Invoke-Native { - ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$RemotePath/update-runtime-url.sh' && '$RemotePath/update-runtime-url.sh' '$AppUrl' '$RemotePath'" + ssh @sshOptions $sshTarget "chmod 700 '$RemotePath/update-runtime-url.sh' && '$RemotePath/update-runtime-url.sh' '$AppUrl' '$RemotePath'" } '更新服务器访问地址失败。' if ($BootstrapServer) { @@ -430,14 +435,14 @@ try { Remove-Item -LiteralPath $localTar -Force $archiveSizeMB = [math]::Round((Get-Item -LiteralPath $localArchive).Length / 1MB, 1) Write-Host "首次初始化全量包:$archiveSizeMB MiB" - Invoke-Native { scp -i $keyFullPath -o BatchMode=yes $localArchive "${sshTarget}:$remoteArchive" } '上传镜像失败。' + Invoke-Native { scp @sshOptions $localArchive "${sshTarget}:$remoteArchive" } '上传镜像失败。' Invoke-Native { - ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && '$RemotePath/activate-release.sh' '$remoteArchive' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages' && '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml'" + ssh @sshOptions $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && '$RemotePath/activate-release.sh' '$remoteArchive' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages' && '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml'" } '服务器激活、健康检查或增量仓库初始化失败。' } else { Invoke-NativeWithRetry { - ssh -i $keyFullPath -o BatchMode=yes -o ConnectTimeout=10 -o ConnectionAttempts=1 $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && (curl -fsS -o /dev/null http://127.0.0.1:5000/v2/ || '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml')" + ssh @sshOptions -o ConnectTimeout=10 -o ConnectionAttempts=1 $sshTarget "chmod 700 '$RemotePath/'*.sh && chmod 644 '$RemotePath/config-db-init.sh' && (curl -fsS -o /dev/null http://127.0.0.1:5000/v2/ || '$RemotePath/setup-incremental-registry.sh' '$RemotePath' '$RemotePath/registry-config.yml')" } '服务器增量镜像仓库初始化失败。' # docker save 导出未压缩层,每次导入重新压缩会改变摘要,导致 Registry 无法复用。 @@ -460,7 +465,7 @@ try { $registryImage = "127.0.0.1:${localRegistryPort}/caiwuxitong/app:$imageTag" $serverRegistryImage = "127.0.0.1:5000/caiwuxitong/app:$imageTag" - $beforeBytesOutput = @(& ssh -i $keyFullPath -o BatchMode=yes $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1") + $beforeBytesOutput = @(& ssh @sshOptions $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1") $beforeBytes = [long](($beforeBytesOutput -join '').Trim()) $uploadTimer = [Diagnostics.Stopwatch]::StartNew() $uploadSucceeded = $false @@ -503,19 +508,19 @@ try { throw '增量镜像层上传失败。' } $uploadTimer.Stop() - $afterBytesOutput = @(& ssh -i $keyFullPath -o BatchMode=yes $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1") + $afterBytesOutput = @(& ssh @sshOptions $sshTarget "du -sb /var/lib/docker-registry 2>/dev/null | cut -f1") $afterBytes = [long](($afterBytesOutput -join '').Trim()) $incrementalMiB = [math]::Round([math]::Max(0, $afterBytes - $beforeBytes) / 1MB, 2) Write-Host "增量新增镜像层:$incrementalMiB MiB;传输耗时:$([math]::Round($uploadTimer.Elapsed.TotalSeconds, 1)) 秒" Invoke-Native { - ssh -i $keyFullPath -o BatchMode=yes $sshTarget "'$RemotePath/activate-incremental-release.sh' '$serverRegistryImage' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages'" + ssh @sshOptions $sshTarget "'$RemotePath/activate-incremental-release.sh' '$serverRegistryImage' '$imageTag' '$RemotePath' '$deploySha' '$migrationFlag' '$KeepImages'" } '服务器增量激活或健康检查失败。' } if ($ConfigureDingTalkCallback) { Invoke-Native { - ssh -i $keyFullPath -o BatchMode=yes $sshTarget "chmod 700 '$RemotePath/configure-dingtalk-callback.sh' && '$RemotePath/configure-dingtalk-callback.sh' '$Server' '$RemotePath'" + ssh @sshOptions $sshTarget "chmod 700 '$RemotePath/configure-dingtalk-callback.sh' && '$RemotePath/configure-dingtalk-callback.sh' '$Server' '$RemotePath'" } '钉钉 HTTP 回调 Nginx 配置失败。' } @@ -523,39 +528,43 @@ try { Write-Host "发布完成:$fullImage -> $AppUrl" } finally { - Pop-Location + try { + Pop-Location - if (Test-Path -LiteralPath $tempRoot) { - Remove-Item -LiteralPath $tempRoot -Recurse -Force - } - - if ($sshTunnel) { - if (-not $sshTunnel.HasExited) { - $sshTunnel.Kill() + if (Test-Path -LiteralPath $tempRoot) { + Remove-Item -LiteralPath $tempRoot -Recurse -Force } - $sshTunnel.Dispose() - } - if ($remoteArchive) { - ssh -i $keyFullPath -o BatchMode=yes -o ConnectTimeout=5 $sshTarget "rm -f '$remoteArchive'" 2>$null | Out-Null - } + if ($sshTunnel) { + if (-not $sshTunnel.HasExited) { + $sshTunnel.Kill() + } + $sshTunnel.Dispose() + } - if ($bootstrapRemote) { - ssh -i $keyFullPath -o BatchMode=yes -o ConnectTimeout=5 $sshTarget "rm -f '$bootstrapRemote'" 2>$null | Out-Null - } + if ($remoteArchive) { + ssh @sshOptions -o ConnectTimeout=5 $sshTarget "rm -f '$remoteArchive'" 2>$null | Out-Null + } - # Keep the compiled PHP base and Composer vendor layers between releases. - # The production build cache is normally about 20 GB; pruning it to 3 GB made - # every deployment rebuild PHP extensions and download all dependencies again. - $pruneHelp = docker buildx prune --help 2>$null | Out-String - $buildCacheMaxAge = "${BuildCacheMaxAgeHours}h" - docker buildx prune --builder $BuilderName --filter "until=$buildCacheMaxAge" --force 2>$null | Out-Null - if ($pruneHelp -match '--max-used-space') { - docker buildx prune --builder $BuilderName --max-used-space $BuildCacheMaxUsedSpace --force 2>$null | Out-Null - } - elseif ($pruneHelp -match '--keep-storage') { - docker buildx prune --builder $BuilderName --keep-storage $BuildCacheMaxUsedSpace --force 2>$null | Out-Null - } + if ($bootstrapRemote) { + ssh @sshOptions -o ConnectTimeout=5 $sshTarget "rm -f '$bootstrapRemote'" 2>$null | Out-Null + } - docker system df + # Keep the compiled PHP base and Composer vendor layers between releases. + # The production build cache is normally about 20 GB; pruning it to 3 GB made + # every deployment rebuild PHP extensions and download all dependencies again. + $pruneHelp = docker buildx prune --help 2>$null | Out-String + $buildCacheMaxAge = "${BuildCacheMaxAgeHours}h" + docker buildx prune --builder $BuilderName --filter "until=$buildCacheMaxAge" --force 2>$null | Out-Null + if ($pruneHelp -match '--max-used-space') { + docker buildx prune --builder $BuilderName --max-used-space $BuildCacheMaxUsedSpace --force 2>$null | Out-Null + } + elseif ($pruneHelp -match '--keep-storage') { + docker buildx prune --builder $BuilderName --keep-storage $BuildCacheMaxUsedSpace --force 2>$null | Out-Null + } + + docker system df + } finally { + Stop-CaiwuDeploymentAuth $authSession + } } diff --git a/scripts/deploy-password-prompt.cmd b/scripts/deploy-password-prompt.cmd new file mode 100644 index 00000000..7c17250c --- /dev/null +++ b/scripts/deploy-password-prompt.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -STA -ExecutionPolicy Bypass -File "%~dp0deploy-password-prompt.ps1" diff --git a/scripts/deploy-password-prompt.ps1 b/scripts/deploy-password-prompt.ps1 new file mode 100644 index 00000000..1d5e7911 --- /dev/null +++ b/scripts/deploy-password-prompt.ps1 @@ -0,0 +1,47 @@ +# OpenSSH invokes this through SSH_ASKPASS. stdout goes only to OpenSSH. +# Never log or pass plaintext as a process argument. Persist only user-bound DPAPI ciphertext. +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false) +# A Codex PowerShell 7 parent may supply a different PSModulePath. +Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1') +Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1') +if ($env:CAIWU_DEPLOY_PASSWORD_UPDATE -ne '1' -and (Test-Path -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE)) { + $secure = (Get-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Raw).Trim() | ConvertTo-SecureString + $credential = [Management.Automation.PSCredential]::new('deploy', $secure) + [Console]::Out.WriteLine($credential.GetNetworkCredential().Password) + exit 0 +} +Add-Type -AssemblyName System.Windows.Forms +Add-Type -AssemblyName System.Drawing +$form = New-Object Windows.Forms.Form +$form.Text = '财务系统:部署登录' +$form.ClientSize = New-Object Drawing.Size(430, 155) +$form.StartPosition = 'CenterScreen' +$form.TopMost = $true +$label = New-Object Windows.Forms.Label +$label.Text = "请输入服务器 $env:CAIWU_DEPLOY_LOGIN 的密码:" +$label.SetBounds(15, 15, 400, 40) +$inputBox = New-Object Windows.Forms.TextBox +$inputBox.UseSystemPasswordChar = $true +$inputBox.SetBounds(15, 60, 400, 25) +$ok = New-Object Windows.Forms.Button +$ok.Text = '登录' +$ok.SetBounds(250, 105, 75, 30) +$ok.DialogResult = [Windows.Forms.DialogResult]::OK +$cancel = New-Object Windows.Forms.Button +$cancel.Text = '取消' +$cancel.SetBounds(335, 105, 75, 30) +$cancel.DialogResult = [Windows.Forms.DialogResult]::Cancel +$form.Controls.AddRange(@($label, $inputBox, $ok, $cancel)) +$form.AcceptButton = $ok +$form.CancelButton = $cancel +try { + if ($form.ShowDialog() -ne [Windows.Forms.DialogResult]::OK) { exit 1 } + # DPAPI ciphertext, restricted to this Windows user, reused by later deployments. + $secure = ConvertTo-SecureString -String $inputBox.Text -AsPlainText -Force + $secure | ConvertFrom-SecureString | Set-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Encoding ASCII + [Console]::Out.WriteLine($inputBox.Text) +} finally { + $inputBox.Clear() + $form.Dispose() +} diff --git a/tests/scripts/deploy-auth-server.py b/tests/scripts/deploy-auth-server.py new file mode 100644 index 00000000..5dde98b3 --- /dev/null +++ b/tests/scripts/deploy-auth-server.py @@ -0,0 +1,86 @@ +"""Loopback-only SSH/SFTP fixture; password arrives through stdin, never logs.""" +import io +import socket +import sys +import threading +import time +import paramiko + +password = sys.stdin.readline().rstrip('\n') +key = paramiko.RSAKey.generate(2048) + +class Server(paramiko.ServerInterface): + def __init__(self): + self.direct = set() + + def check_auth_password(self, username, supplied): + return paramiko.AUTH_SUCCESSFUL if supplied == password else paramiko.AUTH_FAILED + + def get_allowed_auths(self, username): + return 'password' + + def check_channel_request(self, kind, chanid): + return paramiko.OPEN_SUCCEEDED if kind == 'session' else paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED + + def check_channel_direct_tcpip_request(self, chanid, origin, destination): + self.direct.add(chanid) + return paramiko.OPEN_SUCCEEDED + + def check_channel_exec_request(self, channel, command): + def finish(): + time.sleep(0.1) + channel.send_exit_status(0) + channel.close() + threading.Thread(target=finish, daemon=True).start() + return True + +class SFTP(paramiko.SFTPServerInterface): + def stat(self, path): + return paramiko.SFTP_NO_SUCH_FILE + + def open(self, path, flags, attr): + class Handle(paramiko.SFTPHandle): + def chattr(self, attr): + return paramiko.SFTP_OK + handle = Handle(flags) + handle.writefile = io.BytesIO() + return handle + +def connection(client): + transport = paramiko.Transport(client) + transport.add_server_key(key) + class SFTPSubsystem(paramiko.SFTPServer): + def start_subsystem(self, name, transport, channel): + super().start_subsystem(name, transport, channel) + channel.send_exit_status(0) + transport.set_subsystem_handler('sftp', SFTPSubsystem, SFTP) + try: + server = Server() + channels = [] + transport.start_server(server=server) + while transport.is_active(): + channel = transport.accept(0.5) + if channel: + channels.append(channel) + if channel.chanid not in server.direct: + continue + def echo(c): + while not c.closed: + if c.recv_ready(): + data = c.recv(1024) + if data: + c.sendall(data) + time.sleep(0.01) + threading.Thread(target=echo, args=(channel,), daemon=True).start() + except (EOFError, OSError, paramiko.SSHException): + pass + finally: + transport.close() + +listener = socket.socket() +listener.bind(('127.0.0.1', 0)) +listener.listen(10) +print(listener.getsockname()[1], flush=True) +while True: + client, _ = listener.accept() + threading.Thread(target=connection, args=(client,), daemon=True).start() diff --git a/tests/scripts/deploy-password-auth.ps1 b/tests/scripts/deploy-password-auth.ps1 new file mode 100644 index 00000000..69bccd35 --- /dev/null +++ b/tests/scripts/deploy-password-auth.ps1 @@ -0,0 +1,73 @@ +$ErrorActionPreference = 'Stop' +$root = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path +. (Join-Path $root 'scripts/deploy-auth.ps1') +$session = $null +$server = $null +$tunnel = $null +$username = 'test_' + [Guid]::NewGuid().ToString('N') +try { + $password = [Guid]::NewGuid().ToString('N') + '测试 !$`"' + $session = Start-CaiwuDeploymentAuth -Server '127.0.0.1' -SshUser $username -Password (ConvertTo-SecureString $password -AsPlainText -Force) + $info = [Diagnostics.ProcessStartInfo]::new() + $info.FileName = (Get-Command python).Source + $info.ArgumentList.Add((Join-Path $PSScriptRoot 'deploy-auth-server.py')) + $info.UseShellExecute = $false + $info.CreateNoWindow = $true + $info.RedirectStandardInput = $true + $info.StandardInputEncoding = [Text.UTF8Encoding]::new($false) + $info.Environment['PYTHONIOENCODING'] = 'utf-8' + $info.RedirectStandardOutput = $true + $info.RedirectStandardError = $true + $server = [Diagnostics.Process]::Start($info) + $server.StandardInput.WriteLine($password) + $server.StandardInput.Flush() + $port = $server.StandardOutput.ReadLine() + if ($port -notmatch '^\d+$') { throw 'SSH fixture did not start' } + $options = $session.Options + @('-o', "UserKnownHostsFile=$($session.Directory)/known_hosts") + $target = "${username}@127.0.0.1" + & ssh @options -p $port $target true + if ($LASTEXITCODE -ne 0) { throw 'Password SSH failed' } + Stop-CaiwuDeploymentAuth $session + $session = Start-CaiwuDeploymentAuth -Server '127.0.0.1' -SshUser $username + & ssh @options -p $port $target true + if ($LASTEXITCODE -ne 0) { throw 'Saved password reuse failed' } + $upload = Join-Path $session.Directory 'fixture.txt' + 'fixture' | Set-Content -LiteralPath $upload + & scp @options -P $port $upload "${target}:/fixture.txt" + if ($LASTEXITCODE -ne 0) { throw 'Password SFTP upload failed' } + $listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0) + $listener.Start(); $localPort = ([Net.IPEndPoint]$listener.LocalEndpoint).Port; $listener.Stop() + $info = [Diagnostics.ProcessStartInfo]::new() + $info.FileName = (Get-Command ssh).Source + $info.UseShellExecute = $false + $info.CreateNoWindow = $true + foreach ($argument in ($options + @('-p', $port, '-N', '-o', 'ExitOnForwardFailure=yes', '-L', "127.0.0.1:${localPort}:127.0.0.1:1234", $target))) { $info.ArgumentList.Add($argument) } + $tunnel = [Diagnostics.Process]::Start($info) + Start-Sleep -Seconds 2 + $client = [Net.Sockets.TcpClient]::new('127.0.0.1', $localPort) + $stream = $client.GetStream(); $stream.ReadTimeout = 5000 + $bytes = [Text.Encoding]::UTF8.GetBytes('probe'); $stream.Write($bytes, 0, $bytes.Length) + $received = New-Object byte[] 5 + $count = $stream.Read($received, 0, 5) + $client.Dispose() + if ([Text.Encoding]::UTF8.GetString($received, 0, $count) -ne 'probe') { throw 'Password tunnel failed' } + if ((Get-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE -Raw).Contains($password)) { throw 'Plaintext persisted' } + 'wrong-fixture-password' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -LiteralPath $env:CAIWU_DEPLOY_PASSWORD_CACHE + & ssh @options -p $port $target true 2>$null + if ($LASTEXITCODE -eq 0) { throw 'Invalid password accepted' } + $existingKey = Join-Path $session.Directory 'fake-key' + 'fixture' | Set-Content -LiteralPath $existingKey + $keySession = Start-CaiwuDeploymentAuth -Server '127.0.0.1' -SshUser $username -KeyPath $existingKey + if ($keySession.Options -notcontains 'BatchMode=yes' -or $keySession.Directory) { throw 'Key compatibility failed' } + Write-Host 'PASS: supplied password SSH, saved-login reuse, SFTP upload, background tunnel, encrypted storage, rejected wrong password, optional key compatibility' +} finally { + if ($tunnel) { if (-not $tunnel.HasExited) { $tunnel.Kill() }; $tunnel.Dispose() } + if ($server) { if (-not $server.HasExited) { $server.Kill() }; $server.Dispose() } + Stop-CaiwuDeploymentAuth $session + # Only this test-created identity directory may be removed. + if ($session -and (Split-Path -Leaf $session.Directory) -eq "${username}@127.0.0.1") { + $expected = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) "CaiWuXiTong/deploy-credentials/${username}@127.0.0.1" + if ([IO.Path]::GetFullPath($session.Directory) -ne [IO.Path]::GetFullPath($expected)) { throw 'Unexpected test cleanup path' } + Remove-Item -LiteralPath $session.Directory -Recurse -Force + } +} From 284ba383377776bd339b141d68e73baa03bf428d Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 9 Sep 2026 12:05:38 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=E5=8F=96=E6=B6=88=E5=85=B1=E4=BA=AB?= =?UTF-8?q?=E9=95=9C=E5=83=8F=E6=8E=A5=E5=85=A5=E4=B8=8E=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E7=9A=84=E9=87=8D=E5=A4=8D=E4=BA=BA=E5=B7=A5=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=20(#138)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 6 +++--- app/Console/Commands/RegisterBusinessMirror.php | 4 ++-- app/Console/Commands/SyncProductCatalogMirror.php | 2 +- .../Commands/SyncProductPurchasePriceMirror.php | 2 +- docs/team-collaboration.md | 2 +- docs/上游业务镜像清单.md | 6 +++--- docs/开发与部署SOP.md | 12 ++++++------ docs/通用上游数据接入.md | 6 +++--- scripts/deploy-from-workstation.ps1 | 4 ++-- 9 files changed, 22 insertions(+), 22 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 710b99dd..2dd36f51 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ - 提交前检查 `git status`、实际 diff 和暂存区,只提交当前任务文件;不得带入 `.env`、凭据、日志、构建产物或他人的改动。 - PR 说明做了什么、修改文件、验证结果,以及是否涉及金额、权限、数据库或配置。小型低风险任务不要求冗长模板说明。 - 任务 Codex 在需求满足、相关测试通过且完整 diff 自审无误后,可直接执行 Squash merge、验证远程 `main` 并清理已合并分支,不需要另一位开发者或负责人再次操作。 -- 普通代码发布在相关验证通过、完整 diff 自审并合并到最新 `main` 后,由任务 Codex 直接部署和验收,无需另行取得部署授权。生产迁移、数据修复、删除或覆盖配置仍需单独明确授权,不能因为代码已合并而自动执行。 +- 普通代码发布在相关验证通过、完整 diff 自审并合并到最新 `main` 后,由任务 Codex 直接部署和验收,无需另行取得部署授权。上游接入和共享镜像同步按第 6 节自主完成;除此之外的生产迁移、数据修复、删除或覆盖配置仍需单独明确授权。 ## 4. 验证要求 @@ -50,7 +50,7 @@ - 密码、Token、SSH 私钥、数据库连接串、真实财务数据和生产日志不得进入 Git、PR 或公开文档。 - 需要长期保存的敏感信息写入被 Git 忽略的 `runtime/private/敏感信息.md`;写入前用 `git check-ignore` 确认。负责人明确要求时,可在当前一对一对话提供指定范围的敏感信息,但不得扩大传播。 -- 生产数据库写入、迁移、删除、批量导入和凭据轮换必须先说明影响,准备备份或回滚,并取得明确授权。普通本地只读排查和有限业务查询不需要额外审批。 +- 本任务所需的上游只读排查、数据字典刷新、数据集登记和启用、共享镜像建表及索引迁移、首次全量、增量、历史回补和镜像校准,由开发者的 Codex 自主完成,无需负责人逐次授权或代执行。Codex 自行核对来源与范围、备份受影响的配置/镜像及同步状态,使用生产同步节点和现有互斥锁分批执行,并核对源数据、完成状态与真实页面;不把这些工作转交给新人。可从上游重建的镜像修复属于此范围;上游写入、原始业务/财务数据修改、无关数据删除、凭据轮换和覆盖生产连接配置仍需单独授权。 - `caiwu_system_config` 保存用户、权限、设置、连接资料、数据字典和同步状态;`caiwu_business_mirror` 保存项目已正式接入的上游业务数据。二者不是 SQL Server 网络代理。 - 上游数据库统一按只读黑盒处理。业务查询使用固定、参数化的 Repository/查询执行器,禁止把用户输入拼成 SQL 或执行写操作。 - 正式页面优先读取共享业务镜像;尚未迁移的旧页面可继续使用现有快照兼容层。接入新数据时沿用现有镜像数据集、稳定游标、断点同步和同步状态模式,不另造一套链路。 @@ -68,7 +68,7 @@ - Windows 开发机统一使用 `scripts/deploy-from-workstation.ps1`。服务器只运行开发机已构建的 `caiwu_akaunting:` 镜像,禁止在服务器执行 Composer、npm 或 Docker 构建。 - 新人只需表达部署需求;Codex 使用默认生产入口运行脚本。首次通过本机窗口提供一次服务器密码后,加密保存在本人电脑供后续自动使用,不要求新人准备私钥、执行命令或每次重输密码。已有私钥认证仍兼容。 - 当前生产入口为 `https://caiwu.jiansuntuzhi.cn:8442`;公网仍只使用 `8442`,日常发布不得改成无端口地址。 -- 发布脚本检测到新增数据库迁移时必须停止,取得负责人明确授权并完成备份后才能使用迁移开关。 +- 发布脚本检测到新增数据库迁移时,由 Codex 核对全部待执行迁移。仅涉及本任务共享镜像建表、字段、索引和同步登记的迁移,完成备份后自主使用 `-AllowMigrations`;其他迁移仍按第 6 节确认授权。不能因需要迁移开关就把镜像接入停给负责人。 - 容器内 Laravel 命令使用 `www-data`。发布后只需确认部署 SHA、应用容器健康、受影响的真实页面/接口、迁移是否执行,以及当前和上一版镜像可回滚。 - 程序静态资源随应用镜像同源发布;七牛只存用户上传的业务图片、票据和附件。 - 只有本地初始化、服务器维护、生产发布或数据库迁移任务需要读取 `docs/开发与部署SOP.md` 的对应章节;普通功能开发无需加载整份 SOP。 diff --git a/app/Console/Commands/RegisterBusinessMirror.php b/app/Console/Commands/RegisterBusinessMirror.php index a6c96d17..f3f4bbc8 100644 --- a/app/Console/Commands/RegisterBusinessMirror.php +++ b/app/Console/Commands/RegisterBusinessMirror.php @@ -15,10 +15,10 @@ class RegisterBusinessMirror extends Command {--keys= : 逗号分隔的稳定唯一键} {--columns= : 逗号分隔的明确同步字段,必须包含稳定键及增量字段} {--watermark= : 可靠更新时间字段;留空为仅按主键追加} - {--enable-sync : 启用并批准可断点首次同步及后续增量} + {--enable-sync : 启用可断点首次同步及后续增量} {--disable-sync : 停用此数据集的自动同步,保留镜像数据}'; - protected $description = '登记声明式镜像数据集;生产启用前需获得同步范围授权'; + protected $description = '登记声明式镜像数据集;核对范围并备份后可直接启用同步'; public function handle(BusinessMirrorDatasetRegistry $datasets, UpstreamSourceRegistry $sources): int { diff --git a/app/Console/Commands/SyncProductCatalogMirror.php b/app/Console/Commands/SyncProductCatalogMirror.php index 9e245d94..9034d978 100644 --- a/app/Console/Commands/SyncProductCatalogMirror.php +++ b/app/Console/Commands/SyncProductCatalogMirror.php @@ -58,7 +58,7 @@ class SyncProductCatalogMirror extends Command } if ($result['status'] === 'requires_full_sync') { - $this->warn('普通商品尚未完成首次全量同步,需经授权后显式使用 --full。'); + $this->warn('普通商品尚未完成首次全量同步,请完成备份后显式使用 --full。'); return self::SUCCESS; } diff --git a/app/Console/Commands/SyncProductPurchasePriceMirror.php b/app/Console/Commands/SyncProductPurchasePriceMirror.php index 36314e84..f657358b 100644 --- a/app/Console/Commands/SyncProductPurchasePriceMirror.php +++ b/app/Console/Commands/SyncProductPurchasePriceMirror.php @@ -42,7 +42,7 @@ class SyncProductPurchasePriceMirror extends Command } if ($result['status'] === 'requires_full_sync') { - $this->warn('采购单价尚未完成首次全量同步,需经授权后显式使用 --full。'); + $this->warn('采购单价尚未完成首次全量同步,请完成备份后显式使用 --full。'); return self::SUCCESS; } diff --git a/docs/team-collaboration.md b/docs/team-collaboration.md index e4ef257f..46ecaeb3 100644 --- a/docs/team-collaboration.md +++ b/docs/team-collaboration.md @@ -118,7 +118,7 @@ Codex 在合并前必须进入一次独立自审,不得直接沿用开发阶 请进入独立的合并前自审,不要直接沿用开发阶段的完成结论。重新 fetch、读取原始需求和验收标准,并以 origin/main...当前任务分支的完整 diff 为准逐文件审核。检查工作区、WIP 状态、修改边界、公共契约、远程支线重叠、敏感内容、测试证据和目标 main。条件全部满足后,使用 Squash merge 合并到 main,核对远程 main 已包含目标改动,再验证实际页面或接口并删除已合并任务分支。禁止强推;如有冲突、测试失败、自审不通过或涉及尚未授权的生产迁移/数据操作,立即停止并报告。 ``` -日常 PR 自审、合并、主线验证、普通代码部署与验收和分支清理由任务开发者的 Codex 完成,不需要另一位开发者或项目负责人参与,也无需另行取得普通部署授权。开发者不手工执行 Git 合并命令,也不能绕过 PR;用户明确要求暂不上线时遵循其范围。涉及生产迁移、数据修复、删除或覆盖配置时,继续执行仓库现有高风险授权规则。 +日常 PR 自审、合并、主线验证、普通代码部署与验收和分支清理由任务开发者的 Codex 完成,不需要另一位开发者或项目负责人参与,也无需另行取得普通部署授权。开发者不手工执行 Git 合并命令,也不能绕过 PR;用户明确要求暂不上线时遵循其范围。本任务上游接入、共享镜像迁移、首次全量、回补和校准由 Codex 自主完成备份、执行与验收,无需负责人重复授权或代操作;其他生产迁移、数据修复、删除或覆盖配置继续按 `AGENTS.md` 执行。 ## PR 落后或发生冲突 diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index bd2f4262..1c276d68 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -70,13 +70,13 @@ 1. 首次全量只能通过 `business-mirror:sync-tables --full` 显式启动;失败或中断后使用同一命令继续。 2. 日常任务只处理已经完成首次全量的数据集。存在可靠更新时间的表使用 48 小时重叠窗口;没有可靠更新时间的表按稳定主键追加。`rpt.jst_sku` 由普通商品专用任务每分钟优先处理,每轮默认最多 5 批、每批 1000 行,不再参加通用数据集轮转。 3. 全量校准使用新的同步代次,只有全部完成后才删除镜像中本轮未出现的旧行,因此中途失败不会清空当前可用数据。 -4. 普通商品在最近完整校准超过 168 小时后,于周日 02:00-08:00 低峰窗口启动全量校准;一旦启动,后续每分钟从稳定游标继续,直至完整结束。首次全量仍必须显式授权,不能由定时任务自行启动。 +4. 普通商品在最近完整校准超过 168 小时后,于周日 02:00-08:00 低峰窗口启动全量校准;一旦启动,后续每分钟从稳定游标继续,直至完整结束。首次全量由 Codex 备份后自主执行,定时任务保持既有初始化开关。 5. 除专用数据集外,通用任务每轮默认只处理 1 个数据集、每个数据集 2 批,每批 500 行,避免同时压迫两个旧系统。 6. 页面切换必须以“总记录数、第一页、第二页、末页、筛选、汇总、空数据和更新时间”作为验收,不能只看首页有数据。 7. 普通商品的采购单价同步以采购主表 `updateTime` 加明细 `Id` 作为稳定游标;页面按商品编码选择最近完成的 1688 一键代发价格。同步保存全部状态,使完成单后续取消时也能撤回旧价格;首次全量前只显示普通商品自身采购价。 8. 聚水潭官方接口尚未接入时,普通商品历史残留排除由负责人提供的最新完整 XLSX 导出刷新。只排除“导出生成前已创建、但导出中缺失”的镜像行,导出生成后的新增商品保持可见。导入使用新同步代次,只有完整解析成功才原子替换排除表;中断或错误保留上一版。后续接入聚水潭官方“普通商品资料查询”及删除/恢复记录后,由官方接口取代人工导出校准。 9. 店铺维度报表是已批准的中央专用数据集:生产节点按 `Id` 断点推进并回看最近 50000 行;原始账单同步后增量维护按店铺/日期汇总的 `store_report_daily_rows`,页面不得现场扫描千万级原始账单。开发机不运行刷新 worker。 -10. `operations_replica.rpt.jst_originalBillInfo` 是供多个业务功能复用的原始账单镜像。首次同步必须单独授权并在低峰期分批续传;部署、页面请求和普通开发机均不得自动启动。同步完成后,开发者通过固定 Repository 查询 `ops_jst_original_bill_info`,不得各自创建整表快照。 +10. `operations_replica.rpt.jst_originalBillInfo` 是供多个业务功能复用的原始账单镜像。首次同步由 Codex 备份后自主安排在生产同步节点低峰期分批续传,无需另行授权;页面请求和普通开发机不启动刷新 worker。同步完成后,开发者通过固定 Repository 查询 `ops_jst_original_bill_info`,不得各自创建整表快照。 ## 后续切换顺序 @@ -102,7 +102,7 @@ php artisan business-mirror:sync-tables operations_replica.rpt.work_order_form_c php artisan business-mirror:sync-tables operations_replica.rpt.work_order_form_value --full ``` -聚工单“小额打款”两个数据集同样必须在备份和负责人首次写入授权后分别执行全量同步;页面不会在 HTTP 请求中回退直连 `jiansun`: +聚工单“小额打款”两个数据集由 Codex 备份后自主分别执行全量同步;页面不会在 HTTP 请求中回退直连 `jiansun`: ```bash php artisan business-mirror:sync-tables jiansun.dbo.jst_workOrderInfo --full diff --git a/docs/开发与部署SOP.md b/docs/开发与部署SOP.md index 7ad7db0c..94088872 100644 --- a/docs/开发与部署SOP.md +++ b/docs/开发与部署SOP.md @@ -29,7 +29,7 @@ 服务器永远不构建源码。 -普通代码发布在相关验证通过、自审并合并到最新 `main` 后,由任务 Codex 按本 SOP 直接部署并验收,无需用户再次授权部署;用户明确要求暂不上线时遵循其范围。数据库迁移、数据修复、删除和覆盖配置仍按 `AGENTS.md` 的授权边界执行。 +普通代码发布在相关验证通过、自审并合并到最新 `main` 后,由任务 Codex 按本 SOP 直接部署并验收,无需用户再次授权部署;用户明确要求暂不上线时遵循其范围。本任务所需的共享镜像接入、迁移和同步由 Codex 按 `AGENTS.md` 自主完成;其他数据库迁移、数据修复、删除和覆盖配置仍按其授权边界执行。 ## 2. 每台开发机只做一次的设置 @@ -132,7 +132,7 @@ git pull --ff-only 默认禁止自动迁移。脚本发现上次部署后新增了 `database/migrations` 文件时会停止。 -只有负责人明确批准、PR 已写清影响与回滚思路后,才允许: +Codex 先核对全部待执行迁移,并准备受影响数据的备份与回滚。仅涉及本任务共享镜像建表、字段、索引和同步登记时,自主执行以下命令,无需负责人另行批准;其他迁移仍按 `AGENTS.md` 的授权边界执行: ```powershell .\scripts\deploy-from-workstation.ps1 ` @@ -140,7 +140,7 @@ git pull --ff-only -AllowMigrations ``` -镜像回滚不能自动撤销已经执行的数据库结构变更,因此迁移授权必须单独处理。 +应用镜像回滚不能自动撤销数据库结构变更;Codex 必须为本次迁移保留对应的数据备份和恢复路径。 ## 7. 测试分支发布 @@ -154,7 +154,7 @@ git pull --ff-only ## 8. 多上游财务数据库同步 -新数据库和新数据集优先使用 [通用上游数据接入](通用上游数据接入.md):来源由连接记录自动登记,已批准的声明式数据集由调度自动首次同步和增量同步。下面的固定来源、逐项 `--full` 和旧快照说明适用于既有兼容路径,不应当作为新增普通开发任务的重复审批要求。 +新数据库和新数据集优先使用 [通用上游数据接入](通用上游数据接入.md):来源由连接记录自动登记,已启用的声明式数据集由调度自动首次同步和增量同步。下面的固定来源、逐项 `--full` 和旧快照说明适用于既有兼容路径,不应当作为新增普通开发任务的重复审批要求。 ### 8.1 统一接入边界 @@ -236,7 +236,7 @@ php artisan business-mirror:sync-tables 完整数据集、来源对象、镜像表和分阶段切换状态见 `docs/上游业务镜像清单.md`。不得把“已登记同步目录”误报成“页面已经切换完成”;每个业务域仍需在首份全量核对通过后,把对应 Repository 改为只读镜像。 -首次 `--full` 属于生产数据写入,必须先备份 `caiwu_system_config` 和 `caiwu_business_mirror`,并由负责人明确授权。已经在发布说明中批准自动初始化的中央专用数据集,由生产节点在迁移授权后小批量续传;普通开发者不配置、不启动也不审批这些任务。后续无参数命令只执行或继续受控增量。 +首次全量、历史回补和镜像校准由任务 Codex 自主执行:先备份受影响的系统配置、镜像表及同步状态,再在生产同步节点内使用现有上游互斥锁,按稳定游标分批执行或续传 `--full`,直至完成并核对源表/镜像和实际页面。无需负责人另行授权或代跑命令;开发机驱动不支持时直接通过 SSH 使用生产容器,不以本机不能同步为由停止任务。后续无参数命令只执行或继续受控增量,不对无关数据集批量全量。 ### 8.3 开发者需要尚未接入的上游数据时 @@ -272,7 +272,7 @@ php artisan upstream:schema:sync operations_replica 3. **登记同步契约**:定义稳定且可审查的数据集键、上游业务键、同步游标、重叠窗口和镜像表。参数必须有限制,批次必须有稳定排序和行数上限; 4. **分支内完成自动测试**:使用脱敏 fixture 或测试替身验证正常、空数据和不可用状态;开发机能够直连时,通过通用只读入口或新 Repository 用少量真实只读数据验证,不得在测试、日志或截图中输出凭据和敏感业务行; 5. **本地直接验证**:开发阶段可以直接执行固定只读查询确认数据;正式页面测试使用隔离镜像库 fixture,不依赖负责人环境; -6. **生产首次同步**:代码审查和测试通过后合并到 `main`;经数据库写入授权后创建镜像表并执行可断点的首次全量; +6. **生产首次同步**:代码审查和测试通过后合并到 `main`;由 Codex 完成受影响数据备份后自主创建镜像表并执行可断点的首次全量; 7. **完成共享验收**:确认同步状态成功、镜像总数和筛选计数与上游限定查询一致,第二页或末页可读;随后从第二个应用实例读取相同镜像,并证明页面没有再次访问上游; 8. **发现压力立即收口**:慢查询、返回量异常或上游告警时,先从共享记录移除该精确范围并保留证据,再缩小字段、时间窗或分页。禁止通过提高并发、扩大 `*` 或全表扫描解决。 diff --git a/docs/通用上游数据接入.md b/docs/通用上游数据接入.md index 619c63a3..14ba7d81 100644 --- a/docs/通用上游数据接入.md +++ b/docs/通用上游数据接入.md @@ -22,7 +22,7 @@ php artisan business-mirror:register database_17 public example_orders \ --keys=id --columns=id,updated_at,label --watermark=updated_at ``` -登记默认不启动同步。生产首次同步涉及系统库登记和业务镜像表创建/写入,应先说明精确字段、批次、影响及备份,再取得负责人授权。授权后对同一声明追加 `--enable-sync`,生产调度即可自动完成或续传首次全量,完成后转为增量;不再为每次部署、分页、筛选重新审批或生成快照。`--disable-sync` 停止后续自动执行,保留已有镜像。 +登记默认不启动同步。Codex 根据当前功能需求核对精确字段、批次和影响,备份受影响的配置、镜像与同步状态后,自主对同一声明追加 `--enable-sync`;生产调度即可自动完成或续传首次全量,完成后转为增量,无需负责人另行授权。登记和启用均由 Codex 执行,不让新人处理开关或命令。`--disable-sync` 停止后续自动执行,保留已有镜像。 声明式登记不能覆盖代码维护的数据集,也不能悄悄修改已有声明的稳定键、字段和增量口径;此类变化需评估历史数据/游标兼容性。来源表没有可靠更新时间时只按主键追加,不能承诺自动发现历史修改或删除,需另行声明校准策略。 @@ -46,12 +46,12 @@ php artisan business-mirror:register database_17 public example_orders \ 通用调度默认每轮最多8个数据集、30秒周期预算;未完成窗口与常规数据集交替处理,单数据集默认8秒软预算,积压任务默认最多6批。预算在批次之间检查,单条查询仍受驱动超时限制;不提高上游并发。失败任务至少冷却5分钟。专用商品/价格/钉钉调度保持既有路径。 -只对明确批准的登记数据集自动首次同步;既有代码数据集仍保留原首次授权流程。未完成的旧页面切换不等于已经上线,必须逐页验收并与正在开发的 PR 协调。 +调度只对已启用的登记数据集自动首次同步;`initial_sync_approved` 是兼容保留的初始化开关,由 Codex 使用 `--enable-sync` 一并设置,不代表需要负责人审批。既有代码数据集由 Codex 自主在生产同步节点执行对应的 `--full`,沿用互斥锁、分批、断点和验收。未完成的旧页面切换不等于已经上线,必须逐页验收并与正在开发的 PR 协调。 ## 类型及验收 - PostgreSQL 带时区时间戳在镜像中保存为 UTC;业务展示按自己的明确时区换算。无时区日期时间保留原值。`bytea` 使用十六进制文本表示;不自动解释 JSON、数组、枚举中的业务语义。 -- 验收包含:没有修改来源枚举也能发现新库;TLS/只读保护;字段目录;只复制明确字段;首次同步、第二页、末页、总数和筛选;增量插入与更新;源不可达时读旧镜像;失败和未授权状态。 +- 验收包含:没有修改来源枚举也能发现新库;TLS/只读保护;字段目录;只复制明确字段;首次同步、第二页、末页、总数和筛选;增量插入与更新;源不可达时读旧镜像;失败和未启用状态。 - SQL Server 既有 Repository 与专用同步器需回归。不得把“新连接测试成功”当作全项目页面已迁移或所有业务表已同步。 ## 系统连接保存后回滚的排查 diff --git a/scripts/deploy-from-workstation.ps1 b/scripts/deploy-from-workstation.ps1 index d1ef5467..a89422bd 100644 --- a/scripts/deploy-from-workstation.ps1 +++ b/scripts/deploy-from-workstation.ps1 @@ -369,7 +369,7 @@ try { } if ($previousSha -and -not $previousShaExists -and -not $AllowMigrations) { - throw "本地缺少服务器当前提交 $previousSha,无法安全比较数据库迁移。请先 git fetch,或在负责人授权后使用 -AllowMigrations。" + throw "本地缺少服务器当前提交 $previousSha,无法安全比较数据库迁移。请先 git fetch 并核对全部待执行迁移,按 AGENTS.md 完成备份后使用 -AllowMigrations。" } if ($previousSha -and $previousShaExists) { @@ -377,7 +377,7 @@ try { database/migrations ` ':(glob)modules/*/Database/Migrations/*.php' if ($migrationChanges -and -not $AllowMigrations) { - throw "检测到数据库迁移:$($migrationChanges -join ', ')。需负责人确认后添加 -AllowMigrations。" + throw "检测到数据库迁移:$($migrationChanges -join ', ')。由 Codex 核对全部待执行迁移;本任务镜像迁移完成备份后可直接添加 -AllowMigrations,其他迁移按 AGENTS.md 执行。" } }