File size: 7,915 Bytes
8a4a66c
de37515
 
 
 
 
 
 
 
 
 
 
1e668b9
de37515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e668b9
de37515
8a4a66c
 
 
 
 
 
 
 
 
 
 
 
9f57ab7
 
b387830
9f57ab7
8a4a66c
9f57ab7
 
 
 
 
 
 
 
 
 
8a4a66c
1e668b9
8a4a66c
 
 
 
1e668b9
8a4a66c
 
 
 
1e668b9
8a4a66c
 
 
 
 
b387830
de37515
 
 
 
 
 
 
 
8a4a66c
9f57ab7
 
0d2fb64
 
9f57ab7
 
 
 
 
 
 
 
 
 
 
 
 
8a4a66c
9f57ab7
0d2fb64
8a4a66c
 
 
 
1e668b9
8a4a66c
1e668b9
8a4a66c
9f57ab7
8a4a66c
 
0d2fb64
9f57ab7
8a4a66c
0d2fb64
9f57ab7
 
0d2fb64
9f57ab7
 
de37515
 
 
 
 
 
1e668b9
 
9f57ab7
 
 
de37515
 
9f57ab7
 
46a4f8b
f7faab4
 
 
 
 
46a4f8b
 
f7faab4
 
46a4f8b
f7faab4
 
46a4f8b
f7faab4
 
 
9f57ab7
46a4f8b
9f57ab7
f7faab4
9f57ab7
46a4f8b
f7faab4
 
 
 
 
46a4f8b
 
f7faab4
 
46a4f8b
f7faab4
 
46a4f8b
f7faab4
 
 
de37515
46a4f8b
9f57ab7
f7faab4
9f57ab7
 
46a4f8b
de37515
9f57ab7
 
de37515
f7faab4
de37515
b189fed
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
from flask import Flask, render_template, request, jsonify, send_from_directory
from simple_salesforce import Salesforce
from dotenv import load_dotenv
import os
import logging
import uuid
from datetime import datetime

# Load environment variables
load_dotenv()

# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

app = Flask(__name__, template_folder='templates', static_folder='static')

# Salesforce connection function
def get_salesforce_connection():
    try:
        sf = Salesforce(
            username=os.getenv('SFDC_USERNAME'),
            password=os.getenv('SFDC_PASSWORD'),
            security_token=os.getenv('SFDC_SECURITY_TOKEN'),
            domain=os.getenv('SFDC_DOMAIN', 'login')
        )
        logger.info("Successfully connected to Salesforce")
        return sf
    except Exception as e:
        logger.error(f"Error connecting to Salesforce: {str(e)}")
        return None

# Initialize Salesforce connection
sf = get_salesforce_connection()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/static/<path:filename>')
def static_files(filename):
    return send_from_directory(app.static_folder, filename)

@app.route('/get_ingredients', methods=['POST'])
def get_ingredients():
    global sf
    if not sf:
        sf = get_salesforce_connection()
        if not sf:
            return jsonify({"error": "Unable to connect to Salesforce"}), 500

    data = request.json
    dietary_preference = data.get('dietary_preference', 'both').lower()
    print(f"Fetching ingredients for dietary preference: {dietary_preference}")  # Log the request

    try:
        category_map = {
            'vegetarian': 'Veg',
            'non-vegetarian': 'Non-Veg',
            'chicken': 'Non-Veg',
            'beef': 'Non-Veg',
            'lamb': 'Non-Veg',
            'both': 'both'
        }
        category = category_map.get(dietary_preference, 'both')
        soql = f"SELECT Name, Image_URL__c, Category__c FROM Sector_Detail__c WHERE Category__c = '{category}'"
        soql += " LIMIT 200"
        logger.debug(f"Executing SOQL query for Sector_Detail__c: {soql}")
        result = sf.query(soql)
        ingredients = [
            {
                "name": record['Name'],
                "image_url": record.get('Image_URL__c', ''),
                "category": record.get('Category__c', '')
            }
            for record in result['records'] if 'Name' in record
        ]
        logger.debug(f"Fetched {len(ingredients)} ingredients from Sector_Detail__c")
        return jsonify({"ingredients": ingredients})
    except Exception as e:
        logger.error(f"Failed to fetch ingredients: {str(e)}")
        return jsonify({"error": f"Failed to fetch ingredients from Salesforce: {str(e)}"}), 500


