This commit is contained in:
2026-08-04 09:05:28 +08:00
parent fdb1e8af1c
commit 3afcff320a
116 changed files with 6749 additions and 749 deletions
@@ -0,0 +1,171 @@
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidatePattern('^https?://')]
[string]$GatewayBaseUrl,
[string[]]$AccessTokens = @(),
[ValidateRange(1, 4)]
[int]$TaskCount = 1,
[string[]]$TaskIds = @(),
[ValidateRange(1, 7200)]
[int]$TimeoutSeconds = 3600,
[ValidateRange(1, 60)]
[int]$PollSeconds = 2,
[ValidateRange(0, 200000)]
[int]$MinimumRows = 0,
[string]$Keyword = '',
[ValidateSet('', 'PROFILE_REQUIRED', 'PENDING', 'ACTIVE', 'DISABLED', 'REJECTED')]
[string]$Status = '',
[string]$OutputDirectory = '',
[switch]$CreateOnly,
[switch]$SkipDownload
)
$ErrorActionPreference = 'Stop'
$baseUrl = $GatewayBaseUrl.TrimEnd('/')
$apiPath = "$baseUrl/api/platform/v1/files/export-tasks"
if ($AccessTokens.Count -eq 0 -and -not [string]::IsNullOrWhiteSpace($env:ADMIN_ACCESS_TOKEN)) {
$AccessTokens = @($env:ADMIN_ACCESS_TOKEN)
}
if ($AccessTokens.Count -eq 0) {
throw '至少提供一个 -AccessTokens,或通过 ADMIN_ACCESS_TOKEN 环境变量注入。'
}
if ($TaskIds.Count -eq 0 -and $AccessTokens.Count -lt $TaskCount) {
throw "创建 $TaskCount 个并发任务需要至少 $TaskCount 个不同用户的 Access Token,避免 60 秒重复提交合并。"
}
if ($TaskIds.Count -gt 0 -and $AccessTokens.Count -lt $TaskIds.Count) {
throw '恢复验收时每个 TaskId 都需要对应申请人的 Access Token。'
}
function Get-Headers([string]$Token) {
return @{ Authorization = "Bearer $Token" }
}
function Invoke-ApiJson([string]$Method, [string]$Uri, [string]$Token, [object]$Body = $null) {
$arguments = @{
Method = $Method
Uri = $Uri
Headers = Get-Headers $Token
TimeoutSec = 60
}
if ($null -ne $Body) {
$arguments.ContentType = 'application/json'
$arguments.Body = $Body | ConvertTo-Json -Depth 10 -Compress
}
$response = Invoke-RestMethod @arguments
if ($null -eq $response -or [string]$response.code -ne '200') {
$requestId = if ($response.requestId) { " requestId=$($response.requestId)" } else { '' }
$traceId = if ($response.traceId) { " traceId=$($response.traceId)" } else { '' }
throw "API 失败 method=$Method uri=$Uri code=$($response.code) message=$($response.message)$requestId$traceId"
}
return $response.data
}
function New-ExportTask([string]$Token, [int]$Index) {
$parameters = [ordered]@{}
if (-not [string]::IsNullOrWhiteSpace($Keyword)) { $parameters.keyword = $Keyword.Trim() }
if (-not [string]::IsNullOrWhiteSpace($Status)) { $parameters.status = $Status }
$payload = @{
exportType = 'CUSTOMER_LIST'
format = 'XLSX'
taskName = "客户列表验收-$Index"
parameters = $parameters
}
return Invoke-ApiJson POST $apiPath $Token $payload
}
function Wait-ExportTask([string]$TaskId, [string]$Token) {
$deadline = [DateTimeOffset]::UtcNow.AddSeconds($TimeoutSeconds)
$lastStatus = ''
while ([DateTimeOffset]::UtcNow -lt $deadline) {
$task = Invoke-ApiJson GET "$apiPath/$TaskId" $Token
if ($task.status -ne $lastStatus) {
Write-Host "taskId=$TaskId status=$($task.status) processed=$($task.processedRows) total=$($task.totalRows)"
$lastStatus = $task.status
}
if ($task.status -in @('SUCCEEDED', 'FAILED', 'EXPIRED')) { return $task }
Start-Sleep -Seconds $PollSeconds
}
throw "等待导出任务超时 taskId=$TaskId timeoutSeconds=$TimeoutSeconds"
}
function Save-And-VerifyXlsx([object]$Task, [string]$Token, [string]$Directory) {
$target = Join-Path $Directory "$($Task.id).xlsx"
$response = Invoke-WebRequest -UseBasicParsing -Uri "$apiPath/$($Task.id)/download" `
-Headers (Get-Headers $Token) -TimeoutSec 600 -OutFile $target -PassThru
$contentType = [string]$response.Headers['Content-Type']
if ($contentType.ToLowerInvariant().Contains('json')) {
$payload = Get-Content -Raw -LiteralPath $target | ConvertFrom-Json
throw "下载返回业务错误 taskId=$($Task.id) code=$($payload.code) message=$($payload.message) requestId=$($payload.requestId) traceId=$($payload.traceId)"
}
$stream = [IO.File]::OpenRead($target)
try {
$signature = New-Object byte[] 4
if ($stream.Read($signature, 0, 4) -ne 4 -or $signature[0] -ne 0x50 -or $signature[1] -ne 0x4B `
-or $signature[2] -ne 0x03 -or $signature[3] -ne 0x04) {
throw "下载结果不是有效 XLSX/ZIP taskId=$($Task.id) contentType=$contentType"
}
} finally {
$stream.Dispose()
}
return [pscustomobject]@{ Path = $target; Bytes = (Get-Item -LiteralPath $target).Length; ContentType = $contentType }
}
$createdTasks = [System.Collections.Generic.List[object]]::new()
if ($TaskIds.Count -eq 0) {
for ($index = 0; $index -lt $TaskCount; $index++) {
$task = New-ExportTask $AccessTokens[$index] ($index + 1)
$createdTasks.Add([pscustomobject]@{ Task = $task; Token = $AccessTokens[$index] })
Write-Host "created taskId=$($task.id) owner=$($task.requestedBy) status=$($task.status)"
}
$uniqueIds = @($createdTasks | ForEach-Object { [string]$_.Task.id } | Sort-Object -Unique)
if ($uniqueIds.Count -ne $createdTasks.Count) {
throw '多个创建请求被重复提交规则合并;容量验收需使用不同申请用户,或等待 60 秒后重试。'
}
} else {
for ($index = 0; $index -lt $TaskIds.Count; $index++) {
$createdTasks.Add([pscustomobject]@{ Task = [pscustomobject]@{ id = $TaskIds[$index] }; Token = $AccessTokens[$index] })
}
}
if ($CreateOnly) {
$createdTasks | ForEach-Object { [pscustomobject]@{ taskId = [string]$_.Task.id } } | ConvertTo-Json
exit 0
}
$temporaryOutput = [string]::IsNullOrWhiteSpace($OutputDirectory)
if ($temporaryOutput) {
$OutputDirectory = Join-Path ([IO.Path]::GetTempPath()) "baiyue-export-acceptance-$([Guid]::NewGuid())"
}
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
$results = [System.Collections.Generic.List[object]]::new()
try {
foreach ($entry in $createdTasks) {
$task = Wait-ExportTask ([string]$entry.Task.id) $entry.Token
if ($task.status -ne 'SUCCEEDED') {
throw "导出任务未成功 taskId=$($task.id) status=$($task.status) failure=$($task.failureMessage)"
}
if ([long]$task.processedRows -lt $MinimumRows) {
throw "导出行数未达到门槛 taskId=$($task.id) processed=$($task.processedRows) minimum=$MinimumRows"
}
$artifact = $null
if (-not $SkipDownload) { $artifact = Save-And-VerifyXlsx $task $entry.Token $OutputDirectory }
$results.Add([pscustomobject]@{
taskId = [string]$task.id
status = $task.status
processedRows = [long]$task.processedRows
sizeBytes = [long]$task.sizeBytes
downloadedBytes = if ($artifact) { [long]$artifact.Bytes } else { 0 }
file = if ($artifact) { $artifact.Path } else { $null }
})
}
$results | ConvertTo-Json -Depth 5
Write-Host "EXPORT_CENTER_ACCEPTANCE_PASSED=$($results.Count)"
} finally {
if ($temporaryOutput -and (Test-Path -LiteralPath $OutputDirectory)) {
Remove-Item -LiteralPath $OutputDirectory -Recurse -Force
}
}
+85 -22
View File
@@ -3,12 +3,14 @@ param(
[string]$IamUrl = 'http://127.0.0.1:9501',
[string]$FileUrl = 'http://127.0.0.1:9506',
[string]$OrderUrl = 'http://127.0.0.1:9504',
[string]$WarehouseUrl = 'http://127.0.0.1:9505',
[string]$ImagePath,
[string]$PlatformPassword = 'ChangeMe123!'
)
$ErrorActionPreference = 'Stop'
function Invoke-Json($method, $url, $body = $null, $token = $null) {
function Invoke-Json($method, $url, $body = $null, $token = $null, $extraHeaders = @{}) {
$headers = @{}; if ($token) { $headers.Authorization = "Bearer $token" }
foreach ($name in $extraHeaders.Keys) { $headers[$name] = $extraHeaders[$name] }
$args = @{ Method=$method; Uri=$url; Headers=$headers; TimeoutSec=20 }
if ($null -ne $body) { $args.ContentType='application/json'; $args.Body=$body | ConvertTo-Json -Depth 12 }
Invoke-RestMethod @args
@@ -20,6 +22,11 @@ function Invoke-Status($method, $url, $body, $token) {
function Assert-Equal($name, $actual, $expected) {
if ($actual -ne $expected) { throw "$name expected=$expected actual=$actual" }
}
function Assert-Success($name, $response) {
if ($null -eq $response -or [string]$response.code -notin @('200', '0')) {
throw "$name failed code=$($response.code) message=$($response.message)"
}
}
$stamp = Get-Date -Format 'MMddHHmmss'
$username = "phase1_$stamp"; $password = 'Phase1Test123!'
@@ -29,49 +36,105 @@ $registration = Invoke-Json POST "$AuthUrl/api/auth/register" @{
countryCode='CN'; address='No. 1 Test Road, Nanshan, Shenzhen'
}
Assert-Equal 'registration status' $registration.data.tenantStatus 'PROFILE_REQUIRED'
Assert-Equal 'registration next step' $registration.data.nextStep 'LOGIN_AND_COMPLETE_QUALIFICATIONS'
$tenantId = [long]$registration.data.tenantId
$merchantLogin = Invoke-Json POST "$AuthUrl/api/auth/login" @{username=$username;password=$password}
Assert-Success 'merchant login' $merchantLogin
$merchantToken = $merchantLogin.data.accessToken
$platformLogin = Invoke-Json POST "$AuthUrl/api/auth/login" @{username='platform_admin';password=$PlatformPassword}
Assert-Success 'platform login' $platformLogin
$platformToken = $platformLogin.data.accessToken
$partner = Invoke-Json POST "$WarehouseUrl/api/platform/v1/partners?tenantId=$tenantId" @{
partnerCode="E2E-PARTNER-$stamp"; partnerName="Phase One Partner $stamp"; partnerType='SHIPPER'
types=@('SHIPPER','CONSIGNEE'); contactName='Test Partner'; contactPhone='13800138000'
contactEmail="partner_$stamp@example.com"; countryCode='CN'; province='Guangdong'; city='Shenzhen'
district='Nanshan'; addressLine='No. 1 Test Road'; postalCode='518000'; status='ACTIVE'; remark='Phase one E2E'
} $platformToken
Assert-Success 'create tenant partner' $partner
$partnerId = [long]$partner.data
$warehouse = Invoke-Json POST "$WarehouseUrl/api/platform/v1/warehouse-admin" @{
tenantId=$tenantId; warehouseCode="E2E-WH-$stamp"; warehouseName="Phase One Receiving Warehouse $stamp"
warehouseType='DOMESTIC'; countryCode='CN'; timezone='Asia/Shanghai'; contactName='Test Warehouse'
contactPhone='13800138000'; contactEmail="warehouse_$stamp@example.com"; status='ACTIVE'; remark='Phase one E2E'
address=@{addressType='WAREHOUSE';countryCode='CN';stateProvince='Guangdong';city='Shenzhen';district='Nanshan';postalCode='518000';addressLine1='No. 1 Test Road';addressLine2=$null;latitude=$null;longitude=$null}
capabilities=@(@{capabilityCode='RECEIVING';capabilityName='Receiving';enabled=$true;cutoffTime='16:00:00';description='Phase one E2E receiving'})
} $platformToken
Assert-Success 'create tenant receiving warehouse' $warehouse
$warehouseId = [long]$warehouse.data
$order = @{
customerId=$tenantId; customerName="Phase One Enterprise $stamp"; transportMode='SEA'; tradeTerm='FOB'
destinationCountryCode='US'; destinationWarehouseId=1001; destinationWarehouseName='ONT8'
customerId=$partnerId; customerName="Phase One Partner $stamp"; transportMode='SEA'; tradeTerm='FOB'
destinationCountryCode='US'; destinationWarehouseId=$null; destinationWarehouseName='ONT8'
expectedShipDate='2026-08-15'; customerRemark='Phase one E2E'; pickupMethod='PICKUP'
receivingWarehouseId=2001; receivingWarehouseName='Shenzhen Receiving Warehouse'; channelCode='SEA-US-FBA'
receivingWarehouseId=$warehouseId; receivingWarehouseName="Phase One Receiving Warehouse $stamp"; channelCode='SEA-US-FBA'
channelName='US Sea Channel'; taxMode='BUY_DECLARATION'; containerMode='LCL'; customsInspection=$false
destinationType='FBA'; amazonWarehouseCode='ONT8'; shipmentId="FBA$stamp"; referenceId="REF$stamp"
sender=@{companyName="Phase One Enterprise $stamp";contactName='Test Sender';phone='13800138000';email="p$stamp@example.com";countryCode='CN';province='Guangdong';city='Shenzhen';district='Nanshan';addressLine='No. 1 Test Road';postalCode='518000'}
receiver=@{companyName='Amazon';contactName='ONT8';phone='1234567890';email='ont8@example.com';countryCode='US';province='CA';city='Moreno Valley';district='Riverside';addressLine='24300 Nandina Ave';postalCode='92551'}
cargoes=@(@{cargoName='Bluetooth Speaker';hsCode='8518210000';packageType='CARTON';packageCount=2;grossWeightKg=20.5;volumeCbm=0.2;lengthCm=50;widthCm=40;heightCm=30;declaredValue=200;currency='USD';dangerousGoods=$false;cargoRemark='Phase one test';skuNo="SKU$stamp";upcNo='123456789012';cargoNameEn='Bluetooth Speaker';customsHsCode='8518210000';unitsPerPackage=10;totalQuantity=20;netWeightKg=18;unitDeclaredValue=10;material='Plastic';usage='Audio';model='P1';brand='Demo'})
}
$preApprovalStatus = Invoke-Status POST "$OrderUrl/api/merchant/v1/orders/first-leg" $order $merchantToken
Assert-Equal 'pre-approval order status' $preApprovalStatus 403
$draftKey = "phase1-draft-$stamp"
$submitKey = "phase1-submit-$stamp"
$draft = Invoke-Json POST "$OrderUrl/api/merchant/v1/orders/first-leg" $order $merchantToken @{'Idempotency-Key'=$draftKey}
Assert-Success 'pre-approval draft create' $draft
$orderId = [long]$draft.data
$preApproval = Invoke-Json POST "$OrderUrl/api/merchant/v1/orders/first-leg/$orderId/submit" $null $merchantToken @{'Idempotency-Key'=$submitKey}
Assert-Equal 'pre-approval submit code' $preApproval.code 'A0403'
$uploadJson = & curl.exe -sS -X POST "$FileUrl/api/merchant/v1/files/qualifications" `
-H "Authorization: Bearer $merchantToken" -F "file=@$ImagePath;type=image/png" `
-F "certificateNo=91310101$stamp"
if ($LASTEXITCODE -ne 0) { throw 'qualification upload transport failed' }
$upload = $uploadJson | ConvertFrom-Json
Assert-Equal 'upload API code' $upload.code '0'
Assert-Equal 'upload tenant status' $upload.data.tenantStatus 'PENDING'
$creditCode = "91$((Get-Date).ToString('yyyyMMddHHmmss'))A1"
$qualificationTypes = @('BUSINESS_LICENSE', 'LEGAL_PERSON_ID', 'FREIGHT_FORWARDER_CERTIFICATE', 'BANK_ACCOUNT_LICENSE')
$uploads = @{}
foreach ($qualificationType in $qualificationTypes) {
$query = "qualificationType=$qualificationType&replace=false"
if ($qualificationType -eq 'BUSINESS_LICENSE') { $query += "&certificateNo=$creditCode" }
$uploadJson = & curl.exe -sS -X POST "$FileUrl/api/merchant/v1/files/qualifications?$query" `
-H "Authorization: Bearer $merchantToken" -F "file=@$ImagePath;type=image/png"
if ($LASTEXITCODE -ne 0) { throw "qualification upload transport failed: $qualificationType" }
$upload = $uploadJson | ConvertFrom-Json
Assert-Success "upload $qualificationType" $upload
Assert-Equal "upload $qualificationType tenant status" $upload.data.tenantStatus 'PROFILE_REQUIRED'
$uploads[$qualificationType] = $upload
}
$merchantQualifications = Invoke-Json GET "$IamUrl/api/merchant/v1/iam/tenant/qualifications" $null $merchantToken
Assert-Success 'merchant qualification list' $merchantQualifications
$pendingTypes = @($merchantQualifications.data | Where-Object { $_.status -eq 'PENDING' } | ForEach-Object { $_.qualificationType } | Sort-Object -Unique)
Assert-Equal 'pending qualification count' $pendingTypes.Count 4
foreach ($qualificationType in $qualificationTypes) {
if ($qualificationType -notin $pendingTypes) { throw "missing pending qualification: $qualificationType" }
}
$submitted = Invoke-Json POST "$IamUrl/api/merchant/v1/iam/tenant/qualifications/submit-review" $null $merchantToken
Assert-Success 'submit enterprise review' $submitted
Assert-Equal 'submitted tenant status' $submitted.data.status 'PENDING'
$platformLogin = Invoke-Json POST "$AuthUrl/api/auth/login" @{username='platform_admin';password=$PlatformPassword}
$platformToken = $platformLogin.data.accessToken
$reviews = Invoke-Json GET "$IamUrl/api/platform/v1/iam/reviews" $null $platformToken
Assert-Success 'platform review list' $reviews
$review = @($reviews.data) | Where-Object { [long]$_.tenantId -eq $tenantId } | Select-Object -First 1
if ($null -eq $review) { throw 'pending review not found' }
$qualifications = Invoke-Json GET "$IamUrl/api/platform/v1/iam/tenants/$tenantId/qualifications" $null $platformToken
Assert-Equal 'qualification count' @($qualifications.data).Count 1
$fileName = Split-Path $upload.data.documentUrl -Leaf
Assert-Success 'platform qualification list' $qualifications
Assert-Equal 'qualification count' @($qualifications.data).Count 4
$fileName = Split-Path $uploads['BUSINESS_LICENSE'].data.documentUrl -Leaf
$preview = Invoke-WebRequest -UseBasicParsing -Uri "$FileUrl/api/platform/v1/files/qualifications/$tenantId/$fileName" `
-Headers @{Authorization="Bearer $platformToken"} -TimeoutSec 20
Assert-Equal 'platform preview status' $preview.StatusCode 200
Invoke-Json POST "$IamUrl/api/platform/v1/iam/reviews/$($review.id)/approve" @{comment='Phase one E2E approved'} $platformToken | Out-Null
$approval = Invoke-Json POST "$IamUrl/api/platform/v1/iam/reviews/$($review.id)/approve" @{comment='Phase one E2E approved'} $platformToken
Assert-Success 'approve enterprise review' $approval
Assert-Equal 'registered owner retained' $approval.data.administratorCreated $false
$created = Invoke-Json POST "$OrderUrl/api/merchant/v1/orders/first-leg" $order $merchantToken
$orderId = [long]$created.data
Invoke-Json POST "$OrderUrl/api/merchant/v1/orders/first-leg/$orderId/submit" $null $merchantToken | Out-Null
$approvedQualifications = Invoke-Json GET "$IamUrl/api/merchant/v1/iam/tenant/qualifications" $null $merchantToken
Assert-Success 'approved qualification list' $approvedQualifications
$approvedTypes = @($approvedQualifications.data | Where-Object { $_.status -eq 'APPROVED' } | ForEach-Object { $_.qualificationType } | Sort-Object -Unique)
Assert-Equal 'approved qualification count' $approvedTypes.Count 4
$merchantProfile = Invoke-Json GET "$IamUrl/api/merchant/v1/iam/tenant/profile" $null $merchantToken
Assert-Success 'merchant profile after approval' $merchantProfile
Assert-Equal 'active tenant status' $merchantProfile.data.status 'ACTIVE'
$approvedSubmit = Invoke-Json POST "$OrderUrl/api/merchant/v1/orders/first-leg/$orderId/submit" $null $merchantToken @{'Idempotency-Key'=$submitKey}
Assert-Success 'approved order submit' $approvedSubmit
$detail = Invoke-Json GET "$OrderUrl/api/merchant/v1/orders/first-leg/$orderId" $null $merchantToken
Assert-Equal 'submitted order status' $detail.data.order.status 'SUBMITTED'
[pscustomobject]@{username=$username;tenantId=$tenantId;registerStatus='PROFILE_REQUIRED';preApprovalOrderHttp=$preApprovalStatus;uploadStatus='PENDING';reviewId=$review.id;previewHttp=200;orderId=$orderId;finalOrderStatus='SUBMITTED'} | ConvertTo-Json
[pscustomobject]@{username=$username;tenantId=$tenantId;registerStatus='PROFILE_REQUIRED';partnerId=$partnerId;warehouseId=$warehouseId;draftCreatedBeforeApproval=$true;preApprovalSubmitCode=$preApproval.code;pendingQualificationCount=4;reviewId=$review.id;previewHttp=200;approvedQualificationCount=4;orderId=$orderId;finalOrderStatus='SUBMITTED'} | ConvertTo-Json