diff --git a/AGENTS.md b/AGENTS.md index 1883d235..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 直接部署和验收,无需另行取得部署授权。上游接入和共享镜像同步按第 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 或执行写操作。 - 正式页面优先读取共享业务镜像;尚未迁移的旧页面可继续使用现有快照兼容层。接入新数据时沿用现有镜像数据集、稳定游标、断点同步和同步状态模式,不另造一套链路。 @@ -64,10 +64,11 @@ ## 8. 构建与生产部署 -- 只有用户明确要求“部署、上线”时才执行生产发布;正式发布只使用已合并的最新 `main`。 +- 普通代码发布由任务 Codex 在完成验证与合并后直接执行,不要求用户再次说“部署、上线”;用户明确要求仅本地开发、仅审查或暂不上线时遵循其范围。正式发布只使用已合并的最新 `main`。 - 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/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 712c8e08..df0ca982 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -742,20 +742,7 @@ 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', '')), - ]; + $filters = $this->onlineDaifaPriceFilters(request()); $page = max((int) request('page', 1), 1); $limit = min(max((int) setting('default.list_limit', 25), 1), 100); @@ -795,6 +782,86 @@ class Pages extends Controller } } + public function exportOnlineDaifaPrice(Request $request): StreamedResponse + { + abort_unless($this->onlineDaifaPrices->ready(), 503); + + $filters = $this->onlineDaifaPriceFilters($request); + + return response()->streamDownload(function () use ($filters): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new \RuntimeException('无法创建线上代发价格导出流。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, [ + '审批编号', '标题', '状态', '申请人', '收款人全称', '商品ID', '商品名称(匹配)', '店铺名称', + '代发交易单号', '店铺交易单号', '发货数量', '订单实付金额', '代发订单金额', '差价', + '供应商名称', '料号', '创建时间', + ]); + + foreach ($this->onlineDaifaPrices->exportRows($filters) as $row) { + $workflow = (array) ($row['workflow'] ?? []); + $approvalNumber = trim((string) ($workflow['businessId'] ?? '')) ?: (string) ($row['process_instance_id'] ?? ''); + $originator = trim((string) ($workflow['originatorUserName'] ?? '')) + ?: trim((string) ($workflow['originatorUserId'] ?? '')); + $matchedProduct = (array) ($row['matched_product'] ?? []); + $productName = ($matchedProduct['matched'] ?? false) + ? (string) ($matchedProduct['name'] ?? '') + : '(未匹配)'; + + fputcsv($csv, [ + $this->csvIdentifier($approvalNumber), + $this->csvText($workflow['title'] ?? ''), + $this->csvText($row['status_label'] ?? ''), + $this->csvText($originator), + $this->csvText($row['payee_name'] ?? ''), + $this->csvIdentifier($row['product_id'] ?? ''), + $this->csvText($productName), + $this->csvText($row['shop_name'] ?? ''), + $this->csvIdentifier($row['daifa_trade_no'] ?? ''), + $this->csvIdentifier($row['shop_trade_no'] ?? ''), + $row['ship_qty'] ?? null, + $row['paid_amount'] ?? null, + $row['daifa_amount'] ?? null, + $row['price_diff'] ?? null, + $this->csvText($row['supplier_name'] ?? ''), + $this->csvIdentifier($row['material_no'] ?? ''), + $this->csvText($row['workflow_created_at'] ?? ''), + ]); + } + + fclose($csv); + }, '线上代发价格_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** @return array */ + private function onlineDaifaPriceFilters(Request $request): 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->query('status', '')), 0, 30)); + + return [ + 'keyword' => $clean($request->query('keyword', ''), 80), + 'product_id' => $clean($request->query('product_id', ''), 64), + 'shop_name' => $clean($request->query('shop_name', ''), 120), + 'supplier_name' => $clean($request->query('supplier_name', ''), 120), + 'material_no' => $clean($request->query('material_no', ''), 120), + 'status' => preg_match('/^[A-Z_]+$/', $status) === 1 ? $status : '', + 'created_from' => $date($request->query('created_from', '')), + 'created_to' => $date($request->query('created_to', '')), + ]; + } + protected function contentForJingxiRefundData(): array { return [ @@ -2009,6 +2076,22 @@ class Pages extends Controller return preg_match('/^[=+\-@]/u', $text) === 1 ? "'" . $text : $text; } + /** + * Export identifiers as text so Excel does not round or truncate long IDs. + * Keep the formula-injection guard from csvText for values beginning with a + * formula marker. + */ + private function csvIdentifier(mixed $value): string + { + $text = $this->csvText($value); + + if ($text === '' || str_starts_with($text, "'")) { + return $text; + } + + return "'" . $text; + } + private function emptyProductCatalogContent( array $filters, int $limit, diff --git a/database/migrations/2026_09_09_130000_add_daifa_material_no_index.php b/database/migrations/2026_09_09_130000_add_daifa_material_no_index.php new file mode 100644 index 00000000..a7ef1d83 --- /dev/null +++ b/database/migrations/2026_09_09_130000_add_daifa_material_no_index.php @@ -0,0 +1,51 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable(self::TABLE) || $schema->hasIndex(self::TABLE, self::INDEX)) { + return; + } + + $schema->table(self::TABLE, function (Blueprint $table): void { + $table->index('material_no', self::INDEX); + }); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable(self::TABLE) || ! $schema->hasIndex(self::TABLE, self::INDEX)) { + return; + } + + $schema->table(self::TABLE, function (Blueprint $table): void { + $table->dropIndex(self::INDEX); + }); + } +}; diff --git a/docs/team-collaboration.md b/docs/team-collaboration.md index 3f97d2b3..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 cb0b8d15..94088872 100644 --- a/docs/开发与部署SOP.md +++ b/docs/开发与部署SOP.md @@ -29,6 +29,8 @@ 服务器永远不构建源码。 +普通代码发布在相关验证通过、自审并合并到最新 `main` 后,由任务 Codex 按本 SOP 直接部署并验收,无需用户再次授权部署;用户明确要求暂不上线时遵循其范围。本任务所需的共享镜像接入、迁移和同步由 Codex 按 `AGENTS.md` 自主完成;其他数据库迁移、数据修复、删除和覆盖配置仍按其授权边界执行。 + ## 2. 每台开发机只做一次的设置 新人只负责启动 Docker Desktop、在网页中登录,以及输入一次系统数据库密码。下面涉及仓库、脚本、构建、迁移、缓存、容器、数据库验证和排错的动作均由 Codex 执行,不能把命令转交给新人。 @@ -37,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. 为什么后续不会反复全量下载和上传 @@ -69,7 +73,6 @@ ```powershell .\scripts\deploy-from-workstation.ps1 ` -Server 218.93.190.75 ` - -KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem" ` -BootstrapServer ``` @@ -96,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 ``` 脚本自动完成: @@ -131,16 +132,15 @@ git pull --ff-only 默认禁止自动迁移。脚本发现上次部署后新增了 `database/migrations` 文件时会停止。 -只有负责人明确批准、PR 已写清影响与回滚思路后,才允许: +Codex 先核对全部待执行迁移,并准备受影响数据的备份与回滚。仅涉及本任务共享镜像建表、字段、索引和同步登记时,自主执行以下命令,无需负责人另行批准;其他迁移仍按 `AGENTS.md` 的授权边界执行: ```powershell .\scripts\deploy-from-workstation.ps1 ` -Server 218.93.190.75 ` - -KeyPath "C:\Users\你的用户名\.ssh\caiwu.pem" ` -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/modules/EcommerceFinance/Http/Controllers/AccountBills.php b/modules/EcommerceFinance/Http/Controllers/AccountBills.php index 1b8e5104..beccc706 100644 --- a/modules/EcommerceFinance/Http/Controllers/AccountBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AccountBills.php @@ -25,6 +25,17 @@ class AccountBills extends Controller abort(404, '未知的账户类型。'); } + $request->validate([ + 'store_name' => ['nullable', 'string', 'max:255'], + 'bill_item' => ['nullable', 'string', 'max:255'], + 'start' => ['nullable', 'date_format:Y-m-d'], + 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], + 'keyword' => ['nullable', 'string', 'max:255'], + 'export' => ['nullable', 'boolean'], + 'columns' => ['nullable', 'array', 'max:40'], + 'columns.*' => ['string', 'max:128'], + ]); + $query = AccountBill::query() ->where('company_id', company_id()) ->where('bill_type', $billType); @@ -60,6 +71,10 @@ class AccountBills extends Controller $dir = $request->get('dir') === 'asc' ? 'asc' : 'desc'; $query->orderBy($sort, $dir); + if ($request->boolean('export')) { + return $this->export($request, $query, $billType); + } + $perPage = min(max((int) $request->get('limit', 10), 1), 100); $rows = $query->paginate($perPage); @@ -87,6 +102,52 @@ class AccountBills extends Controller return response()->json($data); } + private function export(Request $request, $query, string $billType) + { + $definition = AccountBillColumns::for($billType); + $available = collect($definition['columns'] ?? [])->keyBy('field'); + $requested = $request->input('columns', []); + $columns = $requested === [] + ? $available->values() + : collect($requested)->unique()->map(fn (string $field) => $available->get($field))->filter()->values(); + + abort_if($columns->isEmpty(), 422, '至少选择一个可导出的字段。'); + + return response()->streamDownload(function () use ($query, $columns): void { + $csv = fopen('php://output', 'w'); + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, $columns->pluck('label')->all()); + + foreach ($query->cursor() as $row) { + fputcsv($csv, $columns->map(function (array $column) use ($row): string { + $value = $this->columnValue($row, $column['field']); + + return $this->csvValue($value, $column['kind']); + })->all()); + } + fclose($csv); + }, $billType . '_account_bills.csv', ['Content-Type' => 'text/csv; charset=UTF-8']); + } + + private function columnValue(AccountBill $row, string $field): mixed + { + if (str_starts_with($field, 'payload.')) { + return data_get($row->payload ?? [], substr($field, 8), ''); + } + + return $row->getAttribute($field) ?? ''; + } + + private function csvValue(mixed $value, string $kind): string + { + $text = (string) ($value ?? ''); + if ($kind === 'num' && preg_match('/^\d{12,}$/', $text)) { + return "\t" . $text; + } + + return preg_match('/^[=+\-@]/', $text) ? "'" . $text : $text; + } + public function show(AccountBill $bill) { $this->authorizeStoreReceivingBills(); diff --git a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php index 7cdcf6bc..14471a83 100644 --- a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php @@ -11,6 +11,34 @@ use RuntimeException; class AlipayBills extends Controller { + private const EXPORT_COLUMNS = [ + 'record_code' => '记录编码', + 'store_name' => '原始店铺', + 'custom_remark' => '自定义备注', + 'bill_item' => '账单项目', + 'alipay_account' => '平台渠道', + 'account_order_no' => '账务订单号', + 'business_serial_no' => '业务流水号', + 'merchant_order_no' => '商户订单号', + 'business_base_order_no' => '业务基础订单号', + 'goods_name' => '商品编码', + 'counterparty_account' => '对方账号', + 'occurred_at' => '发生时间', + 'income' => '收入', + 'expense' => '支出', + 'balance' => '收支净额', + 'business_type' => '业务类型', + 'remark' => '备注', + 'online_order_no' => '线上单号', + 'online_real_store' => '线上单号对应实际店铺', + 'business_description' => '业务描述', + 'business_bill_source' => '业务账单来源', + 'business_order_no' => '业务订单号', + 'created_at' => '创建时间', + 'updated_at' => '修改时间', + 'modifier' => '修改人', + ]; + /** * 淘系支付宝账户账单列表(店铺收款账户账单 › 淘系支付宝账户)。 * 经由 admin 路由组(web 会话)暴露,前端带 CSRF 调用即可。 @@ -68,8 +96,13 @@ class AlipayBills extends Controller 'start' => ['nullable', 'date_format:Y-m-d'], 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], 'keyword' => ['nullable', 'string', 'max:255'], + 'columns' => ['nullable', 'array', 'max:25'], + 'columns.*' => ['string', 'max:64'], ]); + $columns = $this->requestedExportColumns($filters['columns'] ?? []); + unset($filters['columns']); + try { $rows = $repository->exportRows(array_map(static fn (mixed $value): string => trim((string) $value), $filters)); } catch (RuntimeException $exception) { @@ -80,17 +113,49 @@ class AlipayBills extends Controller return response()->json(['message' => '淘系支付宝账单共享业务镜像正在首次同步,完成后将自动显示。'], 503); } - return response()->streamDownload(function () use ($rows): void { + return response()->streamDownload(function () use ($rows, $columns): void { $csv = fopen('php://output', 'w'); fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); - fputcsv($csv, ['记录编码', '原始店铺', '平台渠道', '账单项目', '账务订单号', '业务流水号', '商户订单号', '业务基础订单号', '商品编码', '发生时间', '收入(元)', '支出(元)', '收支净额(元)', '收支类型', '线上单号', '业务描述', '业务账单来源', '创建时间', '修改时间']); + fputcsv($csv, array_values($columns)); foreach ($rows as $row) { - fputcsv($csv, [$row['record_code'], $row['store_name'], $row['alipay_account'], $row['bill_item'], $row['account_order_no'], $row['business_serial_no'], $row['merchant_order_no'], $row['business_base_order_no'], $row['goods_name'], $row['occurred_at'], $row['income'], $row['expense'], $row['balance'], $row['business_type'], $row['online_order_no'], $row['business_description'], $row['business_bill_source'], $row['created_at'], $row['updated_at']]); + fputcsv($csv, array_map( + fn (string $field): string => $this->csvValue($row[$field] ?? '', $field), + array_keys($columns), + )); } fclose($csv); }, 'taobao_alipay_bills.csv', ['Content-Type' => 'text/csv; charset=UTF-8']); } + /** @return array */ + private function requestedExportColumns(array $requested): array + { + if ($requested === []) { + return self::EXPORT_COLUMNS; + } + + $columns = []; + foreach ($requested as $field) { + if (isset(self::EXPORT_COLUMNS[$field])) { + $columns[$field] = self::EXPORT_COLUMNS[$field]; + } + } + + abort_if($columns === [], 422, '至少选择一个可导出的字段。'); + + return $columns; + } + + private function csvValue(mixed $value, string $field): string + { + $text = (string) ($value ?? ''); + if (preg_match('/(?:_no|_code|serial|goods_name)$/', $field) && preg_match('/^\d{12,}$/', $text)) { + return "\t" . $text; + } + + return preg_match('/^[=+\-@]/', $text) ? "'" . $text : $text; + } + public function show(AlipayBill $bill) { $this->authorizeStoreReceivingBills(); diff --git a/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php index 301c24b8..53bec88a 100644 --- a/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/DingOnlineDaifaPriceMirrorRepository.php @@ -3,6 +3,7 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Database\ConnectionInterface; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\DingPayableWorkflowStatus; use RuntimeException; @@ -51,6 +52,66 @@ class DingOnlineDaifaPriceMirrorRepository $perPage = min(max($perPage, 1), 100); $state = $this->connection->table('business_mirror_table_states')->where('dataset_key', self::DATASET_KEY)->first(); + $rows = $this->filteredQuery($filters) + ->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 (! $this->matchesStatus($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, []); + $data[] = $this->presentRow($row, $workflow); + } + + 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), + ]; + } + + /** @return \Generator> */ + public function exportRows(array $filters): \Generator + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $statusFilter = strtoupper(trim((string) ($filters['status'] ?? ''))); + $rows = $this->filteredQuery($filters) + ->orderByDesc('workflow_created_at') + ->orderByDesc('process_instance_id') + ->orderByDesc('detail_index') + ->cursor(); + + foreach ($rows as $row) { + $workflow = $this->decode((string) $row->workflow_payload, []); + if (! $this->matchesStatus($workflow, $statusFilter)) { + continue; + } + + yield $this->presentRow($row, $workflow); + } + } + + private function filteredQuery(array $filters): Builder + { $query = $this->connection->table(self::TARGET_TABLE); if (($filters['product_id'] ?? '') !== '') { @@ -59,6 +120,12 @@ class DingOnlineDaifaPriceMirrorRepository if (($filters['shop_name'] ?? '') !== '') { $query->where('shop_name', (string) $filters['shop_name']); } + if (($filters['supplier_name'] ?? '') !== '') { + $query->whereRaw("supplier_name LIKE ? ESCAPE '!'", [$this->contains((string) $filters['supplier_name'])]); + } + if (($filters['material_no'] ?? '') !== '') { + $query->where('material_no', (string) $filters['material_no']); + } if (($filters['keyword'] ?? '') !== '') { $keyword = (string) $filters['keyword']; $query->where(function ($q) use ($keyword): void { @@ -74,64 +141,54 @@ class DingOnlineDaifaPriceMirrorRepository $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(); + return $query; + } - $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; - } + private function matchesStatus(array $workflow, string $statusFilter): bool + { + return $statusFilter === '' || DingPayableWorkflowStatus::key($workflow) === $statusFilter; + } - $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 array */ + private function presentRow(object $row, array $workflow): array + { + $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]; 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), + '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 ?? ''), ]; } + private function contains(string $value): string + { + return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($value)) . '%'; + } + /** @param list $rows */ private function summary(array $rows): array { diff --git a/resources/assets/js/components/business/AccountBills.vue b/resources/assets/js/components/business/AccountBills.vue index 9a3dea5b..a32aed35 100644 --- a/resources/assets/js/components/business/AccountBills.vue +++ b/resources/assets/js/components/business/AccountBills.vue @@ -1,342 +1,72 @@ diff --git a/resources/assets/js/components/business/TableColumnSettings.vue b/resources/assets/js/components/business/TableColumnSettings.vue new file mode 100644 index 00000000..938a7441 --- /dev/null +++ b/resources/assets/js/components/business/TableColumnSettings.vue @@ -0,0 +1,224 @@ + + + + + diff --git a/resources/assets/js/components/business/TaobaoAlipayBills.vue b/resources/assets/js/components/business/TaobaoAlipayBills.vue index 6b5d9c6a..096997ae 100644 --- a/resources/assets/js/components/business/TaobaoAlipayBills.vue +++ b/resources/assets/js/components/business/TaobaoAlipayBills.vue @@ -1,482 +1,119 @@ 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 index d7abafdc..fbe11a8c 100644 --- a/resources/views/business/pages/product-inventory/online-daifa-price.blade.php +++ b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php @@ -66,6 +66,14 @@ +
+ + +
+
+ + +