-
Notifications
You must be signed in to change notification settings - Fork 0
feat(store): 인기 매장 리스트 API (popularStores·실시간 랭킹 집계) #145
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| /** | ||
| * 인기 매장 랭킹 점수 파라미터. | ||
| * | ||
| * 점수 = w_order·ln(1+최근주문수) + w_wishlist·ln(1+찜수) + w_rating·베이지안평점 | ||
| * 비즈니스 KPI가 확정되면 이 상수를 교체한다(추천 기본값으로 운영). | ||
| */ | ||
| export const RANKING_WEIGHTS = { | ||
| order: 1.0, | ||
| wishlist: 0.5, | ||
| rating: 0.4, | ||
| } as const; | ||
|
|
||
| /** 베이지안 평점 신뢰 임계 리뷰수(prior 가중). 리뷰가 적은 신규 매장 콜드스타트 보정. */ | ||
| export const RANKING_BAYESIAN_M = 5; | ||
|
|
||
| /** 최근 주문 집계 기간(일). */ | ||
| export const RANKING_RECENT_ORDER_DAYS = 30; | ||
|
|
||
| /** 인기 점수 가중에 포함되는 유효 주문 상태. */ | ||
| export const RANKING_VALID_ORDER_STATUSES = [ | ||
| 'CONFIRMED', | ||
| 'MADE', | ||
| 'PICKED_UP', | ||
| ] as const; | ||
|
|
||
| /** 전체 리뷰가 전무할 때 베이지안 prior로 사용할 기본 평점. */ | ||
| export const DEFAULT_GLOBAL_RATING_PRIOR = 4.0; | ||
|
|
||
| /** popularStores 기본 페이지 크기. */ | ||
| export const DEFAULT_POPULAR_STORES_LIMIT = 20; | ||
|
|
||
| /** 매장 카드에 노출할 대표 케이크 이미지 최대 장수. */ | ||
| export const POPULAR_STORE_CAKE_IMAGE_LIMIT = 4; |
43 changes: 43 additions & 0 deletions
43
src/features/store/dto/inputs/popular-stores.input.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import 'reflect-metadata'; | ||
|
|
||
| import { plainToInstance } from 'class-transformer'; | ||
| import { validate } from 'class-validator'; | ||
|
|
||
| import { PopularStoresInput } from '@/features/store/dto/inputs/popular-stores.input'; | ||
|
|
||
| function build(plain: object): PopularStoresInput { | ||
| return plainToInstance(PopularStoresInput, plain); | ||
| } | ||
|
|
||
| describe('PopularStoresInput', () => { | ||
| it('빈 입력 통과 (모두 optional)', async () => { | ||
| expect(await validate(build({}))).toHaveLength(0); | ||
| }); | ||
|
|
||
| it('regionIds 문자열 배열 + offset/limit 통과', async () => { | ||
| const errors = await validate( | ||
| build({ regionIds: ['1', '2'], offset: 0, limit: 20 }), | ||
| ); | ||
| expect(errors).toHaveLength(0); | ||
| }); | ||
|
|
||
| it('regionIds 가 배열이 아니면 거절', async () => { | ||
| const errors = await validate(build({ regionIds: '1' })); | ||
| expect(errors[0].property).toBe('regionIds'); | ||
| }); | ||
|
|
||
| it('regionIds 원소가 문자열이 아니면 거절', async () => { | ||
| const errors = await validate(build({ regionIds: [1, 2] })); | ||
| expect(errors[0].property).toBe('regionIds'); | ||
| }); | ||
|
|
||
| it('offset 음수 거절', async () => { | ||
| const errors = await validate(build({ offset: -1 })); | ||
| expect(errors[0].property).toBe('offset'); | ||
| }); | ||
|
|
||
| it('limit 하한(0)·상한(51) 거절', async () => { | ||
| expect((await validate(build({ limit: 0 })))[0].property).toBe('limit'); | ||
| expect((await validate(build({ limit: 51 })))[0].property).toBe('limit'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { | ||
| IsArray, | ||
| IsInt, | ||
| IsOptional, | ||
| IsString, | ||
| Max, | ||
| Min, | ||
| } from 'class-validator'; | ||
|
|
||
| export class PopularStoresInput { | ||
| @IsOptional() | ||
| @IsArray() | ||
| @IsString({ each: true }) | ||
| regionIds?: string[]; | ||
|
|
||
| @IsOptional() | ||
| @IsInt() | ||
| @Min(0) | ||
| offset?: number; | ||
|
|
||
| @IsOptional() | ||
| @IsInt() | ||
| @Min(1) | ||
| @Max(50) | ||
| limit?: number; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| // cross-feature 공개 API. 단일 구현 repo라 토큰/인터페이스 없이 구체 클래스로 주입(의도적). | ||
| export { StoreModule } from '@/features/store/store.module'; | ||
| export { StoreRepository } from '@/features/store/repositories/store.repository'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| import { Injectable } from '@nestjs/common'; | ||
|
|
||
| import { | ||
| POPULAR_STORE_CAKE_IMAGE_LIMIT, | ||
| RANKING_VALID_ORDER_STATUSES, | ||
| } from '@/features/store/constants/store-ranking.constants'; | ||
| import { PrismaService } from '@/prisma'; | ||
|
|
||
| export interface StoreCandidateRow { | ||
| id: bigint; | ||
| store_name: string; | ||
| address_city: string | null; | ||
| address_neighborhood: string | null; | ||
| region: { name: string } | null; | ||
| } | ||
|
|
||
| export interface StoreReviewStat { | ||
| average: number; | ||
| count: number; | ||
| } | ||
|
|
||
| @Injectable() | ||
| export class StoreRepository { | ||
| constructor(private readonly prisma: PrismaService) {} | ||
|
|
||
| /** 인기 매장 랭킹 후보. 활성 매장만, 지역 필터(2차 시군구 다중) 적용. */ | ||
| async findActiveStoresForRanking( | ||
| regionIds?: bigint[], | ||
| ): Promise<StoreCandidateRow[]> { | ||
| return this.prisma.store.findMany({ | ||
| where: { | ||
| is_active: true, | ||
| deleted_at: null, | ||
| ...(regionIds && regionIds.length > 0 | ||
| ? { region_id: { in: regionIds } } | ||
| : {}), | ||
| }, | ||
| select: { | ||
| id: true, | ||
| store_name: true, | ||
| address_city: true, | ||
| address_neighborhood: true, | ||
| region: { select: { name: true } }, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| /** 매장별 활성 찜 수. */ | ||
| async aggregateWishlistCounts( | ||
| storeIds: bigint[], | ||
| ): Promise<Map<bigint, number>> { | ||
| if (storeIds.length === 0) return new Map(); | ||
| const rows = await this.prisma.storeWishlistItem.groupBy({ | ||
| by: ['store_id'], | ||
| where: { store_id: { in: storeIds }, deleted_at: null }, | ||
| _count: { _all: true }, | ||
| }); | ||
| return new Map(rows.map((r) => [r.store_id, r._count._all])); | ||
| } | ||
|
|
||
| /** 매장별 평균 평점·리뷰 수. */ | ||
| async aggregateReviewStats( | ||
| storeIds: bigint[], | ||
| ): Promise<Map<bigint, StoreReviewStat>> { | ||
| if (storeIds.length === 0) return new Map(); | ||
| const rows = await this.prisma.review.groupBy({ | ||
| by: ['store_id'], | ||
| where: { store_id: { in: storeIds }, deleted_at: null }, | ||
| _avg: { rating: true }, | ||
| _count: { _all: true }, | ||
| }); | ||
| return new Map( | ||
| rows.map((r) => [ | ||
| r.store_id, | ||
| { | ||
| average: r._avg.rating !== null ? Number(r._avg.rating) : 0, | ||
| count: r._count._all, | ||
| }, | ||
| ]), | ||
| ); | ||
| } | ||
|
|
||
| /** 매장별 최근 N일 유효 주문(아이템) 수. */ | ||
| async aggregateRecentOrderCounts( | ||
| storeIds: bigint[], | ||
| since: Date, | ||
| ): Promise<Map<bigint, number>> { | ||
| if (storeIds.length === 0) return new Map(); | ||
| const rows = await this.prisma.orderItem.groupBy({ | ||
| by: ['store_id'], | ||
| where: { | ||
| store_id: { in: storeIds }, | ||
| deleted_at: null, | ||
| order: { | ||
| status: { in: [...RANKING_VALID_ORDER_STATUSES] }, | ||
| created_at: { gte: since }, | ||
| // soft-delete extension은 nested relation filter에 deleted_at을 주입하지 | ||
| // 않으므로(=root read만 보정), 삭제된 주문이 랭킹을 부풀리지 않도록 명시한다. | ||
| deleted_at: null, | ||
| }, | ||
| }, | ||
| _count: { _all: true }, | ||
| }); | ||
| return new Map(rows.map((r) => [r.store_id, r._count._all])); | ||
| } | ||
|
|
||
| /** 전체 활성 리뷰 평균 평점(베이지안 prior). 리뷰가 없으면 null. */ | ||
| async globalReviewAverage(): Promise<number | null> { | ||
| const agg = await this.prisma.review.aggregate({ | ||
| where: { deleted_at: null }, | ||
| _avg: { rating: true }, | ||
| }); | ||
| return agg._avg.rating !== null ? Number(agg._avg.rating) : null; | ||
| } | ||
|
|
||
| /** 페이지 매장들의 대표 케이크 이미지(매장당 최대 N장, 활성 상품 1장씩). */ | ||
| async findStoreCakeImages( | ||
| storeIds: bigint[], | ||
| ): Promise<Map<bigint, string[]>> { | ||
| if (storeIds.length === 0) return new Map(); | ||
|
|
||
| // 매장당 이미지 보유 활성 상품을 최대 N개만 조회한다. 전체 상품을 materialize한 | ||
| // 뒤 JS에서 자르면 상품이 많은 매장에서 불필요한 row 스캔이 발생하므로, | ||
| // 쿼리 단계에서 take로 제한한다(페이지 크기만큼의 병렬 조회). | ||
| const entries = await Promise.all( | ||
| storeIds.map(async (storeId) => { | ||
| const products = await this.prisma.product.findMany({ | ||
| where: { | ||
| store_id: storeId, | ||
| is_active: true, | ||
| deleted_at: null, | ||
| images: { some: { deleted_at: null } }, | ||
| }, | ||
| orderBy: { id: 'desc' }, | ||
| take: POPULAR_STORE_CAKE_IMAGE_LIMIT, | ||
| select: { | ||
| images: { | ||
| where: { deleted_at: null }, | ||
| orderBy: { sort_order: 'asc' }, | ||
| take: 1, | ||
| select: { image_url: true }, | ||
| }, | ||
| }, | ||
| }); | ||
| const urls = products | ||
| .map((product) => product.images[0]?.image_url) | ||
| .filter((url): url is string => Boolean(url)); | ||
| return [storeId, urls] as const; | ||
| }), | ||
| ); | ||
|
|
||
| return new Map(entries); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import type { PrismaClient } from '@prisma/client'; | ||
|
|
||
| import { StoreRepository } from '@/features/store/repositories/store.repository'; | ||
| import { StoreQueryResolver } from '@/features/store/resolvers/store-query.resolver'; | ||
| import { StoreListingService } from '@/features/store/services/store-listing.service'; | ||
| import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; | ||
| import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; | ||
| import { createRegion, createStore } from '@/test/factories'; | ||
| import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; | ||
|
|
||
| /** | ||
| * Resolver ↔ Service ↔ Repository ↔ DB 통합 경로 검증. | ||
| * 분기/집계 세부 검증은 service.spec.ts에서 담당. | ||
| */ | ||
| describe('Store Query Resolver (real DB)', () => { | ||
| let resolver: StoreQueryResolver; | ||
| let prisma: PrismaClient; | ||
|
|
||
| beforeAll(async () => { | ||
| const { module, prisma: p } = await createTestingModuleWithRealDb({ | ||
| providers: [StoreQueryResolver, StoreListingService, StoreRepository], | ||
| }); | ||
| resolver = module.get(StoreQueryResolver); | ||
| prisma = p; | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await closeTruncateConnection(); | ||
| await disconnectTestPrismaClient(); | ||
| }); | ||
|
|
||
| beforeEach(async () => { | ||
| await truncateAll(); | ||
| }); | ||
|
|
||
| it('popularStores: 서비스에 위임해 커넥션을 반환한다', async () => { | ||
| await createStore(prisma, { store_name: '리졸버매장' }); | ||
|
|
||
| const result = await resolver.popularStores(); | ||
|
|
||
| expect(result.totalCount).toBe(1); | ||
| expect(result.items[0].storeName).toBe('리졸버매장'); | ||
| expect(result.rankedAt).toBeInstanceOf(Date); | ||
| }); | ||
|
|
||
| it('popularStores: regionIds 필터를 위임한다', async () => { | ||
| const region = await createRegion(prisma, { level: 2, slug: 'sgg-res' }); | ||
| const target = await createStore(prisma, { region_id: region.id }); | ||
| await createStore(prisma); // region 없는 매장 | ||
|
|
||
| const result = await resolver.popularStores({ | ||
| regionIds: [region.id.toString()], | ||
| }); | ||
|
|
||
| expect(result.items).toHaveLength(1); | ||
| expect(result.items[0].id).toBe(target.id.toString()); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { Args, Query, Resolver } from '@nestjs/graphql'; | ||
|
|
||
| import { PopularStoresInput } from '@/features/store/dto/inputs/popular-stores.input'; | ||
| import { StoreListingService } from '@/features/store/services/store-listing.service'; | ||
| import type { PopularStoreConnection } from '@/features/store/types/store-output.type'; | ||
|
|
||
| /** | ||
| * 매장 조회 resolver. 인기 매장 리스트는 비로그인도 접근 가능한 public query. | ||
| */ | ||
| @Resolver('Query') | ||
| export class StoreQueryResolver { | ||
| constructor(private readonly storeListingService: StoreListingService) {} | ||
|
|
||
| @Query('popularStores') | ||
| popularStores( | ||
| @Args('input', { nullable: true }) input?: PopularStoresInput, | ||
| ): Promise<PopularStoreConnection> { | ||
| return this.storeListingService.popularStores(input); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an order row has been soft-deleted but its order items remain, this groupBy still counts those items as recent valid orders because the nested
orderpredicate only checks status andcreated_at; the soft-delete extension insrc/prisma/soft-delete.middleware.tsonly amends the rootOrderItemread, not nested relation filters. That can let removed/test orders continue boosting a store's popularity, so adddeleted_at: nullinside theorderfilter.Useful? React with 👍 / 👎.