cmvr-wms/scripts/projectdev/Backend-Local.ps1
lixiaolong cd86623061 feat(app): 添加服务器连接管理和到货操作功能
- 集成 ServerConnection 组件用于开发环境服务器切换
- 实现多服务器令牌隔离存储机制
- 添加 ArrivalOperation 屏幕处理到货和验收流程
- 支持待登记到货和待验收状态切换
- 优化库存操作界面的字段显示逻辑
- 增强 Excel 文件分片上传支持产品文件识别
- 添加 AI 助手会话滚动跟踪功能
- 实现开发服务器地址持久化存储
- 优化登录界面集成服务器连接组件
- 添加领用出库功能支持项目物资使用
- 改进盘点确认生效的操作流程
- 增强采购到货登记和验收的权限控制
- 优化移动端文件上传的断点续传机制
- 添加服务器切换时的数据清理保护机制
- 实现紧凑金额显示模式减少界面冗余
- 增强库存操作的数量验证和错误提示
- 优化 AI 助手的会话状态同步机制
2026-10-20 10:04:17 +08:00

105 lines
7.6 KiB
PowerShell

param(
[ValidateSet('Start','Restart','Stop','Status')][string]$Action='Start',
[switch]$RealDataReplay,
[switch]$HistoryEntry,
[string]$HistorySource=''
)
$ErrorActionPreference='Stop'
$taskRoot=(Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
$taskRuntime=Join-Path $taskRoot '.codex-tmp/local-services'
$taskStateFile=Join-Path $taskRuntime 'backend.json'
$taskIdentity=[Security.Principal.WindowsIdentity]::GetCurrent()
$taskPrincipal=New-Object Security.Principal.WindowsPrincipal($taskIdentity)
$taskAdmin=$taskPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if($taskAdmin){throw 'Use a normal PowerShell window for the development backend. Administrator mode is not needed.'}
function Get-TaskListener {
@(Get-NetTCPConnection -State Listen -LocalPort 8080 -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique)
}
function Read-TaskState {
if(Test-Path -LiteralPath $taskStateFile){Get-Content -LiteralPath $taskStateFile -Raw | ConvertFrom-Json}
}
function Get-TaskOwnedProcess($state) {
if(!$state){return $null}
$process=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$state.pid)
if(!$process){return $null}
$started=(Get-Process -Id ([int]$state.pid) -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()
if(!$process.ExecutablePath -or !$process.CommandLine -or $started -ne $state.processStartTicks -or
$process.ExecutablePath -ne $state.java -or $process.CommandLine -notlike ('*'+$state.jar+'*') -or
$process.CommandLine -notlike '*--spring.profiles.active=druid*' -or
$state.root -ne $taskRoot -or $state.jar -notlike ($taskRuntime+'\cmvr-wms-*.jar')){
throw 'The recorded process identity has changed. Nothing was stopped.'
}
return $process
}
New-Item -ItemType Directory -Path $taskRuntime -Force | Out-Null
try{$taskLease=[IO.File]::Open((Join-Path $taskRuntime 'backend.lock'),[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)}catch{throw 'Another development backend operation is running. Try again after it finishes.'}
try{
$taskState=Read-TaskState
$taskListeners=Get-TaskListener
if($Action -eq 'Status'){
$taskOwned=Get-TaskOwnedProcess $taskState
[pscustomobject]@{running=[bool]($taskOwned -and $taskListeners -contains $taskOwned.ProcessId);pid=if($taskOwned){$taskOwned.ProcessId}else{$null};administrator=$false;url='http://localhost:8080';managed=[bool]$taskOwned}
return
}
if($Action -in @('Restart','Stop')){
$taskOwned=Get-TaskOwnedProcess $taskState
if($taskOwned){
if($taskListeners.Count -gt 0 -and ($taskListeners.Count -ne 1 -or $taskListeners[0] -ne $taskOwned.ProcessId)){throw 'Port 8080 belongs to another process. Nothing was stopped.'}
Stop-Process -Id $taskOwned.ProcessId -ErrorAction Stop
Wait-Process -Id $taskOwned.ProcessId -Timeout 15 -ErrorAction SilentlyContinue
# Windows may briefly report the terminated listener while releasing its TCP endpoint.
# Only wait for release; never terminate a replacement/unknown port owner.
for($taskReleaseAttempt=0;$taskReleaseAttempt -lt 25;$taskReleaseAttempt++){
if(@(Get-TaskListener).Count -eq 0){break}
Start-Sleep -Milliseconds 200
}
}elseif($taskListeners.Count -gt 0){throw 'Port 8080 is occupied by an unmanaged service. It will not be stopped automatically.'}
if($Action -eq 'Stop'){Write-Output 'Development backend stopped. No other service was changed.';return}
}
$taskListeners=Get-TaskListener
if($taskListeners.Count -gt 0){
$taskOwned=Get-TaskOwnedProcess $taskState
if($taskOwned -and $taskListeners.Count -eq 1 -and $taskListeners[0] -eq $taskOwned.ProcessId){Write-Output 'Development backend already running: http://localhost:8080';return}
throw 'Port 8080 is occupied by an unmanaged service. Nothing was stopped.'
}
$taskBuild=Join-Path $taskRoot 'ruoyi-admin/target/cmvr-wms.jar'
if(!(Test-Path -LiteralPath $taskBuild)){throw 'Build ruoyi-admin/target/cmvr-wms.jar before starting the development backend.'}
$taskJava=if($env:JAVA_HOME -and (Test-Path -LiteralPath (Join-Path $env:JAVA_HOME 'bin/java.exe'))){Join-Path $env:JAVA_HOME 'bin/java.exe'}else{Join-Path $env:USERPROFILE '.jdks/ms-17.0.19/bin/java.exe'}
if(!(Test-Path -LiteralPath $taskJava)){throw 'Configure JAVA_HOME with a Java 17 or newer runtime.'}
$taskJava=(Resolve-Path -LiteralPath $taskJava).Path
New-Item -ItemType Directory -Path $taskRuntime -Force | Out-Null
$taskBuildHash=(Get-FileHash -LiteralPath $taskBuild -Algorithm SHA256).Hash.ToLowerInvariant()
$taskJar=Join-Path $taskRuntime ('cmvr-wms-'+$taskBuildHash.Substring(0,16)+'.jar')
if(!(Test-Path -LiteralPath $taskJar)){Copy-Item -LiteralPath $taskBuild -Destination $taskJar}
if((Get-FileHash -LiteralPath $taskJar -Algorithm SHA256).Hash.ToLowerInvariant() -ne $taskBuildHash){throw 'Development runtime copy does not match the built jar. Nothing was started.'}
$taskTemp=Join-Path $taskRoot '.codex-tmp/jtmp'
New-Item -ItemType Directory -Path $taskTemp -Force | Out-Null
if(!$env:RUOYI_LOG_PATH){$env:RUOYI_LOG_PATH=Join-Path $taskRuntime 'logs'}
# Preserve the configured upload location, including compatible old local attachments.
# Do not change production profiles, credentials, cache namespaces, or Windows policy.
$taskArgs=@('-Dfile.encoding=UTF-8','-Djava.net.preferIPv4Stack=true',('"-Djava.io.tmpdir='+$taskTemp+'"'),('"-Djdk.net.unixdomain.tmpdir='+$taskTemp+'"'),'-jar',('"'+$taskJar+'"'),'--spring.profiles.active=druid','--server.port=8080','--spring.quartz.auto-startup=false','--spring.devtools.restart.enabled=false')
if($RealDataReplay){$taskArgs+='--projectdev.real-data-replay-enabled=true'}
if($HistoryEntry){$taskArgs+='--projectdev.history-entry-enabled=true'}
if($HistorySource){
$taskSourceRoot=(Resolve-Path (Join-Path $taskRoot '.codex-tmp/real-data-replay')).Path
$taskSource=(Resolve-Path -LiteralPath $HistorySource).Path
if(!$taskSource.StartsWith($taskSourceRoot+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase)){throw 'History source must be an inventoried file inside the replay directory.'}
$taskArgs+=('"--projectdev.history-entry-source='+$taskSource+'"')
}
$taskProcess=Start-Process -FilePath $taskJava -ArgumentList $taskArgs -WorkingDirectory $taskRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $taskRuntime 'backend.out.log') -RedirectStandardError (Join-Path $taskRuntime 'backend.err.log') -PassThru
$taskSaved=[ordered]@{root=$taskRoot;pid=$taskProcess.Id;java=$taskJava;jar=$taskJar;buildSha256=$taskBuildHash;processStartTicks=$taskProcess.StartTime.ToUniversalTime().Ticks.ToString();owner=$taskIdentity.Name;administrator=$false;profile='druid';port=8080;ready=$false;productionChanged=$false}
$taskSaved|ConvertTo-Json|Set-Content -LiteralPath $taskStateFile -Encoding UTF8
$taskReady=$false
for($taskAttempt=0;$taskAttempt -lt 40;$taskAttempt++){
if($taskProcess.HasExited){break}
try{if((Get-TaskListener) -contains $taskProcess.Id -and (Invoke-RestMethod 'http://127.0.0.1:8080/captchaImage' -TimeoutSec 2).code -eq 200){$taskReady=$true;break}}catch{}
Start-Sleep -Seconds 1
}
$taskSaved.ready=$taskReady
$taskSaved|ConvertTo-Json|Set-Content -LiteralPath $taskStateFile -Encoding UTF8
if(!$taskReady){if(!$taskProcess.HasExited){$taskOwned=Get-TaskOwnedProcess (Read-TaskState);if($taskOwned){Stop-Process -Id $taskOwned.ProcessId}};throw 'Development backend did not become ready. Inspect .codex-tmp/local-services/backend.err.log and backend.out.log.'}
Write-Output ('Development backend ready without Administrator: http://localhost:8080 (PID '+$taskProcess.Id+')')
}finally{$taskLease.Dispose()}