Spaces:
Sleeping
Sleeping
Download backend/src/services/diningService.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/diningService.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/services/diningService.js
-
curl -L -o diningService.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/services/diningService.js
20.4 kB
| 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(); |