hisham-cmd commited on
Commit
f1db8b0
·
verified ·
1 Parent(s): 64878b9

Update backend with high-quality catalog and fixes

Browse files
app/api/products.py CHANGED
@@ -3,6 +3,7 @@ from typing import Optional
3
  from fastapi import APIRouter, Depends, HTTPException, Query, status
4
  from sqlalchemy.orm import Session, joinedload
5
  from sqlalchemy import or_, desc, asc
 
6
 
7
  from app.db.base import get_db
8
  from app.models.product import Product, ProductImage, Category
@@ -33,7 +34,10 @@ async def list_products(
33
  page_size: int = Query(12, ge=1, le=48),
34
  db: Session = Depends(get_db),
35
  ):
36
- query = db.query(Product).filter(Product.is_active == True) # noqa: E712
 
 
 
37
 
38
  # Search
39
  if search:
@@ -103,7 +107,10 @@ async def list_products(
103
 
104
  # Serialize dates
105
  for item in items:
106
- item["created_at"] = item["created_at"].isoformat()
 
 
 
107
 
108
  total_pages = (total + page_size - 1) // page_size
109
 
@@ -128,11 +135,14 @@ async def get_product(product_id: int, db: Session = Depends(get_db)):
128
  .filter(Product.id == product_id)
129
  .first()
130
  )
131
- if not product:
132
  raise HTTPException(status_code=404, detail="Product not found")
133
 
134
  detail = ProductDetail.model_validate(product).model_dump()
135
- detail["created_at"] = detail["created_at"].isoformat()
 
 
 
136
 