@app.route('/get_menu_items', methods=['POST'])
def get_menu_items():
    global sf
    if not sf:
        sf = get_salesforce_connection()
        if not sf:
            return jsonify({"error": "Unable to connect to Salesforce"}), 500

    data = request.json
    ingredient_names = data.get('ingredient_names', '')
    category = data.get('category', '')

    try:
        soql = "SELECT Name, Description__c, Image1__c, Image2__c, Price__c, Section__c, Veg_NonVeg__c, Total_Ordered__c FROM Menu_Item__c"
        conditions = []
        if ingredient_names:
            words = ingredient_names.split()
            name_conditions = [f"Name LIKE '%{word}%'" for word in words]
            conditions.append(f"({' OR '.join(name_conditions)})")
        if category:
            if category.lower() == 'vegetarian':
                conditions.append("Veg_NonVeg__c = 'Vegetarian'")
            elif category.lower() == 'non-vegetarian':
                conditions.append("Veg_NonVeg__c = 'Non-Vegetarian'")
        if conditions:
            soql += " WHERE " + " AND ".join(conditions)
        soql += " LIMIT 200"
        logger.debug(f"Executing SOQL query for Menu_Item__c: {soql}")
        result = sf.query(soql)
        menu_items = [
            {
                "name": record['Name'],
                "description": record.get('Description__c', 'No description available'),
                "image_url": record.get('Image1__c', '') or record.get('Image2__c', ''),
                "price": record.get('Price__c', 0.0),
                "section": record.get('Section__c', ''),
                "veg_nonveg": record.get('Veg_NonVeg__c', ''),
                "total_ordered": record.get('Total_Ordered__c', 0)
            }
            for record in result['records'] if 'Name' in record
        ]
        logger.debug(f"Fetched {len(menu_items)} menu items")
        return jsonify({"menu_items": menu_items})
    except Exception as e:
        logger.error(f"Failed to fetch menu items: {str(e)}")
        return jsonify({"error": f"Failed to fetch menu items from Salesforce: {str(e)}"}), 500

@app.route('/submit_customization_ingredients', methods=['POST'])
def submit_customization_ingredients():
    global sf
    if not sf:
        sf = get_salesforce_connection()
        if not sf:
            return jsonify({"error": "Unable to connect to Salesforce"}), 500

    data = request.json
    items = data.get('items', [])
    menu_item = data.get('menu_item', {})
    ingredients = data.get('ingredients', [])
    instructions = data.get('instructions', '')

    try:
        if items:  # Cart submission
            for item in items:
                ingredient_names = ', '.join(i['name'] for i in item.get('ingredients', [])) if item.get('ingredients') else ''
                base_price = item.get('price', 0.0)
                quantity = 1
                addons_price = 0
                total_price = (base_price * quantity) + addons_price

                sf.Cart_Item__c.create({
                    'Name': item['name'],
                    'Base_Price__c': base_price,
                    'Quantity__c': quantity,
                    'Add_Ons__c': ingredient_names,
                    'Add_Ons_Price__c': addons_price,
                    'Price__c': total_price,
                    'Image1__c': item.get('image_url', ''),
                    'Instructions__c': item.get('instructions', ''),
                    'Category__c': item.get('veg_nonveg', ''),
                    'Section__c': item.get('section', '')
                })
            logger.debug(f"Submitted {len(items)} items to Cart_Item__c")
            return jsonify({"success": True, "message": f"Submitted {len(items)} items"})

        elif menu_item:  # Single item customization
            ingredient_names = ', '.join(i['name'] for i in ingredients) if ingredients else ''
            base_price = menu_item.get('price', 0.0)
            quantity = 1
            addons_price = 0
            total_price = (base_price * quantity) + addons_price

            sf.Cart_Item__c.create({
                'Name': menu_item['name'],
                'Base_Price__c': base_price,
                'Quantity__c': quantity,
                'Add_Ons__c': ingredient_names,
                'Add_Ons_Price__c': addons_price,
                'Price__c': total_price,
                'Image1__c': menu_item.get('image_url', ''),
                'Instructions__c': instructions,
                'Category__c': menu_item.get('veg_nonveg', ''),
                'Section__c': menu_item.get('section', '')
            })
            logger.debug(f"Submitted customization for {menu_item['name']} to Cart_Item__c")
            return jsonify({"success": True, "message": "Customization submitted"})

        else:
            return jsonify({"error": "No items or menu item provided"}), 400

    except Exception as e:
        logger.error(f"Failed to submit: {str(e)}")
        return jsonify({"error": f"Failed to submit: {str(e)}"}), 500


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=7860)