feat(supply-chain): map archive prices by barcode
This commit is contained in:
parent
b9ec3511ac
commit
cbbf2fbb21
@ -50,6 +50,9 @@
|
||||
| `supplierName` | 供应商 | `rpt.jst_sku.supplier_name` | `archive_supplier_name` | | 原样保留 |
|
||||
| `purchaseOwner` | 采购 | 暂不接入 | `archive_purchase_owner` | | 只取流程采购负责人,不用产品负责人兜底 |
|
||||
| `minimumOrderQuantity` | 产品起订量 | 暂不接入 | `archive_minimum_order_quantity` | | |
|
||||
| `purchasePrice` | 采购价 | `rpt.jst_sku.purchase_price` | | | 按档案条码精确匹配 `jst_sku.sku_id`;匹配不到时留空 |
|
||||
| `costPrice` | 成本价(聚水潭) | `rpt.jst_sku.cost_price` | | | 按档案条码精确匹配 `jst_sku.sku_id`;匹配不到时留空 |
|
||||
| `costPriceSecondary` | 成本价(新品) | | `external.product_catalog_wide_v1.cost_price` | | 按档案条码精确匹配 `barcode_business_key`,只读取 `catalog_source = INTAKE_READY` 的新品行;匹配不到或来源为空时留空 |
|
||||
|
||||
## 3. JST_SKU 第一批字段覆盖率
|
||||
|
||||
|
||||
@ -47,6 +47,9 @@ export type SupplyChainProductArchiveRow = {
|
||||
sales3d: string
|
||||
sales7d: string
|
||||
sales15d: string
|
||||
purchasePrice: string
|
||||
costPrice: string
|
||||
costPriceSecondary: string
|
||||
}
|
||||
|
||||
export const PRODUCT_ARCHIVE_SALES_STATUSES = ['销售', '停产', '退市'] as const
|
||||
|
||||
@ -0,0 +1,113 @@
|
||||
import sql from 'mssql'
|
||||
|
||||
export type JstSkuPriceProfile = {
|
||||
barcode: string
|
||||
purchasePrice: string
|
||||
costPrice: string
|
||||
}
|
||||
|
||||
export interface JstSkuPriceRepository {
|
||||
listByBarcodes(barcodes: readonly string[]): Promise<JstSkuPriceProfile[]>
|
||||
close(): Promise<void>
|
||||
}
|
||||
|
||||
function requiredEnv(name: string) {
|
||||
const value = process.env[name]?.trim()
|
||||
if (!value) throw new Error(`Missing required environment variable: ${name}`)
|
||||
return value
|
||||
}
|
||||
|
||||
function booleanEnv(name: string, fallback: boolean) {
|
||||
const value = process.env[name]?.trim().toLowerCase()
|
||||
if (!value) return fallback
|
||||
return value === 'true' || value === '1'
|
||||
}
|
||||
|
||||
function safeIdentifier(value: string, label: string) {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
|
||||
throw new Error(`${label} is not a valid SQL Server identifier`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function normalizedBarcodes(barcodes: readonly string[]) {
|
||||
return Array.from(
|
||||
new Set(barcodes.map((barcode) => barcode.trim().toUpperCase()).filter(Boolean)),
|
||||
).slice(0, 200)
|
||||
}
|
||||
|
||||
class JstSkuPriceRepositoryClass implements JstSkuPriceRepository {
|
||||
private pool: sql.ConnectionPool | null = null
|
||||
|
||||
private async getPool() {
|
||||
if (this.pool?.connected) return this.pool
|
||||
|
||||
this.pool = await new sql.ConnectionPool({
|
||||
server: requiredEnv('JST_REPORT_DB_HOST'),
|
||||
port: Number(process.env.JST_REPORT_DB_PORT?.trim() || '1433'),
|
||||
database: requiredEnv('JST_REPORT_DB_NAME'),
|
||||
user: requiredEnv('JST_REPORT_DB_USER'),
|
||||
password: requiredEnv('JST_REPORT_DB_PASSWORD'),
|
||||
options: {
|
||||
encrypt: booleanEnv('JST_REPORT_DB_ENCRYPT', true),
|
||||
trustServerCertificate: booleanEnv(
|
||||
'JST_REPORT_DB_TRUST_SERVER_CERTIFICATE',
|
||||
true,
|
||||
),
|
||||
},
|
||||
pool: {
|
||||
min: 0,
|
||||
max: 4,
|
||||
idleTimeoutMillis: 30_000,
|
||||
},
|
||||
requestTimeout: 30_000,
|
||||
connectionTimeout: 15_000,
|
||||
}).connect()
|
||||
return this.pool
|
||||
}
|
||||
|
||||
async listByBarcodes(barcodes: readonly string[]) {
|
||||
const normalized = normalizedBarcodes(barcodes)
|
||||
if (normalized.length === 0) return []
|
||||
|
||||
const schema = safeIdentifier(
|
||||
process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt',
|
||||
'JST_REPORT_DB_SCHEMA',
|
||||
)
|
||||
const pool = await this.getPool()
|
||||
const request = pool.request()
|
||||
const parameters = normalized.map((barcode, index) => {
|
||||
const parameter = `barcode${index}`
|
||||
request.input(parameter, sql.VarChar(100), barcode)
|
||||
return `@${parameter}`
|
||||
})
|
||||
|
||||
const result = await request.query<JstSkuPriceProfile>(`
|
||||
WITH ranked_prices AS (
|
||||
SELECT
|
||||
UPPER(LTRIM(RTRIM(CAST(sku_id AS varchar(100))))) AS barcode,
|
||||
LTRIM(RTRIM(COALESCE(CAST(purchase_price AS varchar(100)), ''))) AS purchasePrice,
|
||||
LTRIM(RTRIM(COALESCE(CAST(cost_price AS varchar(100)), ''))) AS costPrice,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY UPPER(LTRIM(RTRIM(CAST(sku_id AS varchar(100)))))
|
||||
ORDER BY local_updated DESC, modified DESC, autoid DESC
|
||||
) AS row_rank
|
||||
FROM [${schema}].[jst_sku]
|
||||
WHERE item_type = N'成品'
|
||||
AND UPPER(LTRIM(RTRIM(CAST(sku_id AS varchar(100))))) IN (${parameters.join(', ')})
|
||||
)
|
||||
SELECT barcode, purchasePrice, costPrice
|
||||
FROM ranked_prices
|
||||
WHERE row_rank = 1
|
||||
`)
|
||||
return result.recordset
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (!this.pool) return
|
||||
await this.pool.close()
|
||||
this.pool = null
|
||||
}
|
||||
}
|
||||
|
||||
export const jstSkuPriceRepository = new JstSkuPriceRepositoryClass()
|
||||
@ -0,0 +1,40 @@
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export type ProductCatalogCostPriceProfile = {
|
||||
barcode: string
|
||||
costPrice: string | null
|
||||
}
|
||||
|
||||
export interface ProductCatalogCostPriceRepository {
|
||||
listByBarcodes(
|
||||
barcodes: readonly string[],
|
||||
): Promise<ProductCatalogCostPriceProfile[]>
|
||||
}
|
||||
|
||||
function normalizedBarcodes(barcodes: readonly string[]) {
|
||||
return Array.from(
|
||||
new Set(barcodes.map((barcode) => barcode.trim().toUpperCase()).filter(Boolean)),
|
||||
).slice(0, 200)
|
||||
}
|
||||
|
||||
class ProductCatalogCostPriceRepositoryClass
|
||||
implements ProductCatalogCostPriceRepository
|
||||
{
|
||||
async listByBarcodes(barcodes: readonly string[]) {
|
||||
const normalized = normalizedBarcodes(barcodes)
|
||||
if (normalized.length === 0) return []
|
||||
|
||||
return prisma.$queryRaw<ProductCatalogCostPriceProfile[]>(Prisma.sql`
|
||||
SELECT
|
||||
UPPER(BTRIM("barcode_business_key")) AS "barcode",
|
||||
"cost_price"::text AS "costPrice"
|
||||
FROM external.product_catalog_wide_v1
|
||||
WHERE UPPER(BTRIM("barcode_business_key")) IN (${Prisma.join(normalized)})
|
||||
AND "catalog_source" = 'INTAKE_READY'
|
||||
`)
|
||||
}
|
||||
}
|
||||
|
||||
export const productCatalogCostPriceRepository =
|
||||
new ProductCatalogCostPriceRepositoryClass()
|
||||
@ -13,6 +13,16 @@ jest.mock('@/server/repositories/jst-warehouse-profile.repository', () => ({
|
||||
listByNames: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
}))
|
||||
jest.mock('@/server/repositories/jst-sku-price.repository', () => ({
|
||||
jstSkuPriceRepository: {
|
||||
listByBarcodes: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
}))
|
||||
jest.mock('@/server/repositories/product-catalog-cost-price.repository', () => ({
|
||||
productCatalogCostPriceRepository: {
|
||||
listByBarcodes: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
}))
|
||||
|
||||
import {
|
||||
SupplyChainProductArchiveService,
|
||||
@ -122,6 +132,23 @@ describe('supply-chain product archive field mapping', () => {
|
||||
},
|
||||
]),
|
||||
}
|
||||
const jstSkuPriceRepository = {
|
||||
listByBarcodes: jest.fn().mockResolvedValue([
|
||||
{
|
||||
barcode: 'BAR-001',
|
||||
purchasePrice: '88.50',
|
||||
costPrice: '76.20',
|
||||
},
|
||||
]),
|
||||
}
|
||||
const productCatalogCostPriceRepository = {
|
||||
listByBarcodes: jest.fn().mockResolvedValue([
|
||||
{
|
||||
barcode: 'BAR-001',
|
||||
costPrice: '72.30',
|
||||
},
|
||||
]),
|
||||
}
|
||||
const service = new SupplyChainProductArchiveService(
|
||||
repository as never,
|
||||
supplierProfileRepository,
|
||||
@ -132,6 +159,8 @@ describe('supply-chain product archive field mapping', () => {
|
||||
]),
|
||||
} as never,
|
||||
warehouseProfileRepository,
|
||||
jstSkuPriceRepository,
|
||||
productCatalogCostPriceRepository,
|
||||
)
|
||||
|
||||
const page = await service.listPage({ page: 1, pageSize: 50 })
|
||||
@ -170,6 +199,9 @@ describe('supply-chain product archive field mapping', () => {
|
||||
sales3d: '0',
|
||||
sales7d: '32.77',
|
||||
sales15d: '34.72',
|
||||
purchasePrice: '88.50',
|
||||
costPrice: '76.20',
|
||||
costPriceSecondary: '72.30',
|
||||
}),
|
||||
)
|
||||
expect(supplierProfileRepository.listByNames).toHaveBeenCalledWith([
|
||||
@ -181,5 +213,11 @@ describe('supply-chain product archive field mapping', () => {
|
||||
expect(warehouseProfileRepository.listByNames).toHaveBeenCalledWith([
|
||||
'WH-1',
|
||||
])
|
||||
expect(jstSkuPriceRepository.listByBarcodes).toHaveBeenCalledWith([
|
||||
'BAR-001',
|
||||
])
|
||||
expect(productCatalogCostPriceRepository.listByBarcodes).toHaveBeenCalledWith([
|
||||
'BAR-001',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@ -0,0 +1,122 @@
|
||||
import type { SupplyChainProductArchiveRow } from '@/lib/supply-chain-product-archive'
|
||||
import { storageTypeLabel } from '@/lib/supply-chain-product-archive-values'
|
||||
import type { JstSkuPriceProfile } from '@/server/repositories/jst-sku-price.repository'
|
||||
import type { JstStockMonitorProfile } from '@/server/repositories/jst-stock-monitor.repository'
|
||||
import type { JstSupplierProfile } from '@/server/repositories/jst-supplier-profile.repository'
|
||||
import type { ProductCatalogCostPriceProfile } from '@/server/repositories/product-catalog-cost-price.repository'
|
||||
import type { ProductArchiveRecord } from '@/server/repositories/supply-chain-product-archive.repository'
|
||||
|
||||
const DAY_IN_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
function calculateCreateDays(createdAt: Date, now: Date) {
|
||||
return Math.max(0, Math.floor((now.getTime() - createdAt.getTime()) / DAY_IN_MS))
|
||||
}
|
||||
|
||||
function decimalText(value: { toString(): string } | null) {
|
||||
return value?.toString() ?? ''
|
||||
}
|
||||
|
||||
export function normalizeSupplierName(value: string) {
|
||||
return value.trim().toLocaleLowerCase('zh-CN')
|
||||
}
|
||||
|
||||
export function normalizeWarehouseName(value: string) {
|
||||
return value.trim().toLocaleLowerCase('zh-CN')
|
||||
}
|
||||
|
||||
export function normalizeArchiveIdentity(value: string) {
|
||||
return value.trim().toLocaleUpperCase('zh-CN')
|
||||
}
|
||||
|
||||
function supplierStatusLabel(code: string | undefined) {
|
||||
if (code === '1') return '合作'
|
||||
if (code === '2') return '不合作'
|
||||
return ''
|
||||
}
|
||||
|
||||
export function mapProductArchiveRow({
|
||||
record,
|
||||
now,
|
||||
supplierProfile,
|
||||
stockProfile,
|
||||
jstSkuPrice,
|
||||
productCatalogCostPrice,
|
||||
warehouseTypes,
|
||||
warehouseStorageTypes,
|
||||
warehouseHeads,
|
||||
}: {
|
||||
record: ProductArchiveRecord
|
||||
now: Date
|
||||
supplierProfile?: JstSupplierProfile
|
||||
stockProfile?: JstStockMonitorProfile
|
||||
jstSkuPrice?: JstSkuPriceProfile
|
||||
productCatalogCostPrice?: ProductCatalogCostPriceProfile
|
||||
warehouseTypes?: Map<string, string>
|
||||
warehouseStorageTypes?: Map<string, string>
|
||||
warehouseHeads?: Map<string, string>
|
||||
}) {
|
||||
const exactBarcodeStockProfile =
|
||||
stockProfile &&
|
||||
normalizeArchiveIdentity(stockProfile.barcode) ===
|
||||
normalizeArchiveIdentity(record.barcode)
|
||||
? stockProfile
|
||||
: undefined
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
image: record.image?.trim() ?? '',
|
||||
createTime: record.businessCreatedAt.toISOString(),
|
||||
createDays: calculateCreateDays(record.businessCreatedAt, now),
|
||||
updateTime: record.updatedAt.toISOString(),
|
||||
categoryL1: record.categoryL1,
|
||||
categoryL2: record.categoryL2,
|
||||
spu: record.spu,
|
||||
sku: record.sku,
|
||||
barcode: record.barcode,
|
||||
productName: record.productName,
|
||||
designer: record.designer,
|
||||
productStatus: record.productStatus,
|
||||
material: record.material,
|
||||
color: record.color,
|
||||
weight: decimalText(record.weight),
|
||||
length: decimalText(record.length),
|
||||
width: decimalText(record.width),
|
||||
height: decimalText(record.height),
|
||||
volume: decimalText(record.volume),
|
||||
packType: record.packType,
|
||||
productTag: record.productTag,
|
||||
installDocId: record.installDocId,
|
||||
hasDrawing: record.hasDrawing,
|
||||
hasVideo: record.hasVideo,
|
||||
spec: record.spec,
|
||||
brand: record.brand,
|
||||
orderType: record.orderType,
|
||||
inOutWarehouse: record.inOutWarehouse,
|
||||
warehouseType:
|
||||
warehouseTypes?.get(normalizeWarehouseName(record.inOutWarehouse)) ?? '',
|
||||
warehouseHead:
|
||||
warehouseHeads?.get(normalizeWarehouseName(record.inOutWarehouse)) ?? '',
|
||||
storageType: storageTypeLabel(
|
||||
warehouseStorageTypes?.get(normalizeWarehouseName(record.inOutWarehouse)),
|
||||
),
|
||||
isSeasonal: record.isSeasonal,
|
||||
replaceCount: record.replaceCount,
|
||||
supplier: record.supplierName,
|
||||
supplierType: supplierProfile?.supplierType ?? '',
|
||||
supplierStatus: supplierStatusLabel(supplierProfile?.supplierStatusCode),
|
||||
purchaser: supplierProfile?.purchaser || record.purchaseOwner,
|
||||
settleType: supplierProfile?.settlementMethod ?? '',
|
||||
boardProvider: supplierProfile?.boardProvider ?? '',
|
||||
penaltyStatus: supplierProfile?.penaltyStatus ?? '',
|
||||
moq: stockProfile?.minimum || record.minimumOrderQuantity,
|
||||
firstLeadTime: stockProfile?.produceCycle ?? '',
|
||||
palletSpec: stockProfile?.trayParameter ?? '',
|
||||
dailySales: exactBarcodeStockProfile?.purchaseSale ?? '',
|
||||
sales3d: exactBarcodeStockProfile?.threeAvgSale ?? '',
|
||||
sales7d: exactBarcodeStockProfile?.sevenAvgSale ?? '',
|
||||
sales15d: exactBarcodeStockProfile?.fifteenAvgSale ?? '',
|
||||
purchasePrice: jstSkuPrice?.purchasePrice ?? '',
|
||||
costPrice: jstSkuPrice?.costPrice ?? '',
|
||||
costPriceSecondary: productCatalogCostPrice?.costPrice ?? '',
|
||||
} satisfies SupplyChainProductArchiveRow
|
||||
}
|
||||
@ -3,11 +3,9 @@ import type {
|
||||
ProductArchiveFilterOptions,
|
||||
ProductArchiveFilters,
|
||||
SupplyChainProductArchivePage,
|
||||
SupplyChainProductArchiveRow,
|
||||
} from '@/lib/supply-chain-product-archive'
|
||||
import {
|
||||
supplyChainProductArchiveRepository,
|
||||
type ProductArchiveRecord,
|
||||
type SupplyChainProductArchiveRepository,
|
||||
} from '@/server/repositories/supply-chain-product-archive.repository'
|
||||
import {
|
||||
@ -24,108 +22,26 @@ import {
|
||||
jstWarehouseProfileRepository,
|
||||
type JstWarehouseProfileRepository,
|
||||
} from '@/server/repositories/jst-warehouse-profile.repository'
|
||||
import { storageTypeLabel } from '@/lib/supply-chain-product-archive-values'
|
||||
import {
|
||||
jstSkuPriceRepository,
|
||||
type JstSkuPriceProfile,
|
||||
type JstSkuPriceRepository,
|
||||
} from '@/server/repositories/jst-sku-price.repository'
|
||||
import {
|
||||
productCatalogCostPriceRepository,
|
||||
type ProductCatalogCostPriceProfile,
|
||||
type ProductCatalogCostPriceRepository,
|
||||
} from '@/server/repositories/product-catalog-cost-price.repository'
|
||||
import {
|
||||
supplyChainProductArchiveWarehouseConfigRepository,
|
||||
type SupplyChainProductArchiveWarehouseConfigRepository,
|
||||
} from '@/server/repositories/supply-chain-product-archive-warehouse-config.repository'
|
||||
|
||||
const DAY_IN_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
function calculateCreateDays(createdAt: Date, now: Date) {
|
||||
return Math.max(0, Math.floor((now.getTime() - createdAt.getTime()) / DAY_IN_MS))
|
||||
}
|
||||
|
||||
function decimalText(value: { toString(): string } | null) {
|
||||
return value?.toString() ?? ''
|
||||
}
|
||||
|
||||
function normalizeSupplierName(value: string) {
|
||||
return value.trim().toLocaleLowerCase('zh-CN')
|
||||
}
|
||||
|
||||
function normalizeWarehouseName(value: string) {
|
||||
return value.trim().toLocaleLowerCase('zh-CN')
|
||||
}
|
||||
|
||||
function normalizeStockKey(value: string) {
|
||||
return value.trim().toLocaleUpperCase('zh-CN')
|
||||
}
|
||||
|
||||
function supplierStatusLabel(code: string | undefined) {
|
||||
if (code === '1') return '合作'
|
||||
if (code === '2') return '不合作'
|
||||
return ''
|
||||
}
|
||||
|
||||
function mapProductArchiveRow(
|
||||
record: ProductArchiveRecord,
|
||||
now: Date,
|
||||
supplierProfile?: JstSupplierProfile,
|
||||
stockProfile?: JstStockMonitorProfile,
|
||||
warehouseTypes?: Map<string, string>,
|
||||
warehouseStorageTypes?: Map<string, string>,
|
||||
warehouseHeads?: Map<string, string>,
|
||||
) {
|
||||
const exactBarcodeStockProfile =
|
||||
stockProfile &&
|
||||
normalizeStockKey(stockProfile.barcode) === normalizeStockKey(record.barcode)
|
||||
? stockProfile
|
||||
: undefined
|
||||
|
||||
return {
|
||||
id: record.id,
|
||||
image: record.image?.trim() ?? '',
|
||||
createTime: record.businessCreatedAt.toISOString(),
|
||||
createDays: calculateCreateDays(record.businessCreatedAt, now),
|
||||
updateTime: record.updatedAt.toISOString(),
|
||||
categoryL1: record.categoryL1,
|
||||
categoryL2: record.categoryL2,
|
||||
spu: record.spu,
|
||||
sku: record.sku,
|
||||
barcode: record.barcode,
|
||||
productName: record.productName,
|
||||
designer: record.designer,
|
||||
productStatus: record.productStatus,
|
||||
material: record.material,
|
||||
color: record.color,
|
||||
weight: decimalText(record.weight),
|
||||
length: decimalText(record.length),
|
||||
width: decimalText(record.width),
|
||||
height: decimalText(record.height),
|
||||
volume: decimalText(record.volume),
|
||||
packType: record.packType,
|
||||
productTag: record.productTag,
|
||||
installDocId: record.installDocId,
|
||||
hasDrawing: record.hasDrawing,
|
||||
hasVideo: record.hasVideo,
|
||||
spec: record.spec,
|
||||
brand: record.brand,
|
||||
orderType: record.orderType,
|
||||
inOutWarehouse: record.inOutWarehouse,
|
||||
warehouseType: warehouseTypes?.get(normalizeWarehouseName(record.inOutWarehouse)) ?? '',
|
||||
warehouseHead: warehouseHeads?.get(normalizeWarehouseName(record.inOutWarehouse)) ?? '',
|
||||
storageType: storageTypeLabel(
|
||||
warehouseStorageTypes?.get(normalizeWarehouseName(record.inOutWarehouse)),
|
||||
),
|
||||
isSeasonal: record.isSeasonal,
|
||||
replaceCount: record.replaceCount,
|
||||
supplier: record.supplierName,
|
||||
supplierType: supplierProfile?.supplierType ?? '',
|
||||
supplierStatus: supplierStatusLabel(supplierProfile?.supplierStatusCode),
|
||||
purchaser: supplierProfile?.purchaser || record.purchaseOwner,
|
||||
settleType: supplierProfile?.settlementMethod ?? '',
|
||||
boardProvider: supplierProfile?.boardProvider ?? '',
|
||||
penaltyStatus: supplierProfile?.penaltyStatus ?? '',
|
||||
moq: stockProfile?.minimum || record.minimumOrderQuantity,
|
||||
firstLeadTime: stockProfile?.produceCycle ?? '',
|
||||
palletSpec: stockProfile?.trayParameter ?? '',
|
||||
dailySales: exactBarcodeStockProfile?.purchaseSale ?? '',
|
||||
sales3d: exactBarcodeStockProfile?.threeAvgSale ?? '',
|
||||
sales7d: exactBarcodeStockProfile?.sevenAvgSale ?? '',
|
||||
sales15d: exactBarcodeStockProfile?.fifteenAvgSale ?? '',
|
||||
} satisfies SupplyChainProductArchiveRow
|
||||
}
|
||||
import {
|
||||
mapProductArchiveRow,
|
||||
normalizeArchiveIdentity,
|
||||
normalizeSupplierName,
|
||||
normalizeWarehouseName,
|
||||
} from './supply-chain-product-archive.mapper'
|
||||
|
||||
export class SupplyChainProductArchiveService {
|
||||
constructor(
|
||||
@ -147,6 +63,14 @@ export class SupplyChainProductArchiveService {
|
||||
JstWarehouseProfileRepository,
|
||||
'listByNames'
|
||||
> = jstWarehouseProfileRepository,
|
||||
private readonly skuPriceRepository: Pick<
|
||||
JstSkuPriceRepository,
|
||||
'listByBarcodes'
|
||||
> = jstSkuPriceRepository,
|
||||
private readonly catalogCostPriceRepository: Pick<
|
||||
ProductCatalogCostPriceRepository,
|
||||
'listByBarcodes'
|
||||
> = productCatalogCostPriceRepository,
|
||||
) {}
|
||||
|
||||
async listPage(params: {
|
||||
@ -210,14 +134,35 @@ export class SupplyChainProductArchiveService {
|
||||
} catch {
|
||||
// Keep the archive usable when the external warehouse source is temporarily unavailable.
|
||||
}
|
||||
const barcodes = records.map((record) => record.barcode)
|
||||
const [jstSkuPrices, productCatalogCostPrices] = await Promise.all([
|
||||
this.skuPriceRepository
|
||||
.listByBarcodes(barcodes)
|
||||
.catch(() => [] as JstSkuPriceProfile[]),
|
||||
this.catalogCostPriceRepository
|
||||
.listByBarcodes(barcodes)
|
||||
.catch(() => [] as ProductCatalogCostPriceProfile[]),
|
||||
])
|
||||
const jstSkuPriceByBarcode = new Map(
|
||||
jstSkuPrices.map((profile) => [
|
||||
normalizeArchiveIdentity(profile.barcode),
|
||||
profile,
|
||||
]),
|
||||
)
|
||||
const productCatalogCostPriceByBarcode = new Map(
|
||||
productCatalogCostPrices.map((profile) => [
|
||||
normalizeArchiveIdentity(profile.barcode),
|
||||
profile,
|
||||
]),
|
||||
)
|
||||
const stockByBarcode = new Map(
|
||||
stockProfiles
|
||||
.filter((profile) => profile.barcode.trim())
|
||||
.map((profile) => [normalizeStockKey(profile.barcode), profile]),
|
||||
.map((profile) => [normalizeArchiveIdentity(profile.barcode), profile]),
|
||||
)
|
||||
const stockBySku = new Map<string, JstStockMonitorProfile[]>()
|
||||
for (const profile of stockProfiles) {
|
||||
const key = normalizeStockKey(profile.sku)
|
||||
const key = normalizeArchiveIdentity(profile.sku)
|
||||
if (!key) continue
|
||||
const candidates = stockBySku.get(key) ?? []
|
||||
candidates.push(profile)
|
||||
@ -226,18 +171,27 @@ export class SupplyChainProductArchiveService {
|
||||
|
||||
return {
|
||||
rows: records.map((record) =>
|
||||
mapProductArchiveRow(
|
||||
mapProductArchiveRow({
|
||||
record,
|
||||
now,
|
||||
supplierProfiles.get(normalizeSupplierName(record.supplierName)),
|
||||
stockByBarcode.get(normalizeStockKey(record.barcode)) ??
|
||||
(stockBySku.get(normalizeStockKey(record.sku))?.length === 1
|
||||
? stockBySku.get(normalizeStockKey(record.sku))?.[0]
|
||||
supplierProfile: supplierProfiles.get(
|
||||
normalizeSupplierName(record.supplierName),
|
||||
),
|
||||
stockProfile:
|
||||
stockByBarcode.get(normalizeArchiveIdentity(record.barcode)) ??
|
||||
(stockBySku.get(normalizeArchiveIdentity(record.sku))?.length === 1
|
||||
? stockBySku.get(normalizeArchiveIdentity(record.sku))?.[0]
|
||||
: undefined),
|
||||
jstSkuPrice: jstSkuPriceByBarcode.get(
|
||||
normalizeArchiveIdentity(record.barcode),
|
||||
),
|
||||
productCatalogCostPrice: productCatalogCostPriceByBarcode.get(
|
||||
normalizeArchiveIdentity(record.barcode),
|
||||
),
|
||||
warehouseTypes,
|
||||
warehouseStorageTypes,
|
||||
warehouseHeads,
|
||||
),
|
||||
}),
|
||||
),
|
||||
pageInfo: {
|
||||
page,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user