fix(product-stop): validate current push eligibility and isolate admission access
This commit is contained in:
parent
6a5a7f23aa
commit
67ab315ffe
@ -0,0 +1,8 @@
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
|
||||
/** The authorized partition and the queried partition must always agree. */
|
||||
export function parseProductStopAdmission(value: unknown): '是' | '否' {
|
||||
if (value === null || value === undefined || value === '') return '是'
|
||||
if (value === '是' || value === '否') return value
|
||||
throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '准入范围只能为“是”或“否”')
|
||||
}
|
||||
@ -2,15 +2,13 @@ import { NextRequest } from 'next/server'
|
||||
import { handleRequest, jsonSuccess } from '@/server/core/response'
|
||||
import { productStopDetailService } from '@/server/services/product-stop-detail.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
import { parseProductStopAdmission } from '../admission'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const field = request.nextUrl.searchParams.get('field')?.trim() ?? ''
|
||||
const keyword = request.nextUrl.searchParams.get('keyword') ?? ''
|
||||
const admissionValue = request.nextUrl.searchParams.get('admission')
|
||||
const admission = admissionValue === '是' || admissionValue === '否'
|
||||
? admissionValue
|
||||
: undefined
|
||||
const admission = parseProductStopAdmission(request.nextUrl.searchParams.get('admission'))
|
||||
const permissions = await supplyChainPermissionSettingsService
|
||||
.getProductInventoryStopPermissions(ctx.user)
|
||||
const canView = admission === '否'
|
||||
|
||||
@ -9,6 +9,8 @@ import {
|
||||
type ProductStopDetailTextFilter,
|
||||
} from '@/lib/product-stop-detail'
|
||||
|
||||
import { parseProductStopAdmission } from './admission'
|
||||
|
||||
const TEXT_MODES = new Set(['fuzzy', 'exact', 'in'])
|
||||
const NUMBER_OPS = new Set(['gt', 'gte', 'lt', 'lte'])
|
||||
|
||||
@ -64,9 +66,7 @@ export function parseListQuery(searchParams: URLSearchParams) {
|
||||
})
|
||||
const filters: ProductStopDetailFilters = {
|
||||
...quick,
|
||||
admission: ['是', '否'].includes(searchParams.get('admission') ?? '')
|
||||
? searchParams.get('admission') as '是' | '否'
|
||||
: undefined,
|
||||
admission: parseProductStopAdmission(searchParams.get('admission')),
|
||||
recalculatePerformanceShares: searchParams.get('recalculatePerformanceShares') === '1',
|
||||
fieldFilters: parseFieldFilters(searchParams.get('fieldFilters')),
|
||||
}
|
||||
|
||||
@ -0,0 +1,78 @@
|
||||
/** @jest-environment node */
|
||||
jest.mock('@/server/core/response', () => ({
|
||||
handleRequest: jest.fn(async (request, handler) => handler({user: {id: 'detail-only', role: 'USER'}, requestId: 'audit'})),
|
||||
jsonSuccess: jest.fn(data => data), jsonError: jest.fn((code, message, status) => ({code, message, status})),
|
||||
}));
|
||||
jest.mock('@/server/services/product-stop-detail.service', () => ({productStopDetailService: {
|
||||
list: jest.fn(), summarize: jest.fn(), listAllForExport: jest.fn(), getFilterOptions: jest.fn(), searchFilterOptionValues: jest.fn(), getDistributionShops: jest.fn(),
|
||||
}}));
|
||||
jest.mock('@/server/services/product-stop-detail-xlsx.service', () => ({productStopDetailXlsxService: {createExportWorkbook: jest.fn(async () => ({buffer: Buffer.from('xlsx'), fileName: 'test.xlsx'}))}}));
|
||||
jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({supplyChainPermissionSettingsService: {getProductInventoryStopPermissions: jest.fn(), getUserAccess: jest.fn()}}));
|
||||
import {NextRequest} from 'next/server';
|
||||
import {GET as list} from './route';
|
||||
import {GET as summary} from './summary/route';
|
||||
import {GET as exportRows} from './export/route';
|
||||
import {GET as options} from './options/route';
|
||||
import {GET as shops} from './shop-details/route';
|
||||
import {productStopDetailService as service} from '@/server/services/product-stop-detail.service';
|
||||
import {supplyChainPermissionSettingsService as permissions} from '@/server/services/supply-chain-permission-settings.service';
|
||||
const endpoints = [
|
||||
{name: 'list', handler: list, service: service.list},
|
||||
{name: 'summary', handler: summary, service: service.summarize},
|
||||
{name: 'export', handler: exportRows, service: service.listAllForExport},
|
||||
];
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
(permissions.getProductInventoryStopPermissions as jest.Mock).mockResolvedValue({
|
||||
detail: {main: {view: true, query: true, export: true}, attachment: {view: true}},
|
||||
unadmitted: {main: {view: false, query: false, export: false}, attachment: {view: false}},
|
||||
});
|
||||
(service.list as jest.Mock).mockResolvedValue({rows: [], total: 0});
|
||||
(service.summarize as jest.Mock).mockResolvedValue({});
|
||||
(service.listAllForExport as jest.Mock).mockResolvedValue([]);
|
||||
(service.getFilterOptions as jest.Mock).mockResolvedValue({});
|
||||
});
|
||||
describe.each(endpoints)('$name admission boundaries', ({handler, service: query}) => {
|
||||
it('defaults omitted scopes to the admitted partition', async () => {
|
||||
await handler(new NextRequest('http://localhost:3001/api/test'));
|
||||
expect(query).toHaveBeenCalledWith(expect.objectContaining({filters: expect.objectContaining({admission: '是'})}));
|
||||
});
|
||||
it('rejects invalid scopes before issuing a query', async () => {
|
||||
await expect(handler(new NextRequest('http://localhost:3001/api/test?admission=ALL'))).rejects.toThrow('准入范围');
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects unadmitted requests without the separate permission', async () => {
|
||||
await expect(handler(new NextRequest('http://localhost:3001/api/test?admission='+encodeURIComponent('否')))).rejects.toThrow('权限');
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
it('defaults option lookups to the admitted partition', async () => {
|
||||
await options(new NextRequest('http://localhost:3001/api/test'));
|
||||
expect(service.getFilterOptions).toHaveBeenCalledWith('是');
|
||||
});
|
||||
it('does not query unadmitted options without permission', async () => {
|
||||
await options(new NextRequest('http://localhost:3001/api/test?admission='+encodeURIComponent('否')));
|
||||
expect(service.getFilterOptions).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects invalid option scopes', async () => {
|
||||
await expect(options(new NextRequest('http://localhost:3001/api/test?admission=ALL'))).rejects.toThrow('准入范围');
|
||||
expect(service.getFilterOptions).not.toHaveBeenCalled();
|
||||
});
|
||||
it('scopes shop detail lookups to the authorized partition', async () => {
|
||||
await shops(new NextRequest('http://localhost:3001/api/test?barcode=A1'));
|
||||
expect(service.getDistributionShops).toHaveBeenCalledWith('A1', '是');
|
||||
});
|
||||
it('does not read unadmitted shops without separate attachment permission', async () => {
|
||||
const response = await shops(new NextRequest('http://localhost:3001/api/test?barcode=A1&admission='+encodeURIComponent('否')));
|
||||
expect(response).toEqual(expect.objectContaining({status: 403}));
|
||||
expect(service.getDistributionShops).not.toHaveBeenCalled();
|
||||
});
|
||||
it('rejects invalid shop detail scopes', async () => {
|
||||
await expect(shops(new NextRequest('http://localhost:3001/api/test?barcode=A1&admission=ALL'))).rejects.toThrow('准入范围');
|
||||
expect(service.getDistributionShops).not.toHaveBeenCalled();
|
||||
});
|
||||
it('preserves the independent stop demand shop context permission', async () => {
|
||||
(permissions.getUserAccess as jest.Mock).mockResolvedValue({view: true});
|
||||
await shops(new NextRequest('http://localhost:3001/api/test?barcode=A1&context=production-stop-demands'));
|
||||
expect(service.getDistributionShops).toHaveBeenCalledWith('A1');
|
||||
});
|
||||
@ -3,6 +3,7 @@ import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { productStopDetailService } from '@/server/services/product-stop-detail.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
import { parseProductStopAdmission } from '../admission'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
@ -10,7 +11,6 @@ export async function GET(request: NextRequest) {
|
||||
if (!barcode) {
|
||||
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '缺少条码', 400, ctx.requestId)
|
||||
}
|
||||
const admission = request.nextUrl.searchParams.get('admission')
|
||||
const context = request.nextUrl.searchParams.get('context')
|
||||
if (context === 'production-stop-demands') {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
@ -23,17 +23,16 @@ export async function GET(request: NextRequest) {
|
||||
const shops = await productStopDetailService.getDistributionShops(barcode)
|
||||
return jsonSuccess({ shops }, 200, ctx.requestId)
|
||||
}
|
||||
const admission = parseProductStopAdmission(request.nextUrl.searchParams.get('admission'))
|
||||
const permissions = await supplyChainPermissionSettingsService
|
||||
.getProductInventoryStopPermissions(ctx.user)
|
||||
const allowed = admission === '否'
|
||||
? permissions.unadmitted.attachment.view
|
||||
: admission === '是'
|
||||
? permissions.detail.attachment.view
|
||||
: permissions.detail.attachment.view || permissions.unadmitted.attachment.view
|
||||
: permissions.detail.attachment.view
|
||||
if (!allowed) {
|
||||
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有盘停附表查看权限', 403, ctx.requestId)
|
||||
}
|
||||
const shops = await productStopDetailService.getDistributionShops(barcode)
|
||||
const shops = await productStopDetailService.getDistributionShops(barcode, admission)
|
||||
return jsonSuccess({ shops }, 200, ctx.requestId)
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
|
||||
@ -3,13 +3,10 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
Download,
|
||||
Loader2,
|
||||
Pencil,
|
||||
Plus,
|
||||
Save,
|
||||
Trash2,
|
||||
X,
|
||||
} from 'lucide-react'
|
||||
@ -20,6 +17,7 @@ import {
|
||||
import workbench from './logic-config/product-stop-logic-config.module.css'
|
||||
import styles from './product-stop-detail.module.css'
|
||||
import { useIsClient } from './useIsClient'
|
||||
import { ProductStopExportTemplateEditor } from './ProductStopExportTemplateEditor'
|
||||
|
||||
const API_BASE = '/api/supply-chain/management/product-inventory-stop/export-templates'
|
||||
|
||||
@ -68,13 +66,15 @@ export function ProductStopDetailExportDialog({
|
||||
canManageTemplates,
|
||||
onClose,
|
||||
onExport,
|
||||
exporting = false,
|
||||
}: {
|
||||
total: number
|
||||
allFields: ProductStopDetailFieldKey[]
|
||||
visibleFields: ProductStopDetailFieldKey[]
|
||||
canManageTemplates: boolean
|
||||
onClose: () => void
|
||||
onExport: (fields?: ProductStopDetailFieldKey[], includeShopDetails?: boolean) => void
|
||||
onExport: (fields?: ProductStopDetailFieldKey[], includeShopDetails?: boolean) => Promise<void>
|
||||
exporting?: boolean
|
||||
}) {
|
||||
const mounted = useIsClient()
|
||||
const [templates, setTemplates] = useState<ExportTemplate[]>([])
|
||||
@ -91,11 +91,11 @@ export function ProductStopDetailExportDialog({
|
||||
|
||||
useEffect(() => {
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape' && !saving) onClose()
|
||||
if (event.key === 'Escape' && !saving && !exporting) onClose()
|
||||
}
|
||||
document.addEventListener('keydown', onKeyDown)
|
||||
return () => document.removeEventListener('keydown', onKeyDown)
|
||||
}, [onClose, saving])
|
||||
}, [onClose, saving, exporting])
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
@ -186,7 +186,7 @@ export function ProductStopDetailExportDialog({
|
||||
])
|
||||
setSelection(`template:${saved.id}`)
|
||||
setEditorOpen(false)
|
||||
if (exportAfterSave) onExport(saved.fields, includeShopDetails)
|
||||
if (exportAfterSave) await exportNow(saved.fields)
|
||||
} catch (cause) {
|
||||
setError(errorMessage(cause))
|
||||
} finally {
|
||||
@ -194,6 +194,13 @@ export function ProductStopDetailExportDialog({
|
||||
}
|
||||
}
|
||||
|
||||
async function exportNow(fields = selectedFields) {
|
||||
if (exporting) return
|
||||
setError('')
|
||||
try { await onExport(fields, includeShopDetails) }
|
||||
catch (cause) { setError(errorMessage(cause)) }
|
||||
}
|
||||
|
||||
async function deleteTemplate() {
|
||||
if (!selectedTemplate || !canManageTemplates) return
|
||||
if (!window.confirm(`确定删除导出模板“${selectedTemplate.name}”吗?`)) return
|
||||
@ -218,7 +225,7 @@ export function ProductStopDetailExportDialog({
|
||||
<div
|
||||
className={workbench.modalBackdrop}
|
||||
onMouseDown={(event) => {
|
||||
if (event.target === event.currentTarget && !saving) onClose()
|
||||
if (event.target === event.currentTarget && !saving && !exporting) onClose()
|
||||
}}
|
||||
>
|
||||
<div
|
||||
@ -240,7 +247,7 @@ export function ProductStopDetailExportDialog({
|
||||
type="button"
|
||||
className={workbench.iconButton}
|
||||
aria-label="关闭"
|
||||
disabled={saving}
|
||||
disabled={saving || exporting}
|
||||
onClick={onClose}
|
||||
>
|
||||
<X size={17} />
|
||||
@ -248,145 +255,11 @@ export function ProductStopDetailExportDialog({
|
||||
</header>
|
||||
|
||||
{editorOpen ? (
|
||||
<>
|
||||
<div className={`${workbench.modalBody} ${styles.exportTemplateBody}`}>
|
||||
<label className={styles.exportTemplateName}>
|
||||
<span>模板名称</span>
|
||||
<input
|
||||
className={workbench.input}
|
||||
value={templateName}
|
||||
maxLength={80}
|
||||
onChange={(event) => setTemplateName(event.target.value)}
|
||||
placeholder="例如:采购复核模板"
|
||||
autoFocus
|
||||
/>
|
||||
</label>
|
||||
<div className={styles.exportTemplateEditor}>
|
||||
<section className={styles.exportTemplateColumn}>
|
||||
<div className={styles.exportTemplateColumnHeader}>
|
||||
<div>
|
||||
<strong>可用字段</strong>
|
||||
<span>勾选后加入右侧模板</span>
|
||||
</div>
|
||||
<div className={styles.exportTemplateInlineActions}>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.textButton}
|
||||
onClick={() => setTemplateFields(validFields(allFields))}
|
||||
>
|
||||
全选
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.textButton}
|
||||
onClick={() => setTemplateFields([])}
|
||||
>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.exportFieldGrid}>
|
||||
{allFields.map((key) => {
|
||||
const field = PRODUCT_STOP_DETAIL_FIELD_MAP[key]
|
||||
if (!field) return null
|
||||
return (
|
||||
<label key={key} className={styles.exportFieldOption}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={templateFields.includes(key)}
|
||||
onChange={() => toggleTemplateField(key)}
|
||||
/>
|
||||
<span>{field.label}</span>
|
||||
<small>{field.source}</small>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className={styles.exportTemplateColumn}>
|
||||
<div className={styles.exportTemplateColumnHeader}>
|
||||
<div>
|
||||
<strong>已选字段与导出顺序</strong>
|
||||
<span>共 {templateFields.length} 个字段</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.exportOrderedList}>
|
||||
{templateFields.length === 0 ? (
|
||||
<div className={styles.exportFieldEmpty}>请从左侧选择需要导出的字段</div>
|
||||
) : templateFields.map((key, index) => {
|
||||
const field = PRODUCT_STOP_DETAIL_FIELD_MAP[key]
|
||||
if (!field) return null
|
||||
return (
|
||||
<div key={key} className={styles.exportOrderedRow}>
|
||||
<span className={styles.exportOrderNumber}>{index + 1}</span>
|
||||
<span className={styles.exportOrderLabel}>{field.label}</span>
|
||||
<div className={styles.exportOrderActions}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`上移${field.label}`}
|
||||
disabled={index === 0}
|
||||
onClick={() => moveTemplateField(index, -1)}
|
||||
>
|
||||
<ArrowUp size={13} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`下移${field.label}`}
|
||||
disabled={index === templateFields.length - 1}
|
||||
onClick={() => moveTemplateField(index, 1)}
|
||||
>
|
||||
<ArrowDown size={13} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`移除${field.label}`}
|
||||
onClick={() => toggleTemplateField(key)}
|
||||
>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{error ? <div className={workbench.formError}>{error}</div> : null}
|
||||
</div>
|
||||
<footer className={workbench.modalFooter}>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.secondaryButton}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
setError('')
|
||||
setEditorOpen(false)
|
||||
}}
|
||||
>
|
||||
返回
|
||||
</button>
|
||||
<span className={styles.footerSpacer} />
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.secondaryButton}
|
||||
disabled={saving || templateFields.length === 0}
|
||||
onClick={() => void saveTemplate(false)}
|
||||
>
|
||||
{saving ? <Loader2 size={14} className={workbench.spin} /> : <Save size={14} />}
|
||||
保存模板
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.primaryButton}
|
||||
disabled={saving || templateFields.length === 0}
|
||||
onClick={() => void saveTemplate(true)}
|
||||
>
|
||||
<Download size={14} />
|
||||
保存并导出
|
||||
</button>
|
||||
</footer>
|
||||
</>
|
||||
<ProductStopExportTemplateEditor allFields={validFields(allFields)} templateName={templateName}
|
||||
setTemplateName={setTemplateName} templateFields={templateFields} setTemplateFields={setTemplateFields}
|
||||
toggleTemplateField={toggleTemplateField} moveTemplateField={moveTemplateField}
|
||||
error={error} saving={saving} saveTemplate={saveTemplate}
|
||||
onBack={() => { setError(''); setEditorOpen(false) }} />
|
||||
) : (
|
||||
<>
|
||||
<div className={`${workbench.modalBody} ${styles.exportModalBody}`}>
|
||||
@ -490,6 +363,7 @@ export function ProductStopDetailExportDialog({
|
||||
<span key={key}>{PRODUCT_STOP_DETAIL_FIELD_MAP[key]?.label ?? key}</span>
|
||||
))}
|
||||
</div>
|
||||
{exporting ? <div role="status" className={styles.exportLoading}>正在生成导出文件,请稍候…</div> : null}
|
||||
{loading ? (
|
||||
<div className={styles.exportLoading}>
|
||||
<Loader2 size={14} className={workbench.spin} />
|
||||
@ -499,18 +373,18 @@ export function ProductStopDetailExportDialog({
|
||||
{error ? <div className={workbench.formError}>{error}</div> : null}
|
||||
</div>
|
||||
<footer className={workbench.modalFooter}>
|
||||
<button type="button" className={workbench.secondaryButton} onClick={onClose}>
|
||||
<button type="button" className={workbench.secondaryButton} disabled={exporting} onClick={onClose}>
|
||||
取消
|
||||
</button>
|
||||
<span className={styles.footerSpacer} />
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.primaryButton}
|
||||
disabled={loading || selectedFields.length === 0}
|
||||
onClick={() => onExport(selectedFields, includeShopDetails)}
|
||||
disabled={loading || exporting || selectedFields.length === 0}
|
||||
onClick={() => void exportNow()}
|
||||
>
|
||||
<Download size={14} />
|
||||
{includeShopDetails ? '导出主表与店铺明细' : `导出 ${selectedFields.length} 个字段`}
|
||||
{exporting ? '正在导出…' : includeShopDetails ? '导出主表与店铺明细' : `导出 ${selectedFields.length} 个字段`}
|
||||
</button>
|
||||
</footer>
|
||||
</>
|
||||
|
||||
@ -0,0 +1,211 @@
|
||||
'use client'
|
||||
|
||||
import type { PointerEvent } from 'react'
|
||||
import { ArrowUp, ArrowDown, ArrowUpDown, Filter, ImageOff } from 'lucide-react'
|
||||
import { PRODUCT_STOP_DETAIL_LOCKED_KEYS, formatProductStopDetailValue, type ProductStopDetailField, type ProductStopDetailFieldKey, type ProductStopDetailFilters, type ProductStopDetailRow, type ProductStopDetailSort, type ProductStopDetailSubtotal } from '@/lib/product-stop-detail'
|
||||
import styles from './product-stop-detail.module.css'
|
||||
|
||||
function SortHeader({
|
||||
field,
|
||||
sort,
|
||||
onSort,
|
||||
}: {
|
||||
field: Pick<ProductStopDetailField, 'key' | 'label'>
|
||||
sort: ProductStopDetailSort
|
||||
onSort: (field: ProductStopDetailFieldKey) => void
|
||||
}) {
|
||||
const active = sort.key === field.key
|
||||
const Icon = active ? (sort.direction === 'asc' ? ArrowUp : ArrowDown) : ArrowUpDown
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortButton}
|
||||
onClick={() => onSort(field.key)}
|
||||
aria-label={`${field.label}排序`}
|
||||
>
|
||||
<span>{field.label}</span>
|
||||
<Icon size={12} className={active ? styles.sortActive : undefined} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export function ProductStopDetailTable({ rows, visibleColumns, totalWidth, stickyOffsets, fieldFilters, subtotal, filtered, allRowsChecked, selectedBarcode, checkedBarcodes, canQuery, sort, onSort, onOpenFilter, onResize, onToggleAll, onSelect, onToggleRow }: {
|
||||
rows: ProductStopDetailRow[]; visibleColumns: Array<Omit<ProductStopDetailField, 'width'> & { width: number }>; totalWidth: number
|
||||
stickyOffsets: Map<ProductStopDetailFieldKey, number>; fieldFilters: ProductStopDetailFilters['fieldFilters']
|
||||
subtotal: ProductStopDetailSubtotal; filtered: boolean; allRowsChecked: boolean; selectedBarcode: string | null
|
||||
checkedBarcodes: Set<string>; canQuery: boolean; sort: ProductStopDetailSort
|
||||
onSort: (key: ProductStopDetailFieldKey) => void
|
||||
onOpenFilter: (key: ProductStopDetailFieldKey, rect: DOMRect) => void
|
||||
onResize: (event: PointerEvent<HTMLSpanElement>, key: ProductStopDetailFieldKey, width: number) => void
|
||||
onToggleAll: () => void; onSelect: (barcode: string) => void; onToggleRow: (barcode: string) => void
|
||||
}) {
|
||||
return (
|
||||
<table
|
||||
className={styles.table}
|
||||
style={{
|
||||
width: totalWidth + 48,
|
||||
minWidth: totalWidth + 48,
|
||||
}}
|
||||
>
|
||||
<colgroup>
|
||||
<col style={{ width: 48 }} />
|
||||
{visibleColumns.map((field) => (
|
||||
<col key={field.key} style={{ width: field.width }} />
|
||||
))}
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
className={`${styles.headerCell} ${styles.stickyHeaderCell} ${styles.selectionHeaderCell}`}
|
||||
style={{ left: 0 }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allRowsChecked}
|
||||
onChange={onToggleAll}
|
||||
aria-label="选择当前页全部条码"
|
||||
/>
|
||||
</th>
|
||||
{visibleColumns.map((field) => {
|
||||
const locked = stickyOffsets.has(field.key)
|
||||
const activeFilter = Boolean(fieldFilters?.[field.key])
|
||||
return (
|
||||
<th
|
||||
key={field.key}
|
||||
className={`${styles.headerCell} ${locked ? styles.stickyHeaderCell : ''}`}
|
||||
style={locked ? { left: stickyOffsets.get(field.key) } : undefined}
|
||||
>
|
||||
<div className={styles.headerContent}>
|
||||
<SortHeader field={field} sort={sort} onSort={onSort} />
|
||||
{canQuery && field.kind !== 'image' ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.filterButton} ${activeFilter ? styles.filterButtonActive : ''}`}
|
||||
aria-label={`${field.label}筛选`}
|
||||
title={`${field.label}筛选`}
|
||||
onClick={(event) => {
|
||||
const rect = event.currentTarget.getBoundingClientRect()
|
||||
onOpenFilter(field.key, rect)
|
||||
}}
|
||||
>
|
||||
<Filter size={11} />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<span
|
||||
className={styles.columnResizeHandle}
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label={`${field.label}列宽调整`}
|
||||
title="拖动调整列宽"
|
||||
onPointerDown={(event) => onResize(event, field.key, field.width)}
|
||||
/>
|
||||
</th>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
<tr className={styles.subtotalRow}>
|
||||
<th
|
||||
className={`${styles.subtotalCell} ${styles.stickyHeaderCell} ${styles.selectionHeaderCell}`}
|
||||
style={{ left: 0 }}
|
||||
/>
|
||||
<th
|
||||
colSpan={PRODUCT_STOP_DETAIL_LOCKED_KEYS.length}
|
||||
scope="row"
|
||||
className={styles.subtotalLabel}
|
||||
style={{ left: 48 }}
|
||||
>
|
||||
小计 · {filtered ? '筛选结果' : '当前页'}
|
||||
{' '}{subtotal.rowCount.toLocaleString('zh-CN')} 条
|
||||
</th>
|
||||
{visibleColumns.slice(PRODUCT_STOP_DETAIL_LOCKED_KEYS.length).map((field) => {
|
||||
const value = subtotal.values[field.key]
|
||||
return (
|
||||
<td key={field.key} className={styles.subtotalCell}>
|
||||
{value === undefined
|
||||
? ''
|
||||
: formatProductStopDetailValue(value, field.key)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={`${styles.detailSelectableRow} ${selectedBarcode === row.barcode ? styles.detailSelectedRow : ''} ${checkedBarcodes.has(row.barcode) ? styles.rowChecked : ''}`}
|
||||
tabIndex={0}
|
||||
aria-selected={selectedBarcode === row.barcode}
|
||||
onClick={() => onSelect(row.barcode)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onSelect(row.barcode)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<td
|
||||
className={`${styles.bodyCell} ${styles.stickyBodyCell} ${styles.selectionHeaderCell}`}
|
||||
style={{ left: 0 }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checkedBarcodes.has(row.barcode)}
|
||||
onChange={() => onToggleRow(row.barcode)}
|
||||
aria-label={`选择${row.barcode}`}
|
||||
/>
|
||||
</td>
|
||||
{visibleColumns.map((field) => {
|
||||
const locked = stickyOffsets.has(field.key)
|
||||
const value = row[field.key]
|
||||
return (
|
||||
<td
|
||||
key={field.key}
|
||||
className={`${styles.bodyCell} ${locked ? styles.stickyBodyCell : ''}`}
|
||||
style={locked ? { left: stickyOffsets.get(field.key) } : undefined}
|
||||
title={typeof value === 'string' ? value : undefined}
|
||||
>
|
||||
{field.key === 'image' ? (
|
||||
row.image ? (
|
||||
<a
|
||||
href={row.image}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={styles.imageLink}
|
||||
title="打开原图"
|
||||
>
|
||||
{/* 盘停明细图片来自任意产品档案地址,保留原生 img 以避免远程域名白名单限制。 */}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={row.image} alt={row.barcode} loading="lazy" />
|
||||
</a>
|
||||
) : (
|
||||
<span className={styles.imageFallback}><ImageOff size={15} /></span>
|
||||
)
|
||||
) : field.key === 'stopDecision' && row.stopDecision ? (
|
||||
<span className={`${styles.decisionBadge} ${row.stopDecision === '是' ? styles.decisionYes : styles.decisionNo}`}>
|
||||
{row.stopDecision}
|
||||
</span>
|
||||
) : field.key === 'stopSuggestion' && row.stopSuggestion ? (
|
||||
<span className={styles.suggestionText}>{row.stopSuggestion}</span>
|
||||
) : field.key === 'admission' ? (
|
||||
<span className={`${styles.decisionBadge} ${
|
||||
row.admission === '否' ? styles.admissionNo : styles.admissionYes
|
||||
}`}>
|
||||
{row.admission}
|
||||
</span>
|
||||
) : (
|
||||
<span className={field.kind === 'percent' || field.kind === 'number' ? styles.numberText : undefined}>
|
||||
{formatProductStopDetailValue(value, field.key)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@ -12,14 +12,7 @@ import {
|
||||
import {
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpDown,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronsLeft,
|
||||
ChevronsRight,
|
||||
Columns3,
|
||||
Download,
|
||||
Filter,
|
||||
@ -27,7 +20,6 @@ import {
|
||||
History,
|
||||
ImageOff,
|
||||
Loader2,
|
||||
Move,
|
||||
Pencil,
|
||||
RefreshCw,
|
||||
Search,
|
||||
@ -45,7 +37,6 @@ import {
|
||||
calculateProductStopDetailSubtotal,
|
||||
formatProductStopDetailValue,
|
||||
hasProductStopDetailUserFilters,
|
||||
type ProductStopDetailField,
|
||||
type ProductStopDetailFieldKey,
|
||||
type ProductStopDetailFilters,
|
||||
type ProductStopDetailNumberFilter,
|
||||
@ -78,6 +69,10 @@ import {
|
||||
visibleProductStopDetailColumns,
|
||||
} from './product-stop-detail-settings'
|
||||
import styles from './product-stop-detail.module.css'
|
||||
import { FloatingTablePagination } from '@/components/platform/FloatingTablePagination'
|
||||
import { requestJson, errorMessage, downloadUrl, queryString } from './product-stop-detail-client'
|
||||
import { useProductStopExport } from './useProductStopExport'
|
||||
import { ProductStopDetailTable } from './ProductStopDetailTable'
|
||||
|
||||
const API_BASE = '/api/supply-chain/management/product-inventory-stop'
|
||||
const COLUMN_WIDTH_MIN = 60
|
||||
@ -99,65 +94,6 @@ type FilterTarget = {
|
||||
rect: DOMRect
|
||||
}
|
||||
|
||||
async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const body = init?.body
|
||||
const isFormData = typeof FormData !== 'undefined' && body instanceof FormData
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
...(body && !isFormData ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
})
|
||||
const payload = await response.json().catch(() => null) as
|
||||
| { success?: boolean; data?: T; error?: { message?: string } }
|
||||
| null
|
||||
if (!response.ok || !payload?.success) {
|
||||
throw new Error(payload?.error?.message || `请求失败(${response.status})`)
|
||||
}
|
||||
return payload.data as T
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : '操作失败,请稍后重试'
|
||||
}
|
||||
|
||||
function downloadUrl(url: string) {
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.rel = 'noopener'
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
}
|
||||
|
||||
function queryString(input: {
|
||||
page: number
|
||||
pageSize: number
|
||||
filters: ProductStopDetailFilters
|
||||
sort: ProductStopDetailSort
|
||||
includePaging?: boolean
|
||||
}) {
|
||||
const params = new URLSearchParams()
|
||||
if (input.includePaging !== false) {
|
||||
params.set('page', String(input.page))
|
||||
params.set('pageSize', String(input.pageSize))
|
||||
}
|
||||
if (input.filters.quickKeyword) params.set('quickKeyword', input.filters.quickKeyword)
|
||||
if (input.filters.quickMode) params.set('quickMode', input.filters.quickMode)
|
||||
if (input.filters.admission) params.set('admission', input.filters.admission)
|
||||
if (input.filters.recalculatePerformanceShares) {
|
||||
params.set('recalculatePerformanceShares', '1')
|
||||
}
|
||||
if (input.filters.fieldFilters && Object.keys(input.filters.fieldFilters).length) {
|
||||
params.set('fieldFilters', JSON.stringify(input.filters.fieldFilters))
|
||||
}
|
||||
params.set('sortKey', input.sort.key)
|
||||
params.set('sortDirection', input.sort.direction)
|
||||
return params
|
||||
}
|
||||
|
||||
function defaultQuickFilters(): QuickFilters {
|
||||
return {
|
||||
quickKeyword: '',
|
||||
@ -166,30 +102,6 @@ function defaultQuickFilters(): QuickFilters {
|
||||
}
|
||||
}
|
||||
|
||||
function SortHeader({
|
||||
field,
|
||||
sort,
|
||||
onSort,
|
||||
}: {
|
||||
field: Pick<ProductStopDetailField, 'key' | 'label'>
|
||||
sort: ProductStopDetailSort
|
||||
onSort: (field: ProductStopDetailFieldKey) => void
|
||||
}) {
|
||||
const active = sort.key === field.key
|
||||
const Icon = active ? (sort.direction === 'asc' ? ArrowUp : ArrowDown) : ArrowUpDown
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortButton}
|
||||
onClick={() => onSort(field.key)}
|
||||
aria-label={`${field.label}排序`}
|
||||
>
|
||||
<span>{field.label}</span>
|
||||
<Icon size={12} className={active ? styles.sortActive : undefined} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export function ProductStopDetailView({
|
||||
initialPage,
|
||||
initialOptions,
|
||||
@ -241,6 +153,7 @@ export function ProductStopDetailView({
|
||||
const [manualPushOpen, setManualPushOpen] = useState(false)
|
||||
const [changeHistoryOpen, setChangeHistoryOpen] = useState(false)
|
||||
const [exportOpen, setExportOpen] = useState(false)
|
||||
const { exporting, exportNotice, downloadExport } = useProductStopExport()
|
||||
const [warningsOpen, setWarningsOpen] = useState(false)
|
||||
const [filterTarget, setFilterTarget] = useState<FilterTarget | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
@ -503,7 +416,7 @@ export function ProductStopDetailView({
|
||||
setNotice({ type: 'success', text: `已维护 ${data.imported} 条盘停明细图片` })
|
||||
}
|
||||
|
||||
function exportDetail(
|
||||
async function exportDetail(
|
||||
fields?: ProductStopDetailFieldKey[],
|
||||
includeShopDetails = false,
|
||||
) {
|
||||
@ -516,7 +429,7 @@ export function ProductStopDetailView({
|
||||
})
|
||||
if (fields?.length) params.set('fields', fields.join(','))
|
||||
if (includeShopDetails) params.set('includeShopDetails', '1')
|
||||
downloadUrl(`${API_BASE}/export?${params.toString()}`)
|
||||
return downloadExport(`${API_BASE}/export?${params.toString()}`)
|
||||
}
|
||||
|
||||
function saveSettings(next: ProductStopDetailViewSettings) {
|
||||
@ -963,6 +876,12 @@ export function ProductStopDetailView({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{exporting || exportNotice ? (
|
||||
<div role="status" className={`${workbench.notice} ${exportNotice?.type === 'error' ? workbench.noticeError : workbench.noticeSuccess}`}>
|
||||
{exporting ? '正在生成导出文件,请稍候…' : exportNotice?.text}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{notice ? (
|
||||
<div className={`${workbench.notice} ${notice.type === 'error' ? workbench.noticeError : workbench.noticeSuccess}`}>
|
||||
{notice.type === 'error' ? <AlertCircle size={15} /> : <Sparkles size={15} />}
|
||||
@ -1003,231 +922,21 @@ export function ProductStopDetailView({
|
||||
) : null}
|
||||
</div>
|
||||
) : (
|
||||
<table
|
||||
className={styles.table}
|
||||
style={{
|
||||
width: totalWidth + SELECTION_COLUMN_WIDTH,
|
||||
minWidth: totalWidth + SELECTION_COLUMN_WIDTH,
|
||||
}}
|
||||
>
|
||||
<colgroup>
|
||||
<col style={{ width: SELECTION_COLUMN_WIDTH }} />
|
||||
{visibleColumns.map((field) => (
|
||||
<col key={field.key} style={{ width: field.width }} />
|
||||
))}
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
className={`${styles.headerCell} ${styles.stickyHeaderCell} ${styles.selectionHeaderCell}`}
|
||||
style={{ left: 0 }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allPageRowsChecked}
|
||||
onChange={toggleCurrentPageCheckboxes}
|
||||
aria-label="选择当前页全部条码"
|
||||
/>
|
||||
</th>
|
||||
{visibleColumns.map((field) => {
|
||||
const locked = stickyOffsets.has(field.key)
|
||||
const activeFilter = Boolean(fieldFilters[field.key])
|
||||
return (
|
||||
<th
|
||||
key={field.key}
|
||||
className={`${styles.headerCell} ${locked ? styles.stickyHeaderCell : ''}`}
|
||||
style={locked ? { left: stickyOffsets.get(field.key) } : undefined}
|
||||
>
|
||||
<div className={styles.headerContent}>
|
||||
<SortHeader field={field} sort={sort} onSort={toggleSort} />
|
||||
{permissions.main.query && field.kind !== 'image' ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.filterButton} ${activeFilter ? styles.filterButtonActive : ''}`}
|
||||
aria-label={`${field.label}筛选`}
|
||||
title={`${field.label}筛选`}
|
||||
onClick={(event) => {
|
||||
const rect = event.currentTarget.getBoundingClientRect()
|
||||
setFilterTarget({ key: field.key, rect })
|
||||
}}
|
||||
>
|
||||
<Filter size={11} />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<span
|
||||
className={styles.columnResizeHandle}
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label={`${field.label}列宽调整`}
|
||||
title="拖动调整列宽"
|
||||
onPointerDown={(event) => beginColumnResize(event, field.key, field.width)}
|
||||
/>
|
||||
</th>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
<tr className={styles.subtotalRow}>
|
||||
<th
|
||||
className={`${styles.subtotalCell} ${styles.stickyHeaderCell} ${styles.selectionHeaderCell}`}
|
||||
style={{ left: 0 }}
|
||||
/>
|
||||
<th
|
||||
colSpan={PRODUCT_STOP_DETAIL_LOCKED_KEYS.length}
|
||||
scope="row"
|
||||
className={styles.subtotalLabel}
|
||||
style={{ left: SELECTION_COLUMN_WIDTH }}
|
||||
>
|
||||
小计 · {hasProductStopDetailUserFilters(appliedFilters) ? '筛选结果' : '当前页'}
|
||||
{' '}{subtotal.rowCount.toLocaleString('zh-CN')} 条
|
||||
</th>
|
||||
{visibleColumns.slice(PRODUCT_STOP_DETAIL_LOCKED_KEYS.length).map((field) => {
|
||||
const value = subtotal.values[field.key]
|
||||
return (
|
||||
<td key={field.key} className={styles.subtotalCell}>
|
||||
{value === undefined
|
||||
? ''
|
||||
: formatProductStopDetailValue(value, field.key)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{pageData.rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={`${styles.detailSelectableRow} ${selectedBarcode === row.barcode ? styles.detailSelectedRow : ''} ${checkedBarcodes.has(row.barcode) ? styles.rowChecked : ''}`}
|
||||
tabIndex={0}
|
||||
aria-selected={selectedBarcode === row.barcode}
|
||||
onClick={() => setSelectedBarcode(row.barcode)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
setSelectedBarcode(row.barcode)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<td
|
||||
className={`${styles.bodyCell} ${styles.stickyBodyCell} ${styles.selectionHeaderCell}`}
|
||||
style={{ left: 0 }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checkedBarcodes.has(row.barcode)}
|
||||
onChange={() => toggleCheckedBarcode(row.barcode)}
|
||||
aria-label={`选择${row.barcode}`}
|
||||
/>
|
||||
</td>
|
||||
{visibleColumns.map((field) => {
|
||||
const locked = stickyOffsets.has(field.key)
|
||||
const value = row[field.key]
|
||||
return (
|
||||
<td
|
||||
key={field.key}
|
||||
className={`${styles.bodyCell} ${locked ? styles.stickyBodyCell : ''}`}
|
||||
style={locked ? { left: stickyOffsets.get(field.key) } : undefined}
|
||||
title={typeof value === 'string' ? value : undefined}
|
||||
>
|
||||
{field.key === 'image' ? (
|
||||
row.image ? (
|
||||
<a
|
||||
href={row.image}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={styles.imageLink}
|
||||
title="打开原图"
|
||||
>
|
||||
{/* 盘停明细图片来自任意产品档案地址,保留原生 img 以避免远程域名白名单限制。 */}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={row.image} alt={row.barcode} loading="lazy" />
|
||||
</a>
|
||||
) : (
|
||||
<span className={styles.imageFallback}><ImageOff size={15} /></span>
|
||||
)
|
||||
) : field.key === 'stopDecision' && row.stopDecision ? (
|
||||
<span className={`${styles.decisionBadge} ${row.stopDecision === '是' ? styles.decisionYes : styles.decisionNo}`}>
|
||||
{row.stopDecision}
|
||||
</span>
|
||||
) : field.key === 'stopSuggestion' && row.stopSuggestion ? (
|
||||
<span className={styles.suggestionText}>{row.stopSuggestion}</span>
|
||||
) : field.key === 'admission' ? (
|
||||
<span className={`${styles.decisionBadge} ${
|
||||
row.admission === '否' ? styles.admissionNo : styles.admissionYes
|
||||
}`}>
|
||||
{row.admission}
|
||||
</span>
|
||||
) : (
|
||||
<span className={field.kind === 'percent' || field.kind === 'number' ? styles.numberText : undefined}>
|
||||
{formatProductStopDetailValue(value, field.key)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<ProductStopDetailTable rows={pageData.rows} visibleColumns={visibleColumns}
|
||||
totalWidth={totalWidth} stickyOffsets={stickyOffsets} fieldFilters={fieldFilters}
|
||||
subtotal={subtotal} filtered={hasProductStopDetailUserFilters(appliedFilters)}
|
||||
allRowsChecked={allPageRowsChecked} selectedBarcode={selectedBarcode}
|
||||
checkedBarcodes={checkedBarcodes} canQuery={permissions.main.query} sort={sort}
|
||||
onSort={toggleSort} onOpenFilter={(key, rect) => setFilterTarget({ key, rect })}
|
||||
onResize={beginColumnResize} onToggleAll={toggleCurrentPageCheckboxes}
|
||||
onSelect={setSelectedBarcode} onToggleRow={toggleCheckedBarcode} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={styles.footer} aria-label="主表分页与拖动控制">
|
||||
<div className={styles.dragHint}>
|
||||
<Move size={13} />
|
||||
按住表格空白处或 Alt+拖动单元格可上下左右拖动 · 选择列及前 6 列已冻结
|
||||
</div>
|
||||
<div className={styles.pagination}>
|
||||
<span>共 {pageData.total.toLocaleString('zh-CN')} 条</span>
|
||||
<select
|
||||
className={styles.pageSize}
|
||||
value={pageSize}
|
||||
onChange={(event) => changePageSize(Number(event.target.value))}
|
||||
aria-label="主表每页条数"
|
||||
>
|
||||
{PRODUCT_STOP_DETAIL_PAGE_SIZES.map((size) => (
|
||||
<option key={size} value={size}>每页 {size} 条</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pageButton}
|
||||
aria-label="主表第一页"
|
||||
disabled={page <= 1}
|
||||
onClick={() => changePage(1)}
|
||||
>
|
||||
<ChevronsLeft size={14} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pageButton}
|
||||
aria-label="主表上一页"
|
||||
disabled={page <= 1}
|
||||
onClick={() => changePage(page - 1)}
|
||||
>
|
||||
<ChevronLeft size={14} />
|
||||
</button>
|
||||
<span className={styles.pageCurrent}>{page} / {pageData.totalPages}</span>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pageButton}
|
||||
aria-label="主表下一页"
|
||||
disabled={page >= pageData.totalPages}
|
||||
onClick={() => changePage(page + 1)}
|
||||
>
|
||||
<ChevronRight size={14} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.pageButton}
|
||||
aria-label="主表最后一页"
|
||||
disabled={page >= pageData.totalPages}
|
||||
onClick={() => changePage(pageData.totalPages)}
|
||||
>
|
||||
<ChevronsRight size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div className={styles.detailPagination}>
|
||||
<FloatingTablePagination page={page} pageSize={pageSize} total={pageData.total}
|
||||
totalPages={pageData.totalPages} loading={loading} pageSizes={PRODUCT_STOP_DETAIL_PAGE_SIZES}
|
||||
onPageChange={changePage} onPageSizeChange={changePageSize} />
|
||||
</div>
|
||||
|
||||
<div
|
||||
@ -1367,10 +1076,10 @@ export function ProductStopDetailView({
|
||||
visibleFields={visibleKeys}
|
||||
canManageTemplates={permissions.main.settings}
|
||||
onClose={() => setExportOpen(false)}
|
||||
onExport={(fields, includeShopDetails) => {
|
||||
exportDetail(fields, includeShopDetails)
|
||||
setExportOpen(false)
|
||||
onExport={async (fields, includeShopDetails) => {
|
||||
if (await exportDetail(fields, includeShopDetails)) setExportOpen(false)
|
||||
}}
|
||||
exporting={exporting}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
|
||||
@ -0,0 +1,54 @@
|
||||
import React from 'react'
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { useProductStopExport } from './useProductStopExport'
|
||||
import { ProductStopDetailExportDialog } from './ProductStopDetailExportDialog'
|
||||
|
||||
function Probe() {
|
||||
const { exporting, exportNotice, downloadExport } = useProductStopExport()
|
||||
return <><button disabled={exporting} onClick={() => void downloadExport('/api/export').catch(() => {})}>导出</button>
|
||||
<span role="status">{exporting ? '导出中' : exportNotice?.text}</span></>
|
||||
}
|
||||
let click: jest.SpyInstance
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
global.fetch = jest.fn()
|
||||
URL.createObjectURL = jest.fn(() => 'blob:test')
|
||||
URL.revokeObjectURL = jest.fn()
|
||||
click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
})
|
||||
afterEach(() => click.mockRestore())
|
||||
|
||||
it('reports progress, prevents duplicate exports and announces the downloaded filename', async () => {
|
||||
let finish!: (response: unknown) => void
|
||||
;(fetch as jest.Mock).mockImplementation(() => new Promise(resolve => { finish = resolve }))
|
||||
render(<Probe />)
|
||||
fireEvent.click(screen.getByText('导出'))
|
||||
expect(screen.getByRole('status')).toHaveTextContent('导出中')
|
||||
expect(screen.getByText('导出')).toBeDisabled()
|
||||
fireEvent.click(screen.getByText('导出'))
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
await act(async () => finish({ok: true, headers: new Headers({'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'content-disposition': "attachment; filename*=UTF-8''result.xlsx"}), blob: async () => new Blob(['xlsx'])}))
|
||||
await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('导出完成:result.xlsx'))
|
||||
expect(click).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows the server failure and does not download an error response', async () => {
|
||||
;(fetch as jest.Mock).mockResolvedValue({ok: false, status: 500, headers: new Headers(), json: async () => ({error: {message: '数据库暂时不可用'}})})
|
||||
render(<Probe />)
|
||||
fireEvent.click(screen.getByText('导出'))
|
||||
await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('数据库暂时不可用'))
|
||||
expect(click).not.toHaveBeenCalled()
|
||||
expect(screen.getByText('导出')).toBeEnabled()
|
||||
})
|
||||
|
||||
it('keeps the export dialog open with an actionable error when export fails', async () => {
|
||||
;(fetch as jest.Mock).mockResolvedValue({ok: true, json: async () => ({success: true, data: {templates: []}})})
|
||||
const close = jest.fn()
|
||||
render(<ProductStopDetailExportDialog total={1} allFields={['barcode']} visibleFields={['barcode']}
|
||||
canManageTemplates={false} onClose={close} onExport={async () => { throw new Error('导出超时,请重试') }} />)
|
||||
const button = await screen.findByText('导出 1 个字段')
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
fireEvent.click(button)
|
||||
await screen.findByText('导出超时,请重试')
|
||||
expect(close).not.toHaveBeenCalled()
|
||||
})
|
||||
@ -0,0 +1,152 @@
|
||||
'use client'
|
||||
|
||||
import { ArrowUp, ArrowDown, Download, Loader2, Save, X } from 'lucide-react'
|
||||
import { PRODUCT_STOP_DETAIL_FIELD_MAP, type ProductStopDetailFieldKey } from '@/lib/product-stop-detail'
|
||||
import workbench from './logic-config/product-stop-logic-config.module.css'
|
||||
import styles from './product-stop-detail.module.css'
|
||||
|
||||
export function ProductStopExportTemplateEditor({ allFields, templateName, setTemplateName, templateFields, setTemplateFields, toggleTemplateField, moveTemplateField, error, saving, saveTemplate, onBack }: {
|
||||
allFields: ProductStopDetailFieldKey[]; templateName: string; setTemplateName: (value: string) => void
|
||||
templateFields: ProductStopDetailFieldKey[]; setTemplateFields: (value: ProductStopDetailFieldKey[]) => void
|
||||
toggleTemplateField: (key: ProductStopDetailFieldKey) => void; moveTemplateField: (index: number, delta: number) => void
|
||||
error: string; saving: boolean; saveTemplate: (exportAfterSave: boolean) => Promise<void>; onBack: () => void
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<div className={`${workbench.modalBody} ${styles.exportTemplateBody}`}>
|
||||
<label className={styles.exportTemplateName}>
|
||||
<span>模板名称</span>
|
||||
<input
|
||||
className={workbench.input}
|
||||
value={templateName}
|
||||
maxLength={80}
|
||||
onChange={(event) => setTemplateName(event.target.value)}
|
||||
placeholder="例如:采购复核模板"
|
||||
autoFocus
|
||||
/>
|
||||
</label>
|
||||
<div className={styles.exportTemplateEditor}>
|
||||
<section className={styles.exportTemplateColumn}>
|
||||
<div className={styles.exportTemplateColumnHeader}>
|
||||
<div>
|
||||
<strong>可用字段</strong>
|
||||
<span>勾选后加入右侧模板</span>
|
||||
</div>
|
||||
<div className={styles.exportTemplateInlineActions}>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.textButton}
|
||||
onClick={() => setTemplateFields(allFields)}
|
||||
>
|
||||
全选
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.textButton}
|
||||
onClick={() => setTemplateFields([])}
|
||||
>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.exportFieldGrid}>
|
||||
{allFields.map((key) => {
|
||||
const field = PRODUCT_STOP_DETAIL_FIELD_MAP[key]
|
||||
if (!field) return null
|
||||
return (
|
||||
<label key={key} className={styles.exportFieldOption}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={templateFields.includes(key)}
|
||||
onChange={() => toggleTemplateField(key)}
|
||||
/>
|
||||
<span>{field.label}</span>
|
||||
<small>{field.source}</small>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className={styles.exportTemplateColumn}>
|
||||
<div className={styles.exportTemplateColumnHeader}>
|
||||
<div>
|
||||
<strong>已选字段与导出顺序</strong>
|
||||
<span>共 {templateFields.length} 个字段</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.exportOrderedList}>
|
||||
{templateFields.length === 0 ? (
|
||||
<div className={styles.exportFieldEmpty}>请从左侧选择需要导出的字段</div>
|
||||
) : templateFields.map((key, index) => {
|
||||
const field = PRODUCT_STOP_DETAIL_FIELD_MAP[key]
|
||||
if (!field) return null
|
||||
return (
|
||||
<div key={key} className={styles.exportOrderedRow}>
|
||||
<span className={styles.exportOrderNumber}>{index + 1}</span>
|
||||
<span className={styles.exportOrderLabel}>{field.label}</span>
|
||||
<div className={styles.exportOrderActions}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`上移${field.label}`}
|
||||
disabled={index === 0}
|
||||
onClick={() => moveTemplateField(index, -1)}
|
||||
>
|
||||
<ArrowUp size={13} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`下移${field.label}`}
|
||||
disabled={index === templateFields.length - 1}
|
||||
onClick={() => moveTemplateField(index, 1)}
|
||||
>
|
||||
<ArrowDown size={13} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`移除${field.label}`}
|
||||
onClick={() => toggleTemplateField(key)}
|
||||
>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{error ? <div className={workbench.formError}>{error}</div> : null}
|
||||
</div>
|
||||
<footer className={workbench.modalFooter}>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.secondaryButton}
|
||||
disabled={saving}
|
||||
onClick={onBack}
|
||||
>
|
||||
返回
|
||||
</button>
|
||||
<span className={styles.footerSpacer} />
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.secondaryButton}
|
||||
disabled={saving || templateFields.length === 0}
|
||||
onClick={() => void saveTemplate(false)}
|
||||
>
|
||||
{saving ? <Loader2 size={14} className={workbench.spin} /> : <Save size={14} />}
|
||||
保存模板
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={workbench.primaryButton}
|
||||
disabled={saving || templateFields.length === 0}
|
||||
onClick={() => void saveTemplate(true)}
|
||||
>
|
||||
<Download size={14} />
|
||||
保存并导出
|
||||
</button>
|
||||
</footer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,60 @@
|
||||
import type { ProductStopDetailFilters, ProductStopDetailSort } from '@/lib/product-stop-detail'
|
||||
|
||||
export async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const body = init?.body
|
||||
const isFormData = typeof FormData !== 'undefined' && body instanceof FormData
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
...(body && !isFormData ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
})
|
||||
const payload = await response.json().catch(() => null) as
|
||||
| { success?: boolean; data?: T; error?: { message?: string } }
|
||||
| null
|
||||
if (!response.ok || !payload?.success) {
|
||||
throw new Error(payload?.error?.message || `请求失败(${response.status})`)
|
||||
}
|
||||
return payload.data as T
|
||||
}
|
||||
|
||||
export function errorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : '操作失败,请稍后重试'
|
||||
}
|
||||
|
||||
export function downloadUrl(url: string) {
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.rel = 'noopener'
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
}
|
||||
|
||||
export function queryString(input: {
|
||||
page: number
|
||||
pageSize: number
|
||||
filters: ProductStopDetailFilters
|
||||
sort: ProductStopDetailSort
|
||||
includePaging?: boolean
|
||||
}) {
|
||||
const params = new URLSearchParams()
|
||||
if (input.includePaging !== false) {
|
||||
params.set('page', String(input.page))
|
||||
params.set('pageSize', String(input.pageSize))
|
||||
}
|
||||
if (input.filters.quickKeyword) params.set('quickKeyword', input.filters.quickKeyword)
|
||||
if (input.filters.quickMode) params.set('quickMode', input.filters.quickMode)
|
||||
if (input.filters.admission) params.set('admission', input.filters.admission)
|
||||
if (input.filters.recalculatePerformanceShares) {
|
||||
params.set('recalculatePerformanceShares', '1')
|
||||
}
|
||||
if (input.filters.fieldFilters && Object.keys(input.filters.fieldFilters).length) {
|
||||
params.set('fieldFilters', JSON.stringify(input.filters.fieldFilters))
|
||||
}
|
||||
params.set('sortKey', input.sort.key)
|
||||
params.set('sortDirection', input.sort.direction)
|
||||
return params
|
||||
}
|
||||
@ -956,6 +956,19 @@
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.detailPagination {
|
||||
position: relative;
|
||||
flex: 0 0 88px;
|
||||
min-height: 88px;
|
||||
border-top: 1px solid #e4e4e7;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.detailPagination { flex-basis: 116px; min-height: 116px; }
|
||||
.tableWrap { flex: 0 0 280px; min-height: 280px; }
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
flex: 0 0 auto;
|
||||
|
||||
@ -0,0 +1,48 @@
|
||||
'use client'
|
||||
|
||||
import { useRef, useState } from 'react'
|
||||
|
||||
export function useProductStopExport() {
|
||||
const lock = useRef(false)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [exportNotice, setExportNotice] = useState<{ type: 'success' | 'error'; text: string } | null>(null)
|
||||
|
||||
async function downloadExport(url: string) {
|
||||
if (lock.current) return false
|
||||
lock.current = true
|
||||
setExporting(true)
|
||||
setExportNotice(null)
|
||||
try {
|
||||
const response = await fetch(url, { cache: 'no-store' })
|
||||
if (!response.ok || response.headers.get('content-type')?.includes('application/json')) {
|
||||
const payload = await response.json().catch(() => null)
|
||||
throw new Error(payload?.error?.message || `导出失败(${response.status})`)
|
||||
}
|
||||
const blob = await response.blob()
|
||||
if (!blob.size) throw new Error('导出文件为空,请重试')
|
||||
const header = response.headers.get('content-disposition') ?? ''
|
||||
const encoded = /filename\*=UTF-8''([^;]+)/i.exec(header)?.[1]
|
||||
const plain = /filename="?([^";]+)"?/i.exec(header)?.[1]
|
||||
let name = plain || '盘停明细.xlsx'
|
||||
if (encoded) { try { name = decodeURIComponent(encoded) } catch { /* use default */ } }
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = objectUrl
|
||||
anchor.download = name
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)
|
||||
setExportNotice({ type: 'success', text: `导出完成:${name}` })
|
||||
return true
|
||||
} catch (error) {
|
||||
setExportNotice({ type: 'error', text: error instanceof Error ? error.message : '导出失败,请重试' })
|
||||
throw error
|
||||
} finally {
|
||||
lock.current = false
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return { exporting, exportNotice, downloadExport }
|
||||
}
|
||||
@ -22,9 +22,10 @@ function PageInput({page,totalPages,loading,onPageChange}:{
|
||||
}
|
||||
|
||||
/** Product archive pagination pattern. The scroll area must reserve at least 88px below its last row. */
|
||||
export function FloatingTablePagination({ page, pageSize, total, totalPages, loading, onPageChange, onPageSizeChange }: {
|
||||
export function FloatingTablePagination({ page, pageSize, total, totalPages, loading, onPageChange, onPageSizeChange, pageSizes = [50, 100, 200] }: {
|
||||
page: number; pageSize: number; total: number; totalPages: number; loading: boolean
|
||||
onPageChange: (page: number) => void; onPageSizeChange: (size: number) => void
|
||||
pageSizes?: readonly number[]
|
||||
}) {
|
||||
return <nav className={styles.pagination} aria-label="列表分页">
|
||||
<span>共 {total.toLocaleString('zh-CN')} 条</span>
|
||||
@ -33,7 +34,7 @@ export function FloatingTablePagination({ page, pageSize, total, totalPages, loa
|
||||
<button type="button" disabled={loading || page >= totalPages} onClick={() => onPageChange(page + 1)}>下一页<ArrowRight size={12} /></button>
|
||||
<label>每页 <select aria-label="每页条数" value={pageSize} disabled={loading}
|
||||
onChange={event => onPageSizeChange(Number(event.target.value))}>
|
||||
{[50, 100, 200].map(size => <option key={size} value={size}>{size}</option>)}
|
||||
{pageSizes.map(size => <option key={size} value={size}>{size}</option>)}
|
||||
</select> 条</label>
|
||||
</nav>
|
||||
}
|
||||
|
||||
@ -0,0 +1,104 @@
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
|
||||
const pushSnapshotSelect = {
|
||||
barcode: true, productStatus: true, stopDecision: true,
|
||||
stopSuggestion: true, nextStopPushAt: true, generatedAt: true,
|
||||
} as const
|
||||
|
||||
class ProductStopPushRepository {
|
||||
async readLatestSnapshots(barcodes: readonly string[], admission: '是' | '否') {
|
||||
const targets = [...new Set(barcodes.map(b => b.trim().toUpperCase()).filter(Boolean))]
|
||||
const latest = await prisma.productStopDetailSnapshot.findFirst({
|
||||
orderBy: { snapshotDate: 'desc' }, select: { snapshotDate: true },
|
||||
})
|
||||
if (!latest || !targets.length) return { snapshotDate: null, snapshots: [] }
|
||||
const snapshots = await prisma.productStopDetailSnapshot.findMany({
|
||||
where: { snapshotDate: latest.snapshotDate, admission, barcode: { in: targets } },
|
||||
select: pushSnapshotSelect,
|
||||
})
|
||||
return { snapshotDate: latest.snapshotDate, snapshots }
|
||||
}
|
||||
|
||||
findAutomaticSnapshots(snapshotDate: string) {
|
||||
return prisma.productStopDetailSnapshot.findMany({
|
||||
where: { snapshotDate, admission: '是', stopDecision: '是', productStatus: '销售' },
|
||||
select: pushSnapshotSelect,
|
||||
})
|
||||
}
|
||||
|
||||
async isSnapshotReadyForRetry(snapshotDate: string) {
|
||||
const run = await prisma.productStopDetailGenerationRun.findFirst({
|
||||
where: { snapshotDate }, orderBy: { generatedAt: 'desc' },
|
||||
select: { status: true, warnings: true },
|
||||
})
|
||||
return Boolean(run && run.status === 'COMPLETED'
|
||||
&& Array.isArray(run.warnings)
|
||||
&& !run.warnings.some(w => String(w).includes('自动推送已暂停')))
|
||||
}
|
||||
|
||||
enqueue(input: {
|
||||
snapshotDate: string; barcodes: readonly string[]; reasonCategory: string
|
||||
reasonDetail: string; user: Pick<AuthUser, 'id' | 'name'>; requesterDepartment?: string
|
||||
}) {
|
||||
return prisma.productStopPushTask.createMany({
|
||||
data: input.barcodes.map(barcode => ({
|
||||
snapshotDate: input.snapshotDate, barcode: barcode.trim().toUpperCase(),
|
||||
admissionScope: '是', reasonCategory: input.reasonCategory, reasonDetail: input.reasonDetail,
|
||||
requesterId: input.user.id, requesterName: input.user.name,
|
||||
requesterDepartment: input.requesterDepartment ?? '', status: 'PENDING', attemptCount: 0,
|
||||
nextAttemptAt: new Date(Date.now() + 60 * 60 * 1000),
|
||||
lastError: '停产流程数据源暂时无法连接,等待恢复后自动重试',
|
||||
})), skipDuplicates: true,
|
||||
})
|
||||
}
|
||||
|
||||
async persistPushTimes(input: { snapshotDate: string; pushedAtByBarcode: Record<string, string> }) {
|
||||
const entries = Object.entries(input.pushedAtByBarcode)
|
||||
.map(([barcode, time]) => [barcode.trim().toUpperCase(), new Date(time)] as const)
|
||||
.filter(([barcode, time]) => barcode && !Number.isNaN(time.getTime()))
|
||||
if (!entries.length) return []
|
||||
await prisma.$transaction(entries.flatMap(([barcode, pushedAt]) => [
|
||||
prisma.productStopDetailSnapshot.updateMany({
|
||||
where: { snapshotDate: input.snapshotDate, barcode },
|
||||
data: { stopPushAt: pushedAt, inStopFlow: '是' },
|
||||
}),
|
||||
// A person may have changed the override after this demand was submitted.
|
||||
prisma.productStopDemandStateOverride.updateMany({
|
||||
where: { barcode: { in: [barcode] }, updatedAt: { lte: pushedAt } },
|
||||
data: { demandStatus: '', rejectionCategory: '', rejectionReason: '', pushedAt: null, nextPushedAt: null },
|
||||
}),
|
||||
]))
|
||||
return entries.map(([barcode]) => barcode)
|
||||
}
|
||||
|
||||
listDueTasks(now: Date) {
|
||||
return prisma.productStopPushTask.findMany({
|
||||
where: { status: 'PENDING', nextAttemptAt: { lte: now } },
|
||||
orderBy: [{ snapshotDate: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
}
|
||||
|
||||
async claimTask(id: string, now: Date) {
|
||||
const result = await prisma.productStopPushTask.updateMany({
|
||||
where: { id: { in: [id] }, status: 'PENDING', nextAttemptAt: { lte: now } },
|
||||
data: { nextAttemptAt: new Date(now.getTime() + 15 * 60 * 1000) },
|
||||
})
|
||||
return result.count === 1
|
||||
}
|
||||
|
||||
updateTask(id: string, data: Prisma.ProductStopPushTaskUpdateInput) {
|
||||
return prisma.productStopPushTask.update({ where: { id }, data })
|
||||
}
|
||||
|
||||
updatePendingTasks(ids: string[], data: Prisma.ProductStopPushTaskUpdateManyMutationInput) {
|
||||
return prisma.productStopPushTask.updateMany({ where: { id: { in: ids }, status: 'PENDING' }, data })
|
||||
}
|
||||
|
||||
countPending() {
|
||||
return prisma.productStopPushTask.count({ where: { status: 'PENDING' } })
|
||||
}
|
||||
}
|
||||
|
||||
export const productStopPushRepository = new ProductStopPushRepository()
|
||||
@ -174,12 +174,13 @@ class ProductStopDetailService {
|
||||
)
|
||||
}
|
||||
|
||||
async getDistributionShops(barcode: string) {
|
||||
async getDistributionShops(barcode: string, admission?: '是' | '否') {
|
||||
const normalized = barcode.trim().toUpperCase()
|
||||
const [shops, record] = await Promise.all([
|
||||
productStopDetailRepository.listDistributionShops(normalized),
|
||||
productStopDetailRepository.findLatestSnapshotByBarcode(normalized),
|
||||
])
|
||||
const record = await productStopDetailRepository.findLatestSnapshotByBarcode(normalized)
|
||||
if (admission && (!record || record.admission !== admission)) {
|
||||
throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '该条码不在当前准入范围内')
|
||||
}
|
||||
const shops = await productStopDetailRepository.listDistributionShops(normalized)
|
||||
// 主表快照是产品档案 30 日指标与 JSReport 销售窗口指标的最终口径;
|
||||
// 店铺明细按 JSReport 店铺占比拆分后,再校准回同一组主表总量。
|
||||
if (!record) return shops
|
||||
|
||||
@ -0,0 +1,104 @@
|
||||
import { productStopPushRepository } from '@/server/repositories/product-stop-push.repository'
|
||||
import { productionStopDemandsService } from './production-stop-demands.service'
|
||||
import { productStopDemandStateService } from './product-stop-demand-state.service'
|
||||
import { chunk, isFlowSourceUnavailable, type PushBatchInput, type PushResult, type PushSnapshot } from './product-stop-push.types'
|
||||
|
||||
export async function persistActualPushTimes(input: { snapshotDate: string; pushedAtByBarcode: Record<string, string> }) {
|
||||
const barcodes = await productStopPushRepository.persistPushTimes(input)
|
||||
if (barcodes.length) await productStopDemandStateService.syncLatestSnapshotForBarcodes(barcodes)
|
||||
}
|
||||
|
||||
export async function createPushesByReason(input: PushBatchInput): Promise<PushResult> {
|
||||
const groups = new Map<string, PushSnapshot[]>()
|
||||
for (const snapshot of input.snapshots) {
|
||||
const reason = input.reasonDetail(snapshot).trim()
|
||||
const group = groups.get(reason) ?? []
|
||||
group.push(snapshot)
|
||||
groups.set(reason, group)
|
||||
}
|
||||
const result: PushResult = {
|
||||
pushed: 0,
|
||||
queued: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
batches: 0,
|
||||
messages: [],
|
||||
successfulBarcodes: [],
|
||||
skippedDetails: [],
|
||||
failedDetails: [],
|
||||
}
|
||||
for (const [reasonDetail, group] of groups) {
|
||||
for (const barcodes of chunk(group.map((snapshot) => snapshot.barcode), 500)) {
|
||||
result.batches += 1
|
||||
try {
|
||||
const created = await productionStopDemandsService.createDemand({
|
||||
barcodesText: barcodes.join(','),
|
||||
reasonCategory: input.reasonCategory,
|
||||
reasonDetail: reasonDetail || input.reasonCategory,
|
||||
requesterDepartment: input.requesterDepartment,
|
||||
}, input.user)
|
||||
result.pushed += created.demandIds.length
|
||||
result.skipped += created.rejected.length
|
||||
result.successfulBarcodes.push(...created.accepted)
|
||||
result.skippedDetails.push(...created.rejected)
|
||||
if (created.accepted.length) {
|
||||
await persistActualPushTimes({
|
||||
snapshotDate: input.snapshotDate,
|
||||
pushedAtByBarcode: created.pushedAtByBarcode,
|
||||
}).catch((error) => {
|
||||
result.messages.push(
|
||||
`推送成功但回写推送时间失败:${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
)
|
||||
})
|
||||
}
|
||||
for (const warning of created.warnings) {
|
||||
if (!result.messages.includes(warning.message)) {
|
||||
result.messages.push(warning.message)
|
||||
}
|
||||
}
|
||||
if (created.rejected.length) {
|
||||
result.messages.push(
|
||||
...created.rejected.map((item) => `${item.barcode}:${item.reason}`),
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
if (input.queueOnFlowUnavailable && isFlowSourceUnavailable(error)) {
|
||||
try {
|
||||
const queued = (await productStopPushRepository.enqueue({
|
||||
snapshotDate: input.snapshotDate,
|
||||
barcodes,
|
||||
reasonCategory: input.reasonCategory,
|
||||
reasonDetail: reasonDetail || input.reasonCategory,
|
||||
user: input.user,
|
||||
requesterDepartment: input.requesterDepartment,
|
||||
})).count
|
||||
result.queued += queued
|
||||
result.messages.push(
|
||||
`${barcodes.length} 个条码已进入待推送队列,每小时自动重试`,
|
||||
)
|
||||
} catch (queueError) {
|
||||
result.failed += barcodes.length
|
||||
const queueReason = queueError instanceof Error
|
||||
? queueError.message
|
||||
: String(queueError)
|
||||
result.failedDetails.push(...barcodes.map((barcode) => ({
|
||||
barcode,
|
||||
reason: `写入待推送队列失败:${queueReason}`,
|
||||
})))
|
||||
result.messages.push(`写入待推送队列失败:${queueReason}`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
result.failed += barcodes.length
|
||||
result.failedDetails.push(...barcodes.map((barcode) => ({ barcode, reason })))
|
||||
result.messages.push(
|
||||
`${barcodes.slice(0, 3).join('、')}${barcodes.length > 3 ? ' 等' : ''}推送失败:${reason}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@ -0,0 +1,133 @@
|
||||
import { resolveProductStopAutomaticReasonDetail, isProductStopAutoPushDue } from '@/lib/product-stop-push'
|
||||
import { productStopPushRepository as repository } from '@/server/repositories/product-stop-push.repository'
|
||||
import { productionStopDemandRepository } from '@/server/repositories/production-stop-demands.repository'
|
||||
import { productionStopDemandsService } from './production-stop-demands.service'
|
||||
import { persistActualPushTimes } from './product-stop-push-batch.service'
|
||||
import { chunk, isFlowSourceUnavailable, type ProductStopPushRetryResult } from './product-stop-push.types'
|
||||
|
||||
type Task = Awaited<ReturnType<typeof repository.listDueTasks>>[number]
|
||||
type Snapshot = Awaited<ReturnType<typeof repository.readLatestSnapshots>>['snapshots'][number]
|
||||
|
||||
async function skipTasks(tasks: Task[], reason: string, now: Date) {
|
||||
if (!tasks.length) return
|
||||
await repository.updatePendingTasks(tasks.map(t => t.id), {
|
||||
status: 'SKIPPED', lastAttemptAt: now, lastError: reason, completedAt: now,
|
||||
})
|
||||
}
|
||||
|
||||
async function recordCreatedDemands(
|
||||
tasks: Task[], created: Awaited<ReturnType<typeof productionStopDemandsService.createDemand>>,
|
||||
now: Date, result: ProductStopPushRetryResult,
|
||||
) {
|
||||
// Business creation has already succeeded. None of these bookkeeping errors
|
||||
// may turn the created demands into FAILED or cause this code to create again.
|
||||
result.pushed += created.accepted.length
|
||||
result.skipped += created.rejected.length
|
||||
const accepted = new Map(created.accepted.map((barcode, index) => [barcode.toUpperCase(), index]))
|
||||
const rejected = new Map(created.rejected.map(item => [item.barcode.toUpperCase(), item.reason]))
|
||||
for (const task of tasks) {
|
||||
const index = accepted.get(task.barcode.toUpperCase())
|
||||
const reason = rejected.get(task.barcode.toUpperCase())
|
||||
if (index === undefined && reason === undefined) continue
|
||||
try {
|
||||
await repository.updateTask(task.id, {
|
||||
status: index === undefined ? 'SKIPPED' : 'SENT',
|
||||
attemptCount: { increment: 1 }, lastAttemptAt: now,
|
||||
lastError: reason ?? '', completedAt: now,
|
||||
...(index === undefined ? {} : { demandId: created.demandIds[index], demandNo: created.demandNos[index] }),
|
||||
})
|
||||
} catch (error) {
|
||||
result.messages.push(`推送结果已产生,但任务 ${task.id} 回写失败:${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateFailure(tasks: Task[], error: unknown, now: Date, result: ProductStopPushRetryResult) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
const unavailable = isFlowSourceUnavailable(error)
|
||||
const nonSales = reason.includes('均非销售条码')
|
||||
await repository.updatePendingTasks(tasks.map(t => t.id), {
|
||||
attemptCount: { increment: 1 }, lastAttemptAt: now, lastError: reason,
|
||||
...(unavailable ? { nextAttemptAt: new Date(now.getTime() + 60 * 60 * 1000) }
|
||||
: { status: nonSales ? 'SKIPPED' : 'FAILED', completedAt: now }),
|
||||
})
|
||||
if (unavailable) result.messages.push(`${tasks.length} 个条码仍等待 PLM 恢复后重试`)
|
||||
else if (nonSales) result.skipped += tasks.length
|
||||
else {
|
||||
result.failed += tasks.length
|
||||
result.messages.push(`${tasks.length} 个条码重试失败:${reason}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function pushGroup(tasks: Task[], snapshots: Snapshot[], snapshotDate: string,
|
||||
now: Date, result: ProductStopPushRetryResult) {
|
||||
const first = tasks[0]
|
||||
const active = await productionStopDemandRepository.listActiveProcessBarcodes(snapshots.map(s => s.barcode))
|
||||
const activeTasks = tasks.filter(t => active.has(t.barcode.toUpperCase()))
|
||||
await skipTasks(activeTasks, '已在停产需求流程中', now)
|
||||
result.skipped += activeTasks.length
|
||||
const available = snapshots.filter(s => !active.has(s.barcode.toUpperCase()))
|
||||
for (const rows of chunk(available, 500)) {
|
||||
const barcodes = new Set(rows.map(s => s.barcode.toUpperCase()))
|
||||
const groupTasks = tasks.filter(t => barcodes.has(t.barcode.toUpperCase()))
|
||||
result.batches += 1
|
||||
let created: Awaited<ReturnType<typeof productionStopDemandsService.createDemand>>
|
||||
try {
|
||||
created = await productionStopDemandsService.createDemand({
|
||||
barcodesText: [...barcodes].join(','), reasonCategory: first.reasonCategory,
|
||||
reasonDetail: resolveProductStopAutomaticReasonDetail(rows[0].stopSuggestion),
|
||||
requesterDepartment: first.requesterDepartment,
|
||||
}, { id: first.requesterId, name: first.requesterName })
|
||||
} catch (error) {
|
||||
await handleCreateFailure(groupTasks, error, now, result)
|
||||
continue
|
||||
}
|
||||
await recordCreatedDemands(groupTasks, created, now, result)
|
||||
if (created.accepted.length) {
|
||||
try {
|
||||
await persistActualPushTimes({ snapshotDate, pushedAtByBarcode: created.pushedAtByBarcode })
|
||||
} catch (error) {
|
||||
result.messages.push(`推送成功但回写推送时间失败:${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function retryPendingAutomaticPushes(): Promise<ProductStopPushRetryResult> {
|
||||
const now = new Date()
|
||||
const result: ProductStopPushRetryResult = { pushed: 0, skipped: 0, failed: 0, pending: 0, batches: 0, messages: [] }
|
||||
const due = await repository.listDueTasks(now)
|
||||
if (!due.length) return { ...result, pending: await repository.countPending() }
|
||||
const latest = await repository.readLatestSnapshots(due.map(t => t.barcode), '是')
|
||||
if (!latest.snapshotDate || !await repository.isSnapshotReadyForRetry(latest.snapshotDate)) {
|
||||
result.messages.push('最新盘停快照尚未成功生成或已暂停自动推送,保留队列等待下轮检查')
|
||||
return { ...result, pending: await repository.countPending() }
|
||||
}
|
||||
const tasks: Task[] = []
|
||||
for (const task of due) {
|
||||
// Leasing the existing task atomically also prevents two overlapping retry
|
||||
// processes from creating a demand for the same queued task.
|
||||
if (await repository.claimTask(task.id, now)) tasks.push(task)
|
||||
}
|
||||
const byBarcode = new Map(latest.snapshots.map(s => [s.barcode.toUpperCase(), s]))
|
||||
const invalid = tasks.filter(t => {
|
||||
const s = byBarcode.get(t.barcode.toUpperCase())
|
||||
return t.admissionScope !== '是' || !s || s.productStatus !== '销售' || s.stopDecision !== '是'
|
||||
|| !isProductStopAutoPushDue({ nextPushAt: s.nextStopPushAt, reportGeneratedAt: s.generatedAt })
|
||||
})
|
||||
await skipTasks(invalid, '最新快照已不再满足自动推送条件或不在准入范围', now)
|
||||
result.skipped += invalid.length
|
||||
const invalidIds = new Set(invalid.map(t => t.id))
|
||||
const groups = new Map<string, Task[]>()
|
||||
for (const task of tasks.filter(t => !invalidIds.has(t.id))) {
|
||||
const snapshot = byBarcode.get(task.barcode.toUpperCase())!
|
||||
const key = JSON.stringify([task.reasonCategory, resolveProductStopAutomaticReasonDetail(snapshot.stopSuggestion),
|
||||
task.requesterId, task.requesterName, task.requesterDepartment])
|
||||
groups.set(key, [...(groups.get(key) ?? []), task])
|
||||
}
|
||||
for (const group of groups.values()) {
|
||||
const barcodes = [...new Set(group.map(t => t.barcode.toUpperCase()))]
|
||||
await pushGroup(group, barcodes.map(b => byBarcode.get(b)!), latest.snapshotDate, now, result)
|
||||
}
|
||||
return { ...result, pending: await repository.countPending() }
|
||||
}
|
||||
@ -0,0 +1,99 @@
|
||||
jest.mock('@/lib/prisma', () => ({prisma: {
|
||||
productStopDetailSnapshot: {findFirst: jest.fn(), findMany: jest.fn(), updateMany: jest.fn()},
|
||||
productStopDetailGenerationRun: {findFirst: jest.fn()},
|
||||
productStopDemandStateOverride: {updateMany: jest.fn()},
|
||||
productStopPushTask: {findMany: jest.fn(), createMany: jest.fn(), update: jest.fn(), updateMany: jest.fn(), count: jest.fn()},
|
||||
$transaction: jest.fn(async operations => Promise.all(operations)),
|
||||
}}));
|
||||
jest.mock('@/server/repositories/production-stop-demands.repository', () => ({productionStopDemandRepository: {
|
||||
listActiveProcessBarcodes: jest.fn(), findReasonCategoryByName: jest.fn(),
|
||||
createReasonCategory: jest.fn(), updateReasonCategory: jest.fn(),
|
||||
}}));
|
||||
jest.mock('@/server/services/production-stop-demands.service', () => ({productionStopDemandsService: {createDemand: jest.fn()}}));
|
||||
jest.mock('@/server/services/product-stop-demand-state.service', () => ({productStopDemandStateService: {syncLatestSnapshotForBarcodes: jest.fn()}}));
|
||||
import {prisma} from '@/lib/prisma';
|
||||
import {productionStopDemandRepository} from '@/server/repositories/production-stop-demands.repository';
|
||||
import {productionStopDemandsService} from '@/server/services/production-stop-demands.service';
|
||||
import {productStopPushService} from '@/server/services/product-stop-push.service';
|
||||
|
||||
const oldSnapshot = {snapshotDate: '2026-11-11', barcode: 'A1', productStatus: '销售', stopDecision: '是', stopSuggestion: '是:业绩占比靠后', nextStopPushAt: null, generatedAt: new Date('2026-11-11T01:00:00Z'), admission: '是'};
|
||||
const task = {id: 'task-1', snapshotDate: '2026-11-11', barcode: 'A1', admissionScope: '是', reasonCategory: '满足系统自动盘停逻辑', reasonDetail: '业绩占比靠后', requesterId: 'SYS', requesterName: 'SYS', requesterDepartment: 'SYS', status: 'PENDING', attemptCount: 0, nextAttemptAt: new Date('2026-11-11T02:00:00Z'), createdAt: new Date('2026-11-11T01:00:00Z')};
|
||||
|
||||
describe('release safety: automatic push outbox must honor current snapshot', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
(prisma.productStopDetailGenerationRun.findFirst as jest.Mock).mockResolvedValue({status: 'COMPLETED', warnings: []});
|
||||
(prisma.productStopPushTask.updateMany as jest.Mock).mockResolvedValue({count: 1});
|
||||
(prisma.productStopPushTask.findMany as jest.Mock).mockResolvedValue([task]);
|
||||
(prisma.productStopPushTask.count as jest.Mock).mockResolvedValue(0);
|
||||
(productionStopDemandRepository.listActiveProcessBarcodes as jest.Mock).mockResolvedValue(new Map());
|
||||
(productionStopDemandsService.createDemand as jest.Mock).mockResolvedValue({accepted: ['A1'], rejected: [], demandIds: ['demand-1'], demandNos: ['TC001'], pushedAtByBarcode: {A1: '2026-11-12T02:00:00Z'}});
|
||||
(prisma.productStopDetailSnapshot.findFirst as jest.Mock).mockResolvedValue({snapshotDate: '2026-11-12'});
|
||||
});
|
||||
|
||||
it('does not create a demand after the newest report withdraws the stop recommendation', async () => {
|
||||
const newest = {...oldSnapshot, snapshotDate: '2026-11-12', stopDecision: '否', stopSuggestion: '否:业绩已恢复', generatedAt: new Date('2026-11-12T01:00:00Z')};
|
||||
(prisma.productStopDetailSnapshot.findMany as jest.Mock).mockImplementation(async ({where}) => [oldSnapshot, newest].filter(s => s.snapshotDate === where.snapshotDate && where.barcode.in.includes(s.barcode)));
|
||||
const result = await productStopPushService.retryPendingAutomaticPushes();
|
||||
expect(productionStopDemandsService.createDemand).not.toHaveBeenCalled();
|
||||
expect(result.pushed).toBe(0);
|
||||
});
|
||||
|
||||
it('does not create a demand after a newer report postpones the next allowed push', async () => {
|
||||
const newest = {...oldSnapshot, snapshotDate: '2026-11-12', nextStopPushAt: new Date('2026-11-20T01:00:00Z'), generatedAt: new Date('2026-11-12T01:00:00Z')};
|
||||
(prisma.productStopDetailSnapshot.findMany as jest.Mock).mockImplementation(async ({where}) => [oldSnapshot, newest].filter(s => s.snapshotDate === where.snapshotDate && where.barcode.in.includes(s.barcode)));
|
||||
const result = await productStopPushService.retryPendingAutomaticPushes();
|
||||
expect(productionStopDemandsService.createDemand).not.toHaveBeenCalled();
|
||||
expect(result.pushed).toBe(0);
|
||||
});
|
||||
|
||||
it('does not turn a successfully created demand into FAILED when only its snapshot writeback fails', async () => {
|
||||
(prisma.productStopDetailSnapshot.findMany as jest.Mock).mockResolvedValue([oldSnapshot]);
|
||||
(prisma.$transaction as jest.Mock).mockRejectedValueOnce(new Error('snapshot writeback temporarily failed'));
|
||||
const result = await productStopPushService.retryPendingAutomaticPushes();
|
||||
expect(productionStopDemandsService.createDemand).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.productStopPushTask.updateMany).not.toHaveBeenCalledWith(expect.objectContaining({data: expect.objectContaining({status: 'FAILED'})}));
|
||||
expect(result.pushed).toBe(1);
|
||||
expect(result.failed).toBe(0);
|
||||
});
|
||||
|
||||
it('uses the current reason and writes success to the current report', async () => {
|
||||
const current = {...oldSnapshot, snapshotDate: '2026-11-12', stopSuggestion: '是:最新建议原因', generatedAt: new Date('2026-11-12T01:00:00Z')};
|
||||
(prisma.productStopDetailSnapshot.findMany as jest.Mock).mockResolvedValue([current]);
|
||||
const result = await productStopPushService.retryPendingAutomaticPushes();
|
||||
expect(result.pushed).toBe(1);
|
||||
expect(productionStopDemandsService.createDemand).toHaveBeenCalledWith(expect.objectContaining({reasonDetail: '最新建议原因'}), expect.anything());
|
||||
expect(prisma.productStopDetailSnapshot.updateMany).toHaveBeenCalledWith(expect.objectContaining({where: {snapshotDate: '2026-11-12', barcode: 'A1'}}));
|
||||
});
|
||||
|
||||
it('keeps tasks pending when the latest report has paused automatic pushes', async () => {
|
||||
(prisma.productStopDetailSnapshot.findMany as jest.Mock).mockResolvedValue([oldSnapshot]);
|
||||
(prisma.productStopDetailGenerationRun.findFirst as jest.Mock).mockResolvedValue({status: 'COMPLETED', warnings: ['【自动推送已暂停】销售数据不完整']});
|
||||
(prisma.productStopPushTask.count as jest.Mock).mockResolvedValue(1);
|
||||
const result = await productStopPushService.retryPendingAutomaticPushes();
|
||||
expect(productionStopDemandsService.createDemand).not.toHaveBeenCalled();
|
||||
expect(result).toMatchObject({pushed: 0, failed: 0, pending: 1});
|
||||
});
|
||||
|
||||
it('only one overlapping retry process can claim the same pending task', async () => {
|
||||
(prisma.productStopDetailSnapshot.findMany as jest.Mock).mockResolvedValue([oldSnapshot]);
|
||||
let claimed = false;
|
||||
(prisma.productStopPushTask.updateMany as jest.Mock).mockImplementation(async input => {
|
||||
if (input.where.nextAttemptAt) { if (claimed) return {count: 0}; claimed = true; }
|
||||
return {count: 1};
|
||||
});
|
||||
const results = await Promise.all([productStopPushService.retryPendingAutomaticPushes(), productStopPushService.retryPendingAutomaticPushes()]);
|
||||
expect(productionStopDemandsService.createDemand).toHaveBeenCalledTimes(1);
|
||||
expect(results.reduce((sum, r) => sum + r.pushed, 0)).toBe(1);
|
||||
});
|
||||
|
||||
it('does not re-create a demand if recording its successful receipt fails', async () => {
|
||||
(prisma.productStopDetailSnapshot.findMany as jest.Mock).mockResolvedValue([oldSnapshot]);
|
||||
(prisma.productStopPushTask.update as jest.Mock).mockRejectedValueOnce(new Error('receipt temporarily unavailable'));
|
||||
const result = await productStopPushService.retryPendingAutomaticPushes();
|
||||
expect(productionStopDemandsService.createDemand).toHaveBeenCalledTimes(1);
|
||||
expect(result).toMatchObject({pushed: 1, failed: 0});
|
||||
expect(prisma.productStopPushTask.updateMany).not.toHaveBeenCalledWith(expect.objectContaining({data: expect.objectContaining({status: 'FAILED'})}));
|
||||
expect(result.messages.join(' ')).toContain('回写失败');
|
||||
});
|
||||
});
|
||||
@ -5,6 +5,7 @@ jest.mock('@/lib/prisma', () => ({
|
||||
findMany: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
productStopDetailGenerationRun: { findFirst: jest.fn() },
|
||||
productStopDemandStateOverride: {
|
||||
updateMany: jest.fn(),
|
||||
},
|
||||
@ -78,6 +79,7 @@ function snapshot(barcode: string, overrides: Record<string, unknown> = {}) {
|
||||
describe('商品盘停自动与人工推送', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
;(prisma.productStopDetailGenerationRun.findFirst as jest.Mock).mockResolvedValue({status: 'COMPLETED', warnings: []})
|
||||
snapshotFindFirst.mockResolvedValue({ snapshotDate: '2026-11-11' })
|
||||
snapshotFindMany.mockResolvedValue([])
|
||||
listActive.mockResolvedValue(new Map())
|
||||
@ -93,7 +95,7 @@ describe('商品盘停自动与人工推送', () => {
|
||||
createPushTasks.mockResolvedValue({ count: 1 })
|
||||
findPushTasks.mockResolvedValue([])
|
||||
updatePushTask.mockResolvedValue({})
|
||||
updatePushTasks.mockResolvedValue({ count: 0 })
|
||||
updatePushTasks.mockImplementation(async (input) => ({ count: input.data.nextAttemptAt && !input.data.attemptCount ? 1 : 0 }))
|
||||
countPushTasks.mockResolvedValue(0)
|
||||
createDemand.mockResolvedValue({
|
||||
pushedAt: '2026-11-15T00:27:00.000Z',
|
||||
@ -138,7 +140,7 @@ describe('商品盘停自动与人工推送', () => {
|
||||
},
|
||||
})
|
||||
expect(clearOverridePushTimes).toHaveBeenCalledWith({
|
||||
where: { barcode: { in: ['A1'] } },
|
||||
where: { barcode: { in: ['A1'] }, updatedAt: { lte: new Date('2026-11-15T00:27:00.000Z') } },
|
||||
data: {
|
||||
demandStatus: '',
|
||||
rejectionCategory: '',
|
||||
@ -299,7 +301,7 @@ describe('商品盘停自动与人工推送', () => {
|
||||
|
||||
expect(result).toMatchObject({ pushed: 0, failed: 0, pending: 1 })
|
||||
expect(updatePushTasks).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: { id: { in: ['task-1'] } },
|
||||
where: { id: { in: ['task-1'] }, status: 'PENDING' },
|
||||
data: expect.objectContaining({
|
||||
attemptCount: { increment: 1 },
|
||||
nextAttemptAt: expect.any(Date),
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import {
|
||||
PRODUCT_STOP_AUTO_PUSH_REASON_CATEGORY,
|
||||
PRODUCT_STOP_AUTO_REQUESTER_DEPARTMENT,
|
||||
@ -11,145 +10,12 @@ import {
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import { productionStopDemandRepository } from '@/server/repositories/production-stop-demands.repository'
|
||||
import { productionStopDemandsService } from './production-stop-demands.service'
|
||||
import { productStopDemandStateService } from './product-stop-demand-state.service'
|
||||
|
||||
type PushSnapshot = {
|
||||
barcode: string
|
||||
productStatus: string
|
||||
stopDecision: string
|
||||
stopSuggestion: string
|
||||
nextStopPushAt: Date | null
|
||||
generatedAt: Date
|
||||
}
|
||||
|
||||
type PushResult = {
|
||||
pushed: number
|
||||
queued: number
|
||||
skipped: number
|
||||
failed: number
|
||||
batches: number
|
||||
messages: string[]
|
||||
successfulBarcodes: string[]
|
||||
skippedDetails: Array<{ barcode: string; reason: string }>
|
||||
failedDetails: Array<{ barcode: string; reason: string }>
|
||||
}
|
||||
|
||||
export type ProductStopPushRetryResult = {
|
||||
pushed: number
|
||||
skipped: number
|
||||
failed: number
|
||||
pending: number
|
||||
batches: number
|
||||
messages: string[]
|
||||
}
|
||||
|
||||
function chunk<T>(items: readonly T[], size: number) {
|
||||
const result: T[][] = []
|
||||
for (let index = 0; index < items.length; index += size) {
|
||||
result.push(items.slice(index, index + size))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function isFlowSourceUnavailable(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return message.includes('停产流程数据源暂时无法连接')
|
||||
}
|
||||
|
||||
async function enqueueFlowRetryTasks(input: {
|
||||
snapshotDate: string
|
||||
barcodes: readonly string[]
|
||||
reasonCategory: string
|
||||
reasonDetail: string
|
||||
user: Pick<AuthUser, 'id' | 'name'>
|
||||
requesterDepartment?: string
|
||||
}) {
|
||||
const now = new Date()
|
||||
const nextAttemptAt = new Date(now.getTime() + 60 * 60 * 1000)
|
||||
const result = await prisma.productStopPushTask.createMany({
|
||||
data: input.barcodes.map((barcode) => ({
|
||||
snapshotDate: input.snapshotDate,
|
||||
barcode: barcode.trim().toUpperCase(),
|
||||
admissionScope: '是',
|
||||
reasonCategory: input.reasonCategory,
|
||||
reasonDetail: input.reasonDetail,
|
||||
requesterId: input.user.id,
|
||||
requesterName: input.user.name,
|
||||
requesterDepartment: input.requesterDepartment ?? '',
|
||||
status: 'PENDING',
|
||||
attemptCount: 0,
|
||||
nextAttemptAt,
|
||||
lastError: '停产流程数据源暂时无法连接,等待恢复后自动重试',
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
})
|
||||
return result.count
|
||||
}
|
||||
|
||||
async function persistActualPushTimes(input: {
|
||||
snapshotDate: string
|
||||
pushedAtByBarcode: Record<string, string>
|
||||
}) {
|
||||
const entries = Object.entries(input.pushedAtByBarcode)
|
||||
.map(([barcode, pushedAt]) => [
|
||||
barcode.trim().toUpperCase(),
|
||||
new Date(pushedAt),
|
||||
] as const)
|
||||
.filter(([barcode, pushedAt]) => barcode && !Number.isNaN(pushedAt.getTime()))
|
||||
if (!entries.length) return
|
||||
await prisma.$transaction([
|
||||
...entries.map(([barcode, pushedAt]) => prisma.productStopDetailSnapshot.updateMany({
|
||||
where: { snapshotDate: input.snapshotDate, barcode },
|
||||
data: {
|
||||
stopPushAt: pushedAt,
|
||||
inStopFlow: '是',
|
||||
},
|
||||
})),
|
||||
prisma.productStopDemandStateOverride.updateMany({
|
||||
where: { barcode: { in: entries.map(([barcode]) => barcode) } },
|
||||
data: {
|
||||
demandStatus: '',
|
||||
rejectionCategory: '',
|
||||
rejectionReason: '',
|
||||
pushedAt: null,
|
||||
nextPushedAt: null,
|
||||
},
|
||||
}),
|
||||
])
|
||||
await productStopDemandStateService.syncLatestSnapshotForBarcodes(
|
||||
entries.map(([barcode]) => barcode),
|
||||
)
|
||||
}
|
||||
|
||||
async function readLatestSnapshots(
|
||||
barcodes: readonly string[],
|
||||
admissionScope: '是' | '否',
|
||||
) {
|
||||
const targets = [...new Set(barcodes.map((barcode) => barcode.trim().toUpperCase()).filter(Boolean))]
|
||||
if (!targets.length) return { snapshotDate: null, snapshots: [] }
|
||||
const latest = await prisma.productStopDetailSnapshot.findFirst({
|
||||
orderBy: { snapshotDate: 'desc' },
|
||||
select: { snapshotDate: true },
|
||||
})
|
||||
if (!latest) return { snapshotDate: null, snapshots: [] }
|
||||
const snapshots = await prisma.productStopDetailSnapshot.findMany({
|
||||
where: {
|
||||
snapshotDate: latest.snapshotDate,
|
||||
admission: admissionScope,
|
||||
barcode: { in: targets },
|
||||
},
|
||||
select: {
|
||||
barcode: true,
|
||||
productStatus: true,
|
||||
stopDecision: true,
|
||||
stopSuggestion: true,
|
||||
nextStopPushAt: true,
|
||||
generatedAt: true,
|
||||
},
|
||||
})
|
||||
return { snapshotDate: latest.snapshotDate, snapshots }
|
||||
}
|
||||
import { productStopPushRepository } from '@/server/repositories/product-stop-push.repository'
|
||||
import { createPushesByReason } from './product-stop-push-batch.service'
|
||||
import { retryPendingAutomaticPushes } from './product-stop-push-outbox.service'
|
||||
import type { PushSnapshot, PushResult } from './product-stop-push.types'
|
||||
export type { ProductStopPushRetryResult } from './product-stop-push.types'
|
||||
|
||||
async function filterActiveBarcodes(snapshots: readonly PushSnapshot[]) {
|
||||
const active = await productionStopDemandRepository.listActiveProcessBarcodes(
|
||||
@ -161,109 +27,6 @@ async function filterActiveBarcodes(snapshots: readonly PushSnapshot[]) {
|
||||
}
|
||||
}
|
||||
|
||||
async function createPushesByReason(input: {
|
||||
snapshotDate: string
|
||||
snapshots: readonly PushSnapshot[]
|
||||
reasonCategory: string
|
||||
reasonDetail: (snapshot: PushSnapshot) => string
|
||||
user: Pick<AuthUser, 'id' | 'name'>
|
||||
requesterDepartment?: string
|
||||
queueOnFlowUnavailable?: boolean
|
||||
}): Promise<PushResult> {
|
||||
const groups = new Map<string, PushSnapshot[]>()
|
||||
for (const snapshot of input.snapshots) {
|
||||
const reason = input.reasonDetail(snapshot).trim()
|
||||
const group = groups.get(reason) ?? []
|
||||
group.push(snapshot)
|
||||
groups.set(reason, group)
|
||||
}
|
||||
const result: PushResult = {
|
||||
pushed: 0,
|
||||
queued: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
batches: 0,
|
||||
messages: [],
|
||||
successfulBarcodes: [],
|
||||
skippedDetails: [],
|
||||
failedDetails: [],
|
||||
}
|
||||
for (const [reasonDetail, group] of groups) {
|
||||
for (const barcodes of chunk(group.map((snapshot) => snapshot.barcode), 500)) {
|
||||
result.batches += 1
|
||||
try {
|
||||
const created = await productionStopDemandsService.createDemand({
|
||||
barcodesText: barcodes.join(','),
|
||||
reasonCategory: input.reasonCategory,
|
||||
reasonDetail: reasonDetail || input.reasonCategory,
|
||||
requesterDepartment: input.requesterDepartment,
|
||||
}, input.user)
|
||||
result.pushed += created.demandIds.length
|
||||
result.skipped += created.rejected.length
|
||||
result.successfulBarcodes.push(...created.accepted)
|
||||
result.skippedDetails.push(...created.rejected)
|
||||
if (created.accepted.length) {
|
||||
await persistActualPushTimes({
|
||||
snapshotDate: input.snapshotDate,
|
||||
pushedAtByBarcode: created.pushedAtByBarcode,
|
||||
}).catch((error) => {
|
||||
result.messages.push(
|
||||
`推送成功但回写推送时间失败:${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
)
|
||||
})
|
||||
}
|
||||
for (const warning of created.warnings) {
|
||||
if (!result.messages.includes(warning.message)) {
|
||||
result.messages.push(warning.message)
|
||||
}
|
||||
}
|
||||
if (created.rejected.length) {
|
||||
result.messages.push(
|
||||
...created.rejected.map((item) => `${item.barcode}:${item.reason}`),
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
if (input.queueOnFlowUnavailable && isFlowSourceUnavailable(error)) {
|
||||
try {
|
||||
const queued = await enqueueFlowRetryTasks({
|
||||
snapshotDate: input.snapshotDate,
|
||||
barcodes,
|
||||
reasonCategory: input.reasonCategory,
|
||||
reasonDetail: reasonDetail || input.reasonCategory,
|
||||
user: input.user,
|
||||
requesterDepartment: input.requesterDepartment,
|
||||
})
|
||||
result.queued += queued
|
||||
result.messages.push(
|
||||
`${barcodes.length} 个条码已进入待推送队列,每小时自动重试`,
|
||||
)
|
||||
} catch (queueError) {
|
||||
result.failed += barcodes.length
|
||||
const queueReason = queueError instanceof Error
|
||||
? queueError.message
|
||||
: String(queueError)
|
||||
result.failedDetails.push(...barcodes.map((barcode) => ({
|
||||
barcode,
|
||||
reason: `写入待推送队列失败:${queueReason}`,
|
||||
})))
|
||||
result.messages.push(`写入待推送队列失败:${queueReason}`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
result.failed += barcodes.length
|
||||
result.failedDetails.push(...barcodes.map((barcode) => ({ barcode, reason })))
|
||||
result.messages.push(
|
||||
`${barcodes.slice(0, 3).join('、')}${barcodes.length > 3 ? ' 等' : ''}推送失败:${reason}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
class ProductStopPushService {
|
||||
private async ensureAutomaticReasonCategory() {
|
||||
const existing = await productionStopDemandRepository.findReasonCategoryByName(
|
||||
@ -293,22 +56,7 @@ class ProductStopPushService {
|
||||
snapshotDate: string
|
||||
generatedAt: Date
|
||||
}): Promise<PushResult> {
|
||||
const latest = await prisma.productStopDetailSnapshot.findMany({
|
||||
where: {
|
||||
snapshotDate: input.snapshotDate,
|
||||
admission: '是',
|
||||
stopDecision: '是',
|
||||
productStatus: '销售',
|
||||
},
|
||||
select: {
|
||||
barcode: true,
|
||||
productStatus: true,
|
||||
stopDecision: true,
|
||||
stopSuggestion: true,
|
||||
nextStopPushAt: true,
|
||||
generatedAt: true,
|
||||
},
|
||||
}) as PushSnapshot[]
|
||||
const latest = await productStopPushRepository.findAutomaticSnapshots(input.snapshotDate)
|
||||
const due = latest.filter((snapshot) => isProductStopAutoPushDue({
|
||||
nextPushAt: snapshot.nextStopPushAt,
|
||||
reportGeneratedAt: input.generatedAt,
|
||||
@ -369,7 +117,7 @@ class ProductStopPushService {
|
||||
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请填写停产原因详细说明')
|
||||
}
|
||||
const admissionScope = input.admissionScope === '否' ? '否' : '是'
|
||||
const latest = await readLatestSnapshots(barcodes, admissionScope)
|
||||
const latest = await productStopPushRepository.readLatestSnapshots(barcodes, admissionScope)
|
||||
if (!latest.snapshotDate || !latest.snapshots.length) {
|
||||
throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '当前没有可推送的盘停条码')
|
||||
}
|
||||
@ -398,229 +146,7 @@ class ProductStopPushService {
|
||||
return result
|
||||
}
|
||||
|
||||
async retryPendingAutomaticPushes(): Promise<ProductStopPushRetryResult> {
|
||||
const now = new Date()
|
||||
const tasks = await prisma.productStopPushTask.findMany({
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
nextAttemptAt: { lte: now },
|
||||
},
|
||||
orderBy: [{ snapshotDate: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
const result: ProductStopPushRetryResult = {
|
||||
pushed: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
pending: 0,
|
||||
batches: 0,
|
||||
messages: [],
|
||||
}
|
||||
const groups = new Map<string, typeof tasks>()
|
||||
for (const task of tasks) {
|
||||
const key = JSON.stringify([
|
||||
task.snapshotDate,
|
||||
task.reasonCategory,
|
||||
task.reasonDetail,
|
||||
task.requesterId,
|
||||
task.requesterName,
|
||||
task.requesterDepartment,
|
||||
])
|
||||
const group = groups.get(key) ?? []
|
||||
group.push(task)
|
||||
groups.set(key, group)
|
||||
}
|
||||
|
||||
for (const group of groups.values()) {
|
||||
const first = group[0]
|
||||
if (!first) continue
|
||||
const taskByBarcode = new Map(
|
||||
group.map((task) => [task.barcode.toUpperCase(), task]),
|
||||
)
|
||||
const snapshots = await prisma.productStopDetailSnapshot.findMany({
|
||||
where: {
|
||||
snapshotDate: first.snapshotDate,
|
||||
admission: first.admissionScope as '是' | '否',
|
||||
barcode: { in: [...taskByBarcode.keys()] },
|
||||
},
|
||||
select: {
|
||||
barcode: true,
|
||||
productStatus: true,
|
||||
stopDecision: true,
|
||||
stopSuggestion: true,
|
||||
nextStopPushAt: true,
|
||||
generatedAt: true,
|
||||
},
|
||||
}) as PushSnapshot[]
|
||||
const found = new Set(snapshots.map((snapshot) => snapshot.barcode.toUpperCase()))
|
||||
const missing = group.filter((task) => !found.has(task.barcode.toUpperCase()))
|
||||
if (missing.length) {
|
||||
await prisma.productStopPushTask.updateMany({
|
||||
where: { id: { in: missing.map((task) => task.id) } },
|
||||
data: {
|
||||
status: 'SKIPPED',
|
||||
lastAttemptAt: now,
|
||||
lastError: '原快照已不存在或条码已不在快照范围',
|
||||
completedAt: now,
|
||||
},
|
||||
})
|
||||
result.skipped += missing.length
|
||||
}
|
||||
const availableSnapshots = snapshots.filter((snapshot) => (
|
||||
snapshot.productStatus === '销售'
|
||||
&& snapshot.stopDecision === '是'
|
||||
&& isProductStopAutoPushDue({
|
||||
nextPushAt: snapshot.nextStopPushAt,
|
||||
reportGeneratedAt: snapshot.generatedAt,
|
||||
})
|
||||
))
|
||||
const invalid = snapshots.filter((snapshot) => !availableSnapshots.includes(snapshot))
|
||||
if (invalid.length) {
|
||||
await prisma.productStopPushTask.updateMany({
|
||||
where: {
|
||||
id: {
|
||||
in: invalid
|
||||
.map((snapshot) => taskByBarcode.get(snapshot.barcode.toUpperCase())?.id)
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
},
|
||||
},
|
||||
data: {
|
||||
status: 'SKIPPED',
|
||||
lastAttemptAt: now,
|
||||
lastError: '最新快照已不再满足自动推送条件',
|
||||
completedAt: now,
|
||||
},
|
||||
})
|
||||
result.skipped += invalid.length
|
||||
}
|
||||
const { available, active } = await filterActiveBarcodes(availableSnapshots)
|
||||
if (active.size) {
|
||||
const activeTaskIds = [...active.keys()]
|
||||
.map((barcode) => taskByBarcode.get(barcode)?.id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
await prisma.productStopPushTask.updateMany({
|
||||
where: { id: { in: activeTaskIds } },
|
||||
data: {
|
||||
status: 'SKIPPED',
|
||||
lastAttemptAt: now,
|
||||
lastError: '已在停产需求流程中',
|
||||
completedAt: now,
|
||||
},
|
||||
})
|
||||
result.skipped += active.size
|
||||
}
|
||||
for (const availableChunk of chunk(available, 500)) {
|
||||
result.batches += 1
|
||||
const chunkBarcodes = availableChunk.map((snapshot) => snapshot.barcode)
|
||||
const chunkTaskIds = chunkBarcodes
|
||||
.map((barcode) => taskByBarcode.get(barcode.toUpperCase())?.id)
|
||||
.filter((id): id is string => Boolean(id))
|
||||
try {
|
||||
const created = await productionStopDemandsService.createDemand({
|
||||
barcodesText: chunkBarcodes.join(','),
|
||||
reasonCategory: first.reasonCategory,
|
||||
reasonDetail: first.reasonDetail || first.reasonCategory,
|
||||
requesterDepartment: first.requesterDepartment,
|
||||
}, {
|
||||
id: first.requesterId,
|
||||
name: first.requesterName,
|
||||
})
|
||||
const demandNoByBarcode = new Map(
|
||||
created.accepted.map((barcode, index) => [
|
||||
barcode.toUpperCase(),
|
||||
created.demandNos[index] ?? '',
|
||||
]),
|
||||
)
|
||||
const demandIdByBarcode = new Map(
|
||||
created.accepted.map((barcode, index) => [
|
||||
barcode.toUpperCase(),
|
||||
created.demandIds[index] ?? '',
|
||||
]),
|
||||
)
|
||||
await Promise.all(created.accepted.map(async (barcode) => {
|
||||
const task = taskByBarcode.get(barcode.toUpperCase())
|
||||
if (!task) return
|
||||
await prisma.productStopPushTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: 'SENT',
|
||||
attemptCount: { increment: 1 },
|
||||
lastAttemptAt: now,
|
||||
lastError: '',
|
||||
demandId: demandIdByBarcode.get(barcode.toUpperCase()) ?? '',
|
||||
demandNo: demandNoByBarcode.get(barcode.toUpperCase()) ?? '',
|
||||
completedAt: now,
|
||||
},
|
||||
})
|
||||
}))
|
||||
await Promise.all(created.rejected.map(async (item) => {
|
||||
const task = taskByBarcode.get(item.barcode.toUpperCase())
|
||||
if (!task) return
|
||||
await prisma.productStopPushTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: 'SKIPPED',
|
||||
attemptCount: { increment: 1 },
|
||||
lastAttemptAt: now,
|
||||
lastError: item.reason,
|
||||
completedAt: now,
|
||||
},
|
||||
})
|
||||
}))
|
||||
if (created.accepted.length) {
|
||||
await persistActualPushTimes({
|
||||
snapshotDate: first.snapshotDate,
|
||||
pushedAtByBarcode: created.pushedAtByBarcode,
|
||||
})
|
||||
}
|
||||
result.pushed += created.accepted.length
|
||||
result.skipped += created.rejected.length
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
if (isFlowSourceUnavailable(error)) {
|
||||
await prisma.productStopPushTask.updateMany({
|
||||
where: { id: { in: chunkTaskIds } },
|
||||
data: {
|
||||
attemptCount: { increment: 1 },
|
||||
lastAttemptAt: now,
|
||||
nextAttemptAt: new Date(now.getTime() + 60 * 60 * 1000),
|
||||
lastError: reason,
|
||||
},
|
||||
})
|
||||
result.messages.push(`${chunkBarcodes.length} 个条码仍等待 PLM 恢复后重试`)
|
||||
} else if (reason.includes('均非销售条码')) {
|
||||
await prisma.productStopPushTask.updateMany({
|
||||
where: { id: { in: chunkTaskIds } },
|
||||
data: {
|
||||
status: 'SKIPPED',
|
||||
attemptCount: { increment: 1 },
|
||||
lastAttemptAt: now,
|
||||
lastError: reason,
|
||||
completedAt: now,
|
||||
},
|
||||
})
|
||||
result.skipped += chunkTaskIds.length
|
||||
} else {
|
||||
await prisma.productStopPushTask.updateMany({
|
||||
where: { id: { in: chunkTaskIds } },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
attemptCount: { increment: 1 },
|
||||
lastAttemptAt: now,
|
||||
lastError: reason,
|
||||
completedAt: now,
|
||||
},
|
||||
})
|
||||
result.failed += chunkTaskIds.length
|
||||
result.messages.push(`${chunkTaskIds.length} 个条码重试失败:${reason}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result.pending = await prisma.productStopPushTask.count({
|
||||
where: { status: 'PENDING' },
|
||||
})
|
||||
return result
|
||||
}
|
||||
retryPendingAutomaticPushes() { return retryPendingAutomaticPushes() }
|
||||
}
|
||||
|
||||
export const productStopPushService = new ProductStopPushService()
|
||||
|
||||
@ -0,0 +1,53 @@
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
|
||||
export type PushSnapshot = {
|
||||
barcode: string
|
||||
productStatus: string
|
||||
stopDecision: string
|
||||
stopSuggestion: string
|
||||
nextStopPushAt: Date | null
|
||||
generatedAt: Date
|
||||
}
|
||||
|
||||
export type PushResult = {
|
||||
pushed: number
|
||||
queued: number
|
||||
skipped: number
|
||||
failed: number
|
||||
batches: number
|
||||
messages: string[]
|
||||
successfulBarcodes: string[]
|
||||
skippedDetails: Array<{ barcode: string; reason: string }>
|
||||
failedDetails: Array<{ barcode: string; reason: string }>
|
||||
}
|
||||
|
||||
export type ProductStopPushRetryResult = Pick<PushResult,
|
||||
'pushed' | 'skipped' | 'failed' | 'batches' | 'messages'> & { pending: number }
|
||||
|
||||
export type PushBatchInput = {
|
||||
snapshotDate: string
|
||||
snapshots: readonly PushSnapshot[]
|
||||
reasonCategory: string
|
||||
reasonDetail: (snapshot: PushSnapshot) => string
|
||||
user: Pick<AuthUser, 'id' | 'name'>
|
||||
requesterDepartment?: string
|
||||
queueOnFlowUnavailable?: boolean
|
||||
}
|
||||
|
||||
export function chunk<T>(items: readonly T[], size: number) {
|
||||
const result: T[][] = []
|
||||
for (let index = 0; index < items.length; index += size) {
|
||||
result.push(items.slice(index, index + size))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function isFlowSourceUnavailable(error: unknown) {
|
||||
return (error instanceof Error ? error.message : String(error))
|
||||
.includes('停产流程数据源暂时无法连接')
|
||||
}
|
||||
|
||||
export function emptyPushResult(): PushResult {
|
||||
return { pushed: 0, queued: 0, skipped: 0, failed: 0, batches: 0,
|
||||
messages: [], successfulBarcodes: [], skippedDetails: [], failedDetails: [] }
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
/** @jest-environment node */
|
||||
jest.mock('@/server/repositories/product-stop-detail.repository', () => ({productStopDetailRepository: {
|
||||
findLatestSnapshotByBarcode: jest.fn(), listDistributionShops: jest.fn(),
|
||||
}}));
|
||||
jest.mock('./product-stop-detail-generation.service', () => ({productStopDetailGenerationService: {}}));
|
||||
import {productStopDetailRepository as repository} from '@/server/repositories/product-stop-detail.repository';
|
||||
import {productStopDetailService as service} from './product-stop-detail.service';
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
it('rejects a barcode outside the requested partition before reading company shop data', async () => {
|
||||
(repository.findLatestSnapshotByBarcode as jest.Mock).mockResolvedValue({barcode: 'A1', admission: '否'});
|
||||
await expect(service.getDistributionShops('a1', '是')).rejects.toThrow('准入范围');
|
||||
expect(repository.listDistributionShops).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not expose shop data for a barcode missing from the snapshot', async () => {
|
||||
(repository.findLatestSnapshotByBarcode as jest.Mock).mockResolvedValue(null);
|
||||
await expect(service.getDistributionShops('A1', '是')).rejects.toThrow('准入范围');
|
||||
expect(repository.listDistributionShops).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves the separately authorized stop demand context without snapshot membership', async () => {
|
||||
(repository.findLatestSnapshotByBarcode as jest.Mock).mockResolvedValue(null);
|
||||
(repository.listDistributionShops as jest.Mock).mockResolvedValue([{shopName: 'S1'}]);
|
||||
await expect(service.getDistributionShops('a1')).resolves.toEqual([{shopName: 'S1'}]);
|
||||
expect(repository.listDistributionShops).toHaveBeenCalledWith('A1');
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user