Add user database service and unit tests
All checks were successful
Deploy to Web Server flyer-crawler.projectium.com / deploy (push) Successful in 4m28s

- Implement user database service with functions for user management (create, find, update, delete).
- Add comprehensive unit tests for user database service using Vitest.
- Mock database interactions to ensure isolated testing.
- Create setup files for unit tests to handle database connections and global mocks.
- Introduce error handling for unique constraints and foreign key violations.
- Enhance logging for better traceability during database operations.
This commit is contained in:
2025-12-04 15:30:27 -08:00
parent 4cf587c8f0
commit 80d2b1ffe6
62 changed files with 135 additions and 136 deletions

View File

@@ -0,0 +1,214 @@
// src/services/db/admin.db.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
getSuggestedCorrections,
approveCorrection,
rejectCorrection,
updateSuggestedCorrection,
getApplicationStats,
getDailyStatsForLast30Days,
logActivity,
incrementFailedLoginAttempts,
updateBrandLogo,
getMostFrequentSaleItems,
updateRecipeCommentStatus,
getUnmatchedFlyerItems,
updateRecipeStatus,
updateReceiptStatus,
} from './admin.db';
import { getPool } from './connection.db';
import type { SuggestedCorrection } from '../../types';
// Define test-local mock functions. These will be used to control the mock's behavior.
const mockQuery = vi.fn();
// Mock the entire connection module.
vi.mock('./connection', () => ({
// The mock factory for getPool returns an object that uses our test-local mockQuery.
getPool: () => ({
query: mockQuery,
}),
}));
// 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(() => {
// FIX: Reset mocks
mockQuery.mockReset();
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() },
];
mockQuery.mockResolvedValue({ rows: mockCorrections });
const result = await getSuggestedCorrections();
expect(getPool().query).toHaveBeenCalledWith(expect.stringContaining("FROM public.suggested_corrections sc"));
expect(result).toEqual(mockCorrections);
});
});
describe('approveCorrection', () => {
it('should call the approve_correction database function', async () => {
mockQuery.mockResolvedValue({ rows: [] }); // Mock the function call
await approveCorrection(123);
expect(getPool().query).toHaveBeenCalledWith('SELECT public.approve_correction($1)', [123]);
});
});
describe('rejectCorrection', () => {
it('should update the correction status to rejected', async () => {
mockQuery.mockResolvedValue({ rowCount: 1 });
await rejectCorrection(123);
expect(getPool().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() };
mockQuery.mockResolvedValue({ rows: [mockCorrection], rowCount: 1 });
const result = await updateSuggestedCorrection(1, '300');
expect(getPool().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
mockQuery
.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(getPool().query).toHaveBeenCalledTimes(5);
expect(stats).toEqual({
flyerCount: 10,
userCount: 20,
flyerItemCount: 300,
storeCount: 5,
pendingCorrectionCount: 2,
});
});
});
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 }];
mockQuery.mockResolvedValue({ rows: mockStats });
const result = await getDailyStatsForLast30Days();
expect(getPool().query).toHaveBeenCalledWith(expect.stringContaining("WITH date_series AS"));
expect(result).toEqual(mockStats);
});
});
describe('logActivity', () => {
it('should insert a new activity log entry', async () => {
mockQuery.mockResolvedValue({ rows: [] });
const logData = { userId: 'user-123', action: 'test_action', displayText: 'Test activity' };
await logActivity(logData);
expect(getPool().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 () => {
mockQuery.mockResolvedValue({ rows: [] });
await getMostFrequentSaleItems(30, 10);
expect(getPool().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' };
mockQuery.mockResolvedValue({ rows: [mockComment], rowCount: 1 });
const result = await updateRecipeCommentStatus(1, 'hidden');
expect(getPool().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 () => {
mockQuery.mockResolvedValue({ rows: [] });
await getUnmatchedFlyerItems();
expect(getPool().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' };
mockQuery.mockResolvedValue({ rows: [mockRecipe], rowCount: 1 });
const result = await updateRecipeStatus(1, 'public');
expect(getPool().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 () => {
mockQuery.mockResolvedValue({ rows: [] });
await incrementFailedLoginAttempts('user-123');
// Fix: Use regex to match query with variable whitespace
expect(getPool().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 () => {
mockQuery.mockResolvedValue({ rows: [] });
await updateBrandLogo(1, '/logo.png');
expect(getPool().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' };
mockQuery.mockResolvedValue({ rows: [mockReceipt], rowCount: 1 });
const result = await updateReceiptStatus(1, 'completed');
expect(getPool().query).toHaveBeenCalledWith(expect.stringContaining('UPDATE public.receipts'), ['completed', 1]);
expect(result).toEqual(mockReceipt);
});
});
});