Files
flyer-crawler.projectium.com/src/services/db/admin.db.test.ts
Torben Sorensen 6f74de3f88
All checks were successful
Deploy to Web Server flyer-crawler.projectium.com / deploy (push) Successful in 4m41s
more db unit tests - best o luck !
2025-12-06 21:48:27 -08:00

212 lines
8.6 KiB
TypeScript

// src/services/db/admin.db.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { mockPoolInstance } from '../../tests/setup/tests-setup-unit';
import {
getSuggestedCorrections,
approveCorrection,
rejectCorrection,
updateSuggestedCorrection,
getApplicationStats,
getDailyStatsForLast30Days,
logActivity,
incrementFailedLoginAttempts,
updateBrandLogo,
getMostFrequentSaleItems,
updateRecipeCommentStatus,
getUnmatchedFlyerItems,
updateRecipeStatus,
updateReceiptStatus,
} from './admin.db';
import type { SuggestedCorrection } from '../../types';
// Mock the logger to prevent console output during tests
vi.mock('../logger', () => ({
logger: {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
},
}));
describe('Admin DB Service', () => {
beforeEach(() => {
// Reset the global mock's call history before each test.
vi.clearAllMocks();
});
describe('getSuggestedCorrections', () => {
it('should execute the correct query and return corrections', async () => {
const mockCorrections: SuggestedCorrection[] = [
{ suggested_correction_id: 1, flyer_item_id: 101, user_id: 'user-1', correction_type: 'WRONG_PRICE', suggested_value: '250', status: 'pending', created_at: new Date().toISOString() },
];
mockPoolInstance.query.mockResolvedValue({ rows: mockCorrections });
const result = await getSuggestedCorrections();
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining("FROM public.suggested_corrections sc"));
expect(result).toEqual(mockCorrections);
});
});
describe('approveCorrection', () => {
it('should call the approve_correction database function', async () => {
mockPoolInstance.query.mockResolvedValue({ rows: [] }); // Mock the function call
await approveCorrection(123);
expect(mockPoolInstance.query).toHaveBeenCalledWith('SELECT public.approve_correction($1)', [123]);
});
});
describe('rejectCorrection', () => {
it('should update the correction status to rejected', async () => {
mockPoolInstance.query.mockResolvedValue({ rowCount: 1 });
await rejectCorrection(123);
expect(mockPoolInstance.query).toHaveBeenCalledWith(
expect.stringContaining("UPDATE public.suggested_corrections SET status = 'rejected'"),
[123]
);
});
});
describe('updateSuggestedCorrection', () => {
it('should update the suggested value and return the updated correction', async () => {
const mockCorrection: SuggestedCorrection = { suggested_correction_id: 1, flyer_item_id: 101, user_id: 'user-1', correction_type: 'WRONG_PRICE', suggested_value: '300', status: 'pending', created_at: new Date().toISOString() };
mockPoolInstance.query.mockResolvedValue({ rows: [mockCorrection], rowCount: 1 });
const result = await updateSuggestedCorrection(1, '300');
expect(mockPoolInstance.query).toHaveBeenCalledWith(
expect.stringContaining("UPDATE public.suggested_corrections SET suggested_value = $1"),
['300', 1]
);
expect(result).toEqual(mockCorrection);
});
});
describe('getApplicationStats', () => {
it('should execute 5 parallel count queries and return the aggregated stats', async () => {
// Mock responses for each of the 5 parallel queries
mockPoolInstance.query
.mockResolvedValueOnce({ rows: [{ count: '10' }] }) // flyerCount
.mockResolvedValueOnce({ rows: [{ count: '20' }] }) // userCount
.mockResolvedValueOnce({ rows: [{ count: '300' }] }) // flyerItemCount
.mockResolvedValueOnce({ rows: [{ count: '5' }] }) // storeCount
.mockResolvedValueOnce({ rows: [{ count: '2' }] }); // pendingCorrectionCount
const stats = await getApplicationStats();
expect(mockPoolInstance.query).toHaveBeenCalledTimes(5);
expect(stats).toEqual({
flyerCount: 10,
userCount: 20,
flyerItemCount: 300,
storeCount: 5,
pendingCorrectionCount: 2,
});
});
it('should throw an error if one of the parallel queries fails', async () => {
// Mock one query to succeed and another to fail
mockPoolInstance.query
.mockResolvedValueOnce({ rows: [{ count: '10' }] })
.mockRejectedValueOnce(new Error('DB Read Error'));
// The Promise.all should reject, and the function should re-throw the error
await expect(getApplicationStats()).rejects.toThrow('DB Read Error');
});
});
describe('getDailyStatsForLast30Days', () => {
it('should execute the correct query to get daily stats', async () => {
const mockStats = [{ date: '2023-01-01', new_users: 5, new_flyers: 2 }];
mockPoolInstance.query.mockResolvedValue({ rows: mockStats });
const result = await getDailyStatsForLast30Days();
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining("WITH date_series AS"));
expect(result).toEqual(mockStats);
});
});
describe('logActivity', () => {
it('should insert a new activity log entry', async () => {
mockPoolInstance.query.mockResolvedValue({ rows: [] });
const logData = { userId: 'user-123', action: 'test_action', displayText: 'Test activity' };
await logActivity(logData);
expect(mockPoolInstance.query).toHaveBeenCalledWith(
expect.stringContaining("INSERT INTO public.activity_log"),
[logData.userId, logData.action, logData.displayText, null, null]
);
});
});
describe('getMostFrequentSaleItems', () => {
it('should call the correct database function', async () => {
mockPoolInstance.query.mockResolvedValue({ rows: [] });
await getMostFrequentSaleItems(30, 10);
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining('FROM public.flyer_items fi'), [30, 10]);
});
});
describe('updateRecipeCommentStatus', () => {
it('should update the comment status and return the updated comment', async () => {
const mockComment = { comment_id: 1, status: 'hidden' };
mockPoolInstance.query.mockResolvedValue({ rows: [mockComment], rowCount: 1 });
const result = await updateRecipeCommentStatus(1, 'hidden');
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining('UPDATE public.recipe_comments'), ['hidden', 1]);
expect(result).toEqual(mockComment);
});
});
describe('getUnmatchedFlyerItems', () => {
it('should execute the correct query to get unmatched items', async () => {
mockPoolInstance.query.mockResolvedValue({ rows: [] });
await getUnmatchedFlyerItems();
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining('FROM public.unmatched_flyer_items ufi'));
});
});
describe('updateRecipeStatus', () => {
it('should update the recipe status and return the updated recipe', async () => {
const mockRecipe = { recipe_id: 1, status: 'public' };
mockPoolInstance.query.mockResolvedValue({ rows: [mockRecipe], rowCount: 1 });
const result = await updateRecipeStatus(1, 'public');
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining('UPDATE public.recipes'), ['public', 1]);
expect(result).toEqual(mockRecipe);
});
});
describe('incrementFailedLoginAttempts', () => {
it('should execute an UPDATE query to increment failed attempts', async () => {
mockPoolInstance.query.mockResolvedValue({ rows: [] });
await incrementFailedLoginAttempts('user-123');
// Fix: Use regex to match query with variable whitespace
expect(mockPoolInstance.query).toHaveBeenCalledWith(
expect.stringMatching(/UPDATE\s+public\.users\s+SET\s+failed_login_attempts\s*=\s*failed_login_attempts\s*\+\s*1/),
['user-123']
);
});
});
describe('updateBrandLogo', () => {
it('should execute an UPDATE query for the brand logo', async () => {
mockPoolInstance.query.mockResolvedValue({ rows: [] });
await updateBrandLogo(1, '/logo.png');
expect(mockPoolInstance.query).toHaveBeenCalledWith('UPDATE public.brands SET logo_url = $1 WHERE brand_id = $2', ['/logo.png', 1]);
});
});
describe('updateReceiptStatus', () => {
it('should update the receipt status and return the updated receipt', async () => {
const mockReceipt = { receipt_id: 1, status: 'completed' };
mockPoolInstance.query.mockResolvedValue({ rows: [mockReceipt], rowCount: 1 });
const result = await updateReceiptStatus(1, 'completed');
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining('UPDATE public.receipts'), ['completed', 1]);
expect(result).toEqual(mockReceipt);
});
});
});