feat: add unit tests for featured listings, neighborhood scores + price history chart

- Add unit tests for FeatureListingHandler (6 tests) and ActivateFeaturedListingHandler (6 tests)
- Add unit tests for NeighborhoodScoreServiceImpl (5 tests) and GetNeighborhoodScoreHandler (2 tests)
- Add PriceHistoryChart component with recharts LineChart for listing detail page
- Wire up price history API client and integrate chart into listing detail view

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-16 18:21:44 +07:00
parent 0dda2bffdb
commit 8e9d021465
7 changed files with 560 additions and 14 deletions

View File

@@ -0,0 +1,51 @@
import { type INeighborhoodScoreService, type NeighborhoodScoreResult } from '../../domain/services/neighborhood-score.service';
import { GetNeighborhoodScoreHandler } from '../queries/get-neighborhood-score/get-neighborhood-score.handler';
import { GetNeighborhoodScoreQuery } from '../queries/get-neighborhood-score/get-neighborhood-score.query';
const sampleScore: NeighborhoodScoreResult = {
district: 'Quận 1',
city: 'Hồ Chí Minh',
educationScore: 8,
healthcareScore: 7,
transportScore: 9,
shoppingScore: 6,
greeneryScore: 5,
safetyScore: 4,
totalScore: 68.5,
poiCounts: { education: 12, healthcare: 5, transport: 10, shopping: 6, greenery: 3, safety: 2 },
calculatedAt: new Date(),
};
describe('GetNeighborhoodScoreHandler', () => {
let handler: GetNeighborhoodScoreHandler;
let mockService: { [K in keyof INeighborhoodScoreService]: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockService = {
getScore: vi.fn(),
calculateAndSave: vi.fn(),
};
handler = new GetNeighborhoodScoreHandler(mockService as any);
});
it('returns cached score when available', async () => {
mockService.getScore.mockResolvedValue(sampleScore);
const result = await handler.execute(new GetNeighborhoodScoreQuery('Quận 1', 'Hồ Chí Minh'));
expect(result).toEqual(sampleScore);
expect(mockService.getScore).toHaveBeenCalledWith('Quận 1', 'Hồ Chí Minh');
expect(mockService.calculateAndSave).not.toHaveBeenCalled();
});
it('calculates and saves score when no cached score exists', async () => {
mockService.getScore.mockResolvedValue(null);
mockService.calculateAndSave.mockResolvedValue(sampleScore);
const result = await handler.execute(new GetNeighborhoodScoreQuery('Quận 2', 'Hồ Chí Minh'));
expect(result).toEqual(sampleScore);
expect(mockService.getScore).toHaveBeenCalledWith('Quận 2', 'Hồ Chí Minh');
expect(mockService.calculateAndSave).toHaveBeenCalledWith('Quận 2', 'Hồ Chí Minh');
});
});

View File

