Merge remote-tracking branch 'origin/main'

This commit is contained in:
chenxi 2026-10-07 10:41:06 +08:00
commit 2341a839f3
15 changed files with 1117 additions and 76 deletions

View File

@ -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<int,array<string,mixed>> $rows
* @return array<int,string>
*/
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;
}

View File

@ -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;
}

View File

@ -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' => [

View File

@ -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',

View File

@ -35,6 +35,29 @@ class OrderDataMirrorRepository
return $this->datasetsReady(self::DATASETS);
}
/**
* 订单镜像里出现过的店铺名称,按名称排序;供页面上的店铺多选候选使用。
*
* @return array<int,string>
*/
public function shopNames(): array
{
// 非淘系 + 淘系两个来源合并去重(淘系店铺名形如"天猫-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();
}
public function promotionReady(): bool
{
return $this->datasetsReady(self::PROMOTION_DATASETS);
@ -58,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();
@ -117,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
@ -142,8 +193,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']);
@ -156,7 +221,7 @@ class OrderDataMirrorRepository
}
/** @return list<string> */
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',
@ -171,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',
@ -264,27 +329,60 @@ class OrderDataMirrorRepository
/** @param array<int,array<string,mixed>> $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'] ?? '')
@ -323,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 === '') {

View File

@ -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,84 @@ class OrderDataPageData
* date and text normalization independently.
*
* @param array<string,mixed>|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<int,string>,sku_id:string}
*/
public function afterSalesFilters(?array $input = null): array
{
$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' => $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<int,string>
*/
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<int,string>
*/
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 +230,7 @@ class OrderDataPageData
'orderDataFilters' => $filters,
'orderDataStatus' => [],
'orderDataError' => $message,
'orderDataShopOptions' => $this->afterSalesShopOptions(),
'afterSalesWorkOrders' => $this->emptyAfterSalesWorkOrders(),
];
}

View File

