File size: 19,212 Bytes
cde4684
 
bcfae1d
cde4684
d152115
cde4684
d808a4a
9b7a78d
bcfae1d
cde4684
2b2cffb
 
d808a4a
38bb831
 
bcfae1d
 
2b2cffb
bcfae1d
2b2cffb
160060b
2b2cffb
160060b
 
2b2cffb
 
 
 
9d21491
1e90647
950f620
 
 
 
 
 
 
47eb0bc
 
 
950f620
 
 
 
 
 
 
 
 
 
 
d0c9194
950f620
 
d0c9194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d152115
 
 
 
 
 
 
 
 
9253f3c
9d21491
 
 
2b2cffb
9d21491
 
 
 
d152115
9d21491
 
d152115
9d21491
 
 
 
 
 
 
 
 
 
 
d152115
 
9d21491
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d152115
 
 
9d21491
 
 
d152115
 
788d071
9d21491
788d071
9d21491
 
788d071
 
9d21491
 
788d071
9d21491
 
788d071
9d21491
 
d152115
9d21491
 
d152115
9d21491
 
 
d152115
9d21491
 
 
 
 
 
 
 
 
d152115
 
 
9d21491
 
 
 
 
d152115
 
9b7a78d
9d21491
9b7a78d
9d21491
 
9b7a78d
 
9d21491
d152115
9d21491
 
 
 
 
2b2cffb
9d21491
 
d808a4a
9d21491
 
d808a4a
d152115
bcfae1d
9d21491
38bb831
9d21491
 
544f6ed
d152115
 
 
 
 
 
 
 
9d21491
d152115
9d21491
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0c9194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544f6ed
 
 
d0c9194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c0e1ac
bcfae1d
d152115
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
import os
import io
import json
import hashlib
from datetime import datetime, timedelta
from PIL import Image
import pytz
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import google.generativeai as genai
import firebase_admin
from firebase_admin import credentials, db, storage, auth
import pandas as pd
import requests
from urllib.parse import urlparse, unquote

app = Flask(__name__)
CORS(app)

# Firebase initialization
cred = credentials.Certificate('datingi-firebase-adminsdk-obe4r-d63a25b54e.json')
firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://datingi.firebaseio.com',
    'storageBucket': 'datingi.firebasestorage.app'
})

bucket = storage.bucket()
api_key = os.environ['Gemini']
FIREBASE_API_KEY = os.environ.get('FIREBASE_API_KEY')

# Add test account creation function
def create_test_accounts():
    try:
        # Create/admin2@test.com (Admin)
        try:
            admin_user = auth.create_user(
                email='rurumukamuri@gmail.com',
                password='ruvimbo1',
                name='Ruru',
                phone='0776076957'
            )
        except auth.EmailAlreadyExistsError:
            admin_user = auth.get_user_by_email('rurumukamuri@gmail.com')
        
        db.reference(f'users/{admin_user.uid}').set({
            'is_admin': True
        })

        print("Test accounts created/updated successfully")
    except Exception as e:
        print(f"Error creating test accounts: {str(e)}")

# Create test accounts when server starts
create_test_accounts()

# Helper functions
def configure_gemini():
    genai.configure(api_key=api_key)
    return genai.GenerativeModel('gemini-2.0-flash-thinking-exp')

def verify_token(token):
    try:
        decoded_token = auth.verify_id_token(token)
        return decoded_token['uid']
    except Exception:
        return None

def verify_admin(auth_header):
    if not auth_header or not auth_header.startswith('Bearer '):
        raise ValueError('Invalid token')

    token = auth_header.split(' ')[1]
    uid = verify_token(token)
    if not uid:
        raise PermissionError('Invalid user')

    user_ref = db.reference(f'users/{uid}')
    user_data = user_ref.get()
    if not user_data or not user_data.get('is_admin', False):
        raise PermissionError('Admin access required')

    return uid


# Product Categories
CATEGORIES = [
    'Masks',
    'Gloves',
    'Face Shields',
    'Protective Suits',
    'Sanitizers',
    'Disinfectants'
]

