Spaces:
Sleeping
Sleeping
File size: 20,448 Bytes
0b355ec | 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 | const axios = require('axios');
const cheerio = require('cheerio');
const logger = require('../utils/logger');
const DiningMenu = require('../models/DiningMenu');
class DiningService {
constructor() {
this.baseApiUrl = 'https://uga.api.nutrislice.com/menu/api/weeks/school';
this.baseWebUrl = 'https://uga.nutrislice.com';
this.diningLocations = [
{ name: 'Bolton Dining Commons', slug: 'bolton', id: 'bolton-dining-commons' },
{ name: 'Snelling Dining Commons', slug: 'snelling', id: 'snelling-dining-commons' },
{ name: 'Village Summit Dining Hall', slug: 'village', id: 'village-summit' },
{ name: 'Niche Dining Hall', slug: 'niche', id: 'niche' },
{ name: 'Fresh Food Company', slug: 'fresh', id: 'fresh-food-company' }
];
this.mealTypes = ['breakfast', 'lunch', 'dinner'];
}
async getMenuForLocation(locationSlug, date = new Date()) {
const location = this.diningLocations.find(loc => loc.slug === locationSlug);
if (!location) {
throw new Error(`Unknown dining location: ${locationSlug}`);
}
try {
// Check database first
const cachedMenu = await DiningMenu.findByLocationAndDate(locationSlug, date);
if (cachedMenu) {
logger.info(`Serving cached menu for ${location.name} from database`);
return this.formatMenuResponse(cachedMenu);
}
// If not in database, fetch from source and cache
logger.info(`Menu not in cache, fetching fresh data for ${location.name}`);
const freshMenu = await this.fetchAndCacheMenu(location, date);
return freshMenu;
} catch (error) {
logger.error(`Failed to get menu for ${location.name}:`, error);
return this.getFallbackMenu(location, date);
}
}
async fetchAndCacheMenu(location, date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
let menuData = null;
let source = 'fallback';
try {
// Try multiple possible API endpoints
const possibleIds = [location.id, location.slug, location.name.toLowerCase().replace(/\s+/g, '-')];
for (const id of possibleIds) {
for (const mealType of this.mealTypes) {
try {
const apiUrl = `${this.baseApiUrl}/${id}/menu-type/${mealType}/${year}/${month}/${day}/?format=json`;
const response = await axios.get(apiUrl, { timeout: 10000 });
if (response.data && !response.data.detail) {
logger.info(`Successfully fetched menu from API for ${location.name} - ${mealType}`, { url: apiUrl });
menuData = this.parseNutrisliceApiResponse(response.data, location, mealType, date);
source = 'nutrislice-api';
break;
}
} catch (error) {
continue;
}
}
if (menuData) break;
}
// If API fails, try web scraping
if (!menuData) {
logger.info(`API failed for ${location.name}, attempting web scraping`);
menuData = await this.scrapeMenuFromWeb(location, date);
source = 'web-scraping';
}
} catch (error) {
logger.error(`Failed to fetch fresh menu for ${location.name}:`, error);
}
// Use fallback if no data found
if (!menuData) {
menuData = this.getFallbackMenu(location, date);
source = 'fallback';
}
// Cache the menu in database
try {
await this.cacheMenuInDatabase(location, date, menuData, source);
} catch (error) {
logger.error(`Failed to cache menu for ${location.name}:`, error);
}
return menuData;
}
async getAllMenus(date = new Date()) {
const menus = {};
await Promise.all(
this.diningLocations.map(async (location) => {
try {
menus[location.slug] = await this.getMenuForLocation(location.slug, date);
} catch (error) {
logger.error(`Failed to fetch menu for ${location.name}:`, error);
menus[location.slug] = this.getFallbackMenu(location, date);
}
})
);
return menus;
}
parseNutrisliceApiResponse(data, location, mealType, date) {
try {
const menu = {
location: location.name,
slug: location.slug,
date: date.toISOString().split('T')[0],
mealType,
lastUpdated: new Date(),
items: []
};
if (data.menu_items) {
menu.items = data.menu_items.map(item => ({
name: item.text,
description: item.description || '',
station: item.food_category || 'Main',
dietaryInfo: item.icons || [],
nutritionInfo: item.nutrition_details || {},
allergens: item.allergen_details || [],
price: item.price || null
}));
}
return menu;
} catch (error) {
logger.error('Error parsing Nutrislice API response:', error);
return this.getFallbackMenu(location, date);
}
}
async scrapeMenuFromWeb(location, date) {
try {
const dateStr = date.toISOString().split('T')[0];
const webUrl = `${this.baseWebUrl}/menu/${location.slug}/${dateStr}`;
const response = await axios.get(webUrl, {
timeout: 15000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
const $ = cheerio.load(response.data);
const menu = {
location: location.name,
slug: location.slug,
date: dateStr,
mealType: 'all',
lastUpdated: new Date(),
items: []
};
// Extract menu items from the page
$('.menu-item, .food-item, .meal-item').each((index, element) => {
const $item = $(element);
const name = $item.find('.item-name, .food-name, h3, h4').first().text().trim();
const description = $item.find('.item-description, .description').text().trim();
const station = $item.closest('.station, .category').find('.station-name, .category-name').text().trim() || 'Main';
if (name) {
menu.items.push({
name,
description,
station,
dietaryInfo: [],
nutritionInfo: {},
allergens: [],
price: null
});
}
});
logger.info(`Web scraping successful for ${location.name}, found ${menu.items.length} items`);
return menu;
} catch (error) {
logger.error(`Web scraping failed for ${location.name}:`, error);
return this.getFallbackMenu(location, date);
}
}
getFallbackMenu(location, date) {
logger.info(`Using fallback menu for ${location.name}`);
return {
location: location.name,
slug: location.slug,
date: date.toISOString().split('T')[0],
mealType: 'all',
lastUpdated: new Date(),
items: [
{
name: 'Menu information temporarily unavailable',
description: 'Please check the UGA Dining website or visit the dining hall for current menu information.',
station: 'Information',
dietaryInfo: [],
nutritionInfo: {},
allergens: [],
price: null
}
],
error: 'Unable to fetch current menu data'
};
}
async searchMenuItems(query, date = new Date()) {
try {
// Search in database first
const results = await DiningMenu.searchItems(query, date);
if (results.length > 0) {
return results.map(result => ({
...result.item,
location: result.location.name,
locationSlug: result.location.slug,
date: result.date
}));
}
// Fallback to live search if no cached data
const allMenus = await this.getAllMenus(date);
const fallbackResults = [];
Object.values(allMenus).forEach(menu => {
if (menu.items) {
menu.items.forEach(item => {
if (item.name.toLowerCase().includes(query.toLowerCase()) ||
item.description.toLowerCase().includes(query.toLowerCase()) ||
item.station.toLowerCase().includes(query.toLowerCase())) {
fallbackResults.push({
...item,
location: menu.location,
locationSlug: menu.slug
});
}
});
}
});
return fallbackResults;
} catch (error) {
logger.error('Error searching menu items:', error);
return [];
}
}
getDiningHours() {
return {
'bolton': {
name: 'Bolton Dining Commons',
hours: {
monday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
tuesday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
wednesday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
thursday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
friday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
saturday: { brunch: '10:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' },
sunday: { brunch: '10:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' }
}
},
'snelling': {
name: 'Snelling Dining Commons',
hours: {
monday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
tuesday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
wednesday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
thursday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
friday: { breakfast: '7:00 AM - 10:00 AM', lunch: '10:30 AM - 2:30 PM', dinner: '5:00 PM - 8:00 PM' },
saturday: { brunch: '10:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' },
sunday: { brunch: '10:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' }
}
},
'village': {
name: 'Village Summit Dining Hall',
hours: {
monday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 9:00 PM' },
tuesday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 9:00 PM' },
wednesday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 9:00 PM' },
thursday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 9:00 PM' },
friday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 9:00 PM' },
saturday: { closed: true },
sunday: { dinner: '5:00 PM - 9:00 PM' }
}
},
'niche': {
name: 'Niche Dining Hall',
hours: {
monday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' },
tuesday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' },
wednesday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' },
thursday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' },
friday: { lunch: '11:00 AM - 2:00 PM', dinner: '5:00 PM - 8:00 PM' },
saturday: { closed: true },
sunday: { dinner: '5:00 PM - 8:00 PM' }
}
},
'fresh': {
name: 'Fresh Food Company',
hours: {
monday: { continuous: '7:00 AM - 10:00 PM' },
tuesday: { continuous: '7:00 AM - 10:00 PM' },
wednesday: { continuous: '7:00 AM - 10:00 PM' },
thursday: { continuous: '7:00 AM - 10:00 PM' },
friday: { continuous: '7:00 AM - 8:00 PM' },
saturday: { continuous: '10:00 AM - 8:00 PM' },
sunday: { continuous: '10:00 AM - 10:00 PM' }
}
}
};
}
// Database helper methods
async cacheMenuInDatabase(location, date, menuData, source = 'unknown') {
try {
const menuDoc = new DiningMenu({
location: {
name: location.name,
slug: location.slug,
id: location.id
},
date: date,
mealTypes: this.extractMealTypes(menuData),
items: this.formatItemsForDatabase(menuData.items || []),
metadata: {
source: source,
lastUpdated: new Date()
}
});
await menuDoc.save();
logger.info(`Successfully cached menu for ${location.name} in database`);
return menuDoc;
} catch (error) {
if (error.code === 11000) {
// Duplicate key error - update existing
return await DiningMenu.findOneAndUpdate(
{ 'location.slug': location.slug, dateString: date.toISOString().split('T')[0] },
{
items: this.formatItemsForDatabase(menuData.items || []),
mealTypes: this.extractMealTypes(menuData),
'metadata.source': source,
'metadata.lastUpdated': new Date()
},
{ new: true }
);
}
throw error;
}
}
formatMenuResponse(diningMenu) {
return {
location: diningMenu.location.name,
slug: diningMenu.location.slug,
date: diningMenu.dateString,
mealTypes: diningMenu.mealTypes,
lastUpdated: diningMenu.metadata.lastUpdated,
items: diningMenu.items.map(item => ({
name: item.name,
description: item.description,
station: item.station,
dietaryInfo: item.dietaryInfo,
nutritionInfo: item.nutritionInfo,
allergens: item.allergens,
price: item.price,
availability: item.availability
})),
source: diningMenu.metadata.source
};
}
formatItemsForDatabase(items) {
return items.map(item => ({
name: item.name || '',
description: item.description || '',
station: item.station || 'Main',
dietaryInfo: this.parseDietaryInfo(item.dietaryInfo || []),
nutritionInfo: item.nutritionInfo || {},
allergens: this.parseAllergens(item.allergens || []),
price: item.price || null,
availability: {
breakfast: item.mealType === 'breakfast' || item.availability?.breakfast || false,
lunch: item.mealType === 'lunch' || item.availability?.lunch || false,
dinner: item.mealType === 'dinner' || item.availability?.dinner || false,
lateNight: item.availability?.lateNight || false
}
}));
}
extractMealTypes(menuData) {
if (menuData.mealType && menuData.mealType !== 'all') {
return [menuData.mealType];
}
return ['lunch']; // default
}
parseDietaryInfo(dietaryInfo) {
const validDietaryInfo = ['vegan', 'vegetarian', 'gluten-free', 'dairy-free', 'nut-free', 'halal', 'kosher', 'heart-healthy'];
return dietaryInfo.filter(info => validDietaryInfo.includes(info.toLowerCase()));
}
parseAllergens(allergens) {
const validAllergens = ['milk', 'eggs', 'fish', 'shellfish', 'tree-nuts', 'peanuts', 'wheat', 'soybeans', 'sesame'];
return allergens.filter(allergen => validAllergens.includes(allergen.toLowerCase()));
}
// Daily indexing methods
async indexAllMenusForDate(date = new Date()) {
logger.info(`Starting daily menu indexing for ${date.toISOString().split('T')[0]}`);
const results = [];
for (const location of this.diningLocations) {
try {
const menu = await this.fetchAndCacheMenu(location, date);
results.push({
location: location.name,
success: true,
itemCount: menu.items?.length || 0
});
} catch (error) {
logger.error(`Failed to index menu for ${location.name}:`, error);
results.push({
location: location.name,
success: false,
error: error.message
});
}
}
logger.info(`Daily menu indexing completed. Results:`, results);
return results;
}
async cleanupOldMenus(daysToKeep = 7) {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
try {
const result = await DiningMenu.deleteMany({
date: { $lt: cutoffDate }
});
logger.info(`Cleaned up ${result.deletedCount} old menu entries older than ${daysToKeep} days`);
return result.deletedCount;
} catch (error) {
logger.error('Failed to cleanup old menus:', error);
return 0;
}
}
// Dietary filtering methods
applyDietaryFilters(items, filters) {
return items.filter(item => {
// Filter by dietary requirements
if (filters.dietaryInfo && filters.dietaryInfo.length > 0) {
const hasRequiredDietary = filters.dietaryInfo.every(diet =>
item.dietaryInfo && item.dietaryInfo.includes(diet)
);
if (!hasRequiredDietary) return false;
}
// Exclude allergens
if (filters.excludeAllergens && filters.excludeAllergens.length > 0) {
const hasExcludedAllergen = filters.excludeAllergens.some(allergen =>
item.allergens && item.allergens.includes(allergen)
);
if (hasExcludedAllergen) return false;
}
// Filter by station
if (filters.station) {
if (!item.station.toLowerCase().includes(filters.station.toLowerCase())) {
return false;
}
}
// Filter by meal type
if (filters.mealType) {
if (!item.availability || !item.availability[filters.mealType]) {
return false;
}
}
return true;
});
}
async getDietarySummaryByLocation(date = new Date()) {
try {
const menus = await DiningMenu.findByDate(date);
const summary = {};
for (const menu of menus) {
const locationSummary = {
location: menu.location.name,
slug: menu.location.slug,
totalItems: menu.items.length,
dietaryOptions: {
vegan: 0,
vegetarian: 0,
'gluten-free': 0,
'dairy-free': 0,
'nut-free': 0,
halal: 0,
kosher: 0,
'heart-healthy': 0
},
allergenCounts: {
milk: 0,
eggs: 0,
fish: 0,
shellfish: 0,
'tree-nuts': 0,
peanuts: 0,
wheat: 0,
soybeans: 0,
sesame: 0
},
stationCounts: {}
};
// Count dietary options and allergens
menu.items.forEach(item => {
// Count dietary options
if (item.dietaryInfo) {
item.dietaryInfo.forEach(diet => {
if (locationSummary.dietaryOptions[diet] !== undefined) {
locationSummary.dietaryOptions[diet]++;
}
});
}
// Count allergens
if (item.allergens) {
item.allergens.forEach(allergen => {
if (locationSummary.allergenCounts[allergen] !== undefined) {
locationSummary.allergenCounts[allergen]++;
}
});
}
// Count by station
if (item.station) {
locationSummary.stationCounts[item.station] =
(locationSummary.stationCounts[item.station] || 0) + 1;
}
});
summary[menu.location.slug] = locationSummary;
}
return summary;
} catch (error) {
logger.error('Failed to get dietary summary:', error);
return {};
}
}
async getMenusByDietaryRestriction(dietaryRestrictions, date = new Date()) {
try {
const menus = await DiningMenu.findByDate(date);
const filteredMenus = {};
for (const menu of menus) {
const filteredItems = this.applyDietaryFilters(menu.items, {
dietaryInfo: dietaryRestrictions,
excludeAllergens: [],
station: null,
mealType: null
});
if (filteredItems.length > 0) {
filteredMenus[menu.location.slug] = {
...this.formatMenuResponse(menu),
items: filteredItems,
originalItemCount: menu.items.length,
filteredItemCount: filteredItems.length
};
}
}
return filteredMenus;
} catch (error) {
logger.error('Failed to get menus by dietary restriction:', error);
return {};
}
}
}
module.exports = new DiningService(); |