137
  return AuthResponse(
138
  isSuccess=True,
@@ -147,6 +157,9 @@ async def create_product(
147
  user_id: int = Depends(get_current_user),
148
  db: Session = Depends(get_db),
149
  ):
 
 
 
150
  product = Product(
151
  name_ar=request.name_ar,
152
  name_en=request.name_en,
@@ -190,7 +203,7 @@ async def update_product(
190
  db: Session = Depends(get_db),
191
  ):
192
  product = db.query(Product).filter(Product.id == product_id).first()
193
- if not product:
194
  raise HTTPException(status_code=404, detail="Product not found")
195
 
196
  update_data = request.model_dump(exclude_unset=True)
@@ -211,6 +224,29 @@ async def delete_product(
211
  product_id: int,
212
  user_id: int = Depends(get_current_user),
213
  db: Session = Depends(get_db),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  ):
215
  product = db.query(Product).filter(Product.id == product_id).first()
216
  if not product:
@@ -221,6 +257,196 @@ async def delete_product(
221
 
222
  return AuthResponse(
223
  isSuccess=True,
224
- value={"deleted": True},
225
  statusCode=200,
226
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  from fastapi import APIRouter, Depends, HTTPException, Query, status
4
  from sqlalchemy.orm import Session, joinedload
5
  from sqlalchemy import or_, desc, asc
6
+ from datetime import datetime, timezone
7
 
8
  from app.db.base import get_db
9
  from app.models.product import Product, ProductImage, Category
 
34
  page_size: int = Query(12, ge=1, le=48),
35
  db: Session = Depends(get_db),
36
  ):
37
+ query = db.query(Product).filter(
38
+ Product.is_active == True, # noqa: E712
39
+ Product.deleted_at == None # noqa: E711
40
+ )
41
 
42
  # Search
43
  if search:
 
107
 
108
  # Serialize dates
109
  for item in items:
110
+ if isinstance(item.get("created_at"), datetime):
111
+ item["created_at"] = item["created_at"].isoformat()
112
+ if item.get("deleted_at") and isinstance(item["deleted_at"], datetime):
113
+ item["deleted_at"] = item["deleted_at"].isoformat()
114
 
115
  total_pages = (total + page_size - 1) // page_size
116
 
 
135
  .filter(Product.id == product_id)
136
  .first()
137
  )
138
+ if not product or product.deleted_at is not None:
139
  raise HTTPException(status_code=404, detail="Product not found")
140
 
141
  detail = ProductDetail.model_validate(product).model_dump()
142
+ if isinstance(detail.get("created_at"), datetime):
143
+ detail["created_at"] = detail["created_at"].isoformat()
144
+ if detail.get("deleted_at") and isinstance(detail["deleted_at"], datetime):
145
+ detail["deleted_at"] = detail["deleted_at"].isoformat()
146
 
147
  return AuthResponse(
148
  isSuccess=True,
 
157
  user_id: int = Depends(get_current_user),
158
  db: Session = Depends(get_db),
159
  ):
160
+ if not request.images or len(request.images) == 0:
161
+ raise HTTPException(status_code=400, detail="Main image is required / صورة رئيسية مطلوبة")
162
+
163
  product = Product(
164
  name_ar=request.name_ar,
165
  name_en=request.name_en,
 
203
  db: Session = Depends(get_db),
204
  ):
205
  product = db.query(Product).filter(Product.id == product_id).first()
206
+ if not product or product.deleted_at is not None:
207
  raise HTTPException(status_code=404, detail="Product not found")
208
 
209
  update_data = request.model_dump(exclude_unset=True)
 
224
  product_id: int,
225
  user_id: int = Depends(get_current_user),
226
  db: Session = Depends(get_db),
227
+ ):
228
+ product = db.query(Product).filter(Product.id == product_id).first()
229
+ if not product or product.deleted_at is not None:
230
+ raise HTTPException(status_code=404, detail="Product not found")
231
+
232
+ # Soft Delete
233
+ product.deleted_at = datetime.now(timezone.utc)
234
+ product.deleted_by = user_id
235
+ product.deletion_reason = "Manual deletion by admin"
236
+
237
+ db.commit()
238
+
239
+ return AuthResponse(
240
+ isSuccess=True,
241
+ value={"deleted": True, "soft_delete": True},
242
+ statusCode=200,
243
+ )
244
+
245
+ @router.delete("/{product_id}/hard", response_model=AuthResponse)
246
+ async def hard_delete_product(
247
+ product_id: int,
248
+ user_id: int = Depends(get_current_user),
249
+ db: Session = Depends(get_db),
250
  ):
251
  product = db.query(Product).filter(Product.id == product_id).first()
252
  if not product:
 
257
 
258
  return AuthResponse(
259
  isSuccess=True,
260
+ value={"deleted": True, "hard_delete": True},
261
  statusCode=200,
262
  )
263
+
264
+ @router.post("/{product_id}/restore", response_model=AuthResponse)
265
+ async def restore_product(
266
+ product_id: int,
267
+ user_id: int = Depends(get_current_user),
268
+ db: Session = Depends(get_db),
269
+ ):
270
+ product = db.query(Product).filter(Product.id == product_id).first()
271
+ if not product or product.deleted_at is None:
272
+ raise HTTPException(status_code=404, detail="Product not found or not deleted")
273
+
274
+ product.deleted_at = None
275
+ product.deleted_by = None
276
+ product.deletion_reason = None
277
+
278
+ db.commit()
279
+
280
+ return AuthResponse(
281
+ isSuccess=True,
282
+ value={"restored": True},
283
+ statusCode=200,
284
+ )
285
+
286
+ @router.get("/admin/deleted", response_model=PaginatedResponse)
287
+ async def list_deleted_products(
288
+ page: int = Query(1, ge=1),
289
+ page_size: int = Query(12, ge=1, le=48),
290
+ db: Session = Depends(get_db),
291
+ user_id: int = Depends(get_current_user),
292
+ ):
293
+ query = db.query(Product).filter(Product.deleted_at != None) # noqa: E711
294
+
295
+ total = query.count()
296
+ offset = (page - 1) * page_size
297
+ products = (
298
+ query.options(joinedload(Product.category), joinedload(Product.images))
299
+ .order_by(desc(Product.deleted_at))
300
+ .offset(offset)
301
+ .limit(page_size)
302
+ .all()
303
+ )
304
+
305
+ items = []
306
+ for p in products:
307
+ item = ProductDetail.model_validate(p).model_dump()
308
+ if isinstance(item.get("created_at"), datetime):
309
+ item["created_at"] = item["created_at"].isoformat()
310
+ if item.get("deleted_at") and isinstance(item["deleted_at"], datetime):
311
+ item["deleted_at"] = item["deleted_at"].isoformat()
312
+ items.append(item)
313
+
314
+ total_pages = (total + page_size - 1) // page_size
315
+
316
+ return PaginatedResponse(
317
+ isSuccess=True,
318
+ value={
319
+ "items": items,
320
+ "total": total,
321
+ "page": page,
322
+ "page_size": page_size,
323
+ "total_pages": total_pages,
324
+ },
325
+ statusCode=200,
326
+ )
327
+
328
+
329
+ from typing import List
330
+
331
+
332
+ @router.post("/admin/bulk-delete", response_model=AuthResponse)
333
+ async def bulk_soft_delete_products(
334
+ product_ids: List[int],
335
+ reason: str = "Bulk deletion by admin",
336
+ db: Session = Depends(get_db),
337
+ user_id: int = Depends(get_current_user),
338
+ ):
339
+ """Soft delete multiple products at once."""
340
+ deleted_count = 0
341
+
342
+ for product_id in product_ids:
343
+ product = db.query(Product).filter(Product.id == product_id).first()
344
+ if product and product.deleted_at is None:
345
+ product.deleted_at = datetime.now(timezone.utc)
346
+ product.deleted_by = user_id
347
+ product.deletion_reason = reason
348
+ deleted_count += 1
349
+
350
+ db.commit()
351
+
352
+ return AuthResponse(
353
+ isSuccess=True,
354
+ value={"deleted_count": deleted_count, "requested_count": len(product_ids)},
355
+ statusCode=200,
356
+ )
357
+
358
+
359
+ @router.post("/admin/bulk-restore", response_model=AuthResponse)
360
+ async def bulk_restore_products(
361
+ product_ids: List[int],
362
+ db: Session = Depends(get_db),
363
+ user_id: int = Depends(get_current_user),
364
+ ):
365
+ """Restore multiple soft-deleted products."""
366
+ restored_count = 0
367
+
368
+ for product_id in product_ids:
369
+ product = db.query(Product).filter(Product.id == product_id).first()
370
+ if product and product.deleted_at is not None:
371
+ product.deleted_at = None
372
+ product.deleted_by = None
373
+ product.deletion_reason = None
374
+ restored_count += 1
375
+
376
+ db.commit()
377
+
378
+ return AuthResponse(
379
+ isSuccess=True,
380
+ value={"restored_count": restored_count, "requested_count": len(product_ids)},
381
+ statusCode=200,
382
+ )
383
+
384
+
385
+ @router.post("/admin/bulk-hard-delete", response_model=AuthResponse)
386
+ async def bulk_hard_delete_products(
387
+ product_ids: List[int],
388
+ db: Session = Depends(get_db),
389
+ user_id: int = Depends(get_current_user),
390
+ ):
391
+ """Permanently delete multiple products (hard delete)."""
392
+ deleted_count = 0
393
+
394
+ for product_id in product_ids:
395
+ product = db.query(Product).filter(Product.id == product_id).first()
396
+ if product:
397
+ db.delete(product)
398
+ deleted_count += 1
399
+
400
+ db.commit()
401
+
402
+ return AuthResponse(
403
+ isSuccess=True,
404
+ value={"deleted_count": deleted_count, "requested_count": len(product_ids)},
405
+ statusCode=200,
406
+ )
407
+
408
+
409
+ @router.get("/admin/quality/summary", response_model=AuthResponse)
410
+ async def get_quality_summary(
411
+ db: Session = Depends(get_db),
412
+ user_id: int = Depends(get_current_user),
413
+ ):
414
+ """Get quality statistics summary."""
415
+ from sqlalchemy import func
416
+
417
+ try:
418
+ total_products = db.query(Product).filter(Product.deleted_at == None).count()
419
+ total_deleted = db.query(Product).filter(Product.deleted_at != None).count()
420
+
421
+ avg_quality = db.query(func.avg(Product.quality_score)).filter(
422
+ Product.deleted_at == None
423
+ ).scalar() or 0
424
+
425
+ low_quality = db.query(Product).filter(
426
+ Product.deleted_at == None,
427
+ Product.quality_score < 70
428
+ ).count()
429
+
430
+ no_images = 0
431
+ products = db.query(Product).filter(Product.deleted_at == None).all()
432
+ for p in products:
433
+ if not p.images or len(p.images) == 0:
434
+ no_images += 1
435
+
436
+ return AuthResponse(
437
+ isSuccess=True,
438
+ value={
439
+ "total_active": total_products,
440
+ "total_deleted": total_deleted,
441
+ "avg_quality_score": round(float(avg_quality), 1),
442
+ "low_quality_products": low_quality,
443
+ "products_without_images": no_images,
444
+ },
445
+ statusCode=200,
446
+ )
447
+ except Exception as e:
448
+ return AuthResponse(
449
+ isSuccess=False,
450
+ value={"error": str(e)},
451
+ statusCode=500,
452
+ )
app/models/product.py CHANGED
@@ -29,6 +29,12 @@ class Product(Base):
29
  embedding = Column(JSON, nullable=True)
30
  specs = Column(JSON, nullable=True) # Rich specifications from external sources
31
  created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
 
 
 
 
 
 
32
 
33
  category = relationship("Category", back_populates="products")
34
  images = relationship("ProductImage", back_populates="product", cascade="all, delete-orphan")
 
29
  embedding = Column(JSON, nullable=True)
30
  specs = Column(JSON, nullable=True) # Rich specifications from external sources
31
  created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
32
+
33
+ # Soft deletion & Quality
34
+ deleted_at = Column(DateTime, nullable=True)
35
+ deleted_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
36
+ deletion_reason = Column(String(500), nullable=True)
37
+ quality_score = Column(Integer, default=100, nullable=False)
38
 
39
  category = relationship("Category", back_populates="products")
40
  images = relationship("ProductImage", back_populates="product", cascade="all, delete-orphan")
app/schemas/product.py CHANGED
@@ -84,6 +84,8 @@ class ProductListItem(BaseModel):
84
  is_featured: bool
85
  image_url: Optional[str] = None # primary image
86
  created_at: datetime
 
 
87
 
88
  model_config = {"from_attributes": True}
89
 
@@ -105,6 +107,9 @@ class ProductDetail(BaseModel):
105
  is_active: bool
106
  images: List[ProductImageResponse] = []
107
  created_at: datetime
 
 
 
108
 
109
  model_config = {"from_attributes": True}
110
 
@@ -127,3 +132,24 @@ class ProductFilters(BaseModel):
127
  sort_order: str = "desc" # asc, desc
128
  page: int = 1
129
  page_size: int = 12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  is_featured: bool
85
  image_url: Optional[str] = None # primary image
86
  created_at: datetime
87
+ quality_score: int
88
+ deleted_at: Optional[datetime] = None
89
 
90
  model_config = {"from_attributes": True}
91
 
 
107
  is_active: bool
108
  images: List[ProductImageResponse] = []
109
  created_at: datetime
110
+ quality_score: int
111
+ deleted_at: Optional[datetime] = None
112
+ deletion_reason: Optional[str] = None
113
 
114
  model_config = {"from_attributes": True}
115
 
 
132
  sort_order: str = "desc" # asc, desc
133
  page: int = 1
134
  page_size: int = 12
135
+ include_deleted: bool = False # Include soft-deleted products
136
+
137
+
138
+ class ProductVariantSchema(BaseModel):
139
+ id: str
140
+ name_en: str
141
+ name_ar: str
142
+ price_modifier: float = 0.0
143
+ stock: int = 0
144
+ image_url: Optional[str] = None
145
+
146
+ model_config = {"from_attributes": True}
147
+
148
+
149
+ class ProductQualityInfo(BaseModel):
150
+ quality_score: int
151
+ deleted_at: Optional[datetime] = None
152
+ deletion_reason: Optional[str] = None
153
+ deleted_by: Optional[int] = None
154
+
155
+ model_config = {"from_attributes": True}