-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
315 lines (239 loc) · 9.75 KB
/
Copy pathapp.py
File metadata and controls
315 lines (239 loc) · 9.75 KB
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
from flask import Flask, render_template, redirect, url_for, request, Response
from pathlib import Path
from db import db, initialize_database
from models import Product, Customer, Category, Order, ProductOrder
from sqlalchemy import select
from datetime import datetime as dt
from routers import api_bp
import csv
import io
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///store.db"
app.instance_path = Path("./databases").resolve()
db.init_app(app)
with app.app_context():
initialize_database(Product, Category, Customer, Order, ProductOrder)
app.register_blueprint(api_bp, url_prefix="/api")
# Routes
@app.route("/")
def home():
try:
product_count = db.session.execute(db.select(db.func.count(Product.id))).scalar_one()
category_count = db.session.execute(db.select(db.func.count(Category.id))).scalar_one()
customer_count = db.session.execute(db.select(db.func.count(Customer.id))).scalar_one()
order_count = db.session.execute(db.select(db.func.count(Order.id))).scalar_one()
pending_orders = db.session.execute(db.select(db.func.count(Order.id)).where(Order.complete == None)).scalar_one()
total_revenue = db.session.execute(db.select(db.func.sum(Order.amount)).where(Order.complete != None)).scalar_one() or 0
low_stock_count = db.session.execute(
db.select(db.func.count(Product.id)).where(Product.available < 5)
).scalar_one()
except:
product_count = category_count = customer_count = order_count = 0
pending_orders = total_revenue = low_stock_count = 0
return render_template(
"index.html",
product_count=product_count,
category_count=category_count,
customer_count=customer_count,
order_count=order_count,
pending_orders=pending_orders,
total_revenue=total_revenue,
low_stock_count=low_stock_count,
)
@app.route("/products")
def products():
search_query = request.args.get("search", "")
sort = request.args.get("sort")
min_price = request.args.get("min_price", type=float)
max_price = request.args.get("max_price", type=float)
in_stock = request.args.get("in_stock") == "on"
category_filter = request.args.get("category")
statement = select(Product).where(Product.category_rel.has())
if search_query:
statement = statement.where(Product.name.ilike(f"%{search_query}%"))
if min_price is not None:
statement = statement.where(Product.price >= min_price)
if max_price is not None:
statement = statement.where(Product.price <= max_price)
if in_stock:
statement = statement.where(Product.available > 0)
if category_filter:
statement = statement.where(Product.category_rel.has(Category.name == category_filter))
if sort == "price_low":
statement = statement.order_by(Product.price)
elif sort == "price_high":
statement = statement.order_by(Product.price.desc())
elif sort == "name":
statement = statement.order_by(Product.name)
elif sort == "availability":
statement = statement.order_by(Product.available.desc())
products_select = db.session.execute(statement).scalars().all()
for product in products_select:
try:
product.category = product.category_rel.name
except AttributeError:
product.category = "Uncategorized"
categories = db.session.execute(select(Category.name)).scalars().all()
return render_template(
"products.html",
products=products_select,
categories=categories,
search_query=search_query,
min_price=min_price,
max_price=max_price,
in_stock=in_stock,
category_filter=category_filter,
sort=sort,
)
@app.route("/categories")
def categories():
categories_select = db.session.execute(select(Category)).scalars().all()
category_names = [category.name for category in categories_select]
return render_template("categories.html", categories=category_names)
@app.route("/categories/<category>")
def category(category):
products_select = db.session.execute(
select(Product).where(Product.category_rel.has(Category.name == category))
).scalars().all()
for product in products_select:
try:
product.category = product.category_rel.name
except AttributeError:
product.category = "Uncategorized"
return render_template("category.html", category=category, products=products_select)
@app.route("/customers")
def customers():
search_query = request.args.get("search", "")
sort = request.args.get("sort")
statement = select(Customer)
if search_query:
statement = statement.where(
(Customer.nickname.ilike(f"%{search_query}%"))
| (Customer.email.ilike(f"%{search_query}%"))
)
if sort == "nickname":
statement = statement.order_by(Customer.nickname)
elif sort == "email":
statement = statement.order_by(Customer.email)
elif sort == "date":
statement = statement.order_by(Customer.created_at.desc())
elif sort == "id":
statement = statement.order_by(Customer.id)
customers = db.session.execute(statement).scalars().all()
return render_template(
"customers.html", customers=customers, search_query=search_query, sort=sort
)
@app.route("/customers/<customer_id>")
def customer(customer_id):
customer = db.session.execute(select(Customer).where(Customer.id == customer_id)).scalar_one()
return render_template("customer.html", customer=customer)
@app.route("/products/<product_id>")
def product(product_id):
product = db.session.execute(select(Product).where(Product.id == product_id)).scalar_one()
try:
product.category = product.category_rel.name
except AttributeError:
product.category = "Uncategorized"
return render_template("product.html", product=product)
@app.route("/orders")
def orders():
sort = request.args.get("sort")
filter_status = request.args.get("filter")
statement = db.select(Order)
if filter_status == "completed":
statement = statement.where(Order.complete != None)
elif filter_status == "pending":
statement = statement.where(Order.complete == None)
if sort == "id":
statement = statement.order_by(Order.id)
elif sort == "date":
statement = statement.order_by(Order.created.desc())
elif sort == "amount":
statement = statement.order_by(Order.amount.desc())
elif sort == "status":
statement = statement.order_by(Order.complete.is_(None))
orders = db.session.execute(statement).scalars().all()
return render_template("orders.html", orders=orders)
@app.route("/orders/<order_id>")
def order(order_id):
order = db.session.execute(select(Order).where(Order.id == order_id)).scalar_one()
return render_template("order.html", order=order)
@app.route("/orders/<int:id>/complete", methods=["POST"])
def complete_order(id):
print("Completing order with ID:", id)
order = db.session.execute(select(Order).where(Order.id == id)).scalar_one()
for po in order.products:
if po.product.available < po.quantity:
return redirect(url_for("order", order_id=id))
estimated_amount = 0
for po in order.products:
estimated_amount += po.product.price * po.quantity
po.product.available -= po.quantity
order.complete = dt.now()
order.amount = estimated_amount
db.session.commit()
return redirect(url_for("order", order_id=id))
@app.route("/export/products")
def export_products():
products = db.session.execute(select(Product).where(Product.category_rel.has())).scalars().all()
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["ID", "Name", "Price", "Available", "Category"])
for product in products:
try:
category = product.category_rel.name
except AttributeError:
category = "Uncategorized"
writer.writerow(
[product.id, product.name, f"{product.price:.2f}", product.available, category]
)
output.seek(0)
return Response(
output,
mimetype="text/csv",
headers={"Content-Disposition": "attachment;filename=products.csv"},
)
@app.route("/export/orders")
def export_orders():
orders = db.session.execute(select(Order)).scalars().all()
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["Order ID", "Customer", "Date", "Status", "Amount", "Products"])
for order in orders:
products_list = ", ".join(
[f"{po.product.name} (x{po.quantity})" for po in order.products]
)
writer.writerow(
[
order.id,
order.customer.name,
order.created.strftime("%Y-%m-%d %H:%M"),
"Completed" if order.complete else "Pending",
f"{order.amount:.2f}" if order.complete else f"{order.estimate():.2f} (est.)",
products_list,
]
)
output.seek(0)
return Response(
output,
mimetype="text/csv",
headers={"Content-Disposition": "attachment;filename=orders.csv"},
)
@app.route("/export/customers")
def export_customers():
customers = db.session.execute(select(Customer)).scalars().all()
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["ID", "Nickname", "Email", "Orders"])
for customer in customers:
writer.writerow(
[customer.id, customer.nickname, customer.email, len(customer.orders)]
)
output.seek(0)
return Response(
output,
mimetype="text/csv",
headers={"Content-Disposition": "attachment;filename=customers.csv"},
)
if __name__ == "__main__":
app.run(debug=False, port=8888)