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 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006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 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 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 2x 2x 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 3x 2x 2x 2x 2x 2x 24x 2x 2x | // src/routes/ai.routes.ts
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { Router, Request, Response, NextFunction } from 'express';
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { z } from 'zod';
import passport, { optionalAuth } from '../config/passport';
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { aiService, DuplicateFlyerError } from '../services/aiService.server';
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { createUploadMiddleware, handleMulterError } from '../middleware/multer.middleware';
import { logger } from '../services/logger.server'; // Needed for module-level logging (e.g., Zod schema transforms)
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { UserProfile } from '../types'; // This was a duplicate, fixed.
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { validateRequest } from '../middleware/validation.middleware';
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { requiredString } from '../utils/zodUtils';
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { cleanupUploadedFile, cleanupUploadedFiles } from '../utils/fileUtils';
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { monitoringService } from '../services/monitoringService.server';
// All route handlers now use req.log (request-scoped logger) as per ADR-004
import { aiUploadLimiter, aiGenerationLimiter } from '../config/rateLimiters';
import { sendSuccess, sendError, ErrorCode } from '../utils/apiResponse';
const router = Router();
// --- Zod Schemas for AI Routes (as per ADR-003) ---
const uploadAndProcessSchema = z.object({
body: z.object({
// Stricter validation for SHA-256 checksum. It must be a 64-character hexadecimal string.
checksum: requiredString('File checksum is required.').pipe(
z
.string()
.length(64, 'Checksum must be 64 characters long.')
.regex(/^[a-f0-9]+$/, 'Checksum must be a valid hexadecimal string.'),
),
baseUrl: z.string().url().optional(),
}),
});
const jobIdParamSchema = z.object({
params: z.object({
jobId: requiredString('A valid Job ID is required.'),
}),
});
// Helper to safely extract an error message from unknown `catch` values.
const errMsg = (e: unknown) => {
if (e instanceof Error) return e.message;
if (typeof e === 'object' && e !== null && 'message' in e)
return String((e as { message: unknown }).message);
return String(e || 'An unknown error occurred.');
};
const cropAreaObjectSchema = z.object({
x: z.number(),
y: z.number(),
width: z.number().positive('Crop area width must be positive.'),
height: z.number().positive('Crop area height must be positive.'),
});
const rescanAreaSchema = z.object({
body: z.object({
cropArea: requiredString('cropArea must be a valid JSON string.')
.transform((val, ctx) => {
try {
return JSON.parse(val);
} catch (err) {
// Log the actual parsing error for better debugging if invalid JSON is sent.
// Using module-level logger since Zod transforms don't have access to request context
logger.warn(
{ error: errMsg(err), receivedValue: val },
'Failed to parse cropArea in rescanAreaSchema',
);
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'cropArea must be a valid JSON string.',
});
return z.NEVER;
}
})
.pipe(cropAreaObjectSchema), // Further validate the structure of the parsed object
extractionType: z.enum(['store_name', 'dates', 'item_details'], {
message: "extractionType must be one of 'store_name', 'dates', or 'item_details'.",
}),
}),
});
const flyerItemForAnalysisSchema = z
.object({
// Sanitize item and name by trimming whitespace.
// The transform ensures that null/undefined values are preserved
// while trimming any actual string values.
item: z
.string()
.nullish()
.transform((val) => (val ? val.trim() : val)),
name: z
.string()
.nullish()
.transform((val) => (val ? val.trim() : val)),
})
// Using .passthrough() allows extra properties on the item object.
// If the intent is to strictly enforce only 'item' and 'name' (and other known properties),
// consider using .strict() instead for tighter security and data integrity.
.passthrough()
.refine(
(data) =>
// After the transform, the values are already trimmed.
(data.item && data.item.length > 0) || (data.name && data.name.length > 0),
{
message: "Item identifier is required (either 'item' or 'name').",
},
);
const insightsSchema = z.object({
body: z.object({
items: z.array(flyerItemForAnalysisSchema).nonempty("The 'items' array cannot be empty."),
}),
});
const comparePricesSchema = z.object({
body: z.object({
items: z.array(flyerItemForAnalysisSchema).nonempty("The 'items' array cannot be empty."),
}),
});
const planTripSchema = z.object({
body: z.object({
// Consider if this array should be non-empty. If a trip plan requires at least one item,
// you could add `.nonempty('At least one item is required to plan a trip.')`
items: z.array(flyerItemForAnalysisSchema),
store: z.object({ name: requiredString('Store name is required.') }),
userLocation: z.object({
latitude: z
.number()
.min(-90, 'Latitude must be between -90 and 90.')
.max(90, 'Latitude must be between -90 and 90.'),
longitude: z
.number()
.min(-180, 'Longitude must be between -180 and 180.')
.max(180, 'Longitude must be between -180 and 180.'),
}),
}),
});
const generateImageSchema = z.object({
body: z.object({ prompt: requiredString('A prompt is required.') }),
});
const generateSpeechSchema = z.object({
body: z.object({ text: requiredString('Text is required.') }),
});
const searchWebSchema = z.object({
body: z.object({ query: requiredString('A search query is required.') }),
});
const uploadToDisk = createUploadMiddleware({
storageType: 'flyer',
fileSize: 50 * 1024 * 1024, // 50MB limit for flyer uploads
fileFilter: 'image',
});
// Diagnostic middleware: log incoming AI route requests (headers and sizes)
router.use((req: Request, res: Response, next: NextFunction) => {
try {
const contentType = req.headers['content-type'] || '';
const contentLength = req.headers['content-length'] || 'unknown';
const authPresent = !!req.headers['authorization'];
req.log.debug(
{ method: req.method, url: req.originalUrl, contentType, contentLength, authPresent },
'[API /ai] Incoming request',
);
} catch (e: unknown) {
req.log.error({ error: errMsg(e) }, 'Failed to log incoming AI request headers');
}
next();
});
/**
* @openapi
* /ai/upload-and-process:
* post:
* tags: [AI]
* summary: Upload and process flyer
* description: Accepts a single flyer file (PDF or image), enqueues it for background processing, and immediately returns a job ID.
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - flyerFile
* - checksum
* properties:
* flyerFile:
* type: string
* format: binary
* description: Flyer file (PDF or image)
* checksum:
* type: string
* pattern: ^[a-f0-9]{64}$
* description: SHA-256 checksum of the file
* baseUrl:
* type: string
* format: uri
* description: Optional base URL
* responses:
* 202:
* description: Flyer accepted for processing
* 400:
* description: Missing file or invalid checksum
* 409:
* description: Duplicate flyer detected
*/
router.post(
'/upload-and-process',
aiUploadLimiter,
optionalAuth,
uploadToDisk.single('flyerFile'),
// Validation is now handled inside the route to ensure file cleanup on failure.
// validateRequest(uploadAndProcessSchema),
async (req, res, next: NextFunction) => {
try {
// Manually validate the request body. This will throw if validation fails.
const { body } = uploadAndProcessSchema.parse({ body: req.body });
if (!req.file) {
return sendError(
res,
ErrorCode.BAD_REQUEST,
'A flyer file (PDF or image) is required.',
400,
);
}
req.log.debug(
{ filename: req.file.originalname, size: req.file.size, checksum: body.checksum },
'Handling /upload-and-process',
);
// Fix: Explicitly clear userProfile if no auth header is present in test/staging env
// This prevents mockAuth from injecting a non-existent user ID for anonymous requests.
let userProfile = req.user as UserProfile | undefined;
if (
(process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'staging') &&
!req.headers['authorization']
) {
userProfile = undefined;
}
const job = await aiService.enqueueFlyerProcessing(
req.file,
body.checksum,
userProfile,
req.ip ?? 'unknown',
req.log,
body.baseUrl,
);
// Respond immediately to the client with 202 Accepted
sendSuccess(
res,
{
message: 'Flyer accepted for processing.',
jobId: job.id,
},
202,
);
} catch (error) {
await cleanupUploadedFile(req.file);
if (error instanceof DuplicateFlyerError) {
req.log.warn(`Duplicate flyer upload attempt blocked for checksum: ${req.body?.checksum}`);
return sendError(res, ErrorCode.CONFLICT, error.message, 409, { flyerId: error.flyerId });
}
next(error);
}
},
);
/**
* @openapi
* /ai/upload-legacy:
* post:
* tags: [AI]
* summary: Legacy flyer upload (deprecated)
* description: Process a flyer upload synchronously. Deprecated - use /upload-and-process instead.
* deprecated: true
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - flyerFile
* properties:
* flyerFile:
* type: string
* format: binary
* description: Flyer file (PDF or image)
* responses:
* 200:
* description: Flyer processed successfully
* 400:
* description: No flyer file uploaded
* 401:
* description: Unauthorized
* 409:
* description: Duplicate flyer detected
*/
router.post(
'/upload-legacy',
aiUploadLimiter,
passport.authenticate('jwt', { session: false }),
uploadToDisk.single('flyerFile'),
async (req: Request, res: Response, next: NextFunction) => {
try {
if (!req.file) {
return sendError(res, ErrorCode.BAD_REQUEST, 'No flyer file uploaded.', 400);
}
const userProfile = req.user as UserProfile;
const newFlyer = await aiService.processLegacyFlyerUpload(
req.file,
req.body,
userProfile,
req.log,
);
sendSuccess(res, newFlyer);
} catch (error) {
await cleanupUploadedFile(req.file);
if (error instanceof DuplicateFlyerError) {
req.log.warn(`Duplicate legacy flyer upload attempt blocked.`);
return sendError(res, ErrorCode.CONFLICT, error.message, 409, { flyerId: error.flyerId });
}
next(error);
}
},
);
/**
* @openapi
* /ai/jobs/{jobId}/status:
* get:
* tags: [AI]
* summary: Check job status
* description: Checks the status of a background flyer processing job.
* parameters:
* - in: path
* name: jobId
* required: true
* schema:
* type: string
* description: Job ID returned from upload-and-process
* responses:
* 200:
* description: Job status information
* 404:
* description: Job not found
*/
router.get(
'/jobs/:jobId/status',
validateRequest(jobIdParamSchema),
async (req, res, next: NextFunction) => {
type JobIdRequest = z.infer<typeof jobIdParamSchema>;
const {
params: { jobId },
} = req as unknown as JobIdRequest;
try {
const jobStatus = await monitoringService.getFlyerJobStatus(jobId); // This was a duplicate, fixed.
req.log.debug(`[API /ai/jobs] Status check for job ${jobId}: ${jobStatus.state}`);
sendSuccess(res, jobStatus);
} catch (error) {
next(error);
}
},
);
/**
* @openapi
* /ai/flyers/process:
* post:
* tags: [AI]
* summary: Process flyer data (deprecated)
* description: Saves processed flyer data to the database. Deprecated - use /upload-and-process instead.
* deprecated: true
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - flyerImage
* properties:
* flyerImage:
* type: string
* format: binary
* description: Flyer image file
* responses:
* 201:
* description: Flyer processed and saved successfully
* 400:
* description: Flyer image file is required
* 409:
* description: Duplicate flyer detected
*/
router.post(
'/flyers/process',
aiUploadLimiter,
optionalAuth,
uploadToDisk.single('flyerImage'),
async (req, res, next: NextFunction) => {
try {
if (!req.file) {
return sendError(res, ErrorCode.BAD_REQUEST, 'Flyer image file is required.', 400);
}
const userProfile = req.user as UserProfile | undefined;
const newFlyer = await aiService.processLegacyFlyerUpload(
req.file,
req.body,
userProfile,
req.log,
);
sendSuccess(
res,
{ message: 'Flyer processed and saved successfully.', flyer: newFlyer },
201,
);
} catch (error) {
await cleanupUploadedFile(req.file);
if (error instanceof DuplicateFlyerError) {
req.log.warn(`Duplicate flyer upload attempt blocked.`);
return sendError(res, ErrorCode.CONFLICT, error.message, 409, { flyerId: error.flyerId });
}
next(error);
}
},
);
/**
* @openapi
* /ai/check-flyer:
* post:
* tags: [AI]
* summary: Check if image is a flyer
* description: Analyzes an image to determine if it's a grocery store flyer.
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - image
* properties:
* image:
* type: string
* format: binary
* description: Image file to check
* responses:
* 200:
* description: Flyer check result
* 400:
* description: Image file is required
*/
router.post(
'/check-flyer',
aiUploadLimiter,
optionalAuth,
uploadToDisk.single('image'),
async (req, res, next: NextFunction) => {
try {
if (!req.file) {
return sendError(res, ErrorCode.BAD_REQUEST, 'Image file is required.', 400);
}
req.log.info(`Server-side flyer check for file: ${req.file.originalname}`);
sendSuccess(res, { is_flyer: true }); // Stubbed response
} catch (error) {
next(error);
} finally {
await cleanupUploadedFile(req.file);
}
},
);
/**
* @openapi
* /ai/extract-address:
* post:
* tags: [AI]
* summary: Extract address from image
* description: Extracts store address information from a flyer image.
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - image
* properties:
* image:
* type: string
* format: binary
* description: Image file to extract address from
* responses:
* 200:
* description: Extracted address information
* 400:
* description: Image file is required
*/
router.post(
'/extract-address',
aiUploadLimiter,
optionalAuth,
uploadToDisk.single('image'),
async (req, res, next: NextFunction) => {
try {
if (!req.file) {
return sendError(res, ErrorCode.BAD_REQUEST, 'Image file is required.', 400);
}
req.log.info(`Server-side address extraction for file: ${req.file.originalname}`);
sendSuccess(res, { address: 'not identified' }); // Updated stubbed response
} catch (error) {
next(error);
} finally {
await cleanupUploadedFile(req.file);
}
},
);
/**
* @openapi
* /ai/extract-logo:
* post:
* tags: [AI]
* summary: Extract store logo
* description: Extracts store logo from flyer images.
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - images
* properties:
* images:
* type: array
* items:
* type: string
* format: binary
* description: Image files to extract logo from
* responses:
* 200:
* description: Extracted logo as base64
* 400:
* description: Image files are required
*/
router.post(
'/extract-logo',
aiUploadLimiter,
optionalAuth,
uploadToDisk.array('images'),
async (req, res, next: NextFunction) => {
try {
if (!req.files || !Array.isArray(req.files) || req.files.length === 0) {
return sendError(res, ErrorCode.BAD_REQUEST, 'Image files are required.', 400);
}
req.log.info(`Server-side logo extraction for ${req.files.length} image(s).`);
sendSuccess(res, { store_logo_base_64: null }); // Stubbed response
} catch (error) {
next(error);
} finally {
await cleanupUploadedFiles(req.files as Express.Multer.File[]);
}
},
);
/**
* @openapi
* /ai/quick-insights:
* post:
* tags: [AI]
* summary: Get quick insights
* description: Get AI-generated quick insights about flyer items.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - items
* properties:
* items:
* type: array
* items:
* type: object
* minItems: 1
* description: List of flyer items to analyze
* responses:
* 200:
* description: AI-generated quick insights
* 401:
* description: Unauthorized
*/
router.post(
'/quick-insights',
aiGenerationLimiter,
passport.authenticate('jwt', { session: false }),
validateRequest(insightsSchema),
async (req, res, next: NextFunction) => {
try {
req.log.info(`Server-side quick insights requested.`);
sendSuccess(res, { text: 'This is a server-generated quick insight: buy the cheap stuff!' }); // Stubbed response
} catch (error) {
next(error);
}
},
);
/**
* @openapi
* /ai/deep-dive:
* post:
* tags: [AI]
* summary: Get deep dive analysis
* description: Get detailed AI-generated analysis about flyer items.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - items
* properties:
* items:
* type: array
* items:
* type: object
* minItems: 1
* description: List of flyer items to analyze
* responses:
* 200:
* description: Detailed AI analysis
* 401:
* description: Unauthorized
*/
router.post(
'/deep-dive',
aiGenerationLimiter,
passport.authenticate('jwt', { session: false }),
validateRequest(insightsSchema),
async (req, res, next: NextFunction) => {
try {
req.log.info(`Server-side deep dive requested.`);
sendSuccess(res, {
text: 'This is a server-generated deep dive analysis. It is very detailed.',
}); // Stubbed response
} catch (error) {
next(error);
}
},
);
/**
* @openapi
* /ai/search-web:
* post:
* tags: [AI]
* summary: Search web for information
* description: Search the web for product or deal information.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - query
* properties:
* query:
* type: string
* description: Search query
* responses:
* 200:
* description: Search results with sources
* 401:
* description: Unauthorized
*/
router.post(
'/search-web',
aiGenerationLimiter,
passport.authenticate('jwt', { session: false }),
validateRequest(searchWebSchema),
async (req, res, next: NextFunction) => {
try {
req.log.info(`Server-side web search requested.`);
sendSuccess(res, { text: 'The web says this is good.', sources: [] }); // Stubbed response
} catch (error) {
next(error);
}
},
);
/**
* @openapi
* /ai/compare-prices:
* post:
* tags: [AI]
* summary: Compare prices across stores
* description: Compare prices for items across different stores.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - items
* properties:
* items:
* type: array
* items:
* type: object
* minItems: 1
* description: List of items to compare
* responses:
* 200:
* description: Price comparison results
* 401:
* description: Unauthorized
*/
router.post(
'/compare-prices',
aiGenerationLimiter,
passport.authenticate('jwt', { session: false }),
validateRequest(comparePricesSchema),
async (req, res, next: NextFunction) => {
try {
const { items } = req.body;
req.log.info(`Server-side price comparison requested for ${items.length} items.`);
sendSuccess(res, {
text: 'This is a server-generated price comparison. Milk is cheaper at SuperMart.',
sources: [],
}); // Stubbed response
} catch (error) {
next(error);
}
},
);
/**
* @openapi
* /ai/plan-trip:
* post:
* tags: [AI]
* summary: Plan shopping trip
* description: Plan an optimized shopping trip to a store based on items and location.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - items
* - store
* - userLocation
* properties:
* items:
* type: array
* items:
* type: object
* description: List of items to buy
* store:
* type: object
* required:
* - name
* properties:
* name:
* type: string
* description: Store name
* userLocation:
* type: object
* required:
* - latitude
* - longitude
* properties:
* latitude:
* type: number
* minimum: -90
* maximum: 90
* longitude:
* type: number
* minimum: -180
* maximum: 180
* responses:
* 200:
* description: Trip plan with directions
* 401:
* description: Unauthorized
*/
router.post(
'/plan-trip',
aiGenerationLimiter,
passport.authenticate('jwt', { session: false }),
validateRequest(planTripSchema),
async (req, res, next: NextFunction) => {
try {
const { items, store, userLocation } = req.body;
req.log.debug({ itemCount: items.length, storeName: store.name }, 'Trip planning requested.');
const result = await aiService.planTripWithMaps(items, store, userLocation);
sendSuccess(res, result);
} catch (error) {
req.log.error({ error: errMsg(error) }, 'Error in /api/ai/plan-trip endpoint:');
next(error);
}
},
);
// --- STUBBED AI Routes for Future Features ---
/**
* @openapi
* /ai/generate-image:
* post:
* tags: [AI]
* summary: Generate image (not implemented)
* description: Generate an image from a prompt. Currently not implemented.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - prompt
* properties:
* prompt:
* type: string
* description: Image generation prompt
* responses:
* 501:
* description: Not implemented
* 401:
* description: Unauthorized
*/
router.post(
'/generate-image',
aiGenerationLimiter,
passport.authenticate('jwt', { session: false }),
validateRequest(generateImageSchema),
(req: Request, res: Response) => {
// This endpoint is a placeholder for a future feature.
// Returning 501 Not Implemented is the correct HTTP response for this case.
req.log.info('Request received for unimplemented endpoint: /api/ai/generate-image');
sendError(res, ErrorCode.NOT_IMPLEMENTED, 'Image generation is not yet implemented.', 501);
},
);
/**
* @openapi
* /ai/generate-speech:
* post:
* tags: [AI]
* summary: Generate speech (not implemented)
* description: Generate speech from text. Currently not implemented.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - text
* properties:
* text:
* type: string
* description: Text to convert to speech
* responses:
* 501:
* description: Not implemented
* 401:
* description: Unauthorized
*/
router.post(
'/generate-speech',
aiGenerationLimiter,
passport.authenticate('jwt', { session: false }),
validateRequest(generateSpeechSchema),
(req: Request, res: Response) => {
// This endpoint is a placeholder for a future feature.
// Returning 501 Not Implemented is the correct HTTP response for this case.
req.log.info('Request received for unimplemented endpoint: /api/ai/generate-speech');
sendError(res, ErrorCode.NOT_IMPLEMENTED, 'Speech generation is not yet implemented.', 501);
},
);
/**
* @openapi
* /ai/rescan-area:
* post:
* tags: [AI]
* summary: Rescan area of image
* description: Performs a targeted AI scan on a specific area of an image.
* security:
* - bearerAuth: []
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* required:
* - image
* - cropArea
* - extractionType
* properties:
* image:
* type: string
* format: binary
* description: Image file to scan
* cropArea:
* type: string
* description: JSON string with x, y, width, height
* extractionType:
* type: string
* enum: [store_name, dates, item_details]
* description: Type of data to extract
* responses:
* 200:
* description: Extracted data from image area
* 400:
* description: Image file is required
* 401:
* description: Unauthorized
*/
router.post(
'/rescan-area',
aiUploadLimiter,
passport.authenticate('jwt', { session: false }),
uploadToDisk.single('image'),
validateRequest(rescanAreaSchema),
async (req, res, next: NextFunction) => {
try {
if (!req.file) {
return sendError(res, ErrorCode.BAD_REQUEST, 'Image file is required.', 400);
}
// validateRequest transforms the cropArea JSON string into an object in req.body.
// So we use it directly instead of JSON.parse().
const cropArea = req.body.cropArea;
const { extractionType } = req.body;
const { path, mimetype } = req.file;
req.log.debug(
{ extractionType, cropArea, filename: req.file.originalname },
'Rescan area requested',
);
const result = await aiService.extractTextFromImageArea(
path,
mimetype,
cropArea,
extractionType,
req.log,
);
sendSuccess(res, result);
} catch (error) {
next(error);
} finally {
await cleanupUploadedFile(req.file);
}
},
);
/* Catches errors from multer (e.g., file size, file filter) */
router.use(handleMulterError);
export default router;
|