import { describe, it, expect, vi, beforeEach } from 'vitest'; import { PricesService } from './prices.service.js'; import { NotFoundError } from '../../common/errors.js'; describe('PricesService', () => { let service: PricesService; const mockPricesRepo = { create: vi.fn(), createMany: vi.fn(), findByProduct: vi.fn(), compareStores: vi.fn(), getAnalytics: vi.fn(), getLatestForProduct: vi.fn(), }; const mockProductsRepo = { findById: vi.fn(), findByIds: vi.fn(), }; const mockStoresRepo = { findById: vi.fn(), }; beforeEach(() => { vi.clearAllMocks(); service = new PricesService({ pricesRepository: mockPricesRepo as any, productsRepository: mockProductsRepo as any, storesRepository: mockStoresRepo as any, }); }); describe('recordPrice', () => { it('calculates unit price and persists data on existing linkages', async () => { mockProductsRepo.findById.mockResolvedValue({ name: 'Milk' }); mockStoresRepo.findById.mockResolvedValue({ name: 'Target' }); mockPricesRepo.create.mockResolvedValue({ _id: 'rec1' }); const result = await service.recordPrice( { productId: 'p1', storeId: 's1', price: 4, quantity: 2, unit: 'ml' as any, currency: 'USD' }, 'hh1', 'u1' ); expect(mockPricesRepo.create).toHaveBeenCalledWith( expect.objectContaining({ productName: 'Milk', storeName: 'Target', pricePerUnit: 2, }) ); expect(result._id).toBe('rec1'); }); it('throws NotFound if product is invalid', async () => { mockProductsRepo.findById.mockResolvedValue(null); await expect( service.recordPrice( { productId: 'p1', storeId: 's1', price: 1, quantity: 1, unit: 'g' as any, currency: 'USD' }, 'hh1', 'u1' ) ).rejects.toThrow(NotFoundError); }); }); describe('recordBulkPrices', () => { it('ingests multiple mappings throwing notFound if one catalog match fails', async () => { mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' }); mockProductsRepo.findByIds.mockResolvedValue([{ _id: 'p1', name: 'Bread' }]); mockPricesRepo.createMany.mockImplementation(args => args); const result = await service.recordBulkPrices( { storeId: 's1', items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }], }, 'hh1', 'u1' ); expect(mockPricesRepo.createMany).toHaveBeenCalled(); expect(result).toHaveLength(1); expect(result[0].productName).toBe('Bread'); }); }); describe('estimatePrice', () => { it('falls back to generic if requested store history is missing', async () => { // First call (restricted to storeId): empty mockPricesRepo.getLatestForProduct.mockResolvedValueOnce(null); // Second call (generic): matches mockPricesRepo.getLatestForProduct.mockResolvedValueOnce({ price: 12 }); const val = await service.estimatePrice('prod1', 'hh1', 'storeA'); expect(mockPricesRepo.getLatestForProduct).toHaveBeenCalledTimes(2); expect(val).toBe(12); }); }); });