feat(数据看板): 顶部客户多选,预测复用,成本卡按客户过滤 + 表格自适应
- 顶部 SearchableMultiSelect,URL customer_code 逗号串;客户变化后台刷新不卸载筛选框 - 需求预测移除重复客户下拉,使用顶部 customerCodes - 成本/毛利/净利卡接客户过滤;无单号期间成本按当窗客户数分摊 - 需求预测表格 100% 自适应宽度,百分比列宽 - 补 dashboard 契约/helper 测试
This commit is contained in:
@@ -32,6 +32,13 @@ router.get('/summary', authMiddleware, async (req: AuthRequest, res: Response) =
|
||||
const endDate = parseDashboardDateOnly(req.query.end);
|
||||
const customRange =
|
||||
startDate && endDate ? { start: startDate, end: endDate } : null;
|
||||
// 顶部多选客户:新参数 customer_codes,兼容旧 customer_code(都是逗号串/数组)
|
||||
const rawCustomerCodes = req.query.customer_codes ?? req.query.customer_code;
|
||||
const customerCodes = Array.isArray(rawCustomerCodes)
|
||||
? rawCustomerCodes.map((code) => String(code))
|
||||
: rawCustomerCodes == null
|
||||
? null
|
||||
: String(rawCustomerCodes);
|
||||
try {
|
||||
const data = await fetchDashboardSummary(
|
||||
ctx,
|
||||
@@ -39,7 +46,8 @@ router.get('/summary', authMiddleware, async (req: AuthRequest, res: Response) =
|
||||
effectiveBranch,
|
||||
parseDashboardAsOf(req.query.asOf),
|
||||
customRange,
|
||||
typeof req.query.date_field === 'string' ? req.query.date_field : null
|
||||
typeof req.query.date_field === 'string' ? req.query.date_field : null,
|
||||
customerCodes
|
||||
);
|
||||
return res.json({ data });
|
||||
} catch (inner: any) {
|
||||
|
||||
@@ -18,6 +18,9 @@ import {
|
||||
CD_POSTED_STATUS_SQL,
|
||||
costDetailsLinkedOrPeriodCondSql,
|
||||
getDashboardCostOverview,
|
||||
normalizeCustomerCodesFilter,
|
||||
ordersCustomerFilterSql,
|
||||
pushCustomerCodePredicate,
|
||||
normalizeFinanceDateField,
|
||||
orderFinanceRangeCondSql,
|
||||
type FinanceDateField,
|
||||
@@ -97,7 +100,8 @@ export async function fetchDashboardSummary(
|
||||
operatingBranchCode?: string | null,
|
||||
asOf: Date = new Date(),
|
||||
customRange?: { start: Date; end: Date } | null,
|
||||
dateFieldRaw?: string | null
|
||||
dateFieldRaw?: string | null,
|
||||
customerCodesRaw?: string | string[] | null
|
||||
) {
|
||||
const now = Number.isNaN(asOf.getTime()) ? new Date() : asOf;
|
||||
const periodBounds = customRange
|
||||
@@ -131,6 +135,26 @@ export async function fetchDashboardSummary(
|
||||
const periodStartIso = periodBounds.start.toISOString();
|
||||
const periodEndIso = periodBounds.end.toISOString();
|
||||
|
||||
const customerCodes = normalizeCustomerCodesFilter(customerCodesRaw);
|
||||
const periodParams: unknown[] = [periodFrom, periodTo, ...ob3.params];
|
||||
const periodCustomer = ordersCustomerFilterSql(customerCodes, periodParams, 'o');
|
||||
const prevParams: unknown[] = [prevFrom, prevTo, ...ob3.params];
|
||||
const prevCustomer = ordersCustomerFilterSql(customerCodes, prevParams, 'o');
|
||||
const pendingParams: unknown[] = [...ob1.params];
|
||||
const pendingCustomer = ordersCustomerFilterSql(customerCodes, pendingParams, 'o');
|
||||
const pendingDeliveryParams: unknown[] = [...ob1.params];
|
||||
const pendingDeliveryCustomer = ordersCustomerFilterSql(customerCodes, pendingDeliveryParams, 'o');
|
||||
const overdueParams: unknown[] = [...ob1.params];
|
||||
const overdueCustomer = ordersCustomerFilterSql(customerCodes, overdueParams, 'o');
|
||||
const recentParams: unknown[] = [periodFrom, periodTo, ...ob3.params];
|
||||
const recentCustomer = ordersCustomerFilterSql(customerCodes, recentParams, 'o');
|
||||
const customerOrdersParams: unknown[] = [periodFrom, periodTo, ...ob3.params];
|
||||
const customerOrdersCustomer = ordersCustomerFilterSql(customerCodes, customerOrdersParams, 'o');
|
||||
const customerProfilesParams: unknown[] = [...cb1.params];
|
||||
const customerProfilesCustomer = customerCodes.length
|
||||
? ` AND ${pushCustomerCodePredicate(customerCodes, customerProfilesParams, 'c.customer_code')}`
|
||||
: '';
|
||||
|
||||
const [
|
||||
periodStats,
|
||||
previousPeriodStats,
|
||||
@@ -183,8 +207,8 @@ export async function fetchDashboardSummary(
|
||||
) AS delivered_at,
|
||||
${DELIVERY_DEADLINE_AT_SAFE_SQL} AS deadline_at
|
||||
) d ON TRUE
|
||||
WHERE o.deleted_at IS NULL AND ${salesVisibleOrderSql('o')} AND ${orderDateCond}${ob3.clause}`,
|
||||
[periodFrom, periodTo, ...ob3.params]
|
||||
WHERE o.deleted_at IS NULL AND ${salesVisibleOrderSql('o')} AND ${orderDateCond}${ob3.clause}${periodCustomer}`,
|
||||
periodParams
|
||||
),
|
||||
pool.query(
|
||||
`SELECT COUNT(*)::int AS cnt, COALESCE(SUM(rev.revenue), 0) AS amount
|
||||
@@ -194,18 +218,18 @@ export async function fetchDashboardSummary(
|
||||
FROM order_items oi
|
||||
WHERE oi.order_code = o.order_code AND ${salesItemPredicateSql('oi')}
|
||||
) rev ON TRUE
|
||||
WHERE o.deleted_at IS NULL AND ${salesVisibleOrderSql('o')} AND ${orderDateCond}${ob3.clause}`,
|
||||
[prevFrom, prevTo, ...ob3.params]
|
||||
WHERE o.deleted_at IS NULL AND ${salesVisibleOrderSql('o')} AND ${orderDateCond}${ob3.clause}${prevCustomer}`,
|
||||
prevParams
|
||||
),
|
||||
pool.query(
|
||||
`SELECT COUNT(*)::int AS cnt FROM orders o
|
||||
WHERE o.deleted_at IS NULL AND order_status IN (20, 30, 40)${ob1.clause}`,
|
||||
ob1.params
|
||||
WHERE o.deleted_at IS NULL AND order_status IN (20, 30, 40)${ob1.clause}${pendingCustomer}`,
|
||||
pendingParams
|
||||
),
|
||||
pool.query(
|
||||
`SELECT COUNT(*)::int AS cnt FROM orders o
|
||||
WHERE o.deleted_at IS NULL AND order_status = 50${ob1.clause}`,
|
||||
ob1.params
|
||||
WHERE o.deleted_at IS NULL AND order_status = 50${ob1.clause}${pendingDeliveryCustomer}`,
|
||||
pendingDeliveryParams
|
||||
),
|
||||
// 库存预警:只统计商品管理里**填写了安全线**的商品(阈值 0 = 不参与;生鲜不做库存,见 lowStockAlertSql),
|
||||
// 按 SKU 汇总可用量后取 0 < 合计 < 该 SKU 自己的安全线;不再把已耗尽的 0 库存批次算成"低于安全线"。
|
||||
@@ -251,8 +275,8 @@ export async function fetchDashboardSummary(
|
||||
FROM orders o
|
||||
WHERE o.deleted_at IS NULL
|
||||
AND o.delivery_date IS NOT NULL
|
||||
AND o.delivery_date < (NOW() AT TIME ZONE 'Asia/Shanghai')::date${ob1.clause}`,
|
||||
ob1.params
|
||||
AND o.delivery_date < (NOW() AT TIME ZONE 'Asia/Shanghai')::date${ob1.clause}${overdueCustomer}`,
|
||||
overdueParams
|
||||
),
|
||||
// 售后进行中:status 10/20 为未完成(30/40 为已完成/已关闭)
|
||||
// ⚠️ 必须**再按类型排除**建单即终态的三类自动单(order_return/spi_void/inbound_switch):
|
||||
@@ -293,9 +317,9 @@ export async function fetchDashboardSummary(
|
||||
FROM order_items oi
|
||||
WHERE oi.order_code = o.order_code AND ${salesItemPredicateSql('oi')}
|
||||
) rev ON TRUE
|
||||
WHERE o.deleted_at IS NULL AND ${orderDateCond}${ob3.clause}
|
||||
WHERE o.deleted_at IS NULL AND ${orderDateCond}${ob3.clause}${recentCustomer}
|
||||
ORDER BY o.created_at DESC`,
|
||||
[periodFrom, periodTo, ...ob3.params]
|
||||
recentParams
|
||||
),
|
||||
pool.query(
|
||||
`SELECT order_code,
|
||||
@@ -347,13 +371,13 @@ export async function fetchDashboardSummary(
|
||||
pool.query(
|
||||
`SELECT customer_code, company_name, budget_amount, used_budget, created_at
|
||||
FROM customers c
|
||||
WHERE COALESCE(c.status, 10) IN (10, 20, 30)${cb1.clause}`,
|
||||
cb1.params
|
||||
WHERE COALESCE(c.status, 10) IN (10, 20, 30)${cb1.clause}${customerProfilesCustomer}`,
|
||||
customerProfilesParams
|
||||
),
|
||||
pool.query(
|
||||
`SELECT customer_code, order_code, total_amount, created_at, order_status FROM orders o
|
||||
WHERE o.deleted_at IS NULL AND ${orderDateCond}${ob3.clause}`,
|
||||
[periodFrom, periodTo, ...ob3.params]
|
||||
WHERE o.deleted_at IS NULL AND ${orderDateCond}${ob3.clause}${customerOrdersCustomer}`,
|
||||
customerOrdersParams
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -692,6 +716,7 @@ export async function fetchDashboardSummary(
|
||||
* 那是订单表口径 —— 既不过滤未确认/作废单,也不剔除退货行与独立进货单(审计发现的第三套销售额实现)。
|
||||
*/
|
||||
const trendRevenueParams: unknown[] = [periodFrom, periodTo, ...ob3.params];
|
||||
const trendRevenueCustomer = ordersCustomerFilterSql(customerCodes, trendRevenueParams, 'o');
|
||||
const trendMonthExpr =
|
||||
dateField === 'created_at'
|
||||
? `to_char((o.created_at AT TIME ZONE 'Asia/Shanghai'), 'YYYY-MM')`
|
||||
@@ -702,7 +727,7 @@ export async function fetchDashboardSummary(
|
||||
FROM orders o
|
||||
JOIN order_items oi ON oi.order_code = o.order_code
|
||||
WHERE ${salesLinePredicateSql('o', 'oi')}
|
||||
AND ${orderDateCond}${ob3.clause}
|
||||
AND ${orderDateCond}${ob3.clause}${trendRevenueCustomer}
|
||||
GROUP BY 1`,
|
||||
trendRevenueParams
|
||||
);
|
||||
@@ -745,7 +770,8 @@ export async function fetchDashboardSummary(
|
||||
previousBounds.start,
|
||||
previousBounds.end,
|
||||
effectiveBranch || null,
|
||||
dateField
|
||||
dateField,
|
||||
customerCodes
|
||||
);
|
||||
|
||||
const customerProfiles = customers.rows.map((c) => {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const service = readFileSync(
|
||||
new URL('../src/services/dashboardService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const route = readFileSync(new URL('../src/routes/dashboard.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('dashboard customer_codes 后端契约', () => {
|
||||
it('route 解析 customer_codes,兼容 customer_code', () => {
|
||||
expect(route).toContain('req.query.customer_codes');
|
||||
expect(route).toContain('req.query.customer_code');
|
||||
expect(route).toContain('customerCodes');
|
||||
});
|
||||
|
||||
it('service 把客户码用于期间/环比/待处理/待配送/逾期/近期/客户画像/趋势', () => {
|
||||
expect(service).toContain('normalizeCustomerCodesFilter(customerCodesRaw)');
|
||||
for (const flag of [
|
||||
'periodCustomer',
|
||||
'prevCustomer',
|
||||
'pendingCustomer',
|
||||
'pendingDeliveryCustomer',
|
||||
'overdueCustomer',
|
||||
'recentCustomer',
|
||||
'customerOrdersCustomer',
|
||||
'customerProfilesCustomer',
|
||||
'trendRevenueCustomer',
|
||||
]) {
|
||||
expect(service, flag).toContain(flag);
|
||||
}
|
||||
});
|
||||
|
||||
it('无客户维度的库存/临期仍保持原查询(不被误加订单客户条件)', () => {
|
||||
const lowStockBlock = service.slice(
|
||||
service.indexOf('FROM inventory i'),
|
||||
service.indexOf('FROM inventory i') + 700
|
||||
);
|
||||
expect(lowStockBlock).not.toContain('customer_code');
|
||||
const expiringBlock = service.slice(
|
||||
service.indexOf('COUNT(*) FILTER (', service.indexOf('临期 / 已过期')),
|
||||
service.indexOf('COUNT(*) FILTER (', service.indexOf('临期 / 已过期')) + 900
|
||||
);
|
||||
expect(expiringBlock).not.toContain('customer_code');
|
||||
});
|
||||
});
|
||||
+55
-90
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useMenuItemLabel } from '../hooks/useMenuItemLabel';
|
||||
import { useI18n } from '../i18n/I18nProvider';
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
} from '../utils/dashboardPeriod';
|
||||
import { DateRangeFilterButton, type DateRangeValue } from '../components/ui/DateRangeFilterButton';
|
||||
import { SearchableSelect } from '../components/ui/SearchableSelect';
|
||||
import { SearchableMultiSelect } from '../components/ui/SearchableMultiSelect';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { useOperatingBranch } from '../hooks/useOperatingBranch';
|
||||
import { useCategoryRows } from '../hooks/useCategoryRows';
|
||||
@@ -72,6 +73,7 @@ import { SortableThLabel } from '../components/ui/SortableThLabel';
|
||||
import { readElementFont } from '../utils/measureTextWidth';
|
||||
import { StatusBadge } from '../components/StatusBadge';
|
||||
import { useUrlFilterParam } from '../hooks/useUrlFilterParam';
|
||||
import { parseCustomerCodes, serializeCustomerCodesParam } from '../utils/customerCodes';
|
||||
import {
|
||||
normalizeStatementDateField,
|
||||
type StatementDateField,
|
||||
@@ -348,6 +350,11 @@ export const Dashboard: React.FC = () => {
|
||||
const [asOfDate, setAsOfDate] = useState(() => getChinaDateString());
|
||||
const [appliedRange, setAppliedRange] = useState<DashboardRange | null>(() => getTodayRange());
|
||||
const [urlDateField, setUrlDateField] = useUrlFilterParam('date_field');
|
||||
const [customerCode, setCustomerCode] = useUrlFilterParam('customer_code');
|
||||
const customerCodes = useMemo(() => parseCustomerCodes(customerCode), [customerCode]);
|
||||
const [customerOptions, setCustomerOptions] = useState<
|
||||
Array<{ customer_code: string; company_name: string }>
|
||||
>([]);
|
||||
const [dateField, setDateField] = useState<DashboardDateField>(() =>
|
||||
normalizeDashboardDateField(urlDateField)
|
||||
);
|
||||
@@ -372,15 +379,10 @@ export const Dashboard: React.FC = () => {
|
||||
const [forecastError, setForecastError] = useState<string | null>(null);
|
||||
const [selectedForecastCategories, setSelectedForecastCategories] = useState<string[]>([]);
|
||||
const [selectedForecastSkus, setSelectedForecastSkus] = useState<string[]>([]);
|
||||
const [selectedForecastCustomers, setSelectedForecastCustomers] = useState<string[]>([]);
|
||||
/** 计算时间(历史样本窗口);null = 沿用默认近 N 天 */
|
||||
const [forecastCalcRange, setForecastCalcRange] = useState<DateRangeValue | null>(null);
|
||||
/** 上次预测实际使用的计算区间(用于样本窗口卡片展示) */
|
||||
const [forecastCalcRangeUsed, setForecastCalcRangeUsed] = useState<DateRangeValue | null>(null);
|
||||
const [forecastCustomerOptions, setForecastCustomerOptions] = useState<
|
||||
Array<{ customer_code: string; company_name: string }>
|
||||
>([]);
|
||||
const [forecastCustomerLoading, setForecastCustomerLoading] = useState(false);
|
||||
const [forecastSkuOptions, setForecastSkuOptions] = useState<
|
||||
Array<{ sku_code: string; sku_name: string; category_code: string }>
|
||||
>([]);
|
||||
@@ -409,12 +411,26 @@ export const Dashboard: React.FC = () => {
|
||||
const beginDashboardFetch = useFetchGeneration();
|
||||
const beginForecastFetch = useFetchGeneration();
|
||||
const {
|
||||
totalWidth: forecastTableWidth,
|
||||
getColumnStyle: getForecastColumnStyle,
|
||||
widths: forecastColumnWidths,
|
||||
onResizePointerDown: onForecastResizePointerDown,
|
||||
resetWidths: resetForecastWidths,
|
||||
fitToContent: fitForecastToContent,
|
||||
} = useTableColumnWidths(FORECAST_COLUMN_WIDTH_KEY, FORECAST_DEFAULT_WIDTHS, FORECAST_WIDTH_OPTIONS);
|
||||
const forecastWidthTotal = Math.max(
|
||||
1,
|
||||
forecastOrderedColumns.reduce(
|
||||
(sum, col) => sum + (forecastColumnWidths[col.id] ?? FORECAST_DEFAULT_WIDTHS[col.id] ?? 1),
|
||||
0
|
||||
)
|
||||
);
|
||||
/** 百分比列宽:始终铺满容器,避免列宽总和固定导致横向滚动 */
|
||||
const forecastResponsiveStyle = useCallback(
|
||||
(id: ForecastColumnId) => ({
|
||||
width: `${(((forecastColumnWidths[id] ?? FORECAST_DEFAULT_WIDTHS[id] ?? 1) / forecastWidthTotal) * 100).toFixed(4)}%`,
|
||||
minWidth: 0,
|
||||
}),
|
||||
[forecastColumnWidths, forecastWidthTotal]
|
||||
);
|
||||
const forecastSort = useClientTableSort<ForecastSortKey>();
|
||||
|
||||
const [costOverview, setCostOverview] = useState<CostOverview>(EMPTY_COST_OVERVIEW);
|
||||
@@ -441,6 +457,7 @@ export const Dashboard: React.FC = () => {
|
||||
appliedRange?.start,
|
||||
appliedRange?.end,
|
||||
dateField,
|
||||
customerCode,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -479,13 +496,10 @@ export const Dashboard: React.FC = () => {
|
||||
};
|
||||
}, [activeTab, authLoading, isAdmin, isSuperAdmin, operatingBranchCode, dashboardBranchCode]);
|
||||
|
||||
// 客户下拉:status 10/20(正常/预算超额),按当前经营分公司过滤
|
||||
// 顶部客户多选:status 10/20(正常/预算超额),按当前经营分公司过滤
|
||||
useEffect(() => {
|
||||
if (activeTab !== 'ai') return;
|
||||
if (authLoading || !isAdmin) return;
|
||||
if (isSuperAdmin && !operatingBranchCode) return;
|
||||
if (authLoading) return;
|
||||
let cancelled = false;
|
||||
setForecastCustomerLoading(true);
|
||||
(async () => {
|
||||
const base = () =>
|
||||
supabase
|
||||
@@ -500,22 +514,20 @@ export const Dashboard: React.FC = () => {
|
||||
if (cancelled) return;
|
||||
if (error) {
|
||||
console.error(error);
|
||||
setForecastCustomerOptions([]);
|
||||
setForecastCustomerLoading(false);
|
||||
setCustomerOptions([]);
|
||||
return;
|
||||
}
|
||||
setForecastCustomerOptions(
|
||||
setCustomerOptions(
|
||||
(data || []).map((r: any) => ({
|
||||
customer_code: String(r.customer_code || ''),
|
||||
company_name: String(r.company_name || r.customer_code || ''),
|
||||
}))
|
||||
);
|
||||
setForecastCustomerLoading(false);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [activeTab, authLoading, isAdmin, isSuperAdmin, operatingBranchCode, dashboardBranchCode]);
|
||||
}, [authLoading, dashboardBranchCode]);
|
||||
|
||||
const forecastCategorySelectOptions = useMemo(
|
||||
() =>
|
||||
@@ -557,26 +569,6 @@ export const Dashboard: React.FC = () => {
|
||||
}));
|
||||
}, [forecastSkuOptions, selectedForecastSkus]);
|
||||
|
||||
const forecastCustomerSelectOptions = useMemo(
|
||||
() =>
|
||||
forecastCustomerOptions
|
||||
.filter((c) => !selectedForecastCustomers.includes(c.customer_code))
|
||||
.map((c) => ({
|
||||
value: c.customer_code,
|
||||
label: c.company_name,
|
||||
searchText: `${c.customer_code} ${c.company_name}`,
|
||||
})),
|
||||
[forecastCustomerOptions, selectedForecastCustomers]
|
||||
);
|
||||
|
||||
const selectedForecastCustomerTags = useMemo(() => {
|
||||
const byCode = new Map(forecastCustomerOptions.map((c) => [c.customer_code, c.company_name]));
|
||||
return selectedForecastCustomers.map((code) => ({
|
||||
code,
|
||||
label: byCode.get(code) || code,
|
||||
}));
|
||||
}, [forecastCustomerOptions, selectedForecastCustomers]);
|
||||
|
||||
/** 未选客户时的默认样本天数(与后端 defaultDays 一致) */
|
||||
const forecastDefaultWindowDays = forecastHorizon > 7 ? 28 : 14;
|
||||
|
||||
@@ -597,7 +589,7 @@ export const Dashboard: React.FC = () => {
|
||||
limit: 500,
|
||||
category_codes: selectedForecastCategories,
|
||||
sku_codes: selectedForecastSkus,
|
||||
customer_codes: selectedForecastCustomers,
|
||||
customer_codes: customerCodes,
|
||||
date_from: forecastCalcRange?.start,
|
||||
date_to: forecastCalcRange?.end,
|
||||
});
|
||||
@@ -616,15 +608,6 @@ export const Dashboard: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const addForecastCustomer = (code: string) => {
|
||||
if (!code) return;
|
||||
setSelectedForecastCustomers((prev) => (prev.includes(code) ? prev : [...prev, code]));
|
||||
};
|
||||
|
||||
const removeForecastCustomer = (code: string) => {
|
||||
setSelectedForecastCustomers((prev) => prev.filter((c) => c !== code));
|
||||
};
|
||||
|
||||
const addForecastCategory = (code: string) => {
|
||||
if (!code) return;
|
||||
setSelectedForecastCategories((prev) => (prev.includes(code) ? prev : [...prev, code]));
|
||||
@@ -723,13 +706,15 @@ export const Dashboard: React.FC = () => {
|
||||
) => {
|
||||
const { isStale } = beginDashboardFetch();
|
||||
try {
|
||||
setLoading(true);
|
||||
// 不在每次筛选/刷新时把整页切回 loading 骨架:那会卸载顶部客户多选框,
|
||||
// 表现为“每选一个客户就闪一下、下拉被关掉”。初始 loading=true 仍保留首屏骨架。
|
||||
setLoadError(null);
|
||||
const data = await fetchDashboardSummary(period, {
|
||||
asOf,
|
||||
start: range?.start,
|
||||
end: range?.end,
|
||||
date_field: field,
|
||||
customer_codes: customerCodes.length ? customerCodes : undefined,
|
||||
});
|
||||
if (isStale()) return;
|
||||
// 先整体展开服务端 stats,再逐个补默认值。
|
||||
@@ -1315,6 +1300,21 @@ export const Dashboard: React.FC = () => {
|
||||
setAppliedRange(next);
|
||||
}}
|
||||
/>
|
||||
<div className="min-w-[200px] w-56">
|
||||
<SearchableMultiSelect
|
||||
values={customerCodes}
|
||||
onChange={(codes) => setCustomerCode(serializeCustomerCodesParam(codes))}
|
||||
options={customerOptions.map((row) => ({
|
||||
value: row.customer_code,
|
||||
label: row.company_name,
|
||||
searchText: row.customer_code,
|
||||
}))}
|
||||
emptyLabel={t('finance.allCustomers')}
|
||||
placeholder={t('finance.allCustomers')}
|
||||
className="w-full"
|
||||
zIndexClass="z-[100]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1613,7 +1613,6 @@ export const Dashboard: React.FC = () => {
|
||||
onClick={() => {
|
||||
setSelectedForecastCategories([]);
|
||||
setSelectedForecastSkus([]);
|
||||
setSelectedForecastCustomers([]);
|
||||
setForecastCalcRange(null);
|
||||
setForecastCalcRangeUsed(null);
|
||||
setForecast(null);
|
||||
@@ -1625,7 +1624,7 @@ export const Dashboard: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<SearchableSelect
|
||||
value=""
|
||||
onChange={addForecastCategory}
|
||||
@@ -1646,17 +1645,6 @@ export const Dashboard: React.FC = () => {
|
||||
portal
|
||||
maxVisibleOptions={80}
|
||||
/>
|
||||
<SearchableSelect
|
||||
value=""
|
||||
onChange={addForecastCustomer}
|
||||
options={forecastCustomerSelectOptions}
|
||||
placeholder={forecastCustomerLoading ? t('dashboard.forecast.custLoading') : t('dashboard.forecast.addCustomer')}
|
||||
allowEmpty
|
||||
emptyLabel={t('dashboard.forecast.addCustomer')}
|
||||
disabled={forecastCustomerLoading}
|
||||
portal
|
||||
maxVisibleOptions={80}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
@@ -1700,29 +1688,6 @@ export const Dashboard: React.FC = () => {
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
{selectedForecastCustomerTags.map((tag) => (
|
||||
<span
|
||||
key={`cust:${tag.code}`}
|
||||
className="inline-flex items-center gap-1 rounded-md border border-amber-200 bg-amber-50 px-2 py-1 text-xs text-amber-800 dark:border-amber-500/40 dark:bg-amber-500/15 dark:text-amber-200"
|
||||
>
|
||||
<span className="opacity-70">{t('dashboard.forecast.tagCustomer')}</span>
|
||||
<span className="max-w-[12rem] truncate">{tag.label}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded p-0.5 hover:bg-amber-100 dark:hover:bg-amber-500/30"
|
||||
aria-label={t('dashboard.forecast.removeCustomer', { name: tag.label })}
|
||||
onClick={() => removeForecastCustomer(tag.code)}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
{selectedForecastCustomers.length === 0 && (
|
||||
<span className="inline-flex items-center gap-1 rounded-md border border-sky-200 bg-sky-50 px-2 py-1 text-xs text-sky-800 dark:border-sky-500/40 dark:bg-sky-500/15 dark:text-sky-200">
|
||||
<span className="opacity-70">{t('dashboard.forecast.tagCustomer')}</span>
|
||||
<span>{t('dashboard.forecast.allCustomers')}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1808,15 +1773,15 @@ export const Dashboard: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-h-[min(70vh,720px)] overflow-auto isolate">
|
||||
<div className="max-h-[min(70vh,720px)] overflow-y-auto overflow-x-hidden isolate">
|
||||
<table
|
||||
ref={forecastTableRef}
|
||||
className="border-separate border-spacing-0 text-sm table-fixed"
|
||||
style={{ width: forecastTableWidth, minWidth: forecastTableWidth }}
|
||||
className="border-separate border-spacing-0 text-sm table-fixed w-full"
|
||||
style={{ width: '100%', minWidth: '100%' }}
|
||||
>
|
||||
<colgroup>
|
||||
{forecastOrderedColumns.map((col) => (
|
||||
<col key={col.id} style={getForecastColumnStyle(col.id)} />
|
||||
<col key={col.id} style={forecastResponsiveStyle(col.id)} />
|
||||
))}
|
||||
</colgroup>
|
||||
<thead className="sticky top-0 z-30 bg-slate-50 dark:bg-slate-800">
|
||||
@@ -1844,7 +1809,7 @@ export const Dashboard: React.FC = () => {
|
||||
className={`relative sticky top-0 z-30 border border-slate-700 dark:border-slate-500 px-2 py-1 text-xs font-semibold app-foreground whitespace-nowrap select-none bg-slate-50 dark:bg-slate-800 shadow-[0_1px_0_0_rgb(51_65_85)] ${
|
||||
center ? 'text-center' : 'text-left'
|
||||
} ${sortable ? 'cursor-pointer' : ''}`}
|
||||
style={{ ...headerDragStyle, ...getForecastColumnStyle(col.id) }}
|
||||
style={{ ...headerDragStyle, ...forecastResponsiveStyle(col.id) }}
|
||||
onClick={
|
||||
sortable
|
||||
? () => forecastSort.toggle(col.id as ForecastSortKey)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
|
||||
const page = read('./Dashboard.tsx');
|
||||
const api = read('../utils/dashboardApi.ts');
|
||||
const route = read('../../server/src/routes/dashboard.ts');
|
||||
const service = read('../../server/src/services/dashboardService.ts');
|
||||
|
||||
describe('数据看板客户多选 + 需求预测复用', () => {
|
||||
it('顶部 SearchableMultiSelect,URL 仍 customer_code 逗号串', () => {
|
||||
expect(page).toContain('<SearchableMultiSelect');
|
||||
expect(page).toContain('values={customerCodes}');
|
||||
expect(page).toContain('serializeCustomerCodesParam(codes)');
|
||||
expect(page).toContain("useUrlFilterParam('customer_code')");
|
||||
expect(page).toContain('customer_codes: customerCodes.length ? customerCodes : undefined');
|
||||
});
|
||||
|
||||
it('需求预测复用顶部 customerCodes,删除独立客户状态/UI', () => {
|
||||
expect(page).toContain('customer_codes: customerCodes');
|
||||
expect(page).not.toContain('selectedForecastCustomers');
|
||||
expect(page).not.toContain('forecastCustomerOptions');
|
||||
expect(page).not.toContain('addForecastCustomer');
|
||||
});
|
||||
|
||||
it('dashboardApi 非空才带 customer_codes', () => {
|
||||
expect(api).toContain('customer_codes?: string | string[] | null');
|
||||
expect(api).toContain("query.set('customer_codes'");
|
||||
});
|
||||
|
||||
it('后端兼容 customer_codes/customer_code,并在客户维度查询上加过滤', () => {
|
||||
expect(route).toContain('req.query.customer_codes');
|
||||
expect(route).toContain('req.query.customer_code');
|
||||
expect(service).toContain('normalizeCustomerCodesFilter(customerCodesRaw)');
|
||||
for (const flag of [
|
||||
'periodCustomer',
|
||||
'prevCustomer',
|
||||
'pendingCustomer',
|
||||
'pendingDeliveryCustomer',
|
||||
'overdueCustomer',
|
||||
'recentCustomer',
|
||||
'customerOrdersCustomer',
|
||||
'customerProfilesCustomer',
|
||||
'trendRevenueCustomer',
|
||||
]) {
|
||||
expect(service, flag).toContain(flag);
|
||||
}
|
||||
// 库存/临期/损耗/售后查询不因客户筛选而改口径
|
||||
expect(service).toContain('FROM inventory i');
|
||||
expect(service).toContain('getDashboardCostOverview');
|
||||
expect(service).toContain('customerCodes');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { buildApiUrl } from '../lib/apiConfig';
|
||||
import { parseCustomerCodes } from './customerCodes';
|
||||
import { readAuthSessionRaw } from '../lib/authSession';
|
||||
import { getOperatingBranchHeader } from './operatingBranch';
|
||||
import type { DashboardPeriodType } from './dashboardPeriod';
|
||||
@@ -25,7 +26,14 @@ function authHeaders(): Record<string, string> {
|
||||
|
||||
export async function fetchDashboardSummary(
|
||||
period: DashboardPeriodType = DEFAULT_DASHBOARD_PERIOD,
|
||||
options?: { asOf?: string; start?: string; end?: string; date_field?: string }
|
||||
options?: {
|
||||
asOf?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
date_field?: string;
|
||||
/** 顶部客户多选(逗号串/数组) */
|
||||
customer_codes?: string | string[] | null;
|
||||
}
|
||||
) {
|
||||
const query = new URLSearchParams({ period });
|
||||
if (options?.asOf) query.set('asOf', options.asOf);
|
||||
@@ -36,6 +44,10 @@ export async function fetchDashboardSummary(
|
||||
if (options?.date_field && options.date_field !== 'delivery_date') {
|
||||
query.set('date_field', options.date_field);
|
||||
}
|
||||
const customerCodes = Array.isArray(options?.customer_codes)
|
||||
? options.customer_codes
|
||||
: parseCustomerCodes(options?.customer_codes);
|
||||
if (customerCodes.length) query.set('customer_codes', customerCodes.join(','));
|
||||
const response = await fetch(buildApiUrl(`/dashboard/summary?${query.toString()}`), {
|
||||
headers: authHeaders(),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user