feat(clearance): 增加任务外人工清货价导入
This commit is contained in:
parent
9b6a379404
commit
016e7ea408
@ -0,0 +1,31 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { supplyChainClearancePricePushService } from '@/server/services/supply-chain-clearance-price-push.service'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
return handleRequest(
|
||||
request,
|
||||
async (ctx) => {
|
||||
const form = await request.formData()
|
||||
const file = form.get('file')
|
||||
const periodKey = String(form.get('periodKey') ?? '').trim()
|
||||
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(periodKey)) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '清货月份格式不正确', 400, ctx.requestId)
|
||||
}
|
||||
if (!(file instanceof File)) {
|
||||
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请选择人工清货价 Excel', 400, ctx.requestId)
|
||||
}
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, 'Excel 文件不能超过 10MB', 400, ctx.requestId)
|
||||
}
|
||||
const result = await supplyChainClearancePricePushService.importManualPrices({
|
||||
periodKey,
|
||||
user: ctx.user,
|
||||
buffer: Buffer.from(await file.arrayBuffer()),
|
||||
})
|
||||
return jsonSuccess(result, 200, ctx.requestId)
|
||||
},
|
||||
{ requireAuth: true },
|
||||
)
|
||||
}
|
||||
@ -19,6 +19,12 @@ describe('ClearancePricePushView', () => {
|
||||
blob: async () => new Blob(['xlsx']),
|
||||
} as Response)
|
||||
}
|
||||
if (url.includes('/price-push/manual/import')) {
|
||||
return jsonResponse({
|
||||
importedCount: 45,
|
||||
rowCount: 1321,
|
||||
})
|
||||
}
|
||||
if (init?.method === 'POST') {
|
||||
return jsonResponse({
|
||||
rowCount: 2,
|
||||
@ -75,6 +81,26 @@ describe('ClearancePricePushView', () => {
|
||||
expect(await screen.findByText(/已存档 2 条/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('imports manual clearance prices outside the current tasks', async () => {
|
||||
render(<ClearancePricePushView canGenerate />)
|
||||
|
||||
const input = await screen.findByLabelText('选择人工清货价 Excel')
|
||||
fireEvent.change(input, {
|
||||
target: {
|
||||
files: [new File(['xlsx'], '人工清货价.xlsx')],
|
||||
},
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect((global.fetch as jest.Mock).mock.calls.some(([url, init]) => (
|
||||
String(url).includes('/price-push/manual/import')
|
||||
&& init?.method === 'POST'
|
||||
&& init?.body instanceof FormData
|
||||
))).toBe(true)
|
||||
})
|
||||
expect(await screen.findByText(/已导入 45 个人工清货价编码/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('applies server-side filters', async () => {
|
||||
render(<ClearancePricePushView canGenerate canExport />)
|
||||
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Download, RefreshCw, Search } from 'lucide-react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Download, RefreshCw, Search, Upload } from 'lucide-react'
|
||||
import limitStyles from '../custom-table/limit-management.module.css'
|
||||
import ui from './clearance.module.css'
|
||||
import pricePushStyles from './clearance-price-push.module.css'
|
||||
@ -149,6 +149,8 @@ export function ClearancePricePushView({
|
||||
const [filterDraft, setFilterDraft] = useState<FilterDraft>(EMPTY_FILTERS)
|
||||
const [filters, setFilters] = useState<FilterDraft>(EMPTY_FILTERS)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [importing, setImporting] = useState(false)
|
||||
const importInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
@ -247,6 +249,43 @@ export function ClearancePricePushView({
|
||||
}
|
||||
}, [canGenerate, generating, period])
|
||||
|
||||
const importManualPrices = useCallback(async (file: File) => {
|
||||
if (!canGenerate || importing) return
|
||||
setImporting(true)
|
||||
setError('')
|
||||
setMessage('')
|
||||
try {
|
||||
const form = new FormData()
|
||||
form.set('periodKey', period)
|
||||
form.set('file', file)
|
||||
const response = await fetchWithNetworkRetry(
|
||||
'/api/supply-chain/clearance/price-push/manual/import',
|
||||
{ method: 'POST', body: form },
|
||||
1,
|
||||
'导入连接中断,请稍后重试',
|
||||
)
|
||||
const payload = await response.json().catch(() => null) as {
|
||||
success?: boolean
|
||||
data?: { importedCount: number; rowCount: number }
|
||||
error?: { message?: string }
|
||||
} | null
|
||||
if (!response.ok || !payload?.success || !payload.data) {
|
||||
throw new Error(payload?.error?.message || '导入人工清货价失败')
|
||||
}
|
||||
setMessage(
|
||||
`已导入 ${payload.data.importedCount.toLocaleString('zh-CN')} 个人工清货价编码,当前存档共 ${payload.data.rowCount.toLocaleString('zh-CN')} 条`,
|
||||
)
|
||||
setLoading(true)
|
||||
setPage(1)
|
||||
setRefreshKey((value) => value + 1)
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : '导入人工清货价失败')
|
||||
} finally {
|
||||
setImporting(false)
|
||||
if (importInputRef.current) importInputRef.current.value = ''
|
||||
}
|
||||
}, [canGenerate, importing, period])
|
||||
|
||||
const rows = data?.rows ?? []
|
||||
|
||||
return (
|
||||
@ -305,16 +344,38 @@ export function ClearancePricePushView({
|
||||
</button>
|
||||
)}
|
||||
{canGenerate && (
|
||||
<button
|
||||
className={limitStyles.primaryButton}
|
||||
type="button"
|
||||
disabled={generating}
|
||||
onClick={() => void generate()}
|
||||
>
|
||||
{generating
|
||||
? '生成中…'
|
||||
: data?.snapshot ? '更新本月存档' : '生成本月存档'}
|
||||
</button>
|
||||
<>
|
||||
<input
|
||||
ref={importInputRef}
|
||||
type="file"
|
||||
accept=".xlsx"
|
||||
hidden
|
||||
onChange={(event) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (file) void importManualPrices(file)
|
||||
}}
|
||||
aria-label="选择人工清货价 Excel"
|
||||
/>
|
||||
<button
|
||||
className={limitStyles.secondaryButton}
|
||||
type="button"
|
||||
disabled={importing || generating}
|
||||
onClick={() => importInputRef.current?.click()}
|
||||
>
|
||||
<Upload size={14} aria-hidden="true" />
|
||||
{importing ? '导入中…' : '导入人工清货价'}
|
||||
</button>
|
||||
<button
|
||||
className={limitStyles.primaryButton}
|
||||
type="button"
|
||||
disabled={generating || importing}
|
||||
onClick={() => void generate()}
|
||||
>
|
||||
{generating
|
||||
? '生成中…'
|
||||
: data?.snapshot ? '更新本月存档' : '生成本月存档'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@ -0,0 +1,29 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
import { parseClearancePricePushManualImport } from './clearance-price-push-manual-import'
|
||||
|
||||
async function workbookBuffer(rows: unknown[][]) {
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
const worksheet = workbook.addWorksheet('Sheet1')
|
||||
worksheet.addRow(['统计月', '条码', '清货价'])
|
||||
for (const row of rows) worksheet.addRow(row)
|
||||
return Buffer.from(await workbook.xlsx.writeBuffer())
|
||||
}
|
||||
|
||||
describe('parseClearancePricePushManualImport', () => {
|
||||
it('parses manual price codes outside clearance tasks', async () => {
|
||||
await expect(parseClearancePricePushManualImport(await workbookBuffer([
|
||||
[46327, 'manual-001', 12.5],
|
||||
[46327, 'MANUAL-002', '8.8'],
|
||||
]))).resolves.toEqual([
|
||||
{ rowNumber: 2, periodKey: '2026-11', productCode: 'MANUAL-001', clearancePrice: 12.5 },
|
||||
{ rowNumber: 3, periodKey: '2026-11', productCode: 'MANUAL-002', clearancePrice: 8.8 },
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects duplicate product codes', async () => {
|
||||
await expect(parseClearancePricePushManualImport(await workbookBuffer([
|
||||
[46327, 'MANUAL-001', 12.5],
|
||||
[46327, 'MANUAL-001', 10],
|
||||
]))).rejects.toThrow('商品编码重复')
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,78 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
|
||||
export type ClearancePricePushManualImportRow = {
|
||||
rowNumber: number
|
||||
periodKey: string
|
||||
productCode: string
|
||||
clearancePrice: number
|
||||
}
|
||||
|
||||
function cellText(value: ExcelJS.CellValue) {
|
||||
if (value == null) return ''
|
||||
if (value instanceof Date) return value.toISOString().slice(0, 7)
|
||||
if (typeof value === 'object') {
|
||||
if ('text' in value && typeof value.text === 'string') return value.text.trim()
|
||||
if ('result' in value && value.result != null) return String(value.result).trim()
|
||||
throw new Error('单元格包含公式或富文本,请先粘贴为值')
|
||||
}
|
||||
return String(value).trim()
|
||||
}
|
||||
|
||||
function periodOf(value: ExcelJS.CellValue) {
|
||||
if (value instanceof Date) return value.toISOString().slice(0, 7)
|
||||
if (typeof value === 'number') {
|
||||
return new Date(Date.UTC(1899, 11, 30) + Math.trunc(value) * 86_400_000)
|
||||
.toISOString()
|
||||
.slice(0, 7)
|
||||
}
|
||||
const text = cellText(value)
|
||||
if (/^\d{4}-(0[1-9]|1[0-2])$/.test(text)) return text
|
||||
if (/^\d{5}$/.test(text)) {
|
||||
return new Date(Date.UTC(1899, 11, 30) + Number(text) * 86_400_000)
|
||||
.toISOString()
|
||||
.slice(0, 7)
|
||||
}
|
||||
throw new Error(`统计月格式不正确:${text || '空值'}`)
|
||||
}
|
||||
|
||||
export async function parseClearancePricePushManualImport(
|
||||
buffer: Buffer,
|
||||
): Promise<ClearancePricePushManualImportRow[]> {
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.load(buffer as never)
|
||||
const worksheet = workbook.getWorksheet('Sheet1') ?? workbook.worksheets[0]
|
||||
if (!worksheet) throw new Error('Excel 中没有可读取的工作表')
|
||||
|
||||
const headers = new Map<string, number>()
|
||||
worksheet.getRow(1).eachCell((cell, columnNumber) => {
|
||||
headers.set(cellText(cell.value), columnNumber)
|
||||
})
|
||||
for (const required of ['统计月', '条码', '清货价']) {
|
||||
if (!headers.has(required)) throw new Error(`Excel 缺少“${required}”列`)
|
||||
}
|
||||
const periodColumn = headers.get('统计月')!
|
||||
const barcodeColumn = headers.get('条码')!
|
||||
const priceColumn = headers.get('清货价')!
|
||||
|
||||
const rows: ClearancePricePushManualImportRow[] = []
|
||||
const seen = new Set<string>()
|
||||
worksheet.eachRow((row, rowNumber) => {
|
||||
if (rowNumber === 1) return
|
||||
const periodKey = periodOf(row.getCell(periodColumn).value)
|
||||
const productCode = cellText(row.getCell(barcodeColumn).value).toUpperCase()
|
||||
const priceText = cellText(row.getCell(priceColumn).value)
|
||||
if (!productCode && !priceText) return
|
||||
if (!productCode) throw new Error(`第 ${rowNumber} 行条码为空`)
|
||||
if (!priceText) throw new Error(`第 ${rowNumber} 行清货价为空`)
|
||||
const clearancePrice = Number(priceText.replace(/,/g, ''))
|
||||
if (!Number.isFinite(clearancePrice) || clearancePrice <= 0) {
|
||||
throw new Error(`第 ${rowNumber} 行清货价必须为正数`)
|
||||
}
|
||||
if (seen.has(productCode)) throw new Error(`第 ${rowNumber} 行商品编码重复:${productCode}`)
|
||||
seen.add(productCode)
|
||||
rows.push({ rowNumber, periodKey, productCode, clearancePrice })
|
||||
})
|
||||
if (!rows.length) throw new Error('Excel 没有可导入的人工清货价')
|
||||
if (rows.length > 5_000) throw new Error('单次最多导入 5000 条人工清货价')
|
||||
return rows
|
||||
}
|
||||
@ -226,6 +226,12 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method:
|
||||
if (pathname === '/api/supply-chain/clearance/export') {
|
||||
return { targetKey: 'businessManagement' as const, action: 'download' as const }
|
||||
}
|
||||
if (
|
||||
pathname === '/api/supply-chain/clearance/price-push/manual/import'
|
||||
&& method.toUpperCase() === 'POST'
|
||||
) {
|
||||
return { targetKey: 'clearanceReview' as const, action: 'edit' as const }
|
||||
}
|
||||
if (pathname === '/api/supply-chain/clearance/price-push' && method.toUpperCase() !== 'GET') {
|
||||
return { targetKey: 'clearanceReview' as const, action: 'edit' as const }
|
||||
}
|
||||
|
||||
@ -50,6 +50,10 @@ describe('supply chain permission settings', () => {
|
||||
'/api/supply-chain/clearance/price-push',
|
||||
'POST',
|
||||
)).toEqual({ targetKey: 'clearanceReview', action: 'edit' })
|
||||
expect(getSupplyChainApiPermissionRequirement(
|
||||
'/api/supply-chain/clearance/price-push/manual/import',
|
||||
'POST',
|
||||
)).toEqual({ targetKey: 'clearanceReview', action: 'edit' })
|
||||
})
|
||||
|
||||
it('requires business management view for owner queries and edit for mutations', () => {
|
||||
|
||||
@ -31,6 +31,10 @@ export type ClearancePricePushManualItem = {
|
||||
costPrice: number | null
|
||||
}
|
||||
|
||||
export type ClearancePricePushManualItemInput = ClearancePricePushManualItem & {
|
||||
periodKey: string
|
||||
}
|
||||
|
||||
export type ClearancePricePushFilters = {
|
||||
productCode?: string
|
||||
shopKeyword?: string
|
||||
@ -271,6 +275,34 @@ class SupplyChainClearancePricePushRepository {
|
||||
})).filter((row) => row.productCode && Number.isFinite(row.clearancePrice))
|
||||
}
|
||||
|
||||
async listArchiveCostsByProductCodes(productCodes: readonly string[]) {
|
||||
const codes = normalizedCodes(productCodes)
|
||||
if (!codes.length) return []
|
||||
const rows = await prisma.supplyChainProductArchive.findMany({
|
||||
where: { barcode: { in: codes } },
|
||||
select: { barcode: true, costPrice: true },
|
||||
})
|
||||
return rows.flatMap((row) => {
|
||||
const costPrice = Number(row.costPrice)
|
||||
return Number.isFinite(costPrice)
|
||||
? [[row.barcode.trim().toUpperCase(), costPrice] as const]
|
||||
: []
|
||||
})
|
||||
}
|
||||
|
||||
async replaceManualItems(periodKey: string, items: readonly ClearancePricePushManualItemInput[]) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.supplyChainClearancePricePushManualItem.deleteMany({
|
||||
where: { periodKey },
|
||||
})
|
||||
for (let start = 0; start < items.length; start += 500) {
|
||||
await tx.supplyChainClearancePricePushManualItem.createMany({
|
||||
data: items.slice(start, start + 500),
|
||||
})
|
||||
}
|
||||
}, { maxWait: 10_000, timeout: 120_000 })
|
||||
}
|
||||
|
||||
async finalizeHistoricalCostPrices(periodKey: string, productCodes: readonly string[]) {
|
||||
const codes = normalizedCodes(productCodes)
|
||||
if (!codes.length) return 0
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import type { supplyChainClearancePricePushRepository } from '@/server/repositories/supply-chain-clearance-price-push.repository'
|
||||
import {
|
||||
@ -25,6 +26,14 @@ const user = {
|
||||
status: 'ACTIVE',
|
||||
} as AuthUser
|
||||
|
||||
async function manualWorkbook(rows: unknown[][]) {
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
const worksheet = workbook.addWorksheet('Sheet1')
|
||||
worksheet.addRow(['统计月', '条码', '清货价'])
|
||||
for (const row of rows) worksheet.addRow(row)
|
||||
return Buffer.from(await workbook.xlsx.writeBuffer())
|
||||
}
|
||||
|
||||
function repository(overrides: Partial<typeof supplyChainClearancePricePushRepository> = {}) {
|
||||
return {
|
||||
listSnapshots: jest.fn().mockResolvedValue([]),
|
||||
@ -249,4 +258,67 @@ describe('supply chain clearance price push service', () => {
|
||||
['CLEAR-A', 'SKU-A1', 'SKU-A2'],
|
||||
)
|
||||
})
|
||||
|
||||
it('imports manual prices only for codes outside current clearance tasks', async () => {
|
||||
const repo = repository({
|
||||
listProductCodesByClearanceCodes: jest.fn().mockResolvedValue([]),
|
||||
listArchiveCostsByProductCodes: jest.fn().mockResolvedValue([
|
||||
['MANUAL-1', 100],
|
||||
]),
|
||||
replaceManualItems: jest.fn().mockResolvedValue(undefined),
|
||||
listManualItems: jest.fn().mockResolvedValue([{
|
||||
productCode: 'MANUAL-1',
|
||||
clearancePrice: 50,
|
||||
costPrice: 100,
|
||||
}]),
|
||||
})
|
||||
const taskReader = {
|
||||
getTasks: jest.fn().mockResolvedValue({
|
||||
tasks: [{
|
||||
barcode: 'TASK-A',
|
||||
clearanceCode: 'TASK-A',
|
||||
costPrice: 80,
|
||||
clearancePrice: null,
|
||||
}],
|
||||
}),
|
||||
}
|
||||
const service = new SupplyChainClearancePricePushService(repo, taskReader as never)
|
||||
|
||||
await expect(service.importManualPrices({
|
||||
periodKey: '2026-11',
|
||||
user,
|
||||
buffer: await manualWorkbook([[46327, 'MANUAL-1', 50]]),
|
||||
})).resolves.toMatchObject({
|
||||
importedCount: 1,
|
||||
rowCount: 1,
|
||||
})
|
||||
expect(repo.replaceManualItems).toHaveBeenCalledWith('2026-11', [{
|
||||
periodKey: '2026-11',
|
||||
productCode: 'MANUAL-1',
|
||||
clearancePrice: 50,
|
||||
costPrice: 100,
|
||||
}])
|
||||
})
|
||||
|
||||
it('rejects manual prices whose codes already exist in clearance tasks', async () => {
|
||||
const service = new SupplyChainClearancePricePushService(
|
||||
repository(),
|
||||
{
|
||||
getTasks: jest.fn().mockResolvedValue({
|
||||
tasks: [{
|
||||
barcode: 'TASK-A',
|
||||
clearanceCode: 'CLEAR-A',
|
||||
costPrice: 80,
|
||||
clearancePrice: 50,
|
||||
}],
|
||||
}),
|
||||
} as never,
|
||||
)
|
||||
|
||||
await expect(service.importManualPrices({
|
||||
periodKey: '2026-11',
|
||||
user,
|
||||
buffer: await manualWorkbook([[46327, 'TASK-A', 40]]),
|
||||
})).rejects.toThrow('已存在清货任务')
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,5 +1,9 @@
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import {
|
||||
parseClearancePricePushManualImport,
|
||||
type ClearancePricePushManualImportRow,
|
||||
} from '@/lib/clearance-price-push-manual-import'
|
||||
import {
|
||||
supplyChainClearancePricePushRepository,
|
||||
type ClearancePricePushItemInput,
|
||||
@ -19,6 +23,8 @@ type PricePushRepository = Pick<
|
||||
| 'listItems'
|
||||
| 'listProductCodesByClearanceCodes'
|
||||
| 'listManualItems'
|
||||
| 'listArchiveCostsByProductCodes'
|
||||
| 'replaceManualItems'
|
||||
| 'finalizeHistoricalCostPrices'
|
||||
| 'replaceSnapshot'
|
||||
>
|
||||
@ -135,6 +141,90 @@ export class SupplyChainClearancePricePushService {
|
||||
return this.repository.finalizeHistoricalCostPrices(periodKey, productCodes)
|
||||
}
|
||||
|
||||
async importManualPrices(input: {
|
||||
periodKey: string
|
||||
user: AuthUser
|
||||
buffer: Buffer
|
||||
}) {
|
||||
const periodKey = input.periodKey.trim()
|
||||
if (!PERIOD_PATTERN.test(periodKey)) {
|
||||
throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '清货月份格式必须为 YYYY-MM')
|
||||
}
|
||||
let rows: ClearancePricePushManualImportRow[]
|
||||
try {
|
||||
rows = await parseClearancePricePushManualImport(input.buffer)
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
error instanceof Error ? error.message : '人工清货价文件格式不正确',
|
||||
)
|
||||
}
|
||||
const filePeriods = Array.from(new Set(rows.map((row) => row.periodKey)))
|
||||
if (filePeriods.length !== 1 || filePeriods[0] !== periodKey) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
`文件统计月必须为 ${periodKey}`,
|
||||
)
|
||||
}
|
||||
|
||||
const taskResult = await this.taskReader.getTasks(periodKey, {
|
||||
includeFreight: false,
|
||||
})
|
||||
const taskClearanceCodes = Array.from(new Set(taskResult.tasks.flatMap((task) => {
|
||||
const values = [
|
||||
String(task.barcode ?? '').trim().toUpperCase(),
|
||||
String(task.clearanceCode ?? '').trim().toUpperCase(),
|
||||
].filter(Boolean)
|
||||
return values
|
||||
})))
|
||||
const taskProducts = await this.repository.listProductCodesByClearanceCodes(
|
||||
periodKey,
|
||||
taskClearanceCodes,
|
||||
)
|
||||
const reservedCodes = new Set([
|
||||
...taskClearanceCodes,
|
||||
...taskProducts.map((product) => product.productCode.trim().toUpperCase()),
|
||||
])
|
||||
const duplicates = rows
|
||||
.map((row) => row.productCode)
|
||||
.filter((productCode) => reservedCodes.has(productCode))
|
||||
if (duplicates.length) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
`以下编码已存在清货任务,不能作为人工清货价重复导入:${duplicates.slice(0, 10).join('、')}`,
|
||||
)
|
||||
}
|
||||
|
||||
const costs = new Map(await this.repository.listArchiveCostsByProductCodes(
|
||||
rows.map((row) => row.productCode),
|
||||
))
|
||||
const missingCosts = rows
|
||||
.map((row) => row.productCode)
|
||||
.filter((productCode) => !(Number(costs.get(productCode)) > 0))
|
||||
if (missingCosts.length) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_REQUIRED_FIELD,
|
||||
`以下人工清货价编码无法匹配成本价:${missingCosts.slice(0, 10).join('、')}`,
|
||||
)
|
||||
}
|
||||
await this.repository.replaceManualItems(
|
||||
periodKey,
|
||||
rows.map((row) => ({
|
||||
periodKey,
|
||||
productCode: row.productCode,
|
||||
clearancePrice: row.clearancePrice,
|
||||
costPrice: Number(costs.get(row.productCode)),
|
||||
})),
|
||||
)
|
||||
const generated = await this.generate({ periodKey, user: input.user })
|
||||
return {
|
||||
periodKey,
|
||||
importedCount: rows.length,
|
||||
rowCount: generated.rowCount,
|
||||
matchedProductCount: generated.matchedProductCount,
|
||||
}
|
||||
}
|
||||
|
||||
async generate(input: {
|
||||
periodKey: string
|
||||
user: AuthUser
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user