fix(limit-management): 完善破价权限、流程日期与Excel导出
运营默认可申诉、经管默认可审核;流程结束日期缺失时回退限价生效日期;破价订单改为服务端流式XLSX导出并防止重复点击。
This commit is contained in:
parent
a7f8884adc
commit
ff6f4f0da5
@ -97,6 +97,7 @@
|
||||
**例外(2026-10-16 确认)**:期初数据的「更新日期」**晚于**流程完成时间时,以期初数据为准(谁新用谁);
|
||||
期初比流程旧则维持上面的优先级。
|
||||
`SupplyChainStyleLimitPrice.flowEndDate` 保存当前最终生效限价对应的流程结束日期:明细有“结束时间”时优先使用,否则回退流程完成时间。
|
||||
对历史订单,按付款时点选中限价版本后,若该版本的流程结束日期为空,则使用该版本的 `effectiveAt` 作为流程结束日期展示和判断;例如期初限价生效日 `2026-01-04` 会显示在“流程结束日期”列。
|
||||
每日流程同步同时重建 `SupplyChainStyleLimitPriceVersion`,流程、产品限价页面、期初价和人工限价都保留各自 `effectiveAt`,供历史订单按付款时点选版。
|
||||
**非负责人限价一律按最新口径计算**(2026-10-16 确认):负责人限价 × 1.05,且不低于 +10 元;
|
||||
期初数据表 / 产品限价页面里的历史「非负责人限价」(倍数 1%~15% 不统一)不采用,
|
||||
|
||||
@ -0,0 +1,102 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
jest.mock('@/server/core/response', () => ({
|
||||
handleRequest: jest.fn(async (_request, handler) => handler({
|
||||
requestId: 'test-request',
|
||||
user: { id: 'user-1', name: '测试用户' },
|
||||
})),
|
||||
jsonError: jest.fn((_code, message, status) => ({ success: false, message, status })),
|
||||
}))
|
||||
|
||||
const mockResolveViewer = jest.fn()
|
||||
const mockListPage = jest.fn()
|
||||
|
||||
jest.mock('@/server/services/supply-chain-breach-order.service', () => ({
|
||||
supplyChainBreachOrderService: {
|
||||
resolveViewer: (...args: unknown[]) => mockResolveViewer(...args),
|
||||
listPage: (...args: unknown[]) => mockListPage(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
import ExcelJS from 'exceljs'
|
||||
import { GET } from './route'
|
||||
|
||||
describe('破价订单导出接口', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockResolveViewer.mockResolvedValue({
|
||||
id: 'user-1',
|
||||
name: '测试用户',
|
||||
canAppeal: false,
|
||||
canReview: true,
|
||||
})
|
||||
mockListPage.mockResolvedValue({
|
||||
rows: [{
|
||||
id: 'row-1',
|
||||
platform: '京东',
|
||||
shopName: '店铺甲',
|
||||
soId: 'SO-1',
|
||||
oId: 'O-1',
|
||||
payDate: '2026-11-11T02:00:00.000Z',
|
||||
itemCode: 'BAR-1',
|
||||
shopItemCode: 'SHOP-1',
|
||||
shopStyleCode: 'LINK-1',
|
||||
qty: 1,
|
||||
buyerPaidAmount: 80,
|
||||
platformBearAmount: 20,
|
||||
sellerIncomeAmount: 100,
|
||||
limitUnitPrice: 120,
|
||||
limitTotal: 120,
|
||||
gapAmount: -40,
|
||||
ownerName: '运营甲',
|
||||
deptOwner: '部门甲',
|
||||
profitCenter: '中心甲',
|
||||
orderStatus: 'Sent',
|
||||
refundStatus: '',
|
||||
flowEndDate: '2026-11-01T00:00:00.000Z',
|
||||
status: 'PENDING_APPEAL',
|
||||
statusLabel: '待申诉',
|
||||
appealType: '',
|
||||
processNo: '',
|
||||
reviewReason: '',
|
||||
reviewedBy: '',
|
||||
}],
|
||||
pageInfo: { page: 1, pageSize: 5000, total: 1, totalPages: 1 },
|
||||
stats: { total: 0, byStatus: {} },
|
||||
})
|
||||
})
|
||||
|
||||
it('streams an XLSX attachment with the requested filters', async () => {
|
||||
const filters = encodeURIComponent(JSON.stringify({
|
||||
dateFrom: '2026-11-01',
|
||||
dateTo: '2026-11-30',
|
||||
}))
|
||||
const response = await GET({
|
||||
method: 'GET',
|
||||
nextUrl: new URL(
|
||||
`http://localhost/api/supply-chain/limit-management/breach-orders/export?kind=list&filters=${filters}`,
|
||||
),
|
||||
} as never)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('content-type')).toContain('spreadsheetml.sheet')
|
||||
expect(response.headers.get('content-disposition')).toContain('attachment')
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.load(Buffer.from(await response.arrayBuffer()))
|
||||
const sheet = workbook.getWorksheet('破价订单审核')!
|
||||
const headers = sheet.getRow(1).values as unknown[]
|
||||
expect(headers).toContain('付款日期')
|
||||
expect(headers).toContain('流程结束日期')
|
||||
expect(sheet.getRow(2).values).toContain('SO-1')
|
||||
expect(sheet.getRow(2).values).toContain('运营甲')
|
||||
expect(mockListPage).toHaveBeenCalledWith(expect.objectContaining({
|
||||
page: 1,
|
||||
pageSize: 5000,
|
||||
filters: expect.objectContaining({
|
||||
dateFrom: '2026-11-01',
|
||||
dateTo: '2026-11-30',
|
||||
}),
|
||||
includeStats: false,
|
||||
}))
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,230 @@
|
||||
import { PassThrough, Readable } from 'node:stream'
|
||||
import ExcelJS from 'exceljs'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { handleRequest, jsonError } from '@/server/core/response'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { supplyChainBreachOrderService } from '@/server/services/supply-chain-breach-order.service'
|
||||
|
||||
const filtersSchema = z.object({
|
||||
status: z.array(z.string()).optional(),
|
||||
platform: z.array(z.string().max(40)).max(50).optional(),
|
||||
shopName: z.array(z.string().max(120)).max(50).optional(),
|
||||
ownerName: z.array(z.string()).optional(),
|
||||
keyword: z.string().optional(),
|
||||
itemCode: z.array(z.string().max(120)).max(50).optional(),
|
||||
shopStyleCode: z.array(z.string().max(120)).max(50).optional(),
|
||||
shopItemCode: z.array(z.string().max(120)).max(50).optional(),
|
||||
orderNo: z.array(z.string().max(80)).max(50).optional(),
|
||||
ownerKeyword: z.array(z.string().max(60)).max(50).optional(),
|
||||
appealType: z.array(z.string().max(60)).max(50).optional(),
|
||||
dateFrom: z.string().max(10).optional(),
|
||||
dateTo: z.string().max(10).optional(),
|
||||
}).strict()
|
||||
|
||||
const querySchema = z.object({
|
||||
kind: z.enum(['list', 'fine']).default('list'),
|
||||
filters: z.string().optional(),
|
||||
sort: z.string().optional(),
|
||||
})
|
||||
|
||||
const sortSchema = z.object({
|
||||
field: z.string().max(40),
|
||||
direction: z.enum(['asc', 'desc']),
|
||||
}).strict()
|
||||
|
||||
const LIST_COLUMNS = [
|
||||
{ header: '付款日期', key: 'payDate', width: 13 },
|
||||
{ header: '平台', key: 'platform', width: 14 },
|
||||
{ header: '店铺', key: 'shopName', width: 28 },
|
||||
{ header: '线上订单号', key: 'soId', width: 24 },
|
||||
{ header: '内部订单号', key: 'oId', width: 16 },
|
||||
{ header: '商品编码', key: 'itemCode', width: 24 },
|
||||
{ header: '店铺款式编码', key: 'shopStyleCode', width: 20 },
|
||||
{ header: '店铺商品编码', key: 'shopItemCode', width: 20 },
|
||||
{ header: '数量', key: 'qty', width: 10 },
|
||||
{ header: '买家实付', key: 'buyerPaidAmount', width: 14 },
|
||||
{ header: '平台承担', key: 'platformBearAmount', width: 14 },
|
||||
{ header: '商家实收', key: 'sellerIncomeAmount', width: 14 },
|
||||
{ header: '限价单价', key: 'limitUnitPrice', width: 14 },
|
||||
{ header: '限价×数量', key: 'limitTotal', width: 14 },
|
||||
{ header: '价差', key: 'gapAmount', width: 13 },
|
||||
{ header: '运营负责人', key: 'ownerName', width: 16 },
|
||||
{ header: '部门负责人', key: 'deptOwner', width: 16 },
|
||||
{ header: '利润中心', key: 'profitCenter', width: 14 },
|
||||
{ header: '订单状态', key: 'orderStatus', width: 14 },
|
||||
{ header: '退款状态', key: 'refundStatus', width: 14 },
|
||||
{ header: '流程结束日期', key: 'flowEndDate', width: 14 },
|
||||
{ header: '审核状态', key: 'statusLabel', width: 13 },
|
||||
{ header: '申诉类型', key: 'appealType', width: 30 },
|
||||
{ header: '流程号', key: 'processNo', width: 24 },
|
||||
] as const
|
||||
|
||||
const FINE_COLUMNS = [
|
||||
{ header: '线上订单号', key: 'soId', width: 24 },
|
||||
{ header: '内部订单号', key: 'oId', width: 16 },
|
||||
{ header: '平台', key: 'platform', width: 14 },
|
||||
{ header: '店铺', key: 'shopName', width: 28 },
|
||||
{ header: '商品编码', key: 'itemCode', width: 24 },
|
||||
{ header: '运营负责人', key: 'ownerName', width: 16 },
|
||||
{ header: '部门负责人', key: 'deptOwner', width: 16 },
|
||||
{ header: '利润中心', key: 'profitCenter', width: 14 },
|
||||
{ header: '商家实收', key: 'sellerIncomeAmount', width: 14 },
|
||||
{ header: '限价', key: 'limitTotal', width: 14 },
|
||||
{ header: '价差', key: 'gapAmount', width: 13 },
|
||||
{ header: '驳回原因', key: 'reviewReason', width: 26 },
|
||||
{ header: '审核人', key: 'reviewedBy', width: 16 },
|
||||
{ header: '乐捐金额', key: 'fineAmount', width: 14 },
|
||||
] as const
|
||||
|
||||
function day(value: string | Date | null) {
|
||||
return value ? new Date(value).toISOString().slice(0, 10) : ''
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const parsed = querySchema.safeParse({
|
||||
kind: request.nextUrl.searchParams.get('kind') ?? undefined,
|
||||
filters: request.nextUrl.searchParams.get('filters') ?? undefined,
|
||||
sort: request.nextUrl.searchParams.get('sort') ?? undefined,
|
||||
})
|
||||
if (!parsed.success) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '导出参数不正确', 400, ctx.requestId)
|
||||
}
|
||||
|
||||
let filters: z.infer<typeof filtersSchema> = {}
|
||||
if (parsed.data.filters) {
|
||||
const parsedFilters = filtersSchema.safeParse(JSON.parse(parsed.data.filters))
|
||||
if (!parsedFilters.success) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '筛选条件格式不正确', 400, ctx.requestId)
|
||||
}
|
||||
filters = parsedFilters.data
|
||||
}
|
||||
|
||||
let sort: z.infer<typeof sortSchema> | undefined
|
||||
if (parsed.data.sort) {
|
||||
const parsedSort = sortSchema.safeParse(JSON.parse(parsed.data.sort))
|
||||
if (!parsedSort.success) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '排序参数不正确', 400, ctx.requestId)
|
||||
}
|
||||
sort = parsedSort.data
|
||||
}
|
||||
|
||||
const viewer = await supplyChainBreachOrderService.resolveViewer(ctx.user)
|
||||
const kind = parsed.data.kind
|
||||
const effectiveFilters = kind === 'fine'
|
||||
? {
|
||||
...filters,
|
||||
status: ['PENDING_APPEAL', 'PENDING_REVIEW', 'RETURNED', 'REJECTED'],
|
||||
}
|
||||
: filters
|
||||
const output = new PassThrough()
|
||||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||||
stream: output,
|
||||
useSharedStrings: false,
|
||||
useStyles: true,
|
||||
})
|
||||
workbook.creator = '供应链系统'
|
||||
workbook.created = new Date()
|
||||
const worksheet = workbook.addWorksheet(
|
||||
kind === 'fine' ? '破价乐捐明细' : '破价订单审核',
|
||||
{ views: [{ state: 'frozen', ySplit: 1 }] },
|
||||
)
|
||||
worksheet.columns = (kind === 'fine' ? FINE_COLUMNS : LIST_COLUMNS).map((column) => ({ ...column }))
|
||||
worksheet.getRow(1).font = { bold: true }
|
||||
worksheet.getRow(1).fill = {
|
||||
type: 'pattern',
|
||||
pattern: 'solid',
|
||||
fgColor: { argb: 'FFE8EEF5' },
|
||||
}
|
||||
worksheet.getRow(1).commit()
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const seenFineOrders = new Set<string>()
|
||||
let page = 1
|
||||
let totalPages = 1
|
||||
do {
|
||||
const data = await supplyChainBreachOrderService.listPage({
|
||||
page,
|
||||
pageSize: 5000,
|
||||
filters: effectiveFilters,
|
||||
sort,
|
||||
viewer,
|
||||
includeStats: false,
|
||||
})
|
||||
totalPages = data.pageInfo.totalPages
|
||||
for (const row of data.rows) {
|
||||
if (kind === 'fine') {
|
||||
const fineOrderKey = row.soId.trim() || row.id
|
||||
const assessedFine = !seenFineOrders.has(fineOrderKey)
|
||||
&& !['APPROVED', 'LEFT_EMPLOYEE'].includes(row.status)
|
||||
? 10
|
||||
: 0
|
||||
if (assessedFine > 0) seenFineOrders.add(fineOrderKey)
|
||||
worksheet.addRow({
|
||||
soId: row.soId,
|
||||
oId: row.oId,
|
||||
platform: row.platform,
|
||||
shopName: row.shopName,
|
||||
itemCode: row.itemCode,
|
||||
ownerName: row.ownerName,
|
||||
deptOwner: row.deptOwner,
|
||||
profitCenter: row.profitCenter,
|
||||
sellerIncomeAmount: row.sellerIncomeAmount,
|
||||
limitTotal: row.limitTotal,
|
||||
gapAmount: row.gapAmount,
|
||||
reviewReason: row.reviewReason,
|
||||
reviewedBy: row.reviewedBy,
|
||||
fineAmount: assessedFine,
|
||||
}).commit()
|
||||
} else {
|
||||
worksheet.addRow({
|
||||
payDate: day(row.payDate),
|
||||
platform: row.platform,
|
||||
shopName: row.shopName,
|
||||
soId: row.soId,
|
||||
oId: row.oId,
|
||||
itemCode: row.itemCode,
|
||||
shopStyleCode: row.shopStyleCode,
|
||||
shopItemCode: row.shopItemCode,
|
||||
qty: row.qty,
|
||||
buyerPaidAmount: row.buyerPaidAmount,
|
||||
platformBearAmount: row.platformBearAmount,
|
||||
sellerIncomeAmount: row.sellerIncomeAmount,
|
||||
limitUnitPrice: row.limitUnitPrice,
|
||||
limitTotal: row.limitTotal,
|
||||
gapAmount: row.gapAmount,
|
||||
ownerName: row.ownerName,
|
||||
deptOwner: row.deptOwner,
|
||||
profitCenter: row.profitCenter,
|
||||
orderStatus: row.orderStatus,
|
||||
refundStatus: row.refundStatus,
|
||||
flowEndDate: day(row.flowEndDate),
|
||||
statusLabel: row.statusLabel,
|
||||
appealType: row.appealType,
|
||||
processNo: row.processNo,
|
||||
}).commit()
|
||||
}
|
||||
}
|
||||
page += 1
|
||||
} while (page <= totalPages)
|
||||
worksheet.commit()
|
||||
await workbook.commit()
|
||||
} catch (error) {
|
||||
output.destroy(error instanceof Error ? error : new Error('导出失败'))
|
||||
}
|
||||
})()
|
||||
|
||||
const fileName = kind === 'fine' ? '破价订单_乐捐明细.xlsx' : '破价订单_当前筛选.xlsx'
|
||||
return new NextResponse(Readable.toWeb(output) as ReadableStream, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="breach-orders.xlsx"; filename*=UTF-8''${encodeURIComponent(fileName)}`,
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
})
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -105,40 +105,60 @@ describe('BreachOrderTab field layout', () => {
|
||||
expect(screen.queryByRole('button', { name: '导出乐捐明细' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('exports every filtered page instead of only the first 200 rows', async () => {
|
||||
let exportedBlob: Blob | null = null
|
||||
it('downloads one Excel file for the current filters and ignores duplicate clicks', async () => {
|
||||
let exportedHref = ''
|
||||
let exportUrl = ''
|
||||
const originalFetchImpl = (global.fetch as jest.Mock).getMockImplementation() as (
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit,
|
||||
) => Promise<Response>
|
||||
;(global.fetch as jest.Mock).mockImplementation((input, init) => {
|
||||
if (String(input).includes('/breach-orders/export?')) {
|
||||
exportUrl = String(input)
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
blob: async () => new Blob(['xlsx']),
|
||||
headers: new Headers({
|
||||
'content-disposition': "attachment; filename*=UTF-8''%E7%A0%B4%E4%BB%B7%E8%AE%A2%E5%8D%95.xlsx",
|
||||
}),
|
||||
} as Response)
|
||||
}
|
||||
return originalFetchImpl(input, init)
|
||||
})
|
||||
Object.defineProperty(URL, 'createObjectURL', {
|
||||
configurable: true,
|
||||
value: jest.fn((blob: Blob) => {
|
||||
exportedBlob = blob
|
||||
return 'blob:breach-export'
|
||||
}),
|
||||
value: jest.fn(() => 'blob:breach-xlsx'),
|
||||
})
|
||||
Object.defineProperty(URL, 'revokeObjectURL', {
|
||||
configurable: true,
|
||||
value: jest.fn(),
|
||||
})
|
||||
const anchorClick = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
const anchorClick = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
|
||||
exportedHref = this.href
|
||||
})
|
||||
render(<BreachOrderTab canExport />)
|
||||
|
||||
await screen.findByText('SO-1')
|
||||
fireEvent.click(screen.getByRole('button', { name: '导出当前筛选' }))
|
||||
const exportButton = screen.getByRole('button', { name: '导出当前筛选' })
|
||||
fireEvent.click(exportButton)
|
||||
fireEvent.click(exportButton)
|
||||
|
||||
await waitFor(() => {
|
||||
const urls = (global.fetch as jest.Mock).mock.calls.map(([input]) => String(input))
|
||||
expect(urls.some((url) => url.includes('page=1&pageSize=5000') && url.includes('includeStats=0'))).toBe(true)
|
||||
expect(urls.some((url) => url.includes('page=2&pageSize=5000') && url.includes('includeStats=0'))).toBe(true)
|
||||
expect(exportedHref).toBe('blob:breach-xlsx')
|
||||
})
|
||||
expect(anchorClick).toHaveBeenCalled()
|
||||
expect(exportedBlob).not.toBeNull()
|
||||
const csv = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result ?? ''))
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsText(exportedBlob as unknown as Blob)
|
||||
})
|
||||
expect(csv).not.toContain('上架时间')
|
||||
expect(csv).not.toContain('2026-09-01')
|
||||
expect((global.fetch as jest.Mock).mock.calls.filter(([input]) => (
|
||||
String(input).includes('/breach-orders/export?')
|
||||
))).toHaveLength(1)
|
||||
const url = new URL(exportUrl, 'http://localhost')
|
||||
expect(url.searchParams.get('kind')).toBe('list')
|
||||
const filters = JSON.parse(url.searchParams.get('filters') ?? '{}') as {
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
}
|
||||
expect(filters.dateFrom).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
expect(filters.dateTo).toMatch(/^\d{4}-\d{2}-\d{2}$/)
|
||||
expect(screen.getByText('当前筛选 Excel 已下载')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show listing time in the order detail', async () => {
|
||||
|
||||
@ -288,6 +288,7 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
|
||||
}
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
const listRequestIdRef = useRef(0)
|
||||
const exportRequestRef = useRef(false)
|
||||
|
||||
const loadList = useCallback(async () => {
|
||||
const requestId = ++listRequestIdRef.current
|
||||
@ -519,8 +520,10 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
|
||||
}
|
||||
|
||||
const exportRows = async (kind: 'list' | 'fine') => {
|
||||
if (exportRequestRef.current) return
|
||||
exportRequestRef.current = true
|
||||
setBusy(true)
|
||||
setMessage(kind === 'fine' ? '正在导出全部乐捐明细…' : '正在导出全部筛选结果…')
|
||||
setMessage(kind === 'fine' ? '正在生成乐捐明细 Excel…' : '正在生成当前筛选 Excel…')
|
||||
try {
|
||||
const filterPayload: Record<string, unknown> = kind === 'fine'
|
||||
? {
|
||||
@ -538,47 +541,37 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
|
||||
if (appealTypeFilters.length) filterPayload.appealType = appealTypeFilters
|
||||
if (platformFilters.length) filterPayload.platform = platformFilters
|
||||
if (shopFilters.length) filterPayload.shopName = shopFilters
|
||||
const filters = Object.keys(filterPayload).length ? `&filters=${encodeURIComponent(JSON.stringify(filterPayload))}` : ''
|
||||
const sortQuery = sort ? `&sort=${encodeURIComponent(JSON.stringify(sort))}` : ''
|
||||
const rows: BreachOrder[] = []
|
||||
let pageToLoad = 1
|
||||
let totalPages = 1
|
||||
do {
|
||||
const response = await fetch(`/api/supply-chain/limit-management/breach-orders?page=${pageToLoad}&pageSize=5000${filters}${sortQuery}&includeStats=0`, { cache: 'no-store' })
|
||||
const body = await response.json()
|
||||
if (!response.ok || !body?.success) throw new Error(body?.error?.message || '导出数据加载失败')
|
||||
rows.push(...(body.data?.rows ?? []))
|
||||
totalPages = body.data?.pageInfo?.totalPages ?? 1
|
||||
pageToLoad += 1
|
||||
} while (pageToLoad <= totalPages)
|
||||
|
||||
const header = kind === 'fine'
|
||||
? ['线上订单号', '内部订单号', '平台', '店铺', '商品编码', '运营负责人', '部门负责人', '利润中心', '商家实收', '限价', '价差', '驳回原因', '审核人', '乐捐金额']
|
||||
: ['付款日期', '平台', '店铺', '线上订单号', '内部订单号', '商品编码', '店铺款式编码', '店铺商品编码', '数量', '买家实付', '平台承担', '商家实收', '限价单价', '限价×数量', '价差', '运营负责人', '部门负责人', '利润中心', '订单状态', '退款状态', '流程结束日期', '审核状态', '申诉类型', '流程号']
|
||||
const lines = [header.join(',')]
|
||||
const seenFineOrders = new Set<string>()
|
||||
for (const row of rows) {
|
||||
const fineOrderKey = row.soId.trim() || row.id
|
||||
const assessedFine = !seenFineOrders.has(fineOrderKey)
|
||||
&& !['APPROVED', 'LEFT_EMPLOYEE'].includes(row.status)
|
||||
? 10
|
||||
: 0
|
||||
if (assessedFine > 0) seenFineOrders.add(fineOrderKey)
|
||||
const cells = kind === 'fine'
|
||||
? [row.soId, row.oId, row.platform, row.shopName, row.itemCode, row.ownerName, row.deptOwner, row.profitCenter, row.sellerIncomeAmount, row.limitTotal, row.gapAmount, row.reviewReason, row.reviewedBy, assessedFine]
|
||||
: [day(row.payDate), row.platform, row.shopName, row.soId, row.oId, row.itemCode, row.shopStyleCode, row.shopItemCode, row.qty, row.buyerPaidAmount, row.platformBearAmount, row.sellerIncomeAmount, row.limitUnitPrice, row.limitTotal, row.gapAmount, row.ownerName, row.deptOwner, row.profitCenter, row.orderStatus, row.refundStatus, day(row.flowEndDate), row.statusLabel, row.appealType, row.processNo]
|
||||
lines.push(cells.map((value) => `"${String(value ?? '').replaceAll('"', '""')}"`).join(','))
|
||||
const params = new URLSearchParams({ kind })
|
||||
if (Object.keys(filterPayload).length) params.set('filters', JSON.stringify(filterPayload))
|
||||
if (sort) params.set('sort', JSON.stringify(sort))
|
||||
const response = await fetch(
|
||||
`/api/supply-chain/limit-management/breach-orders/export?${params.toString()}`,
|
||||
{ cache: 'no-store' },
|
||||
)
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => null)
|
||||
throw new Error(body?.error?.message || '导出失败')
|
||||
}
|
||||
const blob = new Blob(['\ufeff' + lines.join('\n')], { type: 'text/csv;charset=utf-8' })
|
||||
const blob = await response.blob()
|
||||
const disposition = response.headers.get('content-disposition') ?? ''
|
||||
const encodedName = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
|
||||
const fileName = encodedName
|
||||
? decodeURIComponent(encodedName)
|
||||
: (kind === 'fine' ? '破价订单_乐捐明细.xlsx' : '破价订单_当前筛选.xlsx')
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = URL.createObjectURL(blob)
|
||||
link.download = kind === 'fine' ? '破价订单_乐捐明细.csv' : `破价订单_${STATUS_TABS.find((tab) => tab.key === statusTab)?.label ?? '全部'}.csv`
|
||||
link.href = objectUrl
|
||||
link.download = fileName
|
||||
link.style.display = 'none'
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
URL.revokeObjectURL(link.href)
|
||||
setMessage(`导出完成,共 ${rows.length} 条明细`)
|
||||
link.remove()
|
||||
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)
|
||||
setMessage(kind === 'fine' ? '乐捐明细 Excel 已下载' : '当前筛选 Excel 已下载')
|
||||
} catch (exportError) {
|
||||
setMessage(exportError instanceof Error ? exportError.message : '导出失败')
|
||||
} finally {
|
||||
exportRequestRef.current = false
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
@ -725,12 +718,15 @@ export function BreachOrderTab({ canExport = false }: { canExport?: boolean }) {
|
||||
</button>
|
||||
{canExport && (
|
||||
<>
|
||||
<button type="button" className={styles.btn} onClick={() => void exportRows('list')}>导出当前筛选</button>
|
||||
<button type="button" className={styles.btn} disabled={busy} onClick={() => void exportRows('list')}>导出当前筛选</button>
|
||||
{canReview && (
|
||||
<button type="button" className={styles.btn} onClick={() => void exportRows('fine')}>导出乐捐明细</button>
|
||||
<button type="button" className={styles.btn} disabled={busy} onClick={() => void exportRows('fine')}>导出乐捐明细</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{message && (busy || message.includes('下载') || message.includes('导出')) && (
|
||||
<span className={styles.note}>{message}</span>
|
||||
)}
|
||||
{hasActiveFilters && (
|
||||
<button type="button" className={styles.btn} onClick={() => clearFilters()}>清空筛选条件</button>
|
||||
)}
|
||||
|
||||
@ -97,6 +97,47 @@ function authContext(comboOwnerName = '相宜'): BreachGenerationAuthContext {
|
||||
}
|
||||
|
||||
describe('组合商品拆单破价判定', () => {
|
||||
it('流程结束日期缺失时使用付款时点生效限价版本的生效日期', () => {
|
||||
const barcode = 'INITIAL-BAR'
|
||||
const styleCode = 'INITIAL-SKU'
|
||||
const effectiveAt = new Date('2026-01-04T00:00:00.000Z')
|
||||
const initialVersion: EffectiveLimitPriceVersion = {
|
||||
...version(styleCode, 24.6),
|
||||
source: 'INITIAL',
|
||||
processInstanceId: '',
|
||||
processNo: '',
|
||||
applyType: '限价期初数据',
|
||||
effectiveAt,
|
||||
flowEndDate: null,
|
||||
}
|
||||
const context = authContext()
|
||||
context.barcodeToStyle = new Map([[barcode, styleCode]])
|
||||
context.ownerLimitByStyle = new Map([[styleCode, 24.6]])
|
||||
context.orderOwnerByBarcode = new Map([[barcode, '竹君']])
|
||||
context.saleEligibleBarcodes = new Set([barcode])
|
||||
context.limitTimelineByBarcode = new Map([[barcode, {
|
||||
barcode,
|
||||
styleCode,
|
||||
spu: 'INITIAL-SPU',
|
||||
hasVersionHistory: true,
|
||||
versions: [initialVersion],
|
||||
current: initialVersion,
|
||||
}]])
|
||||
|
||||
const result = buildBreachOrderCandidates([{
|
||||
...line('ORDER-INITIAL', barcode, 1, 20),
|
||||
soId: 'INITIAL-SO',
|
||||
shopStyleCode: 'INITIAL-LINK',
|
||||
srcCombineSkuId: null,
|
||||
linkOwnerName: '竹君',
|
||||
}], [], context)
|
||||
|
||||
expect(result.candidates[0]).toMatchObject({
|
||||
itemCode: barcode,
|
||||
flowEndDate: effectiveAt,
|
||||
})
|
||||
})
|
||||
|
||||
it('三个子单合并后使用非负责人组合限价,等于组合限价时不判破价', () => {
|
||||
const result = buildBreachOrderCandidates([
|
||||
line('10154415', componentB, 1, 37.1832),
|
||||
|
||||
@ -93,6 +93,8 @@ export type BreachGenerationAuthContext = {
|
||||
orderOwnerByBarcode: Map<string, string>
|
||||
/** 货号 → 最终生效限价流程结束日期 */
|
||||
flowEndDateByStyle: Map<string, Date>
|
||||
/** 货号 → 最终生效限价版本的生效日期(流程结束日期缺失时回退) */
|
||||
limitEffectiveAtByStyle?: Map<string, Date>
|
||||
/** 商品编码 → 付款时点限价时间线 */
|
||||
limitTimelineByBarcode?: Map<string, LimitPriceTimeline>
|
||||
/** 货号 → 价格授权列表 */
|
||||
@ -428,7 +430,11 @@ export function buildBreachOrderCandidates(
|
||||
}
|
||||
ownerComboUnitPrice += resolved.ownerUnitPrice * component.quantity
|
||||
nonOwnerComboUnitPrice += resolved.nonOwnerUnitPrice * component.quantity
|
||||
if (resolved.effectiveDetail?.flowEndDate) flowEndDates.push(resolved.effectiveDetail.flowEndDate)
|
||||
if (resolved.effectiveDetail) {
|
||||
flowEndDates.push(
|
||||
resolved.effectiveDetail.flowEndDate ?? resolved.effectiveDetail.effectiveAt,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (missingLimit) {
|
||||
stats.comboSkippedNoLimit += 1
|
||||
@ -572,7 +578,9 @@ export function buildBreachOrderCandidates(
|
||||
const platformBear = Math.max(0, Number((sellerIncome - buyerPaid).toFixed(4)))
|
||||
const listedAt = row.listedAt ?? linkLimit?.listedAt ?? null
|
||||
const flowEndDate = effectiveDetail?.flowEndDate
|
||||
?? effectiveDetail?.effectiveAt
|
||||
?? (limitTimeline ? null : (styleCode ? authContext?.flowEndDateByStyle.get(styleCode) : null))
|
||||
?? (limitTimeline ? null : (styleCode ? authContext?.limitEffectiveAtByStyle?.get(styleCode) : null))
|
||||
?? linkLimit?.flowEndDate
|
||||
?? null
|
||||
const candidateOwnerName = linkOwnerName || orderOwnerName || cleanOwnerName(linkLimit?.ownerName)
|
||||
|
||||
@ -600,6 +600,9 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method:
|
||||
action: method.toUpperCase() === 'GET' ? 'view' as const : 'edit' as const,
|
||||
}
|
||||
}
|
||||
if (pathname.startsWith('/api/supply-chain/limit-management/breach-orders/export')) {
|
||||
return { targetKey: 'limitManagement' as const, action: 'download' as const }
|
||||
}
|
||||
// 限价管理:数据复用产品全量档案,接口使用独立的限价查看权限。
|
||||
if (pathname.startsWith('/api/supply-chain/limit-management')) {
|
||||
return { targetKey: 'limitManagement' as const, action: 'view' as const }
|
||||
|
||||
@ -4,6 +4,7 @@ import {
|
||||
buildSupplyChainPermissionUserKey,
|
||||
canManageSupplyChainPermissions,
|
||||
getSupplyChainRoleDefaultAccess,
|
||||
getSupplyChainTargetRoleDefaultAccess,
|
||||
getSupplyChainApiPermissionRequirement,
|
||||
getSupplyChainPermissionTargetForPath,
|
||||
isSupplyChainExcludedUser,
|
||||
@ -310,6 +311,21 @@ describe('supply chain permission settings', () => {
|
||||
expect(getSupplyChainRoleDefaultAccess({ role: 'USER' })).toBeNull()
|
||||
})
|
||||
|
||||
it('opens breach appeal to operations and breach review to management by role', () => {
|
||||
expect(getSupplyChainTargetRoleDefaultAccess(
|
||||
{ role: 'USER', businessRoles: ['OPERATIONS'] },
|
||||
'limitBreachAppeal',
|
||||
)).toEqual({ view: true, download: false, edit: true })
|
||||
expect(getSupplyChainTargetRoleDefaultAccess(
|
||||
{ role: 'USER', businessRoles: ['MANAGEMENT'] },
|
||||
'limitBreachReview',
|
||||
)).toEqual({ view: true, download: false, edit: true })
|
||||
expect(getSupplyChainTargetRoleDefaultAccess(
|
||||
{ role: 'USER', businessRoles: ['PURCHASING'] },
|
||||
'limitBreachAppeal',
|
||||
)).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps excluded supervisor accounts out of supply chain', () => {
|
||||
expect(
|
||||
getSupplyChainRoleDefaultAccess({
|
||||
@ -442,6 +458,9 @@ describe('supply chain permission settings', () => {
|
||||
expect(
|
||||
getSupplyChainApiPermissionRequirement('/api/supply-chain/limit-management/products', 'GET'),
|
||||
).toEqual({ targetKey: 'limitManagement', action: 'view' })
|
||||
expect(
|
||||
getSupplyChainApiPermissionRequirement('/api/supply-chain/limit-management/breach-orders/export', 'GET'),
|
||||
).toEqual({ targetKey: 'limitManagement', action: 'download' })
|
||||
expect(
|
||||
getSupplyChainApiPermissionRequirement('/api/supply-chain/limit-management/products', 'POST'),
|
||||
).toEqual({ targetKey: 'limitManagement', action: 'view' })
|
||||
|
||||
@ -583,16 +583,23 @@ export function getSupplyChainTargetRoleDefaultAccess(
|
||||
) {
|
||||
if (isSupplyChainExcludedUser(user)) return null
|
||||
if (isAdmin(user)) return { view: true, download: true, edit: true }
|
||||
if (targetKey === 'departmentDistributionConfig' && resolveSupplyChainPermissionSubjectKeys(user).includes('planning')) {
|
||||
const subjectKeys = resolveSupplyChainPermissionSubjectKeys(user)
|
||||
if (targetKey === 'departmentDistributionConfig' && subjectKeys.includes('planning')) {
|
||||
return { view: true, download: false, edit: true }
|
||||
}
|
||||
if (targetKey === 'clearanceOperation' && resolveSupplyChainPermissionSubjectKeys(user).includes('operation')) {
|
||||
if (targetKey === 'clearanceOperation' && subjectKeys.includes('operation')) {
|
||||
return { view: true, download: false, edit: true }
|
||||
}
|
||||
if (targetKey === 'clearanceReview' && resolveSupplyChainPermissionSubjectKeys(user).includes('management')) {
|
||||
if (targetKey === 'clearanceReview' && subjectKeys.includes('management')) {
|
||||
return { view: true, download: false, edit: true }
|
||||
}
|
||||
if (targetKey === 'brandUpgradeApproval' && resolveSupplyChainPermissionSubjectKeys(user).includes('management')) {
|
||||
if (targetKey === 'brandUpgradeApproval' && subjectKeys.includes('management')) {
|
||||
return { view: true, download: false, edit: true }
|
||||
}
|
||||
if (targetKey === 'limitBreachAppeal' && subjectKeys.includes('operation')) {
|
||||
return { view: true, download: false, edit: true }
|
||||
}
|
||||
if (targetKey === 'limitBreachReview' && subjectKeys.includes('management')) {
|
||||
return { view: true, download: false, edit: true }
|
||||
}
|
||||
return null
|
||||
|
||||
@ -21,6 +21,43 @@ const testPrisma = prisma as unknown as {
|
||||
}
|
||||
|
||||
describe('supply chain permission settings service', () => {
|
||||
it('默认开放运营破价申诉和经管审核操作权限', async () => {
|
||||
testPrisma.supplyChainPermissionOverride.findMany.mockResolvedValue([])
|
||||
|
||||
await expect(supplyChainPermissionSettingsService.getUserAccess(
|
||||
{ id: 'operation-1', role: 'USER', businessRoles: ['OPERATIONS'] },
|
||||
'limitBreachAppeal',
|
||||
)).resolves.toEqual({ view: true, download: false, edit: true })
|
||||
await expect(supplyChainPermissionSettingsService.getUserAccess(
|
||||
{ id: 'management-1', role: 'USER', businessRoles: ['MANAGEMENT'] },
|
||||
'limitBreachReview',
|
||||
)).resolves.toEqual({ view: true, download: false, edit: true })
|
||||
})
|
||||
|
||||
it('显式配置可以收紧运营或经管的默认特殊权限', async () => {
|
||||
testPrisma.supplyChainPermissionOverride.findMany.mockResolvedValue([{
|
||||
targetKey: 'limitBreachAppeal',
|
||||
subjectKey: 'operation',
|
||||
action: 'edit',
|
||||
enabled: false,
|
||||
}])
|
||||
await expect(supplyChainPermissionSettingsService.getUserAccess(
|
||||
{ id: 'operation-1', role: 'USER', businessRoles: ['OPERATIONS'] },
|
||||
'limitBreachAppeal',
|
||||
)).resolves.toEqual({ view: false, download: false, edit: false })
|
||||
|
||||
testPrisma.supplyChainPermissionOverride.findMany.mockResolvedValue([{
|
||||
targetKey: 'limitBreachReview',
|
||||
subjectKey: 'management',
|
||||
action: 'edit',
|
||||
enabled: false,
|
||||
}])
|
||||
await expect(supplyChainPermissionSettingsService.getUserAccess(
|
||||
{ id: 'management-1', role: 'USER', businessRoles: ['MANAGEMENT'] },
|
||||
'limitBreachReview',
|
||||
)).resolves.toEqual({ view: false, download: false, edit: false })
|
||||
})
|
||||
|
||||
it('商品计划部的查看权不包含权限管理,只有管理员可更改配置', async () => {
|
||||
const planner = {
|
||||
id: 'planner', email: 'planner@example.com', name: '计划员', role: 'USER' as const,
|
||||
|
||||
@ -796,6 +796,7 @@ class SupplyChainBreachOrderService {
|
||||
}
|
||||
const ownerLimitByStyle = new Map<string, number>()
|
||||
const flowEndDateByStyle = new Map<string, Date>()
|
||||
const limitEffectiveAtByStyle = new Map<string, Date>()
|
||||
for (const row of styleLimits) {
|
||||
const styleCode = row.styleCode.trim().toUpperCase()
|
||||
if (!styleCode) continue
|
||||
@ -804,6 +805,8 @@ class SupplyChainBreachOrderService {
|
||||
ownerLimitByStyle.set(styleCode, ownerLimitPrice)
|
||||
}
|
||||
if (row.flowEndDate) flowEndDateByStyle.set(styleCode, row.flowEndDate)
|
||||
const effectiveAt = row.approvedAt ?? row.updatedAt
|
||||
if (effectiveAt) limitEffectiveAtByStyle.set(styleCode, effectiveAt)
|
||||
}
|
||||
const authsByStyle = new Map<string, BreachGenerationAuth[]>()
|
||||
for (const auth of auths) {
|
||||
@ -825,6 +828,7 @@ class SupplyChainBreachOrderService {
|
||||
ownerLimitByStyle,
|
||||
orderOwnerByBarcode,
|
||||
flowEndDateByStyle,
|
||||
limitEffectiveAtByStyle,
|
||||
authsByStyle,
|
||||
personnelByOwner,
|
||||
saleEligibleBarcodes,
|
||||
|
||||
@ -876,7 +876,6 @@ class SupplyChainPermissionSettingsService {
|
||||
|
||||
// 少数节点按角色默认放行(如「部门数据配置」默认给商品企划)
|
||||
const targetRoleDefaultAccess = getSupplyChainTargetRoleDefaultAccess(user, targetKey)
|
||||
if (targetRoleDefaultAccess) return targetRoleDefaultAccess
|
||||
|
||||
if (targetKey === 'employeeHours') {
|
||||
if (isSupplyChainExcludedUser(user)) return { view: false, download: false, edit: false }
|
||||
@ -896,6 +895,12 @@ class SupplyChainPermissionSettingsService {
|
||||
try {
|
||||
const overrides = await this.readOverrides()
|
||||
const subjectKeys = resolveSupplyChainPermissionSubjectKeys(user)
|
||||
if (
|
||||
targetRoleDefaultAccess
|
||||
&& !hasSupplyChainPermissionOverride(overrides, targetKey, subjectKeys, user.id)
|
||||
) {
|
||||
return targetRoleDefaultAccess
|
||||
}
|
||||
if (targetKey === 'modularProductProcessingOrders') {
|
||||
return this.summarizeModularProcessingPermissions(
|
||||
this.buildModularProcessingPermissions(overrides, subjectKeys, user.id),
|
||||
@ -919,6 +924,7 @@ class SupplyChainPermissionSettingsService {
|
||||
return this.resolveAccessFromOverrides(overrides, targetKey, subjectKeys, user.id)
|
||||
} catch (error) {
|
||||
if (isMissingPermissionTable(error)) {
|
||||
if (targetRoleDefaultAccess) return targetRoleDefaultAccess
|
||||
if (targetKey === 'modularProductProcessingOrders') {
|
||||
return this.summarizeModularProcessingPermissions(emptyModularProcessingPermissions())
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user