@@ -0,0 +1,132 @@
import { NeighborhoodScoreServiceImpl } from '../services/neighborhood-score.service';
describe('NeighborhoodScoreServiceImpl', () => {
let service: NeighborhoodScoreServiceImpl;
let mockPrisma: {
neighborhoodScore: { findUnique: ReturnType<typeof vi.fn>; upsert: ReturnType<typeof vi.fn> };
pOI: { count: ReturnType<typeof vi.fn> };
};
let mockLogger: { log: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockPrisma = {
neighborhoodScore: {
findUnique: vi.fn(),
upsert: vi.fn(),
},
pOI: { count: vi.fn() },
};
mockLogger = { log: vi.fn() };
service = new NeighborhoodScoreServiceImpl(mockPrisma as any, mockLogger as any);
});
describe('getScore', () => {
it('returns existing score from database', async () => {
const stored = {
district: 'Quận 1',
city: 'Hồ Chí Minh',
educationScore: 8,
healthcareScore: 7,
transportScore: 9,
shoppingScore: 6,
greeneryScore: 5,
safetyScore: 4,
totalScore: 68.5,
poiCounts: { education: 12, healthcare: 5 },
calculatedAt: new Date(),
};
mockPrisma.neighborhoodScore.findUnique.mockResolvedValue(stored);
const result = await service.getScore('Quận 1', 'Hồ Chí Minh');
expect(result).not.toBeNull();
expect(result!.district).toBe('Quận 1');
expect(result!.totalScore).toBe(68.5);
expect(result!.poiCounts).toEqual({ education: 12, healthcare: 5 });
});
it('returns null when no score exists', async () => {
mockPrisma.neighborhoodScore.findUnique.mockResolvedValue(null);
const result = await service.getScore('Quận 99', 'Hồ Chí Minh');
expect(result).toBeNull();
});
});
describe('calculateAndSave', () => {
it('calculates scores from POI counts and upserts', async () => {
// Simulate POI counts: education=15 (max), healthcare=4 (50%), transport=6 (50%),
// shopping=5 (50%), greenery=3 (50%), safety=2 (50%)
const poiCountsByCategory = [15, 4, 6, 5, 3, 2];
let callIndex = 0;
mockPrisma.pOI.count.mockImplementation(() => {
return Promise.resolve(poiCountsByCategory[callIndex++]!);
});
mockPrisma.neighborhoodScore.upsert.mockImplementation(({ create }) => {
return Promise.resolve(create);
});
const result = await service.calculateAndSave('Quận 1', 'Hồ Chí Minh');
// education: 15/15 * 10 = 10 → 10 * 20/10 = 20
// healthcare: 4/8 * 10 = 5 → 5 * 20/10 = 10
// transport: 6/12 * 10 = 5 → 5 * 20/10 = 10
// shopping: 5/10 * 10 = 5 → 5 * 15/10 = 7.5
// greenery: 3/6 * 10 = 5 → 5 * 15/10 = 7.5
// safety: 2/4 * 10 = 5 → 5 * 10/10 = 5
// total = 20 + 10 + 10 + 7.5 + 7.5 + 5 = 60
expect(result.educationScore).toBe(10);
expect(result.healthcareScore).toBe(5);
expect(result.totalScore).toBe(60);
expect(mockPrisma.neighborhoodScore.upsert).toHaveBeenCalledTimes(1);
});
it('caps category scores at 10', async () => {
// All categories have way more POIs than max
mockPrisma.pOI.count.mockResolvedValue(100);
mockPrisma.neighborhoodScore.upsert.mockImplementation(({ create }) => {
return Promise.resolve(create);
});
const result = await service.calculateAndSave('Quận 1', 'Hồ Chí Minh');
// All scores capped at 10 → total = sum of weights = 100
expect(result.educationScore).toBe(10);
expect(result.healthcareScore).toBe(10);
expect(result.transportScore).toBe(10);
expect(result.shoppingScore).toBe(10);
expect(result.greeneryScore).toBe(10);
expect(result.safetyScore).toBe(10);
expect(result.totalScore).toBe(100);
});
it('returns 0 scores when no POIs exist', async () => {
mockPrisma.pOI.count.mockResolvedValue(0);
mockPrisma.neighborhoodScore.upsert.mockImplementation(({ create }) => {
return Promise.resolve(create);
});
const result = await service.calculateAndSave('Quận 1', 'Hồ Chí Minh');
expect(result.educationScore).toBe(0);
expect(result.totalScore).toBe(0);
});
it('logs the calculated score', async () => {
mockPrisma.pOI.count.mockResolvedValue(5);
mockPrisma.neighborhoodScore.upsert.mockImplementation(({ create }) => {
return Promise.resolve(create);
});
await service.calculateAndSave('Quận 1', 'Hồ Chí Minh');
expect(mockLogger.log).toHaveBeenCalledWith(
expect.stringContaining('Quận 1'),
'NeighborhoodScoreService',
);
});
});
});

View File

