All files / src/routes budget.routes.ts

97.33% Statements 365/375
73.33% Branches 11/15
100% Functions 7/7
96.95% Lines 318/328

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 3292x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 24x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 24x 10x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 4x 4x 4x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 24x 1x 1x 1x 6x 2x 6x 6x 6x 4x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 5x 2x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 3x 2x 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 5x 2x 5x 5x 5x 2x 2x 3x 2x 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 3x 2x 2x 2x 3x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x  
// src/routes/budget.ts
import express, { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import passport from '../config/passport';
import { budgetRepo } from '../services/db/index.db';
import type { UserProfile } from '../types';
import { validateRequest } from '../middleware/validation.middleware';
import { requiredString, numericIdParam } from '../utils/zodUtils';
import { budgetUpdateLimiter } from '../config/rateLimiters';
import { sendSuccess, sendNoContent } from '../utils/apiResponse';
 
const router = express.Router();
 
// --- Zod Schemas for Budget Routes (as per ADR-003) ---
const budgetIdParamSchema = numericIdParam(
  'id',
  "Invalid ID for parameter 'id'. Must be a number.",
);
 
const createBudgetSchema = z.object({
  body: z.object({
    name: requiredString('Budget name is required.'),
    amount_cents: z.number().int().positive('Amount must be a positive integer.'),
    period: z.enum(['weekly', 'monthly']),
    start_date: z.string().date('Start date must be a valid date in YYYY-MM-DD format.'),
  }),
});
 
const updateBudgetSchema = budgetIdParamSchema.extend({
  body: createBudgetSchema.shape.body.partial().refine((data) => Object.keys(data).length > 0, {
    message: 'At least one field to update must be provided.',
  }),
});
 
const spendingAnalysisSchema = z.object({
  query: z.object({
    startDate: z.string().date('startDate must be a valid date in YYYY-MM-DD format.'),
    endDate: z.string().date('endDate must be a valid date in YYYY-MM-DD format.'),
  }),
});
 
// Middleware to ensure user is authenticated for all budget routes
router.use(passport.authenticate('jwt', { session: false }));
 
// Apply rate limiting to all subsequent budget routes
router.use(budgetUpdateLimiter);
 
/**
 * @openapi
 * /budgets:
 *   get:
 *     tags: [Budgets]
 *     summary: Get all budgets
 *     description: Retrieve all budgets for the authenticated user.
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: List of user budgets
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SuccessResponse'
 *       401:
 *         description: Unauthorized - invalid or missing token
 */
router.get('/', async (req: Request, res: Response, next: NextFunction) => {
  const userProfile = req.user as UserProfile;
  try {
    const budgets = await budgetRepo.getBudgetsForUser(userProfile.user.user_id, req.log);
    sendSuccess(res, budgets);
  } catch (error) {
    req.log.error({ error, userId: userProfile.user.user_id }, 'Error fetching budgets');
    next(error);
  }
});
 
/**
 * @openapi
 * /budgets:
 *   post:
 *     tags: [Budgets]
 *     summary: Create budget
 *     description: Create a new budget for the authenticated user.
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - name
 *               - amount_cents
 *               - period
 *               - start_date
 *             properties:
 *               name:
 *                 type: string
 *                 description: Budget name
 *               amount_cents:
 *                 type: integer
 *                 minimum: 1
 *                 description: Budget amount in cents
 *               period:
 *                 type: string
 *                 enum: [weekly, monthly]
 *                 description: Budget period
 *               start_date:
 *                 type: string
 *                 format: date
 *                 description: Budget start date (YYYY-MM-DD)
 *     responses:
 *       201:
 *         description: Budget created
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SuccessResponse'
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized - invalid or missing token
 */
router.post(
  '/',
  validateRequest(createBudgetSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    const userProfile = req.user as UserProfile;
    type CreateBudgetRequest = z.infer<typeof createBudgetSchema>;
    const { body } = req as unknown as CreateBudgetRequest;
    try {
      const newBudget = await budgetRepo.createBudget(userProfile.user.user_id, body, req.log);
      sendSuccess(res, newBudget, 201);
    } catch (error: unknown) {
      req.log.error({ error, userId: userProfile.user.user_id, body }, 'Error creating budget');
      next(error);
    }
  },
);
 
/**
 * @openapi
 * /budgets/{id}:
 *   put:
 *     tags: [Budgets]
 *     summary: Update budget
 *     description: Update an existing budget.
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Budget ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *                 description: Budget name
 *               amount_cents:
 *                 type: integer
 *                 minimum: 1
 *                 description: Budget amount in cents
 *               period:
 *                 type: string
 *                 enum: [weekly, monthly]
 *                 description: Budget period
 *               start_date:
 *                 type: string
 *                 format: date
 *                 description: Budget start date (YYYY-MM-DD)
 *     responses:
 *       200:
 *         description: Budget updated
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SuccessResponse'
 *       400:
 *         description: Validation error - at least one field required
 *       401:
 *         description: Unauthorized - invalid or missing token
 *       404:
 *         description: Budget not found
 */
router.put(
  '/:id',
  validateRequest(updateBudgetSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    const userProfile = req.user as UserProfile;
    type UpdateBudgetRequest = z.infer<typeof updateBudgetSchema>;
    const { params, body } = req as unknown as UpdateBudgetRequest;
    try {
      const updatedBudget = await budgetRepo.updateBudget(
        params.id,
        userProfile.user.user_id,
        body,
        req.log,
      );
      sendSuccess(res, updatedBudget);
    } catch (error: unknown) {
      req.log.error(
        { error, userId: userProfile.user.user_id, budgetId: params.id },
        'Error updating budget',
      );
      next(error);
    }
  },
);
 
/**
 * @openapi
 * /budgets/{id}:
 *   delete:
 *     tags: [Budgets]
 *     summary: Delete budget
 *     description: Delete a budget by ID.
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Budget ID
 *     responses:
 *       204:
 *         description: Budget deleted
 *       401:
 *         description: Unauthorized - invalid or missing token
 *       404:
 *         description: Budget not found
 */
router.delete(
  '/:id',
  validateRequest(budgetIdParamSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    const userProfile = req.user as UserProfile;
    type DeleteBudgetRequest = z.infer<typeof budgetIdParamSchema>;
    const { params } = req as unknown as DeleteBudgetRequest;
    try {
      await budgetRepo.deleteBudget(params.id, userProfile.user.user_id, req.log);
      sendNoContent(res);
    } catch (error: unknown) {
      req.log.error(
        { error, userId: userProfile.user.user_id, budgetId: params.id },
        'Error deleting budget',
      );
      next(error);
    }
  },
);
 
/**
 * @openapi
 * /budgets/spending-analysis:
 *   get:
 *     tags: [Budgets]
 *     summary: Get spending analysis
 *     description: Get spending breakdown by category for a date range.
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: startDate
 *         required: true
 *         schema:
 *           type: string
 *           format: date
 *         description: Start date (YYYY-MM-DD)
 *       - in: query
 *         name: endDate
 *         required: true
 *         schema:
 *           type: string
 *           format: date
 *         description: End date (YYYY-MM-DD)
 *     responses:
 *       200:
 *         description: Spending breakdown by category
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SuccessResponse'
 *       400:
 *         description: Invalid date format
 *       401:
 *         description: Unauthorized - invalid or missing token
 */
router.get(
  '/spending-analysis',
  validateRequest(spendingAnalysisSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    const userProfile = req.user as UserProfile;
    type SpendingAnalysisRequest = z.infer<typeof spendingAnalysisSchema>;
    const {
      query: { startDate, endDate },
    } = req as unknown as SpendingAnalysisRequest;
 
    try {
      const spendingData = await budgetRepo.getSpendingByCategory(
        userProfile.user.user_id,
        startDate,
        endDate,
        req.log,
      );
      sendSuccess(res, spendingData);
    } catch (error) {
      req.log.error(
        { error, userId: userProfile.user.user_id, startDate, endDate },
        'Error fetching spending analysis',
      );
      next(error);
    }
  },
);
 
export default router;