# Authentication Endpoints
@app.route('/api/auth/register', methods=['POST'])
def register():
    try:
        data = request.get_json()
        email = data.get('email')
        password = data.get('password')
        name = data.get('name')
        
        if not email or not password:
            return jsonify({'error': 'Email and password required'}), 400
            
        # Create user in Firebase Auth
        user = auth.create_user(
            email=email,
            password=password,
            display_name=name
        )
        
        # Create user profile in Realtime Database
        user_ref = db.reference(f'users/{user.uid}')
        user_data = {
            'email': email,
            'name': name,
            'created_at': datetime.now(pytz.UTC).isoformat(),
            'is_admin': False,
            'shipping_addresses': [],
            'phone': data.get('phone', '')
        }
        user_ref.set(user_data)
        
        # If there's a guest cart, transfer it to the user
        session_id = data.get('session_id')
        if session_id:
            guest_cart_ref = db.reference(f'carts/session_{session_id}')
            guest_cart = guest_cart_ref.get()
            if guest_cart:
                user_cart_ref = db.reference(f'carts/{user.uid}')
                user_cart_ref.set(guest_cart)
                guest_cart_ref.delete()
        
        return jsonify({
            'success': True,
            'uid': user.uid,
            'email': user.email,
            'name': user.display_name
        }), 201
        
    except Exception as e:
        return jsonify({'error': str(e)}), 400

@app.route('/api/auth/login', methods=['POST'])
def login():
    try:
        data = request.get_json()
        email = data.get('email')
        password = data.get('password')
        
        if not email or not password:
            return jsonify({'error': 'Email and password required'}), 400
        
        # Sign in with Firebase Admin SDK
        user = auth.get_user_by_email(email)
        
        # Get custom token for client authentication
        custom_token = auth.create_custom_token(user.uid)
        
        # Get user profile data
        user_ref = db.reference(f'users/{user.uid}')
        user_data = user_ref.get()
        
        # Transfer guest cart if exists
        session_id = data.get('session_id')
        if session_id:
            guest_cart_ref = db.reference(f'carts/session_{session_id}')
            guest_cart = guest_cart_ref.get()
            if guest_cart:
                user_cart_ref = db.reference(f'carts/{user.uid}')
                user_cart_ref.set(guest_cart)
                guest_cart_ref.delete()
        
        return jsonify({
            'success': True,
            'token': custom_token,
            'uid': user.uid,
            'email': user.email,
            'name': user.display_name,
            'is_admin': user_data.get('is_admin', False)
        })
        
    except Exception as e:
        return jsonify({'error': 'Invalid email or password'}), 401

