portfolio.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. from fastapi import APIRouter, Depends, HTTPException, Form, UploadFile, File
  2. import db
  3. import schemas
  4. import auth_utils
  5. import config
  6. import os
  7. import uuid
  8. import shutil
  9. from services.global_manager import global_manager
  10. from dependencies import require_admin
  11. from services.audit_service import audit_service
  12. router = APIRouter(tags=["portfolio"])
  13. @router.get("/portfolio")
  14. async def get_public_portfolio():
  15. query = """
  16. SELECT p.id, p.file_path, COALESCE(o.material_name, 'Showcase') as material_name, p.order_id
  17. FROM order_photos p
  18. LEFT JOIN orders o ON p.order_id = o.id
  19. WHERE p.is_public = TRUE AND (o.id IS NULL OR o.allow_portfolio = TRUE)
  20. ORDER BY p.created_at DESC
  21. """
  22. return db.execute_query(query)
  23. @router.get("/admin/all-photos")
  24. async def admin_get_all_photos(admin: dict = Depends(require_admin)):
  25. query = """
  26. SELECT p.id, p.file_path, p.is_public, p.order_id, o.allow_portfolio,
  27. o.first_name, o.last_name, COALESCE(o.material_name, 'Manual') as material_name
  28. FROM order_photos p
  29. JOIN orders o ON p.order_id = o.id
  30. ORDER BY p.created_at DESC
  31. """
  32. return db.execute_query(query)
  33. @router.post("/admin/orders/{order_id}/photos")
  34. async def admin_upload_order_photo(
  35. order_id: int,
  36. is_public: bool = Form(False),
  37. file: UploadFile = File(...),
  38. admin: dict = Depends(require_admin)
  39. ):
  40. order = db.execute_query("SELECT allow_portfolio FROM orders WHERE id = %s", (order_id,))
  41. if not order: raise HTTPException(status_code=404, detail="Order not found")
  42. if is_public and not order[0]['allow_portfolio']:
  43. raise HTTPException(status_code=400, detail="Cannot make public: User did not consent to portfolio usage")
  44. if not file.filename: raise HTTPException(status_code=400, detail="Invalid file")
  45. unique_filename = f"{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
  46. disk_path = os.path.join(config.UPLOAD_DIR, unique_filename)
  47. db_file_path = f"uploads/{unique_filename}"
  48. with open(disk_path, "wb") as buffer:
  49. shutil.copyfileobj(file.file, buffer)
  50. query = "INSERT INTO order_photos (order_id, file_path, is_public) VALUES (%s, %s, %s)"
  51. photo_id = db.execute_commit(query, (order_id, db_file_path, is_public))
  52. await audit_service.log(
  53. user_id=admin['id'],
  54. action="upload_order_photo",
  55. target_type="order",
  56. target_id=order_id,
  57. details={"photo_id": photo_id, "is_public": is_public}
  58. )
  59. # NOTIFY USER VIA WEBSOCKET
  60. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  61. if order_info:
  62. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  63. return {"id": photo_id, "file_path": db_file_path, "is_public": is_public}
  64. @router.patch("/admin/photos/{photo_id}")
  65. async def admin_update_photo_status(photo_id: int, data: schemas.PhotoUpdate, admin: dict = Depends(require_admin)):
  66. query = "SELECT p.*, o.allow_portfolio FROM order_photos p JOIN orders o ON p.order_id = o.id WHERE p.id = %s"
  67. photo_data = db.execute_query(query, (photo_id,))
  68. if not photo_data: raise HTTPException(status_code=404, detail="Photo not found")
  69. if data.is_public and not photo_data[0]['allow_portfolio']:
  70. raise HTTPException(status_code=400, detail="Cannot make public: User did not consent to portfolio usage")
  71. db.execute_commit("UPDATE order_photos SET is_public = %s WHERE id = %s", (data.is_public, photo_id))
  72. await audit_service.log(
  73. user_id=admin['id'],
  74. action="update_photo_visibility",
  75. target_type="photo",
  76. target_id=photo_id,
  77. details={"is_public": data.is_public}
  78. )
  79. # NOTIFY USER VIA WEBSOCKET
  80. order_id = photo_data[0]['order_id']
  81. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  82. if order_info:
  83. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  84. return {"id": photo_id, "is_public": data.is_public}
  85. @router.delete("/admin/photos/{photo_id}")
  86. async def admin_delete_photo(photo_id: int, admin: dict = Depends(require_admin)):
  87. photo = db.execute_query("SELECT file_path, order_id FROM order_photos WHERE id = %s", (photo_id,))
  88. if not photo:
  89. raise HTTPException(status_code=404, detail="Photo not found")
  90. order_id = photo[0]['order_id']
  91. try:
  92. path = os.path.join(config.BASE_DIR, photo[0]['file_path'])
  93. if os.path.exists(path):
  94. os.remove(path)
  95. except Exception as e:
  96. print(f"Error deleting photo file: {e}")
  97. db.execute_commit("DELETE FROM order_photos WHERE id = %s", (photo_id,))
  98. await audit_service.log(
  99. user_id=admin['id'],
  100. action="delete_photo",
  101. target_type="photo",
  102. target_id=photo_id,
  103. details={"order_id": order_id}
  104. )
  105. # NOTIFY USER VIA WEBSOCKET
  106. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  107. if order_info:
  108. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  109. return {"id": photo_id, "status": "deleted"}