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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 24x 2x 2x 2x 2x 24x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 8x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 14x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 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 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 11x 2x 11x 11x 11x 2x 2x 2x 2x 2x 10x 1x 1x 24x 2x 2x 2x 2x 4x 6x 4x 6x 6x 2x 6x 6x 2x 2x 2x 2x 2x 6x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 5x 6x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 1x 1x 1x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 3x 1x 3x 1x 4x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 24x 1x 1x 1x 3x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 24x 2x 1x 1x 4x 1x 4x 1x 4x 1x 4x 1x 1x 1x 1x 1x 1x 2x 4x 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 2x 2x 24x 2x 2x 2x 3x 2x 3x 2x 3x 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 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 3x 2x 3x 2x 3x 2x 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 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 3x 2x 3x 2x 3x 2x 3x 2x 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 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 2x 2x 2x 2x 24x 2x 2x 2x 6x 2x 6x 2x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 6x 2x 2x 2x 2x 2x 2x 5x 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 5x 2x 5x 2x 5x 2x 5x 2x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x | // src/routes/receipt.routes.ts
/**
* @file Receipt Scanning API Routes
* Provides endpoints for uploading, processing, and managing scanned receipts.
*/
import express, { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import passport from '../config/passport';
import type { UserProfile } from '../types';
import { validateRequest } from '../middleware/validation.middleware';
import { numericIdParam, optionalNumeric } from '../utils/zodUtils';
import { sendSuccess, sendNoContent } from '../utils/apiResponse';
import * as receiptService from '../services/receiptService.server';
import * as expiryService from '../services/expiryService.server';
import { createUploadMiddleware, handleMulterError } from '../middleware/multer.middleware';
import { receiptQueue } from '../services/queues.server';
import { requireFileUpload } from '../middleware/fileUpload.middleware';
const router = express.Router();
// Configure multer for receipt image uploads (max 10MB)
const receiptUpload = createUploadMiddleware({
storageType: 'receipt',
fileSize: 10 * 1024 * 1024, // 10MB
fileFilter: 'image',
});
// --- Zod Schemas for Receipt Routes ---
/**
* Receipt status validation
*/
const receiptStatusSchema = z.enum(['pending', 'processing', 'completed', 'failed']);
/**
* Receipt item status validation
*/
const receiptItemStatusSchema = z.enum(['unmatched', 'matched', 'needs_review', 'ignored']);
/**
* Storage location validation (for adding items to inventory)
*/
const storageLocationSchema = z.enum(['fridge', 'freezer', 'pantry', 'room_temp']);
/**
* Schema for receipt ID parameter
*/
const receiptIdParamSchema = numericIdParam(
'receiptId',
"Invalid ID for parameter 'receiptId'. Must be a number.",
);
/**
* Schema for receipt item ID parameter
*/
const _receiptItemIdParamSchema = numericIdParam(
'itemId',
"Invalid ID for parameter 'itemId'. Must be a number.",
);
/**
* Schema for uploading a receipt (used with file upload, not base64)
*/
const uploadReceiptSchema = z.object({
body: z.object({
store_location_id: z
.string()
.optional()
.transform((val) => (val ? parseInt(val, 10) : undefined))
.pipe(z.number().int().positive().optional()),
transaction_date: z.string().date('Transaction date must be in YYYY-MM-DD format.').optional(),
}),
});
/**
* Schema for receipt query
*/
const receiptQuerySchema = z.object({
query: z.object({
limit: optionalNumeric({ default: 50, min: 1, max: 100, integer: true }),
offset: optionalNumeric({ default: 0, min: 0, integer: true }),
status: receiptStatusSchema.optional(),
store_location_id: z
.string()
.optional()
.transform((val) => (val ? parseInt(val, 10) : undefined))
.pipe(z.number().int().positive().optional()),
from_date: z.string().date().optional(),
to_date: z.string().date().optional(),
}),
});
/**
* Schema for updating a receipt item
*/
const updateReceiptItemSchema = z.object({
params: z.object({
receiptId: z.coerce.number().int().positive(),
itemId: z.coerce.number().int().positive(),
}),
body: z
.object({
status: receiptItemStatusSchema.optional(),
master_item_id: z.number().int().positive().nullable().optional(),
product_id: z.number().int().positive().nullable().optional(),
match_confidence: z.number().min(0).max(1).optional(),
})
.refine((data) => Object.keys(data).length > 0, {
message: 'At least one field to update must be provided.',
}),
});
/**
* Schema for confirming receipt items to add to inventory
*/
const confirmItemsSchema = z.object({
params: z.object({
receiptId: z.coerce.number().int().positive(),
}),
body: z.object({
items: z.array(
z.object({
receipt_item_id: z.number().int().positive(),
item_name: z.string().max(255).optional(),
quantity: z.number().positive().optional(),
location: storageLocationSchema.optional(),
expiry_date: z.string().date().optional(),
include: z.boolean(),
}),
),
}),
});
// Middleware to ensure user is authenticated for all receipt routes
router.use(passport.authenticate('jwt', { session: false }));
// ============================================================================
// RECEIPT MANAGEMENT ENDPOINTS
// ============================================================================
/**
* @openapi
* /receipts:
* get:
* tags: [Receipts]
* summary: Get user's receipts
* description: Retrieve the user's scanned receipts with optional filtering.
* security:
* - bearerAuth: []
* parameters:
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* maximum: 100
* default: 50
* - in: query
* name: offset
* schema:
* type: integer
* minimum: 0
* default: 0
* - in: query
* name: status
* schema:
* type: string
* enum: [pending, processing, completed, failed]
* - in: query
* name: store_location_id
* schema:
* type: integer
* - in: query
* name: from_date
* schema:
* type: string
* format: date
* - in: query
* name: to_date
* schema:
* type: string
* format: date
* responses:
* 200:
* description: Receipts retrieved
* 401:
* description: Unauthorized
*/
router.get(
'/',
validateRequest(receiptQuerySchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type ReceiptQueryRequest = z.infer<typeof receiptQuerySchema>;
const { query } = req as unknown as ReceiptQueryRequest;
try {
const result = await receiptService.getReceipts(
{
user_id: userProfile.user.user_id,
status: query.status,
store_location_id: query.store_location_id,
from_date: query.from_date,
to_date: query.to_date,
limit: query.limit,
offset: query.offset,
},
req.log,
);
sendSuccess(res, result);
} catch (error) {
req.log.error({ error, userId: userProfile.user.user_id }, 'Error fetching receipts');
next(error);
}
},
);
/**
* @openapi
* /receipts:
* post:
* tags: [Receipts]
* summary: Upload a receipt
* description: Upload a receipt image for processing and item extraction.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - receipt
* properties:
* receipt:
* type: string
* format: binary
* description: Receipt image file
* store_location_id:
* type: integer
* description: Store location ID if known
* transaction_date:
* type: string
* format: date
* description: Transaction date if known (YYYY-MM-DD)
* responses:
* 201:
* description: Receipt uploaded and queued for processing
* 400:
* description: Validation error
* 401:
* description: Unauthorized
*/
router.post(
'/',
receiptUpload.single('receipt'),
requireFileUpload('receipt'),
validateRequest(uploadReceiptSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type UploadReceiptRequest = z.infer<typeof uploadReceiptSchema>;
const { body } = req as unknown as UploadReceiptRequest;
const file = req.file as Express.Multer.File;
try {
req.log.info(
{ userId: userProfile.user.user_id, filename: file.filename },
'Uploading receipt',
);
// Create receipt record with the actual file path
const receipt = await receiptService.createReceipt(
userProfile.user.user_id,
file.path, // Use the actual file path from multer
req.log,
{
storeLocationId: body.store_location_id,
transactionDate: body.transaction_date,
},
);
// Queue the receipt for processing via BullMQ
const bindings = req.log.bindings?.() || {};
const job = await receiptQueue.add(
'process-receipt',
{
receiptId: receipt.receipt_id,
userId: userProfile.user.user_id,
imagePath: file.path,
meta: {
requestId: bindings.request_id as string | undefined,
userId: userProfile.user.user_id,
origin: 'api',
},
},
{
jobId: `receipt-${receipt.receipt_id}`,
},
);
req.log.info(
{ receiptId: receipt.receipt_id, jobId: job.id },
'Receipt queued for processing',
);
sendSuccess(res, { ...receipt, job_id: job.id }, 201);
} catch (error) {
req.log.error({ error, userId: userProfile.user.user_id }, 'Error uploading receipt');
next(error);
}
},
);
/**
* @openapi
* /receipts/{receiptId}:
* get:
* tags: [Receipts]
* summary: Get receipt by ID
* description: Retrieve a specific receipt with its extracted items.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Receipt retrieved
* 401:
* description: Unauthorized
* 404:
* description: Receipt not found
*/
router.get(
'/:receiptId',
validateRequest(receiptIdParamSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type GetReceiptRequest = z.infer<typeof receiptIdParamSchema>;
const { params } = req as unknown as GetReceiptRequest;
try {
const receipt = await receiptService.getReceiptById(
params.receiptId,
userProfile.user.user_id,
req.log,
);
// Also get the items
const items = await receiptService.getReceiptItems(params.receiptId, req.log);
sendSuccess(res, { receipt, items });
} catch (error) {
req.log.error(
{ error, userId: userProfile.user.user_id, receiptId: params.receiptId },
'Error fetching receipt',
);
next(error);
}
},
);
/**
* @openapi
* /receipts/{receiptId}:
* delete:
* tags: [Receipts]
* summary: Delete receipt
* description: Delete a receipt and all associated data.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* responses:
* 204:
* description: Receipt deleted
* 401:
* description: Unauthorized
* 404:
* description: Receipt not found
*/
router.delete(
'/:receiptId',
validateRequest(receiptIdParamSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type DeleteReceiptRequest = z.infer<typeof receiptIdParamSchema>;
const { params } = req as unknown as DeleteReceiptRequest;
try {
await receiptService.deleteReceipt(params.receiptId, userProfile.user.user_id, req.log);
sendNoContent(res);
} catch (error) {
req.log.error(
{ error, userId: userProfile.user.user_id, receiptId: params.receiptId },
'Error deleting receipt',
);
next(error);
}
},
);
/**
* @openapi
* /receipts/{receiptId}/reprocess:
* post:
* tags: [Receipts]
* summary: Reprocess receipt
* description: Queue a failed receipt for reprocessing.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Receipt queued for reprocessing
* 401:
* description: Unauthorized
* 404:
* description: Receipt not found
*/
router.post(
'/:receiptId/reprocess',
validateRequest(receiptIdParamSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type ReprocessReceiptRequest = z.infer<typeof receiptIdParamSchema>;
const { params } = req as unknown as ReprocessReceiptRequest;
try {
// Verify the receipt exists and belongs to user
const receipt = await receiptService.getReceiptById(
params.receiptId,
userProfile.user.user_id,
req.log,
);
// Queue for reprocessing via BullMQ
const bindings = req.log.bindings?.() || {};
const job = await receiptQueue.add(
'process-receipt',
{
receiptId: receipt.receipt_id,
userId: userProfile.user.user_id,
imagePath: receipt.receipt_image_url, // Use stored image path
meta: {
requestId: bindings.request_id as string | undefined,
userId: userProfile.user.user_id,
origin: 'api-reprocess',
},
},
{
jobId: `receipt-${receipt.receipt_id}-reprocess-${Date.now()}`,
},
);
req.log.info(
{ receiptId: params.receiptId, jobId: job.id },
'Receipt queued for reprocessing',
);
sendSuccess(res, {
message: 'Receipt queued for reprocessing',
receipt_id: receipt.receipt_id,
job_id: job.id,
});
} catch (error) {
req.log.error(
{ error, userId: userProfile.user.user_id, receiptId: params.receiptId },
'Error reprocessing receipt',
);
next(error);
}
},
);
// ============================================================================
// RECEIPT ITEMS ENDPOINTS
// ============================================================================
/**
* @openapi
* /receipts/{receiptId}/items:
* get:
* tags: [Receipts]
* summary: Get receipt items
* description: Get all extracted items from a receipt.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Receipt items retrieved
* 401:
* description: Unauthorized
* 404:
* description: Receipt not found
*/
router.get(
'/:receiptId/items',
validateRequest(receiptIdParamSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type GetItemsRequest = z.infer<typeof receiptIdParamSchema>;
const { params } = req as unknown as GetItemsRequest;
try {
// Verify receipt belongs to user
await receiptService.getReceiptById(params.receiptId, userProfile.user.user_id, req.log);
const items = await receiptService.getReceiptItems(params.receiptId, req.log);
sendSuccess(res, { items, total: items.length });
} catch (error) {
req.log.error(
{ error, userId: userProfile.user.user_id, receiptId: params.receiptId },
'Error fetching receipt items',
);
next(error);
}
},
);
/**
* @openapi
* /receipts/{receiptId}/items/{itemId}:
* put:
* tags: [Receipts]
* summary: Update receipt item
* description: Update a receipt item's matching status or linked product.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* - in: path
* name: itemId
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* enum: [unmatched, matched, needs_review, ignored]
* master_item_id:
* type: integer
* nullable: true
* product_id:
* type: integer
* nullable: true
* match_confidence:
* type: number
* minimum: 0
* maximum: 1
* responses:
* 200:
* description: Item updated
* 400:
* description: Validation error
* 401:
* description: Unauthorized
* 404:
* description: Receipt or item not found
*/
router.put(
'/:receiptId/items/:itemId',
validateRequest(updateReceiptItemSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type UpdateItemRequest = z.infer<typeof updateReceiptItemSchema>;
const { params, body } = req as unknown as UpdateItemRequest;
try {
// Verify receipt belongs to user
await receiptService.getReceiptById(params.receiptId, userProfile.user.user_id, req.log);
const item = await receiptService.updateReceiptItem(params.itemId, body, req.log);
sendSuccess(res, item);
} catch (error) {
req.log.error(
{
error,
userId: userProfile.user.user_id,
receiptId: params.receiptId,
itemId: params.itemId,
},
'Error updating receipt item',
);
next(error);
}
},
);
/**
* @openapi
* /receipts/{receiptId}/items/unadded:
* get:
* tags: [Receipts]
* summary: Get unadded items
* description: Get receipt items that haven't been added to inventory yet.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Unadded items retrieved
* 401:
* description: Unauthorized
* 404:
* description: Receipt not found
*/
router.get(
'/:receiptId/items/unadded',
validateRequest(receiptIdParamSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type GetUnaddedRequest = z.infer<typeof receiptIdParamSchema>;
const { params } = req as unknown as GetUnaddedRequest;
try {
// Verify receipt belongs to user
await receiptService.getReceiptById(params.receiptId, userProfile.user.user_id, req.log);
const items = await receiptService.getUnaddedItems(params.receiptId, req.log);
sendSuccess(res, { items, total: items.length });
} catch (error) {
req.log.error(
{ error, userId: userProfile.user.user_id, receiptId: params.receiptId },
'Error fetching unadded receipt items',
);
next(error);
}
},
);
/**
* @openapi
* /receipts/{receiptId}/confirm:
* post:
* tags: [Receipts]
* summary: Confirm items for inventory
* description: Confirm selected receipt items to add to user's inventory.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - items
* properties:
* items:
* type: array
* items:
* type: object
* required:
* - receipt_item_id
* - include
* properties:
* receipt_item_id:
* type: integer
* item_name:
* type: string
* maxLength: 255
* quantity:
* type: number
* minimum: 0
* location:
* type: string
* enum: [fridge, freezer, pantry, room_temp]
* expiry_date:
* type: string
* format: date
* include:
* type: boolean
* responses:
* 200:
* description: Items added to inventory
* 400:
* description: Validation error
* 401:
* description: Unauthorized
* 404:
* description: Receipt not found
*/
router.post(
'/:receiptId/confirm',
validateRequest(confirmItemsSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type ConfirmItemsRequest = z.infer<typeof confirmItemsSchema>;
const { params, body } = req as unknown as ConfirmItemsRequest;
try {
req.log.info(
{
userId: userProfile.user.user_id,
receiptId: params.receiptId,
itemCount: body.items.length,
},
'Confirming receipt items for inventory',
);
const addedItems = await expiryService.addItemsFromReceipt(
userProfile.user.user_id,
params.receiptId,
body.items,
req.log,
);
sendSuccess(res, { added_items: addedItems, count: addedItems.length });
} catch (error) {
req.log.error(
{ error, userId: userProfile.user.user_id, receiptId: params.receiptId },
'Error confirming receipt items',
);
next(error);
}
},
);
// ============================================================================
// PROCESSING LOGS ENDPOINT
// ============================================================================
/**
* @openapi
* /receipts/{receiptId}/logs:
* get:
* tags: [Receipts]
* summary: Get processing logs
* description: Get the processing log history for a receipt.
* security:
* - bearerAuth: []
* parameters:
* - in: path
* name: receiptId
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Processing logs retrieved
* 401:
* description: Unauthorized
* 404:
* description: Receipt not found
*/
router.get(
'/:receiptId/logs',
validateRequest(receiptIdParamSchema),
async (req: Request, res: Response, next: NextFunction) => {
const userProfile = req.user as UserProfile;
type GetLogsRequest = z.infer<typeof receiptIdParamSchema>;
const { params } = req as unknown as GetLogsRequest;
try {
// Verify receipt belongs to user
await receiptService.getReceiptById(params.receiptId, userProfile.user.user_id, req.log);
const logs = await receiptService.getProcessingLogs(params.receiptId, req.log);
sendSuccess(res, { logs, total: logs.length });
} catch (error) {
req.log.error(
{ error, userId: userProfile.user.user_id, receiptId: params.receiptId },
'Error fetching processing logs',
);
next(error);
}
},
);
/* Catches errors from multer (e.g., file size, file filter) */
router.use(handleMulterError);
export default router;
|