@app.route('/api/auth/password-reset', methods=['POST'])
def request_password_reset():
    try:
        data = request.get_json()
        email = data.get('email')
        
        if not email:
            return jsonify({'error': 'Email required'}), 400
            
        # Generate password reset link
        link = auth.generate_password_reset_link(email)
        
        # In a production environment, you would typically send this link via email
        # For this example, we'll just return it
        return jsonify({
            'success': True,
            'reset_link': link
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 400

@app.route('/api/user/profile', methods=['GET', 'PUT'])
def user_profile():
    try:
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({'error': 'Authorization required'}), 401
            
        uid = verify_token(auth_header.split(' ')[1])
        if not uid:
            return jsonify({'error': 'Invalid token'}), 401
            
        user_ref = db.reference(f'users/{uid}')
        
        if request.method == 'GET':
            user_data = user_ref.get()
            return jsonify(user_data)
            
        elif request.method == 'PUT':
            data = request.get_json()
            updates = {}
            
            # Allow updating specific fields
            if 'name' in data:
                updates['name'] = data['name']
                auth.update_user(uid, display_name=data['name'])
                
            if 'phone' in data:
                updates['phone'] = data['phone']
                
            if 'shipping_addresses' in data:
                updates['shipping_addresses'] = data['shipping_addresses']
                
            if updates:
                user_ref.update(updates)
                
            return jsonify({
                'success': True,
                'updated_fields': list(updates.keys())
            })
            
    except Exception as e:
        return jsonify({'error': str(e)}), 

# Product Management Endpoints
@app.route('/api/admin/products', methods=['POST'])
def create_product():
    try:
        verify_admin(request.headers.get('Authorization', ''))
        
        if 'image' not in request.files:
            return jsonify({'error': 'No image file uploaded'}), 400
            
        file = request.files['image']
        name = request.form.get('name')
        category = request.form.get('category')
        price = float(request.form.get('price'))
        description = request.form.get('description')
        stock = int(request.form.get('stock', 0))
        
        if category not in CATEGORIES:
            return jsonify({'error': 'Invalid category'}), 400
            
        # Upload image
        image_bytes = file.read()
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        file_hash = hashlib.md5(image_bytes).hexdigest()
        blob = bucket.blob(f'products/{timestamp}_{file_hash}.jpg')
        blob.upload_from_string(image_bytes, content_type='image/jpeg')
        image_url = blob.public_url
        
        # Create product
        product_ref = db.reference('products').push({
            'name': name,
            'category': category,
            'price': price,
            'description': description,
            'stock': stock,
            'image_url': image_url,
            'created_at': datetime.now(pytz.UTC).isoformat(),
            'active': True
        })
        
        return jsonify({
            'success': True,
            'product_id': product_ref.key
        }), 201
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/products/<string:product_id>', methods=['PUT'])
def update_product(product_id):
    try:
        verify_admin(request.headers.get('Authorization', ''))
        
        updates = {}
        if 'name' in request.form:
            updates['name'] = request.form['name']
        if 'category' in request.form and request.form['category'] in CATEGORIES:
            updates['category'] = request.form['category']
        if 'price' in request.form:
            updates['price'] = float(request.form['price'])
        if 'description' in request.form:
            updates['description'] = request.form['description']
        if 'stock' in request.form:
            updates['stock'] = int(request.form['stock'])
        if 'active' in request.form:
            updates['active'] = request.form['active'].lower() == 'true'
            
        if 'image' in request.files:
            file = request.files['image']
            image_bytes = file.read()
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            file_hash = hashlib.md5(image_bytes).hexdigest()
            blob = bucket.blob(f'products/{timestamp}_{file_hash}.jpg')
            blob.upload_from_string(image_bytes, content_type='image/jpeg')
            updates['image_url'] = blob.public_url
            
        db.reference(f'products/{product_id}').update(updates)
        
        return jsonify({'success': True})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# Shopping Cart and Order Management
@app.route('/api/cart/add', methods=['POST'])
def add_to_cart():
    try:
        data = request.get_json()
        product_id = data['product_id']
        quantity = int(data['quantity'])
        
        # Get user ID if logged in
        auth_header = request.headers.get('Authorization')
        uid = verify_token(auth_header.split(' ')[1]) if auth_header else None
        
        # Use session ID for non-logged in users
        session_id = data.get('session_id')
        if not uid and not session_id:
            return jsonify({'error': 'Either login or provide session_id'}), 400
            
        cart_id = uid if uid else f'session_{session_id}'
        cart_ref = db.reference(f'carts/{cart_id}')
        
        # Check product availability
        product = db.reference(f'products/{product_id}').get()
        if not product:
            return jsonify({'error': 'Product not found'}), 404
        if not product.get('active', False):
            return jsonify({'error': 'Product not available'}), 400
        if product.get('stock', 0) < quantity:
            return jsonify({'error': 'Insufficient stock'}), 400
            
        # Update cart
        cart_item = cart_ref.child(product_id).get() or {'quantity': 0}
        new_quantity = cart_item['quantity'] + quantity
        
        cart_ref.child(product_id).set({
            'quantity': new_quantity,
            'price': product['price'],
            'name': product['name']
        })
        
        return jsonify({'success': True})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/orders', methods=['POST'])
def create_order():
    try:
        data = request.get_json()
        auth_header = request.headers.get('Authorization')
        uid = verify_token(auth_header.split(' ')[1]) if auth_header else None
        
        cart_id = uid if uid else f'session_{data["session_id"]}'
        cart_ref = db.reference(f'carts/{cart_id}')
        cart = cart_ref.get()
        
        if not cart:
            return jsonify({'error': 'Cart is empty'}), 400
            
        # Validate stock and calculate total
        total = 0
        items = []
        for product_id, item in cart.items():
            product = db.reference(f'products/{product_id}').get()
            if not product or not product.get('active', False):
                return jsonify({'error': f'Product {product_id} not available'}), 400
            if product['stock'] < item['quantity']:
                return jsonify({'error': f'Insufficient stock for {product["name"]}'}), 400
                
            total += item['quantity'] * product['price']
            items.append({
                'product_id': product_id,
                'quantity': item['quantity'],
                'price': product['price'],
                'name': product['name']
            })
            
            # Update stock
            db.reference(f'products/{product_id}').update({
                'stock': product['stock'] - item['quantity']
            })
            
        # Create order
        order_ref = db.reference('orders').push({
            'user_id': uid,
            'session_id': None if uid else data.get('session_id'),
            'items': items,
            'total': total,
            'status': 'pending',
            'shipping_address': data.get('shipping_address'),
            'contact_email': data.get('contact_email'),
            'created_at': datetime.now(pytz.UTC).isoformat()
        })
        
        # Clear cart
        cart_ref.delete()
        
        return jsonify({
            'success': True,
            'order_id': order_ref.key
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# AI Reporting
@app.route('/api/admin/reports', methods=['POST'])
def generate_report():
    try:
        verify_admin(request.headers.get('Authorization', ''))
        data = request.get_json()
        start_date = datetime.fromisoformat(data['start_date'])
        end_date = datetime.fromisoformat(data['end_date'])
        
        # Get orders within date range
        orders_ref = db.reference('orders')
        orders = orders_ref.get() or {}
        
        filtered_orders = {
            k: v for k, v in orders.items()
            if start_date <= datetime.fromisoformat(v['created_at']) <= end_date
        }
        
        prompt = f"""Analyze this e-commerce data for medical PPE products and generate a comprehensive business report.
        Focus on:
        1. Total sales and revenue
        2. Popular products and categories
        3. Customer behavior patterns
        4. Stock management recommendations
        5. Market trends and insights
        
        Data period: {start_date.date()} to {end_date.date()}"""
        
        model = configure_gemini()
        response = model.generate_content([prompt, json.dumps(filtered_orders)])
        
        return jsonify({
            'report': response.text,
            'data': {
                'total_orders': len(filtered_orders),
                'total_revenue': sum(order['total'] for order in filtered_orders.values())
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# Product Browsing
@app.route('/api/products', methods=['GET'])
def get_products():
    try:
        category = request.args.get('category')
        search = request.args.get('search', '').lower()
        
        products_ref = db.reference('products')
        products = products_ref.get() or {}
        
        filtered_products = []
        for product_id, product in products.items():
            if not product.get('active', False):
                continue
            if category and product['category'] != category:
                continue
            if search and search not in product['name'].lower():
                continue
                
            filtered_products.append({
                'id': product_id,
                **product
            })
            
        return jsonify(filtered_products)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# User Order History
@app.route('/api/user/orders', methods=['GET'])
def get_user_orders():
    try:
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({'error': 'Authorization required'}), 401
            
        uid = verify_token(auth_header.split(' ')[1])
        if not uid:
            return jsonify({'error': 'Invalid token'}), 401
            
        orders_ref = db.reference('orders')
        orders = orders_ref.order_by_child('user_id').equal_to(uid).get() or {}
        
        return jsonify([{
            'id': order_id,
            **order_data
        } for order_id, order_data in orders.items()])
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# Admin Dashboard Data
@app.route('/api/admin/dashboard', methods=['GET'])
def get_admin_dashboard():
    try:
        verify_admin(request.headers.get('Authorization', ''))
        
        # Get recent orders
        orders_ref = db.reference('orders')
        recent_orders = orders_ref.order_by_child('created_at').limit_to_last(10).get() or {}
        
        # Get low stock products
        products_ref = db.reference('products')
        products = products_ref.get() or {}
        low_stock = [
            {'id': pid, **p}
            for pid, p in products.items()
            if p.get('active', False) and p.get('stock', 0) < 10
        ]
        
        # Calculate statistics
        total_revenue = sum(order['total'] for order in recent_orders.values())
        total_orders = len(recent_orders)
        
        return jsonify({
            'recent_orders': recent_orders,
            'low_stock_products': low_stock,
            'statistics': {
                'total_revenue': total_revenue,
                'total_orders': total_orders,
                'total_products': len(products),
                'low_stock_count': len(low_stock)
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

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