From cd641ddfbdb7459dba4bfa7105cb25092c85ab5e Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Wed, 7 Oct 2026 10:02:00 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E6=AF=8F=E6=97=A5=E8=B4=A6=E5=8D=95?= =?UTF-8?q?=E8=84=9A=E6=9C=AC=EF=BC=9A=E8=BF=9C=E7=AB=AF=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E9=87=8D=E8=AF=95=20+=20=E4=B8=8D=E5=86=8D=E6=8A=8A=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E5=BD=93=E6=88=90=E5=8A=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 erp-remote.ps1:上传与远程执行统一重试(默认 3 次,重试前重新上传 CSV) - run-erp-daily.ps1:导出失败重试一次;导出/转CSV/笔数核对/上传/导入回验失败都不写状态、不归档,退出码 1,下次自动重导 - 实测:真实 SSH 断连两次后第 3 次重试成功(8002 笔 / 283870.49 / 46435.6);连续失败的一次按新逻辑记失败并 exit 1 --- scripts/erp-daily-bills/README.md | 2 + scripts/erp-daily-bills/erp-remote.ps1 | 77 +++++++++++++++++++++ scripts/erp-daily-bills/run-erp-daily.ps1 | 83 ++++++++++++++++------- 3 files changed, 139 insertions(+), 23 deletions(-) create mode 100644 scripts/erp-daily-bills/erp-remote.ps1 diff --git a/scripts/erp-daily-bills/README.md b/scripts/erp-daily-bills/README.md index bf67e1f6..9c5c2336 100644 --- a/scripts/erp-daily-bills/README.md +++ b/scripts/erp-daily-bills/README.md @@ -26,6 +26,8 @@ pwsh -File scripts\erp-daily-bills\run-erp-daily.ps1 -Platform toutiao -Through - **无差异跳过**:该平台该月已导入且笔数/收入/支出完全一致时跳过导入(`-ForceImport` 可强制重刷);状态记在 `runtime/private/erp-exports/imported-state.json`。 - 超过胜算同步导出上限(响应 `超出同步导出允许最大数据量`)时,脚本自动轮询「异步导出下载管理」取回本次任务的全部分片,逐片转 CSV 后合并成一份再导入;仍可用 `-Start/-Through` 分段导出。 - 导入前用页面笔数(共 N 条)与导出行数核对,不一致就跳过导入(`-ForceImport` 可强制),避免只导入一部分。 +- 稳定性:导出失败自动重试一次(胜算页面偶发日历面板/授权弹窗异常);上传与"导入+回验"失败自动重试 3 次(含重新上传 CSV),用于吸收服务器 SSH 偶发断连。 +- 失败即失败:导出/转 CSV/笔数核对/上传/导入回验任一步失败,都会**不写本地状态、不归档**,并在结束时以退出码 1 结束(下次运行会重新导入),不会把失败当成功记入 `imported-state.json`。 ## 组成 diff --git a/scripts/erp-daily-bills/erp-remote.ps1 b/scripts/erp-daily-bills/erp-remote.ps1 new file mode 100644 index 00000000..536bd554 --- /dev/null +++ b/scripts/erp-daily-bills/erp-remote.ps1 @@ -0,0 +1,77 @@ +<# + 每日账单脚本的远程执行辅助:上传 + 远程执行 + 失败重试。 + + 远端命令失败(包括 SSH 连接被服务器断开)时不再静默当成功: + 统一返回 { Ok; Output; Attempts },由调用方决定是否写本地状态、是否归档。 + 上传与远程执行都按 Attempts 重试;重试时会重新上传 CSV, + 避免上一次失败已经把远端文件删掉导致二次失败。 +#> + +function New-ErpRemoteResult { + param([bool]$Ok, [string]$Output, [int]$Attempts) + + return [pscustomobject]@{ Ok = $Ok; Output = $Output; Attempts = $Attempts } +} + +function Invoke-ErpRemoteUpload { + param( + [Parameter(Mandatory = $true)][string]$PwshPath, + [Parameter(Mandatory = $true)][string]$UploaderScript, + [Parameter(Mandatory = $true)][string]$LocalFile, + [Parameter(Mandatory = $true)][string]$RemoteFile + ) + + $out = (& $PwshPath -NoProfile -ExecutionPolicy Bypass -File $UploaderScript -LocalPath $LocalFile -RemotePath $RemoteFile 2>&1 | Out-String) + + return (New-ErpRemoteResult -Ok ($LASTEXITCODE -eq 0) -Output $out -Attempts 1) +} + +function Invoke-ErpRemote { + param( + [Parameter(Mandatory = $true)][string]$PwshPath, + [Parameter(Mandatory = $true)][string]$SshScript, + [Parameter(Mandatory = $true)][string]$Body, + [string]$LocalFile = '', + [string]$RemoteFile = '', + [string]$UploaderScript = '', + [int]$Attempts = 3, + [int]$RetryDelaySeconds = 10, + [scriptblock]$Log = $null + ) + + $write = { param([string]$Message) if ($Log) { & $Log $Message } } + $tmp = [IO.Path]::GetTempFileName() + '.sh' + [IO.File]::WriteAllText($tmp, ($Body -replace "`r`n", "`n")) + try { + $output = '' + for ($attempt = 1; $attempt -le $Attempts; $attempt++) { + if ($LocalFile -and $RemoteFile -and $UploaderScript) { + $upload = Invoke-ErpRemoteUpload -PwshPath $PwshPath -UploaderScript $UploaderScript -LocalFile $LocalFile -RemoteFile $RemoteFile + if (-not $upload.Ok) { + $output = $upload.Output + & $write ('上传失败(第 {0}/{1} 次):{2}' -f $attempt, $Attempts, ($output.Trim() -replace "`r?`n", ' | ')) + if ($attempt -lt $Attempts) { + Start-Sleep -Seconds $RetryDelaySeconds + continue + } + + return (New-ErpRemoteResult -Ok $false -Output $output -Attempts $attempt) + } + } + + $output = (& $PwshPath -NoProfile -ExecutionPolicy Bypass -File $SshScript -ScriptPath $tmp 2>&1 | Out-String) + if ($LASTEXITCODE -eq 0) { + return (New-ErpRemoteResult -Ok $true -Output $output -Attempts $attempt) + } + + & $write ('远程执行失败(第 {0}/{1} 次,exit={2}):{3}' -f $attempt, $Attempts, $LASTEXITCODE, ($output.Trim() -replace "`r?`n", ' | ')) + if ($attempt -lt $Attempts) { + Start-Sleep -Seconds $RetryDelaySeconds + } + } + + return (New-ErpRemoteResult -Ok $false -Output $output -Attempts $Attempts) + } finally { + Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue + } +} diff --git a/scripts/erp-daily-bills/run-erp-daily.ps1 b/scripts/erp-daily-bills/run-erp-daily.ps1 index fcd76949..00b9fa7a 100644 --- a/scripts/erp-daily-bills/run-erp-daily.ps1 +++ b/scripts/erp-daily-bills/run-erp-daily.ps1 @@ -53,30 +53,51 @@ $state = if (Test-Path -LiteralPath $stateFile) { (Get-Content -LiteralPath $sta $auth = Start-CaiwuDeploymentAuth -Server '218.93.190.75' -SshUser 'root' $sshOptions = $auth.Options + @('-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no', '-o', 'NumberOfPasswordPrompts=1', '-o', 'ConnectTimeout=15') +. (Join-Path $root 'erp-remote.ps1') +$remoteSshScript = Join-Path $root '..\..\runtime\private\server-ssh.ps1' +$remoteUploaderScript = Join-Path $root '..\..\runtime\private\upload-to-server.ps1' + +# 远程执行包装:失败自动重试(含重新上传 CSV),并返回 { Ok; Output; Attempts } function Invoke-Remote { - param([Parameter(Mandatory = $true)][string]$Body) - $tmp = [IO.Path]::GetTempFileName() + '.sh' - [IO.File]::WriteAllText($tmp, ($Body -replace "`r`n", "`n")) - try { - $out = (& $self -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root '..\..\runtime\private\server-ssh.ps1') -ScriptPath $tmp 2>&1 | Out-String) - return $out - } finally { - Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue - } + param( + [Parameter(Mandatory = $true)][string]$Body, + [string]$LocalFile = '', + [string]$RemoteFile = '' + ) + + return Invoke-ErpRemote ` + -PwshPath $self ` + -SshScript $remoteSshScript ` + -UploaderScript $remoteUploaderScript ` + -Body $Body ` + -LocalFile $LocalFile ` + -RemoteFile $RemoteFile ` + -Log { param($message) Write-Log $message } } +$failed = $false try { foreach ($target in $targets) { $spec = $specs[$target] Write-Log ('=== ' + $spec.label + ':开始 ===') - # 1) 导出 - $args = @((Join-Path $root 'export-daily.mjs'), ('--platform=' + $target), ('--out=' + $exportDir)) - if ($Start) { $args += ('--start=' + $Start) } - if ($Through) { $args += ('--through=' + $Through) } - $exportOut = (& $node @args 2>&1 | Out-String) - Write-Log ('导出:' + ($exportOut.Trim() -replace "`r?`n", ' | ')) - if ($LASTEXITCODE -ne 0) { Write-Log ($spec.label + ' 导出失败(exit=' + $LASTEXITCODE + ')'); continue } + # 1) 导出(胜算页面偶发日历面板/授权弹窗异常,失败后自动重试一次) + $exportArgs = @((Join-Path $root 'export-daily.mjs'), ('--platform=' + $target), ('--out=' + $exportDir)) + if ($Start) { $exportArgs += ('--start=' + $Start) } + if ($Through) { $exportArgs += ('--through=' + $Through) } + $exportAttempts = 2 + $exportOk = $false + for ($exportTry = 1; $exportTry -le $exportAttempts -and -not $exportOk; $exportTry++) { + $exportOut = (& $node @exportArgs 2>&1 | Out-String) + Write-Log ('导出:' + ($exportOut.Trim() -replace "`r?`n", ' | ')) + if ($LASTEXITCODE -eq 0) { + $exportOk = $true + break + } + Write-Log ($spec.label + ' 导出失败(exit=' + $LASTEXITCODE + ',第 ' + $exportTry + '/' + $exportAttempts + ' 次)') + if ($exportTry -lt $exportAttempts) { Start-Sleep -Seconds 20 } + } + if (-not $exportOk) { $failed = $true; continue } $summary = Get-Content -LiteralPath (Join-Path $exportDir 'last-export.json') -Raw | ConvertFrom-Json if ($summary.empty) { @@ -87,7 +108,7 @@ try { $rawFiles = @() if (($summary.PSObject.Properties.Name -contains 'files') -and $summary.files) { $rawFiles = @($summary.files) } if ($rawFiles.Count -eq 0 -and $summary.file) { $rawFiles = @($summary.file) } - if ($rawFiles.Count -eq 0) { Write-Log ($spec.label + ' 导出结果里没有文件名,跳过'); continue } + if ($rawFiles.Count -eq 0) { Write-Log ($spec.label + ' 导出结果里没有文件名'); $failed = $true; continue } $rawFile = $rawFiles[0] # 多分片时 CSV 用合并后的名字(不带 _partN),避免看起来只落了第一片 $csvFile = if ($rawFiles.Count -gt 1) { @@ -102,7 +123,7 @@ try { $conv = (& $python -X utf8 (Join-Path $root 'xlsx-to-csv.py') $rawFile $csvFile 2>&1 | Out-String) } $line = (($conv -split "`n") | Where-Object { $_ -match '^csv=' } | Select-Object -First 1) - if (-not $line) { Write-Log ($spec.label + ' 转 CSV 失败:' + ($conv.Trim() -replace "`r?`n", ' | ')); continue } + if (-not $line) { Write-Log ($spec.label + ' 转 CSV 失败:' + ($conv.Trim() -replace "`r?`n", ' | ')); $failed = $true; continue } $rows = [int]([regex]::Match($line, 'rows=(\d+)').Groups[1].Value) $income = [double]([regex]::Match($line, 'income=([\-\d\.]+)').Groups[1].Value) $expense = [double]([regex]::Match($line, 'expense=([\-\d\.]+)').Groups[1].Value) @@ -114,6 +135,7 @@ try { $pageCount = if ($summary.pageCount) { [int]$summary.pageCount } else { 0 } if ($pageCount -gt 0 -and $pageCount -ne $rows -and -not $ForceImport) { Write-Log ('跳过导入:页面笔数 {0} 与导出行数 {1} 不一致(分片可能未下全),未改动生产' -f $pageCount, $rows) + $failed = $true continue } @@ -127,10 +149,15 @@ try { } if ($SkipImport) { Write-Log '已指定 -SkipImport,跳过导入'; continue } - # 3) 上传 + 导入 + 页面回验 + # 3) 上传 + 导入 + 页面回验(远端失败/断连自动重试;整段失败则本平台失败,不写状态、不归档) $remoteFile = '/tmp/' + $target + '_daily_' + (Get-Date -Format 'yyyyMMdd_HHmmss') + '.csv' - $upload = (& $self -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root '..\..\runtime\private\upload-to-server.ps1') -LocalPath $csvFile -RemotePath $remoteFile 2>&1 | Out-String) - Write-Log ('上传:' + ($upload.Trim() -replace "`r?`n", ' | ')) + $upload = Invoke-ErpRemoteUpload -PwshPath $self -UploaderScript $remoteUploaderScript -LocalFile $csvFile -RemoteFile $remoteFile + Write-Log ('上传:' + ($upload.Output.Trim() -replace "`r?`n", ' | ')) + if (-not $upload.Ok) { + Write-Log ($spec.label + ' 上传失败:未写入本地状态、未归档(下次运行会重新尝试)') + $failed = $true + continue + } $verifyPhp = @" cat > /tmp/verify_daily.php <<'PHP' @@ -159,8 +186,13 @@ docker cp $remoteFile caiwu_app:/tmp/daily_bills.csv $verifyPhp rm -f /tmp/daily_bills.csv $remoteFile "@ - $importOut = Invoke-Remote -Body $body - Write-Log ('导入/回验:' + ($importOut.Trim() -replace "`r?`n", ' | ')) + $import = Invoke-Remote -Body $body -LocalFile $csvFile -RemoteFile $remoteFile + Write-Log ('导入/回验:' + ($import.Output.Trim() -replace "`r?`n", ' | ')) + if (-not $import.Ok) { + Write-Log ($spec.label + ' 导入/回验失败(已尝试 ' + $import.Attempts + ' 次):未写入本地状态、未归档,下次运行会重新导入') + $failed = $true + continue + } # 4) 记录状态 + 归档 $state | Add-Member -NotePropertyName $key -NotePropertyValue ([pscustomobject]@{ rows = $rows; income = $income; expense = $expense; file = $csvFile; at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }) -Force @@ -180,6 +212,11 @@ rm -f /tmp/daily_bills.csv $remoteFile } Write-Log ('=== ' + $spec.label + ':完成 ===') } + + if ($failed) { + Write-Log '本次运行存在失败平台(详见上面日志):相关平台未写状态、未归档' + exit 1 + } } finally { Stop-CaiwuDeploymentAuth $auth } From eda10bd74055767b6d968e7ceb29e6d1010d3555 Mon Sep 17 00:00:00 2001 From: renshen <1005457301@qq.com> Date: Tue, 6 Oct 2026 17:31:23 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=94=AE=E5=90=8E?= =?UTF-8?q?=E8=B4=B9=E7=94=A8=E6=98=8E=E7=BB=86=EF=BC=9A=E5=BA=97=E9=93=BA?= =?UTF-8?q?=E7=AD=9B=E9=80=89=E6=94=B9=E4=B8=BA=E5=8F=AF=E7=82=B9=E9=80=89?= =?UTF-8?q?=E7=9A=84=E5=A4=9A=E9=80=89=E6=A8=A1=E7=B3=8A=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 店铺名称由单个输入框改为可点选的多选下拉:候选里可按关键字模糊筛选、多选、全选当前结果/清空 - 提交 shop_name[],多个店铺取并集逐个模糊匹配;保留旧的单值 shop_name 兼容 - 候选来自订单镜像中真实出现过的店铺,缓存 1 小时;单次最多 50 个店铺,超出在面板内提示 - 补充仓库层与页面层用例 --- .../OrderDataMirrorRepository.php | 37 +- .../View/OrderDataPageData.php | 64 +++- .../order-data/after-sales-expenses.blade.php | 329 +++++++++++++++++- .../Business/OrderDataPagesUpstreamTest.php | 40 +++ .../OrderDataMirrorRepositoryTest.php | 66 ++++ 5 files changed, 530 insertions(+), 6 deletions(-) diff --git a/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php b/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php index 07ca40c5..68d09e16 100644 --- a/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php @@ -35,6 +35,25 @@ class OrderDataMirrorRepository return $this->datasetsReady(self::DATASETS); } + /** + * 订单镜像里出现过的店铺名称,按名称排序;供页面上的店铺多选候选使用。 + * + * @return array + */ + public function shopNames(): array + { + return $this->connection->table('ops_jst_orders') + ->select('shop_name') + ->distinct() + ->whereNotNull('shop_name') + ->where('shop_name', '<>', '') + ->orderBy('shop_name') + ->pluck('shop_name') + ->map(static fn (mixed $name): string => (string) $name) + ->values() + ->all(); + } + public function promotionReady(): bool { return $this->datasetsReady(self::PROMOTION_DATASETS); @@ -142,8 +161,22 @@ class OrderDataMirrorRepository ->orWhereRaw("i.outer_oi_id LIKE ? ESCAPE '!'", [$needle]); }); } - if (($filters['shop_name'] ?? '') !== '') { - $query->whereRaw("o.shop_name LIKE ? ESCAPE '!'", [$this->contains((string) $filters['shop_name'])]); + $shopNames = array_values(array_filter(array_map( + static fn (mixed $name): string => trim((string) $name), + (array) ($filters['shop_names'] ?? []), + ), static fn (string $name): bool => $name !== '')); + + if ($shopNames === [] && ($filters['shop_name'] ?? '') !== '') { + $shopNames = [trim((string) $filters['shop_name'])]; + } + + if ($shopNames !== []) { + // 多店铺:每个店铺做一个模糊匹配再取并集,选中的是完整店铺名时等同于精确匹配。 + $query->where(function (Builder $shop) use ($shopNames): void { + foreach ($shopNames as $name) { + $shop->orWhereRaw("o.shop_name LIKE ? ESCAPE '!'", [$this->contains($name)]); + } + }); } if (($filters['sku_id'] ?? '') !== '') { $needle = $this->contains((string) $filters['sku_id']); diff --git a/modules/EcommerceFinance/View/OrderDataPageData.php b/modules/EcommerceFinance/View/OrderDataPageData.php index 95b20c99..13dce4ef 100644 --- a/modules/EcommerceFinance/View/OrderDataPageData.php +++ b/modules/EcommerceFinance/View/OrderDataPageData.php @@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\View; use Illuminate\Pagination\Paginator; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Cache; use Modules\EcommerceFinance\Repositories\OrderDataRepository; use Modules\EcommerceFinance\Repositories\OrderDataMirrorRepository; use Modules\EcommerceFinance\Repositories\WorkOrderMirrorRepository; @@ -43,6 +44,7 @@ class OrderDataPageData 'orderDataFilters' => $filters, 'orderDataStatus' => $result['status'] ?? [], 'orderDataError' => null, + 'orderDataShopOptions' => $this->afterSalesShopOptions(), 'afterSalesWorkOrders' => $includeWorkOrders ? $this->afterSalesWorkOrders($filters) : $this->emptyAfterSalesWorkOrders(), ]; } catch (ServiceUnavailableHttpException $exception) { @@ -60,21 +62,78 @@ class OrderDataPageData * date and text normalization independently. * * @param array|null $input - * @return array{from:string,to:string,order_no:string,shop_name:string,sku_id:string} + * @return array{from:string,to:string,order_no:string,shop_name:string,shop_names:array,sku_id:string} */ public function afterSalesFilters(?array $input = null): array { $input ??= request()->query(); + $shopNames = $this->shopNames($input['shop_name'] ?? $input['shop_names'] ?? null); return [ 'from' => $this->date($input['from'] ?? null) ?: now()->subDays(6)->toDateString(), 'to' => $this->date($input['to'] ?? null) ?: now()->toDateString(), 'order_no' => $this->text($input['order_no'] ?? null), - 'shop_name' => $this->text($input['shop_name'] ?? null), + // shop_name 保留单值形态,兼容只认单值的调用方;多选统一用 shop_names。 + 'shop_name' => $shopNames[0] ?? '', + 'shop_names' => $shopNames, 'sku_id' => $this->text($input['sku_id'] ?? null), ]; } + /** + * 店铺筛选支持多选(shop_name[]=A&shop_name[]=B),也兼容原来的单个 shop_name。 + * + * @return array + */ + private function shopNames(mixed $value): array + { + $values = is_array($value) ? $value : [$value]; + $names = []; + + foreach ($values as $item) { + if (! is_scalar($item)) { + continue; + } + + $name = $this->text($item); + if ($name === '') { + continue; + } + + $names[$name] = true; + + // 单次最多 50 个店铺,避免拼出过长的 WHERE。 + if (count($names) >= 50) { + break; + } + } + + return array_keys($names); + } + + /** + * 店铺多选候选:订单镜像里出现过的店铺名称(缓存 1 小时,避免每次页面请求都扫表去重)。 + * + * @return array + */ + public function afterSalesShopOptions(): array + { + try { + $mirror = $this->mirrorOrders ?? app(OrderDataMirrorRepository::class); + $names = Cache::remember( + 'order-data.after-sales.shop-options', + now()->addHour(), + fn (): array => $mirror->shopNames(), + ); + + return is_array($names) ? array_values($names) : []; + } catch (Throwable $exception) { + report($exception); + + return []; + } + } + /** * Fetch raw after-sales rows for a page. Both the page and CSV export use * this method so source selection, filters, joins and row normalization stay @@ -165,6 +224,7 @@ class OrderDataPageData 'orderDataFilters' => $filters, 'orderDataStatus' => [], 'orderDataError' => $message, + 'orderDataShopOptions' => $this->afterSalesShopOptions(), 'afterSalesWorkOrders' => $this->emptyAfterSalesWorkOrders(), ]; } diff --git a/resources/views/business/pages/order-data/after-sales-expenses.blade.php b/resources/views/business/pages/order-data/after-sales-expenses.blade.php index 5cca1d2b..777235e1 100644 --- a/resources/views/business/pages/order-data/after-sales-expenses.blade.php +++ b/resources/views/business/pages/order-data/after-sales-expenses.blade.php @@ -179,6 +179,156 @@ .order-data-date-picker__trigger .material-icons-outlined { font-size: 1.125rem; } + + /* 店铺名称:可点选的多选下拉(模糊搜索 + 多选),沿用黑金设计令牌 */ + .order-data-shop { position: relative; } + + .order-data-shop__toggle { + display: inline-flex; + width: 100%; + min-width: 12rem; + height: 2.125rem; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + padding: 0 0.65rem; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: 0.5rem; + background: var(--vip-surface, #ffffff); + color: var(--vip-content-ink, #171717); + font-size: 0.8125rem; + text-align: left; + cursor: pointer; + } + + .order-data-shop__toggle:hover { border-color: var(--vip-content-accent, #b9954f); } + + .order-data-shop__toggle[aria-expanded="true"], + .order-data-shop__toggle:focus-visible { + border-color: var(--vip-content-accent-dark, #856632); + outline: none; + box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.2); + } + + .order-data-shop__toggle.is-set { + color: var(--vip-content-accent-dark, #856632); + font-weight: 600; + } + + .order-data-shop__label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .order-data-shop__toggle .material-icons-outlined { + flex: 0 0 auto; + font-size: 1.125rem; + color: var(--vip-content-muted, #595959); + } + + .order-data-shop__panel { + position: absolute; + z-index: 30; + top: calc(100% + 4px); + left: 0; + display: flex; + width: min(22rem, 86vw); + flex-direction: column; + gap: 0.5rem; + padding: 0.65rem; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: 0.5rem; + background: var(--vip-surface, #ffffff); + box-shadow: 0 4px 8px rgba(23, 23, 23, 0.10); + } + + .order-data-shop__panel[hidden] { display: none; } + + .order-data-shop .order-data-shop__search { + height: 2rem; + padding: 0 0.55rem; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: 0.5rem; + color: var(--vip-content-ink, #171717); + font-size: 0.8125rem; + } + + .order-data-shop .order-data-shop__search:focus { + border-color: var(--vip-content-accent-dark, #856632); + outline: none; + box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.2); + } + + .order-data-shop__actions { display: flex; gap: 0.4rem; } + + .order-data-shop__actions button { + height: 1.75rem; + padding: 0 0.5rem; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: 0.5rem; + background: var(--vip-surface, #ffffff); + color: var(--vip-content-ink, #171717); + font-size: 0.75rem; + cursor: pointer; + } + + .order-data-shop__actions button:hover { + border-color: var(--vip-content-accent-dark, #856632); + color: var(--vip-content-accent-dark, #856632); + } + + .order-data-shop__options { + display: flex; + max-height: 16rem; + flex-direction: column; + gap: 2px; + overflow-y: auto; + } + + .order-data-shop__option { + display: flex; + align-items: center; + gap: 0.45rem; + padding: 0.3rem 0.4rem; + border-radius: 0.375rem; + color: var(--vip-content-ink, #171717); + font-size: 0.8125rem; + cursor: pointer; + } + + .order-data-shop__option:hover { background: var(--vip-content-accent-soft, #f7f0de); } + + /* 覆盖 .upstream-data-field input 的通用输入框样式,复选框不能撑成整行输入框 */ + .order-data-shop .order-data-shop__option input[type="checkbox"] { + flex: 0 0 auto; + width: 0.95rem; + height: 0.95rem; + min-width: 0.95rem; + margin: 0; + padding: 0; + border: 1px solid var(--vip-border, #d8d2c7); + border-radius: 0.25rem; + background: var(--vip-surface, #ffffff); + accent-color: var(--vip-content-accent-dark, #856632); + } + + .order-data-shop__option span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .order-data-shop__option.is-selected { background: var(--vip-content-accent-soft, #f7f0de); } + + .order-data-shop__hint, + .order-data-shop__empty { + padding: 0.35rem 0.4rem; + color: var(--vip-content-muted, #595959); + font-size: 0.75rem; + } + + .order-data-shop__hint[hidden] { display: none; }
@@ -213,8 +363,25 @@
- - + +
+ + + +
@@ -474,3 +641,161 @@ }); })(); + + diff --git a/tests/Feature/Business/OrderDataPagesUpstreamTest.php b/tests/Feature/Business/OrderDataPagesUpstreamTest.php index 7be3f58d..2abafd30 100644 --- a/tests/Feature/Business/OrderDataPagesUpstreamTest.php +++ b/tests/Feature/Business/OrderDataPagesUpstreamTest.php @@ -3,6 +3,7 @@ namespace Tests\Feature\Business; use App\Models\Auth\Permission; +use Illuminate\Support\Facades\Cache; use Mockery; use Modules\EcommerceFinance\Repositories\OrderDataMirrorRepository; use Modules\EcommerceFinance\Repositories\WorkOrderMirrorRepository; @@ -19,6 +20,7 @@ class OrderDataPagesUpstreamTest extends FeatureTestCase $mirror = Mockery::mock(OrderDataMirrorRepository::class); $mirror->shouldReceive('ready')->zeroOrMoreTimes()->andReturnFalse(); $mirror->shouldReceive('promotionReady')->zeroOrMoreTimes()->andReturnFalse(); + $mirror->shouldReceive('shopNames')->zeroOrMoreTimes()->andReturn([]); $this->app->instance(OrderDataMirrorRepository::class, $mirror); $workOrders = Mockery::mock(WorkOrderMirrorRepository::class); @@ -32,6 +34,7 @@ class OrderDataPagesUpstreamTest extends FeatureTestCase 'sync_status' => ['ready' => false, 'code' => 'initial_sync_pending', 'last_succeeded_at' => null, 'datasets' => []], ]); $this->app->instance(WorkOrderMirrorRepository::class, $workOrders); + Cache::forget('order-data.after-sales.shop-options'); } public function test_after_sales_prefers_complete_business_mirror_without_registering_a_snapshot(): void @@ -39,6 +42,7 @@ class OrderDataPagesUpstreamTest extends FeatureTestCase $this->allowOrderDataPages(); $mirror = Mockery::mock(OrderDataMirrorRepository::class); $mirror->shouldReceive('ready')->once()->andReturnTrue(); + $mirror->shouldReceive('shopNames')->zeroOrMoreTimes()->andReturn([]); $mirror->shouldReceive('afterSales')->once()->andReturn(['rows' => [[ 'internal_order_no' => 'MIRROR-ORDER-1', 'shop_name' => '共享镜像店铺', @@ -57,6 +61,42 @@ class OrderDataPagesUpstreamTest extends FeatureTestCase ->assertSeeText('MIRROR'); } + public function test_after_sales_page_offers_a_selectable_multi_shop_filter(): void + { + $this->allowOrderDataPages(); + $mirror = Mockery::mock(OrderDataMirrorRepository::class); + $mirror->shouldReceive('ready')->zeroOrMoreTimes()->andReturnTrue(); + $mirror->shouldReceive('shopNames')->zeroOrMoreTimes()->andReturn(['拼多多-甲店', '京东-乙店']); + $mirror->shouldReceive('afterSales')->once() + ->with( + Mockery::on(static fn (array $filters): bool => ($filters['shop_names'] ?? null) === ['拼多多-甲店', '京东-乙店']), + 1, + 25, + ) + ->andReturn(['rows' => [[ + 'internal_order_no' => 'ORDER-MULTI-1', + 'shop_name' => '拼多多-甲店', + 'product_amount' => 12.5, + ]]]); + $this->app->instance(OrderDataMirrorRepository::class, $mirror); + $factory = Mockery::mock(UpstreamQueryCacheFactory::class); + $factory->shouldNotReceive('forSource'); + $this->app->instance(UpstreamQueryCacheFactory::class, $factory); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'order-data', + 'page' => 'raw-data', + 'tab' => 'after-sales-expenses', + 'shop_name' => ['拼多多-甲店', '京东-乙店'], + ])) + ->assertOk() + ->assertSee('data-shop-picker', false) + ->assertSee('data-shop-options', false) + ->assertSee('京东-乙店', false) + ->assertSeeText('拼多多-甲店') + ->assertSeeText('ORDER-MULTI-1'); + } + public function test_order_data_pages_render_cached_upstream_rows_and_filters(): void { $this->allowOrderDataPages(); diff --git a/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php index fed58fee..50d809a6 100644 --- a/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php @@ -113,6 +113,72 @@ class OrderDataMirrorRepositoryTest extends TestCase $this->assertTrue((new OrderDataMirrorRepository($datasets, $mirror))->promotionReady()); } + public function test_after_sales_filters_by_multiple_shop_names(): void + { + $db = DB::connection('business_mirror'); + $this->insertOrder($db, 1, 'SO-A', '拼多多-甲店'); + $this->insertOrder($db, 2, 'SO-B', '京东-乙店'); + $this->insertOrder($db, 3, 'SO-C', '抖音-丙店'); + + $repository = $this->repository($db); + $base = ['from' => '2026-08-01', 'to' => '2026-08-02', 'order_no' => '', 'shop_name' => '', 'sku_id' => '']; + + $both = $repository->afterSales(array_replace($base, ['shop_names' => ['甲店', '乙店']]), 1, 25); + $this->assertSame(['京东-乙店', '拼多多-甲店'], $this->sortedShops($both['rows'])); + + $single = $repository->afterSales(array_replace($base, ['shop_names' => ['甲店']]), 1, 25); + $this->assertSame(['拼多多-甲店'], $this->sortedShops($single['rows'])); + + // 兼容旧的单值 shop_name 过滤。 + $legacy = $repository->afterSales(array_replace($base, ['shop_name' => '丙店']), 1, 25); + $this->assertSame(['抖音-丙店'], $this->sortedShops($legacy['rows'])); + + $none = $repository->afterSales(array_replace($base, ['shop_names' => ['没有这个店铺']]), 1, 25); + $this->assertSame([], $none['rows']); + } + + public function test_shop_names_lists_distinct_shops_from_the_order_mirror(): void + { + $db = DB::connection('business_mirror'); + $this->insertOrder($db, 1, 'SO-A', '拼多多-甲店'); + $this->insertOrder($db, 2, 'SO-B', '拼多多-甲店'); + $this->insertOrder($db, 3, 'SO-C', '京东-乙店'); + + $names = $this->repository($db)->shopNames(); + sort($names); + + $this->assertSame(['京东-乙店', '拼多多-甲店'], $names); + } + + private function repository(\Illuminate\Database\ConnectionInterface $db): OrderDataMirrorRepository + { + $mirror = Mockery::mock(GenericBusinessMirrorRepository::class); + $mirror->shouldReceive('connection')->andReturn($db); + + return new OrderDataMirrorRepository(Mockery::mock(BusinessMirrorDatasetRegistry::class), $mirror); + } + + private function insertOrder(\Illuminate\Database\ConnectionInterface $db, int $id, string $soId, string $shopName): void + { + $db->table('ops_jst_orders')->insert([ + 'o_id' => $id, 'so_id' => $soId, 'order_date' => '2026-08-01 09:00:00', + 'shop_name' => $shopName, 'shop_id' => 'SHOP-' . $id, + ]); + $db->table('ops_jst_order_item')->insert([ + 'oi_id' => 100 + $id, 'o_id' => $id, 'outer_oi_id' => 'SUB-' . $id, + 'sku_id' => 'SKU-' . $id, 'qty' => 1, 'amount' => 10, + ]); + } + + /** @param array> $rows */ + private function sortedShops(array $rows): array + { + $names = array_map(static fn (array $row): string => (string) ($row['shop_name'] ?? ''), $rows); + sort($names); + + return $names; + } + private function createTables(): void { $schema = Schema::connection('business_mirror'); From 83e5108ce628846afee672aa82fa080bc39a4d49 Mon Sep 17 00:00:00 2001 From: renshen <1005457301@qq.com> Date: Tue, 6 Oct 2026 18:12:16 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=94=AE=E5=90=8E?= =?UTF-8?q?=E8=B4=B9=E7=94=A8=E6=98=8E=E7=BB=86=EF=BC=9A=E9=87=8D=E7=BD=AE?= =?UTF-8?q?=E5=90=8E=E4=B8=8D=E5=86=8D=E8=87=AA=E5=8A=A8=E5=B8=A6=E6=97=A5?= =?UTF-8?q?=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 点“重置”或提交空日期时,不再回填近 7 天默认区间,日期框保持为空并做不限日期查询 - 首次进入页面仍保留近 7 天默认区间;导出文件名在无日期时显示“不限日期” - 补充过滤归一化与页面渲染用例 --- .../View/OrderDataPageData.php | 10 +++- .../order-data/after-sales-expenses.blade.php | 6 ++- .../Business/OrderDataPagesUpstreamTest.php | 52 +++++++++++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/modules/EcommerceFinance/View/OrderDataPageData.php b/modules/EcommerceFinance/View/OrderDataPageData.php index 13dce4ef..f7a62620 100644 --- a/modules/EcommerceFinance/View/OrderDataPageData.php +++ b/modules/EcommerceFinance/View/OrderDataPageData.php @@ -68,10 +68,16 @@ class OrderDataPageData { $input ??= request()->query(); $shopNames = $this->shopNames($input['shop_name'] ?? $input['shop_names'] ?? null); + $from = $this->date($input['from'] ?? null); + $to = $this->date($input['to'] ?? null); + + // 首次进入页面时给一个近 7 天的默认区间;点了“重置”或提交了空日期后, + // 明确不加日期条件(页面上的日期框保持为空),由用户自己决定下一步再看什么。 + $cleared = ! empty($input['reset']) || array_key_exists('from', $input) || array_key_exists('to', $input); return [ - 'from' => $this->date($input['from'] ?? null) ?: now()->subDays(6)->toDateString(), - 'to' => $this->date($input['to'] ?? null) ?: now()->toDateString(), + 'from' => $from !== '' ? $from : ($cleared ? '' : now()->subDays(6)->toDateString()), + 'to' => $to !== '' ? $to : ($cleared ? '' : now()->toDateString()), 'order_no' => $this->text($input['order_no'] ?? null), // shop_name 保留单值形态,兼容只认单值的调用方;多选统一用 shop_names。 'shop_name' => $shopNames[0] ?? '', diff --git a/resources/views/business/pages/order-data/after-sales-expenses.blade.php b/resources/views/business/pages/order-data/after-sales-expenses.blade.php index 777235e1..e330161f 100644 --- a/resources/views/business/pages/order-data/after-sales-expenses.blade.php +++ b/resources/views/business/pages/order-data/after-sales-expenses.blade.php @@ -124,6 +124,9 @@ ]); $rows = $orderData['orderDataRows']; $filters = $orderData['orderDataFilters']; + $exportRangeLabel = ($filters['from'] ?? '') === '' && ($filters['to'] ?? '') === '' + ? '不限日期' + : (($filters['from'] ?: '不限') . '_' . ($filters['to'] ?: '不限')); $status = data_get($orderData, 'orderDataStatus.X-Caiwu-Data-Status'); $orderDataError = $orderData['orderDataError']; $afterSalesWorkOrders = $orderData['afterSalesWorkOrders'] ?? [ @@ -396,6 +399,7 @@ 'section' => $section['slug'], 'page' => $page['slug'], 'tab' => $activeTab['slug'] ?? null, + 'reset' => 1, ]) }}" class="upstream-data-button"> 重置 @@ -405,7 +409,7 @@ id="order-data-after-sales-export-button" data-export-contract="order-data.after-sales.current-page-export" data-export-table="order-data-after-sales-table" - data-export-filename="订单售后费用明细_{{ $filters['from'] ?? '开始' }}_{{ $filters['to'] ?? '结束' }}_第{{ $rows?->currentPage() ?? 1 }}页.csv" + data-export-filename="订单售后费用明细_{{ $exportRangeLabel }}_第{{ $rows?->currentPage() ?? 1 }}页.csv" @class(['upstream-data-button', 'is-disabled' => !$rows || $rows->isEmpty()]) @if (!$rows || $rows->isEmpty()) disabled="disabled" aria-disabled="true" @endif aria-label="导出当前页" diff --git a/tests/Feature/Business/OrderDataPagesUpstreamTest.php b/tests/Feature/Business/OrderDataPagesUpstreamTest.php index 2abafd30..615e5da0 100644 --- a/tests/Feature/Business/OrderDataPagesUpstreamTest.php +++ b/tests/Feature/Business/OrderDataPagesUpstreamTest.php @@ -97,6 +97,58 @@ class OrderDataPagesUpstreamTest extends FeatureTestCase ->assertSeeText('ORDER-MULTI-1'); } + public function test_after_sales_filter_normalization_keeps_defaults_and_clears_on_reset(): void + { + $data = app(\Modules\EcommerceFinance\View\OrderDataPageData::class); + + // 首次进入(没有任何参数)仍给近 7 天的默认区间。 + $default = $data->afterSalesFilters([]); + $this->assertSame(now()->subDays(6)->toDateString(), $default['from']); + $this->assertSame(now()->toDateString(), $default['to']); + + // 点“重置”后不再带日期条件,页面上日期框保持为空。 + $cleared = $data->afterSalesFilters(['reset' => 1]); + $this->assertSame('', $cleared['from']); + $this->assertSame('', $cleared['to']); + + $blank = $data->afterSalesFilters(['from' => '', 'to' => '']); + $this->assertSame('', $blank['from']); + $this->assertSame('', $blank['to']); + + $explicit = $data->afterSalesFilters(['from' => '2026-08-01', 'to' => '2026-08-31']); + $this->assertSame('2026-08-01', $explicit['from']); + $this->assertSame('2026-08-31', $explicit['to']); + } + + public function test_after_sales_reset_renders_empty_date_inputs(): void + { + $this->allowOrderDataPages(); + $mirror = Mockery::mock(OrderDataMirrorRepository::class); + $mirror->shouldReceive('ready')->zeroOrMoreTimes()->andReturnTrue(); + $mirror->shouldReceive('shopNames')->zeroOrMoreTimes()->andReturn([]); + $mirror->shouldReceive('afterSales')->once() + ->with( + Mockery::on(static fn (array $filters): bool => $filters['from'] === '' && $filters['to'] === ''), + 1, + 25, + ) + ->andReturn(['rows' => []]); + $this->app->instance(OrderDataMirrorRepository::class, $mirror); + $factory = Mockery::mock(UpstreamQueryCacheFactory::class); + $factory->shouldNotReceive('forSource'); + $this->app->instance(UpstreamQueryCacheFactory::class, $factory); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'order-data', + 'page' => 'raw-data', + 'tab' => 'after-sales-expenses', + 'reset' => 1, + ])) + ->assertOk() + ->assertSee('name="from" type="date" value=""', false) + ->assertSee('name="to" type="date" value=""', false); + } + public function test_order_data_pages_render_cached_upstream_rows_and_filters(): void { $this->allowOrderDataPages(); From cf7924fdc6742991172ac186915d780fab735c9e Mon Sep 17 00:00:00 2001 From: renshen <1005457301@qq.com> Date: Wed, 7 Oct 2026 07:35:39 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=94=AE=E5=90=8E?= =?UTF-8?q?=E8=B4=B9=E7=94=A8=E6=98=8E=E7=BB=86=EF=BC=9A=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E6=B7=98=E7=B3=BB=EF=BC=88=E5=A4=A9=E7=8C=AB/=E6=B7=98?= =?UTF-8?q?=E5=AE=9D=EF=BC=89=E8=AE=A2=E5=8D=95=E6=9D=A5=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 聚水潭把淘系订单放在 jst_qmcust_* 系列;页面镜像已接入后,报表改为两套来源合并: - 订单、明细、售后分别按来源取数(ops_jst_orders* 与 ops_jst_qmcust_*),列映射一致; 淘系明细没有 send_warehouse,用订单上的 wms_co_id 兜底 - 每套来源各自下推筛选条件并按当前页各取所需行数再合并,避免整表物化后排序 - 店铺候选同时包含两类店铺(天猫-/淘宝- 前缀) - 镜像数据集登记:jst_qmcust_orderlist/_item、jst_qmcust_refundlist/_item 及分层策略 - 用例:淘系订单与售后进入报表、店铺候选包含淘系、双源多店铺筛选 --- config/business_data.php | 19 +++ config/upstream_mirrors.php | 55 +++++++ .../OrderDataMirrorRepository.php | 142 +++++++++++++----- .../OrderDataMirrorRepositoryTest.php | 77 ++++++++++ 4 files changed, 258 insertions(+), 35 deletions(-) diff --git a/config/business_data.php b/config/business_data.php index 73a976e2..212426f7 100644 --- a/config/business_data.php +++ b/config/business_data.php @@ -79,6 +79,25 @@ return [ 'partition_column' => 'fee_time', 'sync' => 'always', ], + // 淘系(天猫/淘宝)订单与售后:聚水潭 qmcust 表族,订单售后费用明细页需要与 + // jst_Orders 系列合并读取,因此保持常规同步(不等待列式库启用)。 + 'operations_replica.rpt.jst_qmcust_orderlist' => [ + 'role' => 'fact', 'target_store' => 'mariadb', 'consumer' => '订单售后费用明细·淘系订单', + 'partition_column' => 'order_date', 'sync' => 'always', + ], + 'operations_replica.rpt.jst_qmcust_orderlist_item' => [ + 'role' => 'fact', 'target_store' => 'mariadb', 'consumer' => '订单售后费用明细·淘系订单明细', + 'sync' => 'always', + ], + 'operations_replica.rpt.jst_qmcust_refundlist' => [ + 'role' => 'fact', 'target_store' => 'mariadb', 'consumer' => '订单售后费用明细·淘系售后', + 'partition_column' => 'as_date', 'sync' => 'always', + ], + 'operations_replica.rpt.jst_qmcust_refundlist_item' => [ + 'role' => 'fact', 'target_store' => 'mariadb', 'consumer' => '订单售后费用明细·淘系售后明细', + 'sync' => 'always', + ], + // This 20M+ row mapping is not queried by the current promotion page. // Keep/archive its existing data, but stop upstream refresh immediately. 'operations_replica.rpt.jst_skumap' => [ diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index a11b72a2..2898034d 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -274,6 +274,61 @@ return [ ], ], 'operations_replica.rpt.jst_shopInfo' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_shopInfo', 'target' => 'ops_jst_shop_info', 'keys' => ['Id'], 'watermark' => 'updateTime'], + + // 淘系(天猫/淘宝)订单与售后:聚水潭单独存放在 qmcust 这套表里, + // 与 jst_Orders / jst_OrderItem / jst_returnAndRefundInfo 分开。 + // 订单售后费用明细等页面需要把两套来源合并展示。 + 'operations_replica.rpt.jst_qmcust_orderlist' => [ + 'source_key' => 'operations_replica', + 'schema' => 'rpt', + 'object' => 'jst_qmcust_orderlist', + 'target' => 'ops_jst_qmcust_orders', + 'keys' => ['Id'], + 'watermark' => 'local_updated', + 'indexes' => [ + ['o_id', 'Id'], + ['order_date', 'o_id', 'Id'], + ['so_id(64)', 'Id'], + ['shop_name(128)', 'Id'], + ], + ], + 'operations_replica.rpt.jst_qmcust_orderlist_item' => [ + 'source_key' => 'operations_replica', + 'schema' => 'rpt', + 'object' => 'jst_qmcust_orderlist_item', + 'target' => 'ops_jst_qmcust_order_items', + 'keys' => ['Id'], + 'watermark' => 'local_updated', + 'indexes' => [ + ['o_id', 'Id'], + ['oi_id', 'Id'], + ['outer_oi_id(64)', 'Id'], + ], + ], + 'operations_replica.rpt.jst_qmcust_refundlist' => [ + 'source_key' => 'operations_replica', + 'schema' => 'rpt', + 'object' => 'jst_qmcust_refundlist', + 'target' => 'ops_jst_qmcust_refunds', + 'keys' => ['as_id'], + 'watermark' => 'local_updated', + 'indexes' => [ + ['as_id'], + ['o_id', 'as_id'], + ['as_date', 'as_id'], + ], + ], + 'operations_replica.rpt.jst_qmcust_refundlist_item' => [ + 'source_key' => 'operations_replica', + 'schema' => 'rpt', + 'object' => 'jst_qmcust_refundlist_item', + 'target' => 'ops_jst_qmcust_refund_items', + 'keys' => ['asi_id'], + 'watermark' => 'local_updated', + 'indexes' => [ + ['as_id', 'asi_id'], + ], + ], 'operations_replica.rpt.jst_originalBillInfo' => [ 'source_key' => 'operations_replica', 'schema' => 'rpt', diff --git a/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php b/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php index 68d09e16..860d5938 100644 --- a/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/OrderDataMirrorRepository.php @@ -42,14 +42,18 @@ class OrderDataMirrorRepository */ public function shopNames(): array { - return $this->connection->table('ops_jst_orders') - ->select('shop_name') - ->distinct() - ->whereNotNull('shop_name') - ->where('shop_name', '<>', '') + // 非淘系 + 淘系两个来源合并去重(淘系店铺名形如"天猫-xx/淘宝-xx")。 + $plain = $this->connection->table('ops_jst_orders') + ->select('shop_name')->whereNotNull('shop_name')->where('shop_name', '<>', ''); + $taobao = $this->connection->table('ops_jst_qmcust_orders') + ->select('shop_name')->whereNotNull('shop_name')->where('shop_name', '<>', ''); + + return $plain->union($taobao) ->orderBy('shop_name') + ->get() ->pluck('shop_name') ->map(static fn (mixed $name): string => (string) $name) + ->unique() ->values() ->all(); } @@ -77,13 +81,12 @@ class OrderDataMirrorRepository public function afterSales(array $filters, int $page, int $limit): array { $limit = min(max($limit, 1), 100); - $query = $this->baseQuery(); - $this->applyFilters($query, $filters); - $rows = $query - ->select($this->columns()) + // 两套来源各取够当前页需要的行数再合并,避免把上千万行整体物化后再排序。 + $perBranch = ($page * $limit) + 1; + $rows = $this->baseQuery($filters, $perBranch) // 跨表追加 i.oi_id 会让 MariaDB 对日期范围内全部订单建立临时表 // 再 filesort;o_id 已唯一确定订单,明细通过 (o_id, Id) 索引稳定读取。 - ->orderByDesc('o.order_date')->orderByDesc('o.o_id') + ->orderByDesc('order_time')->orderByDesc('internal_order_no') ->offset((max($page, 1) - 1) * $limit) ->limit($limit + 1) ->get()->map(static fn (object $row): array => (array) $row)->all(); @@ -136,13 +139,42 @@ class OrderDataMirrorRepository return ['rows' => $rows, 'date' => $date]; } - private function baseQuery(): Builder + private function baseQuery(array $filters, int $perBranch): Builder { - return $this->connection->table('ops_jst_orders as o') - ->join('ops_jst_order_item as i', 'i.o_id', '=', 'o.o_id') - ->leftJoin('ops_jst_warehouse_info as wh', function ($join): void { - $join->on('wh.wms_co_id', '=', $this->connection->raw('COALESCE(i.send_warehouse, o.wms_co_id)')); - }); + // 同一份报表口径要同时覆盖两个来源:聚水潭非淘系订单(jst_Orders 系列)和 + // 淘系(天猫/淘宝)订单(jst_qmcust 系列)。两边的列名基本一致,淘系明细没有 + // send_warehouse,用订单上的 wms_co_id 兜底;source_branch 用于后续按来源补售后。 + // + // 筛选条件必须分别下推到两个分支:否则 MariaDB 会先合并上千万行再筛, + // 既用不上各自订单日期索引,也会把连接拖到超时。 + $plain = $this->sourceQuery('ops_jst_orders', 'ops_jst_order_item', 'COALESCE(i.send_warehouse, o.wms_co_id)', 'i.send_warehouse', 'plain'); + $this->applyFilters($plain, $filters); + $plain->orderByDesc('o.order_date')->orderByDesc('o.o_id')->limit($perBranch); + + $taobao = $this->sourceQuery('ops_jst_qmcust_orders', 'ops_jst_qmcust_order_items', 'o.wms_co_id', 'o.wms_co_id', 'taobao'); + $this->applyFilters($taobao, $filters); + $taobao->orderByDesc('o.order_date')->orderByDesc('o.o_id')->limit($perBranch); + + return $this->connection->query()->fromSub( + $plain->unionAll($taobao), + 'u', + ); + } + + private function sourceQuery( + string $ordersTable, + string $itemsTable, + string $warehouseJoinKey, + string $warehouseColumn, + string $branch, + ): Builder { + return $this->connection->table($ordersTable . ' as o') + ->join($itemsTable . ' as i', 'i.o_id', '=', 'o.o_id') + ->leftJoin('ops_jst_warehouse_info as wh', function ($join) use ($warehouseJoinKey): void { + $join->on('wh.wms_co_id', '=', $this->connection->raw($warehouseJoinKey)); + }) + ->select($this->columns($warehouseColumn)) + ->selectRaw('? as source_branch', [$branch]); } private function applyFilters(Builder $query, array $filters): void @@ -189,7 +221,7 @@ class OrderDataMirrorRepository } /** @return list */ - private function columns(): array + private function columns(string $warehouseColumn = 'i.send_warehouse'): array { return [ 'o.o_id as internal_order_no', 'o.so_id as online_order_no', @@ -204,7 +236,7 @@ class OrderDataMirrorRepository 'i.seller_income_amount', 'i.is_gift', 'i.src_combine_sku_id', 'o.type as order_type', 'o.labels as order_tags', 'o.free_amount as merchant_discount', 'o.freight as freight_income', - 'i.send_warehouse', 'o.wms_co_id', 'o.l_id as express_no', + $warehouseColumn . ' as send_warehouse', 'o.wms_co_id', 'o.l_id as express_no', 'o.logistics_company as express_company', 'o.receiver_state as province', 'o.receiver_city as city', 'o.creator_name as salesperson', 'wh.name as shipping_warehouse', 'wh.remark1 as operation_cloud_warehouse', @@ -297,27 +329,60 @@ class OrderDataMirrorRepository /** @param array> $rows */ private function hydrateRefunds(array &$rows): void { - $orderIds = array_values(array_unique(array_filter(array_column($rows, 'internal_order_no')))); - if ($orderIds === []) { + // 两个来源的售后表不同:非淘系读 ops_jst_return_refund_*,淘系读 ops_jst_qmcust_refund*。 + // 按来源分组取数,再用 "来源:o_id" 匹配,避免两个来源的 o_id 撞号。 + $idsByBranch = ['plain' => [], 'taobao' => []]; + foreach ($rows as $row) { + $orderId = (string) ($row['internal_order_no'] ?? ''); + if ($orderId === '') { + continue; + } + $idsByBranch[self::branchOf($row)][$orderId] = true; + } + + if ($idsByBranch['plain'] === [] && $idsByBranch['taobao'] === []) { + foreach ($rows as &$row) { + unset($row['source_branch']); + } + unset($row); + return; } - $refunds = $this->connection->table('ops_jst_return_refund_info as a') - ->join('ops_jst_return_refund_item as ri', 'ri.as_id', '=', 'a.as_id') - ->whereIn('a.o_id', $orderIds) - ->orderByDesc('a.as_date')->orderByDesc('a.as_id') - ->get([ - 'a.o_id as internal_order_no', 'a.as_id as after_sales_id', - 'a.outer_as_id as outside_after_sales_id', 'a.as_date as after_sales_time', - 'a.type as refund_type', 'a.question_type', 'a.labels as after_sales_tags', - 'a.refund as refund_amount', 'a.free_amount as platform_subsidy', - 'ri.outer_oi_id as sub_order_no', 'ri.sku_id as product_code', - 'ri.type as detail_return_type', 'ri.qty as application_quantity', - 'ri.amount as application_amount', 'ri.r_qty as return_quantity', - 'ri.shop_amount as return_amount', 'ri.defective_qty as defective_quantity', - ])->groupBy('internal_order_no'); + + $refunds = collect(); + $sources = [ + 'plain' => ['ops_jst_return_refund_info', 'ops_jst_return_refund_item'], + 'taobao' => ['ops_jst_qmcust_refunds', 'ops_jst_qmcust_refund_items'], + ]; + + foreach ($sources as $branch => [$infoTable, $itemTable]) { + $orderIds = array_keys($idsByBranch[$branch]); + if ($orderIds === []) { + continue; + } + + $grouped = $this->connection->table($infoTable . ' as a') + ->join($itemTable . ' as ri', 'ri.as_id', '=', 'a.as_id') + ->whereIn('a.o_id', $orderIds) + ->orderByDesc('a.as_date')->orderByDesc('a.as_id') + ->get([ + 'a.o_id as internal_order_no', 'a.as_id as after_sales_id', + 'a.outer_as_id as outside_after_sales_id', 'a.as_date as after_sales_time', + 'a.type as refund_type', 'a.question_type', 'a.labels as after_sales_tags', + 'a.refund as refund_amount', 'a.free_amount as platform_subsidy', + 'ri.outer_oi_id as sub_order_no', 'ri.sku_id as product_code', + 'ri.type as detail_return_type', 'ri.qty as application_quantity', + 'ri.amount as application_amount', 'ri.r_qty as return_quantity', + 'ri.shop_amount as return_amount', 'ri.defective_qty as defective_quantity', + ])->groupBy('internal_order_no'); + + foreach ($grouped as $orderId => $items) { + $refunds->put($branch . ':' . $orderId, $items); + } + } foreach ($rows as &$row) { - $matches = collect($refunds->get($row['internal_order_no'], collect()))->filter( + $matches = collect($refunds->get(self::branchOf($row) . ':' . ($row['internal_order_no'] ?? ''), collect()))->filter( static function (object $refund) use ($row): bool { return (string) ($refund->sub_order_no ?? '') !== '' ? (string) $refund->sub_order_no === (string) ($row['sub_order_no'] ?? '') @@ -356,10 +421,17 @@ class OrderDataMirrorRepository $row['actual_shipped_quantity'] = $row['product_quantity'] - $preReturned; $row['actual_shipped_amount'] = $row['product_amount'] - $row['pre_return_amount']; $row['actual_shipped_cost'] = $row['actual_shipped_quantity'] * $unitCost; + unset($row['source_branch']); } unset($row); } + /** 判断订单行来自哪一套来源表。 */ + private static function branchOf(array $row): string + { + return ($row['source_branch'] ?? 'plain') === 'taobao' ? 'taobao' : 'plain'; + } + private function productLink(string $site, string $shopName, string $itemId): ?string { if ($itemId === '') { diff --git a/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php index 50d809a6..b774cb3e 100644 --- a/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/OrderDataMirrorRepositoryTest.php @@ -150,6 +150,54 @@ class OrderDataMirrorRepositoryTest extends TestCase $this->assertSame(['京东-乙店', '拼多多-甲店'], $names); } + public function test_after_sales_includes_taobao_orders_and_their_refunds(): void + { + $db = DB::connection('business_mirror'); + $this->insertOrder($db, 1, 'SO-A', '拼多多-甲店'); + + // 淘系(天猫)订单与售后走另一套表,必须一起出现在报表里。 + $db->table('ops_jst_qmcust_orders')->insert([ + 'Id' => 9001, 'o_id' => 9325277, 'so_id' => '5127742981080004116', + 'order_date' => '2026-09-11 13:22:54', 'pay_date' => '2026-09-11 13:23:08', + 'send_date' => '2026-09-15 10:00:00', + 'shop_name' => '天猫-卓禾家具旗舰店', 'shop_id' => '18525257', 'shop_site' => '淘宝天猫', + 'type' => '普通订单', 'wms_co_id' => 'WH-1', + ]); + $db->table('ops_jst_qmcust_order_items')->insert([ + 'Id' => 8001, 'oi_id' => 9380102, 'o_id' => 9325277, + 'outer_oi_id' => '5127742981080004116', 'sku_id' => 'SKU-TB-1', + 'i_id' => 'STYLE-TB-1', 'name' => '天猫商品', 'qty' => 1, 'amount' => 88.0, + ]); + $db->table('ops_jst_qmcust_refunds')->insert([ + 'as_id' => 7001, 'o_id' => 9325277, 'outer_as_id' => 'AF-TB-1', + 'as_date' => '2026-09-20 10:00:00', 'type' => '退货退款', + 'question_type' => '质量问题', 'labels' => '售后', 'refund' => 30, + ]); + $db->table('ops_jst_qmcust_refund_items')->insert([ + 'asi_id' => 6001, 'as_id' => 7001, 'outer_oi_id' => '5127742981080004116', + 'sku_id' => 'SKU-TB-1', 'type' => '退货', 'qty' => 1, 'amount' => 30, 'r_qty' => 1, + ]); + + $result = $this->repository($db)->afterSales([ + 'from' => '2026-09-01', 'to' => '2026-09-30', + 'order_no' => '', 'shop_name' => '', 'sku_id' => '', + ], 1, 25); + + $rows = collect($result['rows'])->keyBy('shop_name'); + $this->assertTrue($rows->has('天猫-卓禾家具旗舰店')); + + $taobao = $rows->get('天猫-卓禾家具旗舰店'); + $this->assertSame('5127742981080004116', $taobao['online_order_no']); + $this->assertSame('AF-TB-1', $taobao['after_sales_no']); + $this->assertSame('质量问题', $taobao['question_type']); + $this->assertSame(1.0, $taobao['post_return_quantity']); + $this->assertArrayNotHasKey('source_branch', $taobao); + + // 店铺候选也要包含淘系店铺。 + $names = $this->repository($db)->shopNames(); + $this->assertContains('天猫-卓禾家具旗舰店', $names); + } + private function repository(\Illuminate\Database\ConnectionInterface $db): OrderDataMirrorRepository { $mirror = Mockery::mock(GenericBusinessMirrorRepository::class); @@ -228,5 +276,34 @@ class OrderDataMirrorRepositoryTest extends TestCase $schema->create('ops_jst_shop_info', function (Blueprint $t): void { $t->integer('shop_id'); $t->string('shop_name'); }); + // 淘系(天猫/淘宝)订单与售后:与 jst_Orders 系列并列的第二套来源。 + $schema->create('ops_jst_qmcust_orders', function (Blueprint $t): void { + $t->integer('Id'); $t->integer('o_id'); $t->string('so_id')->nullable(); $t->dateTime('order_date'); + $t->dateTime('pay_date')->nullable(); $t->dateTime('end_time')->nullable(); $t->dateTime('send_date')->nullable(); + $t->string('shop_name'); $t->string('shop_id')->nullable(); $t->string('shop_site')->nullable(); + $t->string('type')->nullable(); $t->string('labels')->nullable(); $t->string('wms_co_id')->nullable(); + $t->string('l_id')->nullable(); $t->string('logistics_company')->nullable(); + $t->string('receiver_state')->nullable(); $t->string('receiver_city')->nullable(); + $t->string('creator_name')->nullable(); $t->decimal('free_amount')->nullable(); $t->decimal('freight')->nullable(); + }); + $schema->create('ops_jst_qmcust_order_items', function (Blueprint $t): void { + $t->integer('Id'); $t->integer('oi_id'); $t->integer('o_id'); $t->string('outer_oi_id')->nullable(); + $t->string('sku_id'); $t->string('i_id')->nullable(); $t->string('shop_sku_id')->nullable(); + $t->string('shop_i_id')->nullable(); $t->string('properties_value')->nullable(); $t->string('name')->nullable(); + $t->decimal('qty')->nullable(); $t->decimal('amount')->nullable(); $t->decimal('buyer_paid_amount')->nullable(); + $t->decimal('seller_income_amount')->nullable(); $t->integer('is_gift')->nullable(); + $t->string('src_combine_sku_id')->nullable(); + }); + $schema->create('ops_jst_qmcust_refunds', function (Blueprint $t): void { + $t->integer('as_id'); $t->integer('o_id'); $t->string('outer_as_id')->nullable(); + $t->dateTime('as_date'); $t->string('type')->nullable(); $t->string('question_type')->nullable(); + $t->string('labels')->nullable(); $t->decimal('refund')->nullable(); $t->decimal('free_amount')->nullable(); + }); + $schema->create('ops_jst_qmcust_refund_items', function (Blueprint $t): void { + $t->integer('asi_id'); $t->integer('as_id'); $t->string('outer_oi_id')->nullable(); + $t->string('sku_id')->nullable(); $t->string('type')->nullable(); $t->decimal('qty')->nullable(); + $t->decimal('amount')->nullable(); $t->decimal('r_qty')->nullable(); $t->decimal('shop_amount')->nullable(); + $t->decimal('defective_qty')->nullable(); + }); } } From fb154020038a7785eac9610e756d2362c0ba603f Mon Sep 17 00:00:00 2001 From: DoDo <1060330844@qq.com> Date: Wed, 7 Oct 2026 10:01:13 +0800 Subject: [PATCH 5/6] =?UTF-8?q?feat:=20=E5=BA=97=E9=93=BA=E7=BB=B4?= =?UTF-8?q?=E5=BA=A6=E6=8A=A5=E8=A1=A8=E6=97=A0=E4=B8=9A=E7=BB=A9=E6=9C=88?= =?UTF-8?q?=E4=BB=BD=E5=88=97=E9=BB=98=E8=AE=A4=E9=9A=90=E8=97=8F=20(#281)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Business/UpstreamBusinessInformation.php | 22 ++++-- .../pages/partials/directory-table.blade.php | 11 ++- tests/Feature/Business/PrototypePageTest.php | 68 +++++++++++++++++-- .../StoreReportRepositoryTest.php | 30 ++++++++ 4 files changed, 117 insertions(+), 14 deletions(-) diff --git a/app/Business/UpstreamBusinessInformation.php b/app/Business/UpstreamBusinessInformation.php index 3cdf2f74..9c17dcd1 100644 --- a/app/Business/UpstreamBusinessInformation.php +++ b/app/Business/UpstreamBusinessInformation.php @@ -152,6 +152,13 @@ SQL); { $filters = StoreReportRepository::requestFilters(); $rows = $this->storeReportRows($filters); + + // 所有店铺该月都没有业绩的月份列默认隐藏;「筛选字段」中仍保留勾选项,可手动选出来。 + request()->attributes->set( + 'store-report.default_hidden_columns', + $this->columnsWithoutData($rows, 'sales_', zeroCountsAsData: false), + ); + $offset = ($page - 1) * $perPage; return ['data' => array_slice($rows, $offset, $perPage), 'total' => count($rows)]; @@ -299,7 +306,7 @@ SQL); // 所有主体该月收入均为空时,该月份列在页面上默认隐藏;「筛选字段」中仍保留勾选项,可手动选出来。 request()->attributes->set( 'subject-operating-report.default_hidden_columns', - $this->subjectReportColumnsWithoutData($rows), + $this->columnsWithoutData($rows, 'income_', zeroCountsAsData: true), ); $rows = array_values(array_filter($rows, fn (array $row): bool => $this->subjectMatchesFilters($row, $filters))); @@ -311,23 +318,28 @@ SQL); } /** - * 没有数据的月份列:全部主体该月收入都为空(null/空字符串)时才视为没有数据。 - * 金额为 0 的月份代表当月有账单,不隐藏。 + * 没有数据的月份列:所有行该月都没有数值时返回该列名,页面据此默认隐藏。 + * + * 收入(income_)以 null/空字符串表示无账单,金额 0 也算有账单; + * 销量(sales_)没有空值标记,数值 0 视为当月没有业绩。 * * @param array> $rows * @return array */ - private function subjectReportColumnsWithoutData(array $rows): array + private function columnsWithoutData(array $rows, string $prefix, bool $zeroCountsAsData): array { $columns = []; for ($month = 1; $month <= 12; $month++) { - $key = sprintf('income_%02d', $month); + $key = sprintf('%s%02d', $prefix, $month); foreach ($rows as $row) { $value = $row[$key] ?? null; if ($value === null || $value === '') { continue; } + if (! $zeroCountsAsData && (float) $value === 0.0) { + continue; + } continue 2; } diff --git a/resources/views/business/pages/partials/directory-table.blade.php b/resources/views/business/pages/partials/directory-table.blade.php index e9cbee1b..1fc1fb18 100644 --- a/resources/views/business/pages/partials/directory-table.blade.php +++ b/resources/views/business/pages/partials/directory-table.blade.php @@ -1126,12 +1126,17 @@ array_filter(explode(',', (string) request('columns', ''))), $directoryColumnNames, )); - // 主体维度经营报表:没有数据的月份列默认隐藏,仍保留在「筛选字段」中供手动勾选显示。 + // 主体维度经营报表、店铺维度报表:没有数据的月份列默认隐藏,仍保留在「筛选字段」中供手动勾选显示。 $directoryDefaultColumns = $directoryColumnNames; - if ($directoryPageKey === 'company-management/subject-operating-report') { + $directoryDefaultHiddenColumns = match ($directoryPageKey) { + 'company-management/subject-operating-report' => request()->attributes->get('subject-operating-report.default_hidden_columns', []), + 'store-management/store-report' => request()->attributes->get('store-report.default_hidden_columns', []), + default => [], + }; + if ((array) $directoryDefaultHiddenColumns !== []) { $directoryDefaultColumns = array_values(array_diff( $directoryColumnNames, - (array) request()->attributes->get('subject-operating-report.default_hidden_columns', []), + (array) $directoryDefaultHiddenColumns, )); } $visibleDirectoryColumns = request()->has('columns') ? $requestedDirectoryColumns : $directoryDefaultColumns; diff --git a/tests/Feature/Business/PrototypePageTest.php b/tests/Feature/Business/PrototypePageTest.php index 7c250929..89f0be0d 100644 --- a/tests/Feature/Business/PrototypePageTest.php +++ b/tests/Feature/Business/PrototypePageTest.php @@ -177,9 +177,9 @@ class PrototypePageTest extends FeatureTestCase $html = $response->getContent(); // 没有数据的月份默认隐藏,但表头和「筛选字段」勾选项仍在页面中。 - $this->assertMatchesRegularExpression('/data-column-key="income_01"[^>]*is-column-hidden/', $html); - $this->assertMatchesRegularExpression('/data-column-key="income_02"[^>]*is-column-hidden/', $html); - $this->assertDoesNotMatchRegularExpression('/data-column-key="income_03"[^>]*is-column-hidden/', $html); + $this->assertMatchesRegularExpression('/]*data-column-key="income_01"[^>]*is-column-hidden/', $html); + $this->assertMatchesRegularExpression('/]*data-column-key="income_02"[^>]*is-column-hidden/', $html); + $this->assertDoesNotMatchRegularExpression('/]*data-column-key="income_03"[^>]*is-column-hidden/', $html); $this->assertStringContainsString('value="income_01" data-directory-query-column', $html); $this->assertStringNotContainsString('value="income_01" data-directory-query-column checked', $html); $this->assertStringContainsString('value="income_03" data-directory-query-column checked', $html); @@ -194,8 +194,64 @@ class PrototypePageTest extends FeatureTestCase $restored->assertOk(); $restoredHtml = $restored->getContent(); - $this->assertDoesNotMatchRegularExpression('/data-column-key="income_01"[^>]*is-column-hidden/', $restoredHtml); - $this->assertDoesNotMatchRegularExpression('/data-column-key="income_03"[^>]*is-column-hidden/', $restoredHtml); - $this->assertMatchesRegularExpression('/data-column-key="income_04"[^>]*is-column-hidden/', $restoredHtml); + $this->assertDoesNotMatchRegularExpression('/]*data-column-key="income_01"[^>]*is-column-hidden/', $restoredHtml); + $this->assertDoesNotMatchRegularExpression('/]*data-column-key="income_03"[^>]*is-column-hidden/', $restoredHtml); + $this->assertMatchesRegularExpression('/]*data-column-key="income_04"[^>]*is-column-hidden/', $restoredHtml); + } + + public function testStoreReportHidesSalesMonthsWithoutDataAndKeepsThemSelectable(): void + { + $service = Mockery::mock(UpstreamBusinessInformation::class); + $service->shouldReceive('paginate')->with('store-management', 'store-report', 50) + ->andReturnUsing(function (): LengthAwarePaginator { + request()->attributes->set( + 'store-report.default_hidden_columns', + ['sales_01', 'sales_08'], + ); + + return new LengthAwarePaginator([(object) [ + 'erp_store_name' => 'ERP测试店铺', + 'store_name' => '前台测试店铺', + 'store_id' => 'SHOP-001', + 'status' => '开店中', + 'entity' => '测试主体', + 'company_type' => '普通公司', + 'period_sales' => 100, + 'sales_01' => 0, + 'sales_07' => 100, + 'sales_08' => 0, + ]], 1, 50, 1, ['path' => '/']); + }); + $this->app->instance(UpstreamBusinessInformation::class, $service); + + $response = $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'store-management', + 'page' => 'store-report', + ])); + + $response->assertOk(); + $html = $response->getContent(); + + // 没有业绩的月份默认隐藏,但表头和「筛选字段」勾选项仍在页面中。 + $this->assertMatchesRegularExpression('/]*data-column-key="sales_01"[^>]*is-column-hidden/', $html); + $this->assertMatchesRegularExpression('/]*data-column-key="sales_08"[^>]*is-column-hidden/', $html); + $this->assertDoesNotMatchRegularExpression('/]*data-column-key="sales_07"[^>]*is-column-hidden/', $html); + $this->assertStringContainsString('value="sales_01" data-directory-query-column', $html); + $this->assertStringNotContainsString('value="sales_01" data-directory-query-column checked', $html); + $this->assertStringContainsString('value="sales_07" data-directory-query-column checked', $html); + $this->assertStringContainsString('筛选字段 24/26', $html); + + // 手动勾选(columns 参数)后,对应月份列恢复显示。 + $restored = $this->get(route('business.pages.show', [ + 'section' => 'store-management', + 'page' => 'store-report', + 'columns' => 'erp_store_name,store_name,store_id,status,entity,period_sales,sales_01,sales_07', + ])); + + $restored->assertOk(); + $restoredHtml = $restored->getContent(); + $this->assertDoesNotMatchRegularExpression('/]*data-column-key="sales_01"[^>]*is-column-hidden/', $restoredHtml); + $this->assertDoesNotMatchRegularExpression('/]*data-column-key="sales_07"[^>]*is-column-hidden/', $restoredHtml); + $this->assertMatchesRegularExpression('/]*data-column-key="sales_08"[^>]*is-column-hidden/', $restoredHtml); } } diff --git a/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php b/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php index 4e88c374..2be1f47b 100644 --- a/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php @@ -238,6 +238,36 @@ class StoreReportRepositoryTest extends TestCase $this->assertSame(60.0, $paginator->items()[0]->period_sales); } + public function test_store_report_hides_sales_months_without_data_by_default(): void + { + Carbon::setTestNow('2026-09-15 10:00:00'); + $this->insertBill('店铺A', '2026-07-05', 60); + $mirror = Mockery::mock(BusinessInformationMirrorRepository::class); + $mirror->shouldReceive('ready')->with('store-information.read')->andReturnTrue(); + $mirror->shouldReceive('allStores')->once()->andReturn([[ + 'erp_store_name' => '店铺A', 'company_name' => '主体甲', 'store_status' => '0', + ]]); + $accounts = Mockery::mock(StoreAccountMirrorRepository::class); + $accounts->shouldReceive('ownershipByStoreName')->andReturn([]); + $service = new UpstreamBusinessInformation( + Mockery::mock(UpstreamQueryCacheFactory::class), + $mirror, + Mockery::mock(InstallationDetailMirrorRepository::class), + $this->repository, + $accounts, + ); + + $paginator = $service->paginate('store-management', 'store-report', 50); + + // 只有 7 月有业绩,其余月份列默认隐藏。 + $this->assertSame( + ['sales_01', 'sales_02', 'sales_03', 'sales_04', 'sales_05', 'sales_06', 'sales_08', 'sales_09', 'sales_10', 'sales_11', 'sales_12'], + $this->app['request']->attributes->get('store-report.default_hidden_columns'), + ); + $this->assertSame(1, $paginator->total()); + $this->assertSame(60.0, (float) $paginator->items()[0]->sales_07); + } + public function test_subject_operating_report_aggregates_income_by_entity(): void { Carbon::setTestNow('2026-09-01 10:00:00'); From 4258bd4e0ebb47eb1b8e88be574e1fab13937c69 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Wed, 7 Oct 2026 10:27:20 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E4=BE=A7=E8=BE=B9=E6=A0=8F=E6=9D=83?= =?UTF-8?q?=E9=99=90=EF=BC=9A=E6=96=B0=E5=A2=9E=E4=B8=80=E7=BA=A7=E8=8F=9C?= =?UTF-8?q?=E5=8D=95=E3=80=8C=E7=A7=8D=E8=8F=9C=E6=95=B0=E6=8D=AE=E6=B1=87?= =?UTF-8?q?=E6=80=BB=E3=80=8D=E4=B8=8D=E5=86=8D=E8=A2=AB=E6=97=A7=E6=9D=83?= =?UTF-8?q?=E9=99=90=E9=9B=86=E5=90=88=E9=9A=90=E8=97=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 种菜明细表 / 聚水潭订单标签明细 原本挂在「账单流水数据」下,移入新一级菜单「种菜数据汇总」后, 按页面键保存过精确权限的访问组(总账组/结算组/税务组)里没有新 section,导致菜单不显示、直达链接 403。 按既有 company-management 兼容做法:能看「账单流水数据」即可见「种菜数据汇总」。 生产数据实测(临时容器、同镜像、只读):修复前 12 个访问组账号全部看不到,修复后 21 个账号全部可见。 --- app/Utilities/SidebarPermissions.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/app/Utilities/SidebarPermissions.php b/app/Utilities/SidebarPermissions.php index 25567d0a..56d134df 100644 --- a/app/Utilities/SidebarPermissions.php +++ b/app/Utilities/SidebarPermissions.php @@ -149,6 +149,19 @@ class SidebarPermissions } unset($section); + // 「种菜明细表 / 聚水潭订单标签明细」原先挂在「账单流水数据」下,后来移入新的一级菜单 + // 「种菜数据汇总」。按页面键保存过精确权限的账号(访问组/角色)里不会有新的 planting-data, + // 会因此看不到这两个被移动的页面;这里按「能看账单流水数据 就能看这两个页面」兼容旧配置。 + $slugs = array_column($navigation, 'slug'); + if (! in_array('planting-data', $slugs, true) && in_array('billing-transactions', $slugs, true)) { + $plantingSection = collect(BusinessNavigation::all())->firstWhere('slug', 'planting-data'); + + if (! empty($plantingSection)) { + $billingIndex = array_search('billing-transactions', $slugs, true); + array_splice($navigation, $billingIndex + 1, 0, [$plantingSection]); + } + } + return $navigation; }