Files
psp_api/src/inventories/inventories.service.ts
T

73 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@nestjs/common'
import { ShortEntity } from '../common/interfaces/response-models'
import { ResponseMapper } from '../common/response/response-mapper'
import { PrismaService } from '../prisma/prisma.service'
@Injectable()
export class InventoriesService {
constructor(private prisma: PrismaService) {}
async create(data: any) {
const item = await this.prisma.inventory.create({ data })
return ResponseMapper.create(item)
}
async findAll() {
const items = await this.prisma.inventory.findMany({
include: { productCharges: { include: { product: true } } },
})
const mapped = items.map(i => {
const productsMap: Record<number, ShortEntity> = {}
for (const pc of i.productCharges ?? []) {
if (pc.product) {
productsMap[pc.product.id] = { id: pc.product.id, name: pc.product.name }
}
}
const groupedProducts = Object.values(productsMap)
const { productCharges, ...rest } = i as any
return { ...rest, groupedProducts }
})
return ResponseMapper.list(mapped)
}
async findOne(id: number) {
const item = await this.prisma.inventory.findUnique({
where: { id },
include: { productCharges: { include: { product: true } } },
})
if (!item) return null
const productsMap: Record<number, { id: number; name: string; count: number }> = {}
for (const pc of item.productCharges ?? []) {
const pid = pc.productId
const pname = pc.product?.name ?? `#${pid}`
if (!productsMap[pid]) productsMap[pid] = { id: pid, name: pname, count: 0 }
productsMap[pid].count += Number(pc.count)
}
const productsWithCount = Object.values(productsMap)
const groupedProducts: ShortEntity[] = productsWithCount.map(p => ({
id: p.id,
name: p.name,
}))
const { productCharges, ...rest } = item as any
const itemWithCounts = {
...rest,
products: productsWithCount,
groupedProducts,
}
return ResponseMapper.single(itemWithCounts)
}
async update(id: number, data: any) {
const item = await this.prisma.inventory.update({ where: { id }, data })
return ResponseMapper.update(item)
}
async remove(id: number) {
const item = await this.prisma.inventory.delete({ where: { id } })
return ResponseMapper.single(item)
}
}