portfolio.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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, p.caption
  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, p.caption, o.allow_portfolio,
  27. o.first_name, o.last_name, COALESCE(o.material_name, 'Manual') as material_name
  28. FROM order_photos p
  29. LEFT 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. caption: Optional[str] = Form(None),
  38. file: UploadFile = File(...),
  39. admin: dict = Depends(require_admin)
  40. ):
  41. order = db.execute_query("SELECT allow_portfolio FROM orders WHERE id = %s", (order_id,))
  42. if not order: raise HTTPException(status_code=404, detail="Order not found")
  43. if is_public and not order[0]['allow_portfolio']:
  44. raise HTTPException(status_code=400, detail="Cannot make public: User did not consent to portfolio usage")
  45. if not file.filename: raise HTTPException(status_code=400, detail="Invalid file")
  46. unique_filename = f"{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
  47. disk_path = os.path.join(config.UPLOAD_DIR, unique_filename)
  48. db_file_path = f"uploads/{unique_filename}"
  49. with open(disk_path, "wb") as buffer:
  50. shutil.copyfileobj(file.file, buffer)
  51. query = "INSERT INTO order_photos (order_id, file_path, is_public, caption) VALUES (%s, %s, %s, %s)"
  52. photo_id = db.execute_commit(query, (order_id, db_file_path, is_public, caption))
  53. await audit_service.log(
  54. user_id=admin['id'],
  55. action="upload_order_photo",
  56. target_type="order",
  57. target_id=order_id,
  58. details={"photo_id": photo_id, "is_public": is_public, "caption": caption}
  59. )
  60. # NOTIFY USER VIA WEBSOCKET
  61. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  62. if order_info:
  63. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  64. return {"id": photo_id, "file_path": db_file_path, "is_public": is_public, "caption": caption}
  65. @router.post("/admin/portfolio/upload")
  66. async def admin_upload_portfolio_photo(
  67. is_public: bool = Form(True),
  68. caption: Optional[str] = Form(None),
  69. file: UploadFile = File(...),
  70. admin: dict = Depends(require_admin)
  71. ):
  72. if not file.filename: raise HTTPException(status_code=400, detail="Invalid file")
  73. unique_filename = f"{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
  74. disk_path = os.path.join(config.UPLOAD_DIR, unique_filename)
  75. db_file_path = f"uploads/{unique_filename}"
  76. with open(disk_path, "wb") as buffer:
  77. shutil.copyfileobj(file.file, buffer)
  78. query = "INSERT INTO order_photos (order_id, file_path, is_public, caption) VALUES (%s, %s, %s, %s)"
  79. photo_id = db.execute_commit(query, (None, db_file_path, is_public, caption))
  80. await audit_service.log(
  81. user_id=admin['id'],
  82. action="upload_portfolio_photo",
  83. target_type="photo",
  84. target_id=photo_id,
  85. details={"is_public": is_public, "caption": caption}
  86. )
  87. return {"id": photo_id, "file_path": db_file_path, "is_public": is_public, "caption": caption}
  88. @router.patch("/admin/photos/{photo_id}")
  89. async def admin_update_photo_status(photo_id: int, data: schemas.PhotoUpdate, admin: dict = Depends(require_admin)):
  90. query = "SELECT p.*, o.allow_portfolio FROM order_photos p LEFT JOIN orders o ON p.order_id = o.id WHERE p.id = %s"
  91. photo_data = db.execute_query(query, (photo_id,))
  92. if not photo_data: raise HTTPException(status_code=404, detail="Photo not found")
  93. # Check consent if linked to order
  94. if data.is_public and photo_data[0]['order_id'] is not None and not photo_data[0]['allow_portfolio']:
  95. raise HTTPException(status_code=400, detail="Cannot make public: User did not consent to portfolio usage")
  96. db.execute_commit("UPDATE order_photos SET is_public = %s, caption = %s WHERE id = %s", (data.is_public, data.caption, photo_id))
  97. await audit_service.log(
  98. user_id=admin['id'],
  99. action="update_photo_visibility",
  100. target_type="photo",
  101. target_id=photo_id,
  102. details={"is_public": data.is_public, "caption": data.caption}
  103. )
  104. # NOTIFY USER VIA WEBSOCKET if linked to order
  105. order_id = photo_data[0]['order_id']
  106. if order_id:
  107. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  108. if order_info:
  109. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  110. return {"id": photo_id, "is_public": data.is_public, "caption": data.caption}
  111. @router.delete("/admin/photos/{photo_id}")
  112. async def admin_delete_photo(photo_id: int, admin: dict = Depends(require_admin)):
  113. photo = db.execute_query("SELECT file_path, order_id FROM order_photos WHERE id = %s", (photo_id,))
  114. if not photo:
  115. raise HTTPException(status_code=404, detail="Photo not found")
  116. order_id = photo[0]['order_id']
  117. try:
  118. path = os.path.join(config.BASE_DIR, photo[0]['file_path'])
  119. if os.path.exists(path):
  120. os.remove(path)
  121. except Exception as e:
  122. print(f"Error deleting photo file: {e}")
  123. db.execute_commit("DELETE FROM order_photos WHERE id = %s", (photo_id,))
  124. await audit_service.log(
  125. user_id=admin['id'],
  126. action="delete_photo",
  127. target_type="photo",
  128. target_id=photo_id,
  129. details={"order_id": order_id}
  130. )
  131. # NOTIFY USER VIA WEBSOCKET
  132. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  133. if order_info:
  134. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  135. return {"id": photo_id, "status": "deleted"}