@@ -0,0 +1,113 @@
import { ActivateFeaturedListingHandler } from '../event-handlers/activate-featured-listing.handler';
describe('ActivateFeaturedListingHandler', () => {
let handler: ActivateFeaturedListingHandler;
let mockPrisma: {
payment: { findUnique: ReturnType<typeof vi.fn> };
listing: { findUnique: ReturnType<typeof vi.fn>; update: ReturnType<typeof vi.fn> };
};
let mockLogger: { log: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockPrisma = {
payment: { findUnique: vi.fn() },
listing: { findUnique: vi.fn(), update: vi.fn() },
};
mockLogger = { log: vi.fn() };
handler = new ActivateFeaturedListingHandler(
mockPrisma as any,
mockLogger as any,
);
});
it('activates featured listing for 7 days on 199000 VND payment', async () => {
mockPrisma.payment.findUnique.mockResolvedValue({
type: 'FEATURED_LISTING',
transactionId: 'listing-1',
amountVND: 199000n,
});
mockPrisma.listing.findUnique.mockResolvedValue({ featuredUntil: null });
mockPrisma.listing.update.mockResolvedValue({});
await handler.handle({ aggregateId: 'pay-1' } as any);
expect(mockPrisma.listing.update).toHaveBeenCalledWith({
where: { id: 'listing-1' },
data: { featuredUntil: expect.any(Date) },
});
const updateCall = mockPrisma.listing.update.mock.calls[0][0];
const featuredUntil = updateCall.data.featuredUntil as Date;
const diffDays = Math.round((featuredUntil.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
expect(diffDays).toBe(7);
});
it('activates featured listing for 3 days on 99000 VND payment', async () => {
mockPrisma.payment.findUnique.mockResolvedValue({
type: 'FEATURED_LISTING',
transactionId: 'listing-1',
amountVND: 99000n,
});
mockPrisma.listing.findUnique.mockResolvedValue({ featuredUntil: null });
mockPrisma.listing.update.mockResolvedValue({});
await handler.handle({ aggregateId: 'pay-1' } as any);
const updateCall = mockPrisma.listing.update.mock.calls[0][0];
const featuredUntil = updateCall.data.featuredUntil as Date;
const diffDays = Math.round((featuredUntil.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
expect(diffDays).toBe(3);
});
it('extends from existing featuredUntil if still in the future', async () => {
const futureDate = new Date(Date.now() + 5 * 24 * 60 * 60 * 1000); // 5 days from now
mockPrisma.payment.findUnique.mockResolvedValue({
type: 'FEATURED_LISTING',
transactionId: 'listing-1',
amountVND: 199000n,
});
mockPrisma.listing.findUnique.mockResolvedValue({ featuredUntil: futureDate });
mockPrisma.listing.update.mockResolvedValue({});
await handler.handle({ aggregateId: 'pay-1' } as any);
const updateCall = mockPrisma.listing.update.mock.calls[0][0];
const featuredUntil = updateCall.data.featuredUntil as Date;
// Should extend from futureDate (5 days out) + 7 days = ~12 days from now
const diffDays = Math.round((featuredUntil.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
expect(diffDays).toBe(12);
});
it('ignores non-FEATURED_LISTING payments', async () => {
mockPrisma.payment.findUnique.mockResolvedValue({
type: 'SUBSCRIPTION',
transactionId: 'listing-1',
amountVND: 199000n,
});
await handler.handle({ aggregateId: 'pay-1' } as any);
expect(mockPrisma.listing.update).not.toHaveBeenCalled();
});
it('ignores payments without transactionId', async () => {
mockPrisma.payment.findUnique.mockResolvedValue({
type: 'FEATURED_LISTING',
transactionId: null,
amountVND: 199000n,
});
await handler.handle({ aggregateId: 'pay-1' } as any);
expect(mockPrisma.listing.update).not.toHaveBeenCalled();
});
it('ignores payments that do not exist', async () => {
mockPrisma.payment.findUnique.mockResolvedValue(null);
await handler.handle({ aggregateId: 'pay-1' } as any);
expect(mockPrisma.listing.update).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,128 @@
import { ListingEntity } from '@modules/listings/domain/entities/listing.entity';
import { type IListingRepository } from '@modules/listings/domain/repositories/listing.repository';
import { Price } from '@modules/listings/domain/value-objects/price.vo';
import { FeatureListingCommand } from '../commands/feature-listing/feature-listing.command';
import { FeatureListingHandler } from '../commands/feature-listing/feature-listing.handler';
function createListing(
id = 'listing-1',
sellerId = 'seller-1',
agentId: string | null = null,
status: 'DRAFT' | 'PENDING_REVIEW' | 'ACTIVE' = 'ACTIVE',
): ListingEntity {
const price = Price.create(2_000_000_000n).unwrap();
const listing = ListingEntity.createNew(id, 'prop-1', sellerId, 'SALE', price, 80, agentId ?? undefined);
if (status === 'PENDING_REVIEW' || status === 'ACTIVE') listing.submitForReview();
if (status === 'ACTIVE') listing.approve();
listing.clearDomainEvents();
return listing;
}
describe('FeatureListingHandler', () => {
let handler: FeatureListingHandler;
let mockListingRepo: Pick<IListingRepository, 'findById'>;
let mockCommandBus: { execute: ReturnType<typeof vi.fn> };
let mockLogger: { log: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockListingRepo = { findById: vi.fn() };
mockCommandBus = {
execute: vi.fn().mockResolvedValue({
paymentId: 'pay-1',
paymentUrl: 'https://pay.example.com/checkout',
providerTxId: 'tx-1',
}),
};
mockLogger = { log: vi.fn(), error: vi.fn() };
handler = new FeatureListingHandler(
mockListingRepo as any,
mockCommandBus as any,
mockLogger as any,
);
});
it('creates payment for a valid feature request', async () => {
const listing = createListing('listing-1', 'seller-1', null, 'ACTIVE');
(mockListingRepo.findById as ReturnType<typeof vi.fn>).mockResolvedValue(listing);
const command = new FeatureListingCommand(
'listing-1', 'seller-1', '7_days', 'VNPAY',
'https://goodgo.vn/callback', '127.0.0.1',
);
const result = await handler.execute(command);
expect(result.paymentId).toBe('pay-1');
expect(result.paymentUrl).toBe('https://pay.example.com/checkout');
expect(result.package_).toBe('7_days');
expect(result.priceVND).toBe('199000');
expect(mockCommandBus.execute).toHaveBeenCalledTimes(1);
});
it('allows the assigned agent to feature the listing', async () => {
const listing = createListing('listing-1', 'seller-1', 'agent-1', 'ACTIVE');
(mockListingRepo.findById as ReturnType<typeof vi.fn>).mockResolvedValue(listing);
const command = new FeatureListingCommand(
'listing-1', 'agent-1', '3_days', 'MOMO',
'https://goodgo.vn/callback', '127.0.0.1',
);
const result = await handler.execute(command);
expect(result.paymentId).toBe('pay-1');
expect(result.priceVND).toBe('99000');
});
it('rejects feature request from unauthorized user', async () => {
const listing = createListing('listing-1', 'seller-1', null, 'ACTIVE');
(mockListingRepo.findById as ReturnType<typeof vi.fn>).mockResolvedValue(listing);
const command = new FeatureListingCommand(
'listing-1', 'stranger', '7_days', 'VNPAY',
'https://goodgo.vn/callback', '127.0.0.1',
);
await expect(handler.execute(command)).rejects.toThrow(/người bán|môi giới/);
});
it('rejects feature request for non-ACTIVE listing', async () => {
const listing = createListing('listing-1', 'seller-1', null, 'DRAFT');
(mockListingRepo.findById as ReturnType<typeof vi.fn>).mockResolvedValue(listing);
const command = new FeatureListingCommand(
'listing-1', 'seller-1', '7_days', 'VNPAY',
'https://goodgo.vn/callback', '127.0.0.1',
);
await expect(handler.execute(command)).rejects.toThrow(/hoạt động/);
});
it('throws NotFoundException for non-existent listing', async () => {
(mockListingRepo.findById as ReturnType<typeof vi.fn>).mockResolvedValue(null);
const command = new FeatureListingCommand(
'nonexistent', 'seller-1', '7_days', 'VNPAY',
'https://goodgo.vn/callback', '127.0.0.1',
);
await expect(handler.execute(command)).rejects.toThrow('Listing');
});
it('uses correct pricing for each package', async () => {
const listing = createListing('listing-1', 'seller-1', null, 'ACTIVE');
(mockListingRepo.findById as ReturnType<typeof vi.fn>).mockResolvedValue(listing);
for (const [pkg, expectedPrice] of [
['3_days', '99000'],
['7_days', '199000'],
['30_days', '499000'],
] as const) {
const command = new FeatureListingCommand(
'listing-1', 'seller-1', pkg, 'VNPAY',
'https://goodgo.vn/callback', '127.0.0.1',
);
const result = await handler.execute(command);
expect(result.priceVND).toBe(expectedPrice);
}
});
});