gopichandra commited on
Commit
0bd0d08
·
verified ·
1 Parent(s): 005b66d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -91
app.py CHANGED
@@ -1,91 +1,107 @@
1
- from flask import Flask, render_template, send_from_directory
2
- from celery import Celery
3
- import pandas as pd
4
- from simple_salesforce import Salesforce
5
- import os
6
-
7
- # Salesforce credentials
8
- SALESFORCE_USERNAME = "venkatramana@sandbox.com"
9
- SALESFORCE_PASSWORD = "Seta12345@"
10
- SALESFORCE_SECURITY_TOKEN = "ZOnDC5se0y3CACNjNSsBWQPl"
11
-
12
- # Initialize Flask app
13
- app = Flask(__name__)
14
-
15
- # Initialize Celery
16
- celery = Celery(app.name, broker='redis://localhost:6379/0')
17
-
18
- # Salesforce connection
19
- def connect_to_salesforce():
20
- try:
21
- sf = Salesforce(username=SALESFORCE_USERNAME, password=SALESFORCE_PASSWORD, security_token=SALESFORCE_SECURITY_TOKEN)
22
- return sf
23
- except Exception as e:
24
- print(f"Error connecting to Salesforce: {e}")
25
- return None
26
-
27
- # Fetch quote line items from Salesforce
28
- def fetch_quote_line_items(sf):
29
- try:
30
- query = """
31
- SELECT Id, Product__c, Quantity__c, Price_c__c
32
- FROM Quote_Line_Item__c
33
- LIMIT 50
34
- """
35
- line_items = sf.query(query)
36
- return line_items['records']
37
- except Exception as e:
38
- print(f"Error fetching quote line items: {e}")
39
- return None
40
-
41
- # Fetch products and calculate totals
42
- def fetch_products():
43
- sf = connect_to_salesforce()
44
- if not sf:
45
- return []
46
-
47
- line_items = fetch_quote_line_items(sf)
48
- products = []
49
- for item in line_items:
50
- product = item.get('Product__c', 'N/A')
51
- quantity = item.get('Quantity__c', 'N/A')
52
- price = item.get('Price_c__c', 'N/A')
53
- total = float(quantity) * float(price) if quantity and price else 'N/A'
54
- products.append({
55
- 'Product': product,
56
- 'Quantity': quantity,
57
- 'Price': price,
58
- 'Total': total
59
- })
60
- return products
61
-
62
- # Save products to Excel
63
- def save_to_excel(products, file_path):
64
- df = pd.DataFrame(products)
65
- df.to_excel(file_path, index=False)
66
-
67
- # Celery task for Excel generation
68
- @celery.task
69
- def generate_excel_task():
70
- products = fetch_products()
71
- file_path = "products_data.xlsx"
72
- save_to_excel(products, file_path)
73
- print(f"Excel file generated at {file_path}")
74
-
75
- # Flask routes
76
- @app.route('/')
77
- def index():
78
- files = [f for f in os.listdir('.') if f.endswith('.xlsx')]
79
- return render_template('index.html', files=files)
80
-
81
- @app.route('/download/<filename>')
82
- def download_file(filename):
83
- return send_from_directory('.', filename)
84
-
85
- @app.route('/generate_excel')
86
- def generate_excel():
87
- generate_excel_task.delay() # Trigger Celery task
88
- return "Excel generation started!"
89
-
90
- if __name__ == '__main__':
91
- app.run(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import FileResponse
3
+ from fastapi.templating import Jinja2Templates
4
+ from fastapi.staticfiles import StaticFiles
5
+ from starlette.requests import Request
6
+ from celery import Celery
7
+ import pandas as pd
8
+ from simple_salesforce import Salesforce
9
+ import os
10
+
11
+ # Salesforce credentials
12
+ SALESFORCE_USERNAME = "venkatramana@sandbox.com"
13
+ SALESFORCE_PASSWORD = "Seta12345@"
14
+ SALESFORCE_SECURITY_TOKEN = "ZOnDC5se0y3CACNjNSsBWQPl"
15
+
16
+ # Initialize FastAPI app
17
+ app = FastAPI()
18
+
19
+ # Initialize Celery
20
+ celery = Celery("app", broker="redis://localhost:6379/0")
21
+
22
+ # Set up Jinja2 templates
23
+ templates = Jinja2Templates(directory="templates")
24
+
25
+ # Serve static files (if needed)
26
+ app.mount("/static", StaticFiles(directory="static"), name="static")
27
+
28
+ # Salesforce connection
29
+ def connect_to_salesforce():
30
+ try:
31
+ sf = Salesforce(
32
+ username=SALESFORCE_USERNAME,
33
+ password=SALESFORCE_PASSWORD,
34
+ security_token=SALESFORCE_SECURITY_TOKEN,
35
+ )
36
+ return sf
37
+ except Exception as e:
38
+ print(f"Error connecting to Salesforce: {e}")
39
+ return None
40
+
41
+ # Fetch quote line items from Salesforce
42
+ def fetch_quote_line_items(sf):
43
+ try:
44
+ query = """
45
+ SELECT Id, Product__c, Quantity__c, Price_c__c
46
+ FROM Quote_Line_Item__c
47
+ LIMIT 50
48
+ """
49
+ line_items = sf.query(query)
50
+ return line_items["records"]
51
+ except Exception as e:
52
+ print(f"Error fetching quote line items: {e}")
53
+ return None
54
+
55
+ # Fetch products and calculate totals
56
+ def fetch_products():
57
+ sf = connect_to_salesforce()
58
+ if not sf:
59
+ return []
60
+
61
+ line_items = fetch_quote_line_items(sf)
62
+ products = []
63
+ for item in line_items:
64
+ product = item.get("Product__c", "N/A")
65
+ quantity = item.get("Quantity__c", "N/A")
66
+ price = item.get("Price_c__c", "N/A")
67
+ total = float(quantity) * float(price) if quantity and price else "N/A"
68
+ products.append(
69
+ {
70
+ "Product": product,
71
+ "Quantity": quantity,
72
+ "Price": price,
73
+ "Total": total,
74
+ }
75
+ )
76
+ return products
77
+
78
+ # Save products to Excel
79
+ def save_to_excel(products, file_path):
80
+ df = pd.DataFrame(products)
81
+ df.to_excel(file_path, index=False)
82
+
83
+ # Celery task for Excel generation
84
+ @celery.task
85
+ def generate_excel_task():
86
+ products = fetch_products()
87
+ file_path = "products_data.xlsx"
88
+ save_to_excel(products, file_path)
89
+ print(f"Excel file generated at {file_path}")
90
+
91
+ # FastAPI route: Home page
92
+ @app.get("/")
93
+ async def index(request: Request):
94
+ files = [f for f in os.listdir(".") if f.endswith(".xlsx")]
95
+ return templates.TemplateResponse("index.html", {"request": request, "files": files})
96
+
97
+ # FastAPI route: Download file
98
+ @app.get("/download/{filename}")
99
+ async def download_file(filename: str):
100
+ file_path = os.path.join(".", filename)
101
+ return FileResponse(file_path, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
102
+
103
+ # FastAPI route: Generate Excel
104
+ @app.get("/generate_excel")
105
+ async def generate_excel():
106
+ generate_excel_task.delay() # Trigger Celery task
107
+ return {"message": "Excel generation started!"}