@ -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'] ?? [
@ -179,6 +182,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; }
</style>
<form method="GET" class="upstream-data-toolbar" aria-label="订单售后费用明细筛选">
@ -213,8 +366,25 @@
<input id="order-data-order-no" name="order_no" type="text" value="{{ $filters['order_no'] ?? '' }}" placeholder="内部、线上或子订单号">
</div>
<div class="upstream-data-field">
<label for="order-data-shop">店铺名称</label>
<input id="order-data-shop" name="shop_name" type="text" value="{{ $filters['shop_name'] ?? '' }}">
<label for="order-data-shop-toggle">店铺名称</label>
<div class="order-data-shop" data-shop-picker>
<button type="button" id="order-data-shop-toggle" class="order-data-shop__toggle"
data-shop-toggle aria-haspopup="true" aria-expanded="false">
<span class="order-data-shop__label" data-shop-label>全部</span>
<span class="material-icons-outlined" aria-hidden="true">expand_more</span>
</button>
<div class="order-data-shop__panel" data-shop-panel hidden>
<input type="search" class="order-data-shop__search" data-shop-search
placeholder="输入关键字筛选店铺" aria-label="搜索店铺">
<div class="order-data-shop__actions">
<button type="button" data-shop-action="all">全选当前结果</button>
<button type="button" data-shop-action="none">清空</button>
</div>
<div class="order-data-shop__options" data-shop-options role="group" aria-label="店铺候选"></div>
<div class="order-data-shop__hint" data-shop-hint hidden></div>
</div>
<span data-shop-inputs></span>
</div>
</div>
<div class="upstream-data-field">
<label for="order-data-sku">商品编码</label>
@ -229,6 +399,7 @@
'section' => $section['slug'],
'page' => $page['slug'],
'tab' => $activeTab['slug'] ?? null,
'reset' => 1,
]) }}" class="upstream-data-button">
<span class="material-icons-outlined" aria-hidden="true">refresh</span>
<span>重置</span>
@ -238,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="导出当前页"
@ -474,3 +645,161 @@
});
})();
</script>
<script>
// 店铺名称:可点选的多选下拉,支持在候选里模糊搜索,提交为 shop_name[](多个取并集)。
(() => {
const picker = document.querySelector('[data-shop-picker]');
if (!picker) {
return;
}
const options = @json(array_values($orderData['orderDataShopOptions'] ?? []), JSON_UNESCAPED_UNICODE);
const chosen = @json(array_values($filters['shop_names'] ?? []), JSON_UNESCAPED_UNICODE);
const maxRender = 300;
// 与后端 shopNames() 的上限一致:一次最多筛 50 个店铺,避免 URL 过长和查询过慢。
const maxSelect = 50;
const toggle = picker.querySelector('[data-shop-toggle]');
const label = picker.querySelector('[data-shop-label]');
const panel = picker.querySelector('[data-shop-panel]');
const search = picker.querySelector('[data-shop-search]');
const list = picker.querySelector('[data-shop-options]');
const hint = picker.querySelector('[data-shop-hint]');
const inputs = picker.querySelector('[data-shop-inputs]');
let keyword = '';
const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (ch) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
}[ch]));
function listed() {
if (!keyword) {
return options.slice();
}
return options.filter((name) => String(name).toLowerCase().includes(keyword));
}
function renderOptions() {
const items = listed();
if (!items.length) {
list.innerHTML = '<div class="order-data-shop__empty">没有匹配的店铺,换个关键字试试</div>';
} else {
list.innerHTML = items.slice(0, maxRender).map((name) => {
const active = chosen.indexOf(name) >= 0;
return '<label class="order-data-shop__option' + (active ? ' is-selected' : '') + '">'
+ '<input type="checkbox" value="' + escapeHtml(name) + '"' + (active ? ' checked' : '') + '>'
+ '<span>' + escapeHtml(name) + '</span></label>';
}).join('');
}
const overflow = items.length - maxRender;
hint.hidden = overflow <= 0;
if (overflow > 0) {
hint.textContent = '还有 ' + overflow + ' 个店铺,输入更精确的关键字再选';
}
}
function showLimitHint() {
hint.hidden = false;
hint.textContent = '一次最多筛选 ' + maxSelect + ' 个店铺,请先清空或缩小关键字范围。';
}
function sync() {
inputs.innerHTML = chosen
.map((name) => '<input type="hidden" name="shop_name[]" value="' + escapeHtml(name) + '">')
.join('');
if (!chosen.length) {
label.textContent = '全部';
toggle.classList.remove('is-set');
toggle.title = '全部店铺';
} else if (chosen.length === 1) {
label.textContent = chosen[0];
toggle.classList.add('is-set');
toggle.title = chosen[0];
} else {
label.textContent = chosen[0] + ' 等 ' + chosen.length + ' 个店铺';
toggle.classList.add('is-set');
toggle.title = chosen.join('、');
}
}
function closePanel() {
panel.hidden = true;
toggle.setAttribute('aria-expanded', 'false');
}
function openPanel() {
panel.hidden = false;
toggle.setAttribute('aria-expanded', 'true');
search.focus();
}
toggle.addEventListener('click', () => (panel.hidden ? openPanel() : closePanel()));
search.addEventListener('input', () => {
keyword = search.value.trim().toLowerCase();
renderOptions();
});
list.addEventListener('change', (event) => {
const checkbox = event.target.closest('input[type="checkbox"]');
if (!checkbox) {
return;
}
const index = chosen.indexOf(checkbox.value);
if (checkbox.checked && index < 0) {
if (chosen.length >= maxSelect) {
checkbox.checked = false;
showLimitHint();
return;
}
chosen.push(checkbox.value);
} else if (!checkbox.checked && index >= 0) {
chosen.splice(index, 1);
}
checkbox.closest('.order-data-shop__option')?.classList.toggle('is-selected', checkbox.checked);
sync();
});
panel.querySelector('[data-shop-action="all"]').addEventListener('click', () => {
const items = listed().slice(0, maxRender);
items.forEach((name) => {
if (chosen.length < maxSelect && chosen.indexOf(name) < 0) {
chosen.push(name);
}
});
renderOptions();
if (items.length > maxSelect) {
showLimitHint();
}
sync();
});
panel.querySelector('[data-shop-action="none"]').addEventListener('click', () => {
chosen.length = 0;
renderOptions();
sync();
});
document.addEventListener('click', (event) => {
if (!picker.contains(event.target)) {
closePanel();
}
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
closePanel();
}
});
renderOptions();
sync();
})();
</script>

View File

@ -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;

View File

@ -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`。
## 组成

View File

@ -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
}
}

View File

@ -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
}

View File

@ -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,94 @@ 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_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();

View File

@ -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('/<th[^>]*data-column-key="income_01"[^>]*is-column-hidden/', $html);
$this->assertMatchesRegularExpression('/<th[^>]*data-column-key="income_02"[^>]*is-column-hidden/', $html);
$this->assertDoesNotMatchRegularExpression('/<th[^>]*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('/<th[^>]*data-column-key="income_01"[^>]*is-column-hidden/', $restoredHtml);
$this->assertDoesNotMatchRegularExpression('/<th[^>]*data-column-key="income_03"[^>]*is-column-hidden/', $restoredHtml);
$this->assertMatchesRegularExpression('/<th[^>]*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('/<th[^>]*data-column-key="sales_01"[^>]*is-column-hidden/', $html);
$this->assertMatchesRegularExpression('/<th[^>]*data-column-key="sales_08"[^>]*is-column-hidden/', $html);
$this->assertDoesNotMatchRegularExpression('/<th[^>]*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('/<th[^>]*data-column-key="sales_01"[^>]*is-column-hidden/', $restoredHtml);
$this->assertDoesNotMatchRegularExpression('/<th[^>]*data-column-key="sales_07"[^>]*is-column-hidden/', $restoredHtml);
$this->assertMatchesRegularExpression('/<th[^>]*data-column-key="sales_08"[^>]*is-column-hidden/', $restoredHtml);
}
}

View File

@ -113,6 +113,120 @@ 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);
}
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);
$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<int,array<string,mixed>> $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');
@ -162,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();
});
}
}

View File

@ -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');