sortowanie_w_mass_add

This commit is contained in:
Mateusz Gruszczyński
2025-08-16 12:22:22 +02:00
parent 68f235d605
commit 529130a622
3 changed files with 188 additions and 122 deletions

54
app.py
View File

@@ -1952,46 +1952,46 @@ def suggest_products():
@app.route("/all_products")
def all_products():
query = request.args.get("q", "")
sort = request.args.get("sort", "popularity")
limit = request.args.get("limit", type=int) or 50
offset = request.args.get("offset", type=int) or 0
top_products_query = SuggestedProduct.query
if query:
top_products_query = top_products_query.filter(
SuggestedProduct.name.ilike(f"%{query}%")
)
top_products = (
# Liczenie popularności
popularity_subquery = (
db.session.query(
func.lower(Item.name).label("name"), func.sum(Item.quantity).label("count")
func.lower(Item.name).label("name"),
func.sum(Item.quantity).label("count")
)
.join(ShoppingList, ShoppingList.id == Item.list_id)
.filter(Item.purchased.is_(True))
.group_by(func.lower(Item.name))
.order_by(func.sum(Item.quantity).desc())
.limit(5)
.all()
.subquery()
)
top_names = [s.name for s in top_products]
rest_query = SuggestedProduct.query
if query:
rest_query = rest_query.filter(SuggestedProduct.name.ilike(f"%{query}%"))
query_base = db.session.query(
SuggestedProduct.name,
popularity_subquery.c.count
).outerjoin(
popularity_subquery, func.lower(SuggestedProduct.name) == popularity_subquery.c.name
)
if top_names:
rest_query = rest_query.filter(~SuggestedProduct.name.in_(top_names))
if sort == "alphabetical":
query_base = query_base.order_by(func.lower(SuggestedProduct.name).asc(), popularity_subquery.c.count.desc())
else: # popularity
query_base = query_base.order_by(popularity_subquery.c.count.desc().nullslast(), func.lower(SuggestedProduct.name).asc())
products = query_base.offset(offset).limit(limit).all()
products_list = [
{"name": name, "count": count or 0}
for name, count in products
]
return jsonify({"products": products_list, "limit": limit})
rest_products = rest_query.order_by(SuggestedProduct.name.asc()).limit(200).all()
all_names = top_names + [s.name for s in rest_products]
seen = set()
unique_names = []
for name in all_names:
name_lower = name.strip().lower()
if name_lower not in seen:
unique_names.append(name)
seen.add(name_lower)
return {"allproducts": unique_names}
@app.route("/upload_receipt/<int:list_id>", methods=["POST"])