refactor(goods): streamline goods service and controller, remove favorites module

- Removed the PosGoodFavorite module, controller, and service to simplify the codebase.
- Updated goods service to handle cache invalidation directly.
- Refactored goods controller to remove commented-out code and improve clarity.
- Introduced OwnedGoods module for better organization of owned goods functionality.
- Updated DTOs to extend from existing structures for consistency.
- Enhanced cache invalidation logic in goods service and owned goods service.
This commit is contained in:
2026-05-20 20:22:00 +03:30
parent fc27b9d616
commit 1d47fb1a1d
31 changed files with 1166 additions and 345 deletions
+9 -15
View File
@@ -1,25 +1,19 @@
import { Injectable } from '@nestjs/common'
import { PosKeyMaker } from '@/common/utils'
import { RedisService } from '@/redis/redis.service'
import { Injectable } from '@nestjs/common'
@Injectable()
export class PosCacheInvalidationService {
constructor(private readonly redisService: RedisService) {}
async invalidateGoodsListByGuild(guildId: string): Promise<void> {
const client = await this.redisService.getClient()
const keys = await client.keys(`pos:ba:*:guild:${guildId}:goods:list`)
if (keys.length > 0) {
await client.del(keys)
}
}
async invalidateGoodsListByBusinessActivity(
async invalidatePosGoodsList(
guildId: string,
businessActivityId: string,
): Promise<void> {
const client = await this.redisService.getClient()
const keys = await client.keys(`pos:ba:${businessActivityId}:guild:*:goods:list`)
if (keys.length > 0) {
await client.del(keys)
}
this.redisService.delete(PosKeyMaker.goodList(guildId, businessActivityId))
}
async invalidatePosGoodsByGuildPattern(guildId: string): Promise<void> {
this.redisService.deleteByPattern(PosKeyMaker.goodListByGuildPattern(guildId))
}
}
+3 -44
View File
@@ -1,47 +1,6 @@
import { GoodPricingModel } from '@/generated/prisma/enums'
import { ApiProperty, PartialType } from '@nestjs/swagger'
import { IsEnum, IsNumber, IsOptional, IsString } from 'class-validator'
import { CreateGuildGoodDto } from '@/modules/admin/guilds/goods/dto/create-good.dto'
import { PartialType } from '@nestjs/swagger'
export class CreateGoodDto {
@IsString()
@ApiProperty()
name: string
@IsOptional()
@IsString()
@ApiProperty({ required: false })
description?: string
@IsString()
@ApiProperty({ required: true })
sku_id: string
@IsString()
@ApiProperty()
local_sku: string
@IsEnum(GoodPricingModel)
@ApiProperty({ required: true, enum: GoodPricingModel })
pricing_model: GoodPricingModel
@IsOptional()
@IsString()
@ApiProperty({ required: false })
barcode?: string
@IsOptional()
@IsString()
@ApiProperty({ required: false })
category_id?: string
@IsOptional()
@IsNumber()
@ApiProperty({ required: false })
base_sale_price?: number
@IsString()
@ApiProperty({ required: true })
measure_unit_id: string
}
export class CreateGoodDto extends CreateGuildGoodDto {}
export class UpdateGoodDto extends PartialType(CreateGoodDto) {}
@@ -1,5 +1,4 @@
import type { GoodsService } from '../goods.service'
export type GoodsServiceCreateResponseDto = Awaited<ReturnType<GoodsService['create']>>
export type GoodsServiceFindAllResponseDto = Awaited<ReturnType<GoodsService['findAll']>>
export type GoodsServiceFindOneResponseDto = Awaited<ReturnType<GoodsService['findOne']>>
@@ -1,8 +1,8 @@
import { RedisService } from '@/redis/redis.service'
import { Injectable } from '@nestjs/common'
import { ResponseMapper } from '../../../common/response/response-mapper'
import { PrismaService } from '../../../prisma/prisma.service'
import { PosCacheInvalidationService } from '../cache/pos-cache-invalidation.service'
import { ResponseMapper } from '../../../../common/response/response-mapper'
import { PrismaService } from '../../../../prisma/prisma.service'
import { PosCacheInvalidationService } from '../../cache/pos-cache-invalidation.service'
@Injectable()
export class PosGoodFavoriteService {
@@ -45,9 +45,7 @@ export class PosGoodFavoriteService {
},
})
await this.posCacheInvalidationService.invalidateGoodsListByBusinessActivity(
business_id,
)
await this.posCacheInvalidationService.invalidatePosGoodsList(guild_id, business_id)
return ResponseMapper.create(favorite)
}
@@ -79,9 +77,7 @@ export class PosGoodFavoriteService {
},
})
await this.posCacheInvalidationService.invalidateGoodsListByBusinessActivity(
business_id,
)
await this.posCacheInvalidationService.invalidatePosGoodsList(guild_id, business_id)
return ResponseMapper.delete()
}
+2 -2
View File
@@ -21,7 +21,7 @@ export class GoodsController {
}
// @Post()
// create(@Body() data: CreateGoodDto, @PosInfo() { complex_id, guild_id }: IPosPayload) {
// return this.goodsService.create(data, complex_id, guild_id)
// create(@Body() data: CreateGoodDto, @PosInfo('complex_id') complex_id: string) {
// return this.goodsService.create(data, complex_id)
// }
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common'
import { PosGoodFavoriteModule } from '../favorite/favorite.module'
import { PosGoodFavoriteModule } from './favorite/favorite.module'
import { GoodsController } from './goods.controller'
import { GoodsService } from './goods.service'
+124 -139
View File
@@ -1,19 +1,15 @@
import { ResponseMapper } from '@/common/response/response-mapper'
import { RedisKeyMaker } from '@/common/utils/redisKeyMaker'
import { GoodSelect } from '@/generated/prisma/models'
import { PosCacheInvalidationService } from '@/modules/pos/cache/pos-cache-invalidation.service'
import { PrismaService } from '@/prisma/prisma.service'
import { RedisService } from '@/redis/redis.service'
import { Injectable } from '@nestjs/common'
import { ResponseMapper } from '../../../common/response/response-mapper'
import { PrismaService } from '../../../prisma/prisma.service'
import { CreateGoodDto } from './dto/create-good.dto'
import { UpdateGoodDto } from './dto/update-good.dto'
@Injectable()
export class GoodsService {
constructor(
private prisma: PrismaService,
private readonly redisService: RedisService,
private readonly posCacheInvalidationService: PosCacheInvalidationService,
) {}
private readonly listCacheTtlSeconds = 300
@@ -56,44 +52,47 @@ export class GoodsService {
guild_id: string,
consumer_account_id: string,
) {
const cacheKey = RedisKeyMaker.posGoodsList(business_activity_id, guild_id)
const cached = await this.redisService.getJson<unknown[]>(cacheKey)
if (cached) {
return ResponseMapper.list(cached)
}
const goods = await this.prisma.good.findMany({
where: {
OR: [
{
is_default_guild_good: true,
category: {
guild_id,
const cacheKey = RedisKeyMaker.posGoodsList(guild_id, business_activity_id)
try {
const cached = await this.redisService.getJson<unknown[]>(cacheKey)
if (cached) {
return ResponseMapper.list(cached)
}
throw new Error('Cache miss')
} catch (error) {
const goods = await this.prisma.good.findMany({
where: {
OR: [
{
is_default_guild_good: true,
category: {
guild_id,
},
},
{
business_activity_id,
},
],
},
select: {
...this.defaultSelect,
consumer_account_good_favorites: {
where: {
consumer_account_id,
},
},
{
business_activity_id,
},
],
},
select: {
...this.defaultSelect,
consumer_account_good_favorites: {
where: {
consumer_account_id,
},
},
},
})
})
const mappedGoods = goods.map(good => ({
...good,
is_favorite: good.consumer_account_good_favorites.length > 0,
}))
const mappedGoods = goods.map(good => ({
...good,
is_favorite: good.consumer_account_good_favorites.length > 0,
}))
await this.redisService.setJson(cacheKey, mappedGoods, this.listCacheTtlSeconds)
await this.redisService.setJson(cacheKey, mappedGoods, this.listCacheTtlSeconds)
return ResponseMapper.list(mappedGoods)
return ResponseMapper.list(mappedGoods)
}
}
async findOne(good_id: string, business_activity_id: string, guild_id: string) {
@@ -111,113 +110,99 @@ export class GoodsService {
return ResponseMapper.single(good)
}
async create(data: CreateGoodDto, business_activity_id: string) {
const { category_id, sku_id, measure_unit_id, ...rest } = data
// async create(data: CreateGoodDto, business_activity_id: string, guild_id: string) {
// const { category_id, sku_id, measure_unit_id, ...rest } = data
const dataToCreate = {
...rest,
business_activity_id,
connect: {
category: {
id: category_id,
},
},
}
// const dataToCreate = {
// ...rest,
// measure_unit: {
// connect: {
// id: measure_unit_id,
// },
// },
// sku: {
// connect: {
// id: sku_id,
// },
// },
// category: {
// connect: {
// id: category_id,
// },
// },
// business_activity: {
// connect: {
// id: business_activity_id,
// },
// },
// }
const good = await this.prisma.good.create({
data: {
...rest,
measure_unit: {
connect: {
id: measure_unit_id,
},
},
sku: {
connect: {
id: sku_id,
},
},
category: {
connect: {
id: category_id,
},
},
business_activity: {
connect: {
id: business_activity_id,
},
},
},
select: this.defaultSelect,
})
// const good = await this.prisma.good.create({
// data: {
// ...dataToCreate,
// },
// select: this.defaultSelect,
// })
await this.posCacheInvalidationService.invalidateGoodsListByBusinessActivity(
business_activity_id,
)
// await this.posCacheInvalidationService.invalidatePosGoodsList(
// guild_id,
// business_activity_id,
// )
return ResponseMapper.create(good)
}
// return ResponseMapper.create(good)
// }
async update(id: string, data: UpdateGoodDto, business_activity_id: string) {
const { category_id, sku_id, measure_unit_id, ...rest } = data
// async update(
// id: string,
// data: UpdateGoodDto,
// business_activity_id: string,
// guild_id: string,
// ) {
// const { category_id, sku_id, measure_unit_id, ...rest } = data
const good = await this.prisma.good.update({
where: {
id,
business_activity_id,
},
data: {
...rest,
...(measure_unit_id
? {
measure_unit: {
connect: {
id: measure_unit_id,
},
},
}
: {}),
...(sku_id
? {
sku: {
connect: {
id: sku_id,
},
},
}
: {}),
...(category_id
? {
category: {
connect: {
id: category_id,
},
},
}
: {}),
},
select: this.defaultSelect,
})
// const good = await this.prisma.good.update({
// where: {
// id,
// business_activity_id,
// },
// data: {
// ...rest,
// ...(measure_unit_id
// ? {
// measure_unit: {
// connect: {
// id: measure_unit_id,
// },
// },
// }
// : {}),
// ...(sku_id
// ? {
// sku: {
// connect: {
// id: sku_id,
// },
// },
// }
// : {}),
// ...(category_id
// ? {
// category: {
// connect: {
// id: category_id,
// },
// },
// }
// : {}),
// },
// select: this.defaultSelect,
// })
await this.posCacheInvalidationService.invalidateGoodsListByBusinessActivity(
business_activity_id,
)
// await this.posCacheInvalidationService.invalidatePosGoodsList(
// guild_id,
// business_activity_id,
// )
return ResponseMapper.update(good)
}
async delete(id: string, business_activity_id: string) {
await this.prisma.good.delete({
where: {
id,
business_activity_id,
},
})
await this.posCacheInvalidationService.invalidateGoodsListByBusinessActivity(
business_activity_id,
)
return ResponseMapper.delete()
}
// return ResponseMapper.update(good)
// }
}
@@ -0,0 +1,3 @@
import { CreateGuildGoodDto } from '@/modules/admin/guilds/goods/dto/create-good.dto'
export class CreateOwnedGoodsDto extends CreateGuildGoodDto {}
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger'
import { CreateOwnedGoodsDto } from './create-owned-goods.dto'
export class UpdateOwnedGoodsDto extends PartialType(CreateOwnedGoodsDto) {}
@@ -0,0 +1,72 @@
import { PosInfo } from '@/common/decorators/posInfo.decorator'
import type { IPosPayload } from '@/common/models'
import { multerImageOptions } from '@/multer.config'
import {
Body,
Controller,
Get,
Param,
Patch,
Post,
UploadedFile,
UseInterceptors,
} from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { ApiBody, ApiConsumes } from '@nestjs/swagger'
import { CreateOwnedGoodsDto } from './dto/create-owned-goods.dto'
import { UpdateOwnedGoodsDto } from './dto/update-owned-goods.dto'
import { OwnedGoodsService } from './owned-goods.service'
@Controller('pos/owned-goods')
export class OwnedGoodsController {
constructor(private readonly service: OwnedGoodsService) {}
@Get()
findAll(@PosInfo('business_id') business_id: string) {
return this.service.findAll(business_id)
}
@Get(':id')
findOne(@PosInfo('business_id') business_id: string, @Param('id') id: string) {
return this.service.findOne(business_id, id)
}
@Post()
@UseInterceptors(FileInterceptor('image', multerImageOptions))
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
image: { type: 'string', format: 'binary' },
},
},
})
create(
@PosInfo() { business_id, guild_id }: IPosPayload,
@UploadedFile() file: Express.Multer.File,
@Body() dto: CreateOwnedGoodsDto,
) {
return this.service.create(guild_id, business_id, dto, file)
}
@Patch(':id')
@UseInterceptors(FileInterceptor('image', multerImageOptions))
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
image: { type: 'string', format: 'binary' },
},
},
})
update(
@PosInfo() { business_id, guild_id }: IPosPayload,
@Param('id') id: string,
@UploadedFile() file: Express.Multer.File,
@Body() dto: UpdateOwnedGoodsDto,
) {
return this.service.update(guild_id, business_id, id, dto, file)
}
}
@@ -0,0 +1,12 @@
import { UploaderModule } from '@/modules/uploader/uploader.module'
import { PrismaService } from '@/prisma/prisma.service'
import { Module } from '@nestjs/common'
import { OwnedGoodsController } from './owned-goods.controller'
import { OwnedGoodsService } from './owned-goods.service'
@Module({
controllers: [OwnedGoodsController],
providers: [OwnedGoodsService, PrismaService],
imports: [UploaderModule],
})
export class OwnedGoodsModule {}
@@ -0,0 +1,191 @@
import { UploadedFileTypes } from '@/common/enums/enums'
import { ResponseMapper } from '@/common/response/response-mapper'
import { GoodSelect, GoodWhereInput } from '@/generated/prisma/models'
import { UploaderService } from '@/modules/uploader/uploader.service'
import { PrismaService } from '@/prisma/prisma.service'
import { Injectable } from '@nestjs/common'
import { PosCacheInvalidationService } from '../cache/pos-cache-invalidation.service'
import { CreateOwnedGoodsDto } from './dto/create-owned-goods.dto'
import { UpdateOwnedGoodsDto } from './dto/update-owned-goods.dto'
@Injectable()
export class OwnedGoodsService {
constructor(
private readonly prisma: PrismaService,
private readonly uploaderService: UploaderService,
private readonly posCacheInvalidationService: PosCacheInvalidationService,
) {}
private readonly where = (business_activity_id: string): GoodWhereInput => ({
is_default_guild_good: false,
business_activity_id,
})
private readonly select: GoodSelect = {
id: true,
name: true,
pricing_model: true,
image_url: true,
description: true,
sku: {
select: {
id: true,
name: true,
code: true,
},
},
measure_unit: {
select: {
id: true,
name: true,
code: true,
},
},
category: {
select: {
id: true,
name: true,
},
},
}
async findAll(business_activity_id: string) {
const items = await this.prisma.good.findMany({
where: this.where(business_activity_id),
select: this.select,
})
return ResponseMapper.list(items)
}
async findOne(business_activity_id: string, id: string) {
const item = await this.prisma.good.findUnique({
where: { ...(this.where(business_activity_id) as any), id },
select: this.select,
})
return ResponseMapper.single(item)
}
async create(
guild_id: string,
business_activity_id: string,
data: CreateOwnedGoodsDto,
file: Express.Multer.File,
) {
const { category_id, measure_unit_id, sku_id, ...rest } = data
const good = await this.prisma.$transaction(async tx => {
let image_url = ''
if (file) {
const uploadedUrl = await this.uploaderService.uploadFile(
file,
UploadedFileTypes.GOOD,
)
image_url = uploadedUrl || ''
}
return await tx.good.create({
data: {
...rest,
is_default_guild_good: true,
image_url,
sku: {
connect: {
id: sku_id,
},
},
measure_unit: {
connect: {
id: measure_unit_id,
},
},
category: {
connect: {
id: category_id,
},
},
business_activity: {
connect: {
id: business_activity_id,
},
},
},
select: this.select,
})
})
await this.posCacheInvalidationService.invalidatePosGoodsList(
guild_id,
business_activity_id,
)
return ResponseMapper.create(good)
}
async update(
guild_id: string,
business_activity_id: string,
id: string,
data: UpdateOwnedGoodsDto,
file: Express.Multer.File,
) {
const { category_id, measure_unit_id, sku_id, ...rest } = data
const good = await this.prisma.$transaction(async tx => {
let image_url = undefined as string | undefined
if (file) {
const uploadedUrl = await this.uploaderService.uploadFile(
file,
UploadedFileTypes.GOOD,
)
image_url = uploadedUrl
}
const prevImage = await tx.good.findUnique({
where: { id },
select: { image_url: true },
})
if (image_url && prevImage?.image_url) {
this.uploaderService.deleteFile(prevImage.image_url, UploadedFileTypes.GOOD)
}
return await tx.good.update({
where: { ...(this.where(business_activity_id) as any), id },
data: {
...rest,
is_default_guild_good: false,
image_url,
sku: {
connect: {
id: sku_id,
},
},
measure_unit: {
connect: {
id: measure_unit_id,
},
},
category: {
connect: {
id: category_id,
},
},
business_activity: {
connect: {
id: business_activity_id,
},
},
},
select: this.select,
})
})
await this.posCacheInvalidationService.invalidatePosGoodsList(
guild_id,
business_activity_id,
)
return ResponseMapper.create(good)
}
}
+2
View File
@@ -3,6 +3,7 @@ import { JwtService } from '@nestjs/jwt'
import { PosCustomersModule } from './customers/customers.module'
import { PosGoodCategoriesModule } from './good-categories/good-categories.module'
import { PosGoodsModule } from './goods/goods.module'
import { OwnedGoodsModule } from './owned-goods/owned-goods.module'
import { PosController } from './pos.controller'
import { PosMiddleware } from './pos.middleware'
import { PosService } from './pos.service'
@@ -16,6 +17,7 @@ import { PosSalesInvoicesModule } from './sales-invoices/sales-invoices.module'
PosGoodCategoriesModule,
PosGoodsModule,
PosSalesInvoicesModule,
OwnedGoodsModule,
],
})
export class PosModule implements NestModule {