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 1/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 2/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 3/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 执行。" } } From 01a2e6bfa87c092820a7a6bfec1868898471481a Mon Sep 17 00:00:00 2001 From: chenxi Date: Wed, 9 Sep 2026 13:21:38 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E8=B4=A2=E5=8A=A1?= =?UTF-8?q?=E8=B4=A6=E5=8D=95=E8=A1=A8=E6=A0=BC=E6=8E=92=E7=89=88=E4=B8=8E?= =?UTF-8?q?=E4=BA=A4=E4=BA=92=20(#139)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Http/Controllers/AccountBills.php | 61 ++ .../Http/Controllers/AlipayBills.php | 71 ++- .../js/components/business/AccountBills.vue | 372 ++---------- .../business/TableColumnSettings.vue | 224 ++++++++ .../components/business/TaobaoAlipayBills.vue | 537 +++--------------- resources/views/business/pages/show.blade.php | 1 + 6 files changed, 492 insertions(+), 774 deletions(-) create mode 100644 resources/assets/js/components/business/TableColumnSettings.vue 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/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/show.blade.php b/resources/views/business/pages/show.blade.php index 416d3a0f..540626c1 100644 --- a/resources/views/business/pages/show.blade.php +++ b/resources/views/business/pages/show.blade.php @@ -1060,6 +1060,7 @@ 'biz-card mt-6', 'business-blank-page' => ($page['slug'] ?? null) === 'store-receiving-bills', ]) + @if (($page['slug'] ?? null) === 'store-receiving-bills') data-table-preferences-user="{{ user()->id }}" @endif aria-label="{{ $activeTab['title'] ?? ($page['title'] ?? $section['title']) }}" >
From 5dcab54e0697949495a9217e03c276b4f1122e8b Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Wed, 9 Sep 2026 13:56:38 +0800 Subject: [PATCH 5/5] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E7=BA=BF?= =?UTF-8?q?=E4=B8=8A=E4=BB=A3=E5=8F=91=E4=BB=B7=E6=A0=BC=E7=AD=9B=E9=80=89?= =?UTF-8?q?=E5=92=8C=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Http/Controllers/Business/Pages.php | 111 ++++++++++-- ..._09_130000_add_daifa_material_no_index.php | 51 ++++++ .../DingOnlineDaifaPriceMirrorRepository.php | 159 ++++++++++++------ .../online-daifa-price.blade.php | 9 + routes/admin.php | 4 + .../Business/OnlineDaifaPricePageTest.php | 99 +++++++++++ ...gPayableWorkflowMirrorSynchronizerTest.php | 39 +++++ 7 files changed, 407 insertions(+), 65 deletions(-) create mode 100644 database/migrations/2026_09_09_130000_add_daifa_material_no_index.php 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/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/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 @@ +
+ + +
+
+ + +