portfolio.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. from fastapi import APIRouter, Depends, HTTPException, Form, UploadFile, File
  2. from typing import Optional
  3. from pydantic import BaseModel
  4. import db
  5. import schemas
  6. import auth_utils
  7. import config
  8. import os
  9. import uuid
  10. import shutil
  11. import zipfile
  12. import json
  13. from services.global_manager import global_manager
  14. from dependencies import require_admin
  15. from services.audit_service import audit_service
  16. # Test deployment trigger - comment update
  17. router = APIRouter(tags=["portfolio"])
  18. class ScanUpdate(BaseModel):
  19. is_public: bool
  20. @router.get("/portfolio")
  21. async def get_public_portfolio():
  22. query = """
  23. SELECT p.id, p.file_path, COALESCE(o.material_name, 'Showcase') as material_name, p.order_id, p.caption
  24. FROM order_photos p
  25. LEFT JOIN orders o ON p.order_id = o.id
  26. WHERE p.is_public = TRUE AND (o.id IS NULL OR o.allow_portfolio = TRUE)
  27. ORDER BY p.created_at DESC
  28. """
  29. return db.execute_query(query)
  30. @router.get("/admin/all-photos")
  31. async def admin_get_all_photos(admin: dict = Depends(require_admin)):
  32. query = """
  33. SELECT p.id, p.file_path, p.is_public, p.order_id, p.caption, o.allow_portfolio,
  34. o.first_name, o.last_name, COALESCE(o.material_name, 'Manual') as material_name
  35. FROM order_photos p
  36. LEFT JOIN orders o ON p.order_id = o.id
  37. ORDER BY p.created_at DESC
  38. """
  39. return db.execute_query(query)
  40. @router.post("/admin/orders/{order_id}/photos")
  41. async def admin_upload_order_photo(
  42. order_id: int,
  43. is_public: bool = Form(False),
  44. caption: Optional[str] = Form(None),
  45. file: UploadFile = File(...),
  46. admin: dict = Depends(require_admin)
  47. ):
  48. order = db.execute_query("SELECT allow_portfolio FROM orders WHERE id = %s", (order_id,))
  49. if not order: raise HTTPException(status_code=404, detail="Order not found")
  50. if is_public and not order[0]['allow_portfolio']:
  51. raise HTTPException(status_code=400, detail="Cannot make public: User did not consent to portfolio usage")
  52. if not file.filename: raise HTTPException(status_code=400, detail="Invalid file")
  53. unique_filename = f"{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
  54. disk_path = os.path.join(config.UPLOAD_DIR, unique_filename)
  55. db_file_path = f"uploads/{unique_filename}"
  56. with open(disk_path, "wb") as buffer:
  57. shutil.copyfileobj(file.file, buffer)
  58. query = "INSERT INTO order_photos (order_id, file_path, is_public, caption) VALUES (%s, %s, %s, %s)"
  59. photo_id = db.execute_commit(query, (order_id, db_file_path, is_public, caption))
  60. await audit_service.log(
  61. user_id=admin['id'],
  62. action="upload_order_photo",
  63. target_type="order",
  64. target_id=order_id,
  65. details={"photo_id": photo_id, "is_public": is_public, "caption": caption}
  66. )
  67. # NOTIFY USER VIA WEBSOCKET
  68. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  69. if order_info:
  70. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  71. return {"id": photo_id, "file_path": db_file_path, "is_public": is_public, "caption": caption}
  72. @router.post("/admin/portfolio/upload")
  73. async def admin_upload_portfolio_photo(
  74. is_public: bool = Form(True),
  75. caption: Optional[str] = Form(None),
  76. file: UploadFile = File(...),
  77. admin: dict = Depends(require_admin)
  78. ):
  79. if not file.filename: raise HTTPException(status_code=400, detail="Invalid file")
  80. unique_filename = f"{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
  81. disk_path = os.path.join(config.UPLOAD_DIR, unique_filename)
  82. db_file_path = f"uploads/{unique_filename}"
  83. with open(disk_path, "wb") as buffer:
  84. shutil.copyfileobj(file.file, buffer)
  85. query = "INSERT INTO order_photos (order_id, file_path, is_public, caption) VALUES (%s, %s, %s, %s)"
  86. photo_id = db.execute_commit(query, (None, db_file_path, is_public, caption))
  87. await audit_service.log(
  88. user_id=admin['id'],
  89. action="upload_portfolio_photo",
  90. target_type="photo",
  91. target_id=photo_id,
  92. details={"is_public": is_public, "caption": caption}
  93. )
  94. return {"id": photo_id, "file_path": db_file_path, "is_public": is_public, "caption": caption}
  95. @router.patch("/admin/photos/{photo_id}")
  96. async def admin_update_photo_status(photo_id: int, data: schemas.PhotoUpdate, admin: dict = Depends(require_admin)):
  97. query = "SELECT p.*, o.allow_portfolio FROM order_photos p LEFT JOIN orders o ON p.order_id = o.id WHERE p.id = %s"
  98. photo_data = db.execute_query(query, (photo_id,))
  99. if not photo_data: raise HTTPException(status_code=404, detail="Photo not found")
  100. # Check consent if linked to order
  101. if data.is_public and photo_data[0]['order_id'] is not None and not photo_data[0]['allow_portfolio']:
  102. raise HTTPException(status_code=400, detail="Cannot make public: User did not consent to portfolio usage")
  103. db.execute_commit("UPDATE order_photos SET is_public = %s, caption = %s WHERE id = %s", (data.is_public, data.caption, photo_id))
  104. await audit_service.log(
  105. user_id=admin['id'],
  106. action="update_photo_visibility",
  107. target_type="photo",
  108. target_id=photo_id,
  109. details={"is_public": data.is_public, "caption": data.caption}
  110. )
  111. # NOTIFY USER VIA WEBSOCKET if linked to order
  112. order_id = photo_data[0]['order_id']
  113. if order_id:
  114. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  115. if order_info:
  116. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  117. return {"id": photo_id, "is_public": data.is_public, "caption": data.caption}
  118. @router.delete("/admin/photos/{photo_id}")
  119. async def admin_delete_photo(photo_id: int, admin: dict = Depends(require_admin)):
  120. photo = db.execute_query("SELECT file_path, order_id FROM order_photos WHERE id = %s", (photo_id,))
  121. if not photo:
  122. raise HTTPException(status_code=404, detail="Photo not found")
  123. order_id = photo[0]['order_id']
  124. try:
  125. path = os.path.join(config.BASE_DIR, photo[0]['file_path'])
  126. if os.path.exists(path):
  127. os.remove(path)
  128. except Exception as e:
  129. print(f"Error deleting photo file: {e}")
  130. db.execute_commit("DELETE FROM order_photos WHERE id = %s", (photo_id,))
  131. await audit_service.log(
  132. user_id=admin['id'],
  133. action="delete_photo",
  134. target_type="photo",
  135. target_id=photo_id,
  136. details={"order_id": order_id}
  137. )
  138. # NOTIFY USER VIA WEBSOCKET
  139. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  140. if order_info:
  141. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  142. return {"id": photo_id, "status": "deleted"}
  143. # --- 3D Scan Portfolio Endpoints ---
  144. @router.get("/scans")
  145. async def get_public_scans():
  146. query = """
  147. SELECT id, title_en, title_ru, title_me, title_ua,
  148. description_en, description_ru, description_me, description_ua,
  149. folder_name, frames_count, created_at
  150. FROM portfolio_scans
  151. WHERE is_public = TRUE
  152. ORDER BY created_at DESC
  153. """
  154. scans = db.execute_query(query)
  155. scans_dir = os.path.join(config.UPLOAD_DIR, "scans")
  156. for scan in scans:
  157. photo_path = os.path.join(scans_dir, scan["folder_name"], "photo.webp")
  158. scan["has_photo"] = os.path.exists(photo_path)
  159. return scans
  160. @router.get("/admin/scans")
  161. async def admin_get_all_scans(admin: dict = Depends(require_admin)):
  162. query = """
  163. SELECT id, title_en, title_ru, title_me, title_ua,
  164. description_en, description_ru, description_me, description_ua,
  165. folder_name, frames_count, is_public, created_at
  166. FROM portfolio_scans
  167. ORDER BY created_at DESC
  168. """
  169. scans = db.execute_query(query)
  170. scans_dir = os.path.join(config.UPLOAD_DIR, "scans")
  171. for scan in scans:
  172. photo_path = os.path.join(scans_dir, scan["folder_name"], "photo.webp")
  173. scan["has_photo"] = os.path.exists(photo_path)
  174. return scans
  175. @router.post("/admin/scans/upload-bundle")
  176. async def admin_upload_scan_bundle(
  177. file: UploadFile = File(...),
  178. admin: dict = Depends(require_admin)
  179. ):
  180. if not file.filename or not file.filename.endswith(".zip"):
  181. raise HTTPException(status_code=400, detail="Invalid file: must be a ZIP archive")
  182. scan_id = str(uuid.uuid4())
  183. scans_dir = os.path.join(config.UPLOAD_DIR, "scans")
  184. os.makedirs(scans_dir, exist_ok=True)
  185. dest_dir = os.path.join(scans_dir, f"scan_{scan_id}")
  186. os.makedirs(dest_dir, exist_ok=True)
  187. temp_zip_path = os.path.join(dest_dir, "temp_bundle.zip")
  188. with open(temp_zip_path, "wb") as buffer:
  189. shutil.copyfileobj(file.file, buffer)
  190. try:
  191. # Extract files
  192. with zipfile.ZipFile(temp_zip_path, 'r') as zip_ref:
  193. zip_ref.extractall(dest_dir)
  194. # Clean up zip
  195. if os.path.exists(temp_zip_path):
  196. os.remove(temp_zip_path)
  197. # Validate metadata.json
  198. metadata_path = os.path.join(dest_dir, "metadata.json")
  199. if not os.path.exists(metadata_path):
  200. raise HTTPException(status_code=400, detail="Invalid bundle: metadata.json is missing")
  201. with open(metadata_path, "r", encoding="utf-8") as f:
  202. metadata = json.load(f)
  203. title_en = metadata.get("title_en")
  204. if not title_en:
  205. raise HTTPException(status_code=400, detail="Invalid bundle: title_en is required")
  206. title_ru = metadata.get("title_ru", "") or title_en
  207. title_me = metadata.get("title_me", "") or title_en
  208. title_ua = metadata.get("title_ua", "") or title_en
  209. description_en = metadata.get("description_en", "")
  210. description_ru = metadata.get("description_ru", "") or description_en
  211. description_me = metadata.get("description_me", "") or description_en
  212. description_ua = metadata.get("description_ua", "") or description_en
  213. frames_count = int(metadata.get("frames_count", 48))
  214. # Verify frame WebP files
  215. for i in range(frames_count):
  216. frame_path = os.path.join(dest_dir, f"{i:03d}.webp")
  217. if not os.path.exists(frame_path):
  218. raise HTTPException(status_code=400, detail=f"Invalid bundle: frame {i:03d}.webp is missing")
  219. # Verify thumbnail
  220. thumbnail_path = os.path.join(dest_dir, "thumbnail.webp")
  221. if not os.path.exists(thumbnail_path):
  222. raise HTTPException(status_code=400, detail="Invalid bundle: thumbnail.webp is missing")
  223. # Check and convert original photograph if present
  224. for ext in [".webp", ".png", ".jpg", ".jpeg"]:
  225. p_path = os.path.join(dest_dir, f"photo{ext}")
  226. if os.path.exists(p_path):
  227. if ext != ".webp":
  228. from PIL import Image
  229. try:
  230. with Image.open(p_path) as img:
  231. img.save(os.path.join(dest_dir, "photo.webp"), "WEBP", quality=85)
  232. os.remove(p_path)
  233. except Exception as ex:
  234. print(f"Failed to convert photo to WebP: {ex}")
  235. break
  236. # Insert DB record
  237. query = """
  238. INSERT INTO portfolio_scans (
  239. title_en, title_ru, title_me, title_ua,
  240. description_en, description_ru, description_me, description_ua,
  241. folder_name, frames_count, is_public
  242. ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  243. """
  244. db_id = db.execute_commit(query, (
  245. title_en, title_ru, title_me, title_ua,
  246. description_en, description_ru, description_me, description_ua,
  247. f"scan_{scan_id}", frames_count, 1
  248. ))
  249. await audit_service.log(
  250. user_id=admin['id'],
  251. action="upload_scan_bundle",
  252. target_type="scan",
  253. target_id=db_id,
  254. details={"title_en": title_en, "folder_name": f"scan_{scan_id}"}
  255. )
  256. return {
  257. "id": db_id,
  258. "title_en": title_en,
  259. "folder_name": f"scan_{scan_id}",
  260. "frames_count": frames_count
  261. }
  262. except Exception as e:
  263. if os.path.exists(dest_dir):
  264. shutil.rmtree(dest_dir)
  265. if isinstance(e, HTTPException):
  266. raise e
  267. raise HTTPException(status_code=500, detail=f"Error processing bundle: {str(e)}")
  268. @router.patch("/admin/scans/{scan_id}")
  269. async def admin_update_scan_status(
  270. scan_id: int,
  271. data: ScanUpdate,
  272. admin: dict = Depends(require_admin)
  273. ):
  274. scan = db.execute_query("SELECT id FROM portfolio_scans WHERE id = %s", (scan_id,))
  275. if not scan:
  276. raise HTTPException(status_code=404, detail="Scan not found")
  277. db.execute_commit("UPDATE portfolio_scans SET is_public = %s WHERE id = %s", (data.is_public, scan_id))
  278. await audit_service.log(
  279. user_id=admin['id'],
  280. action="update_scan_visibility",
  281. target_type="scan",
  282. target_id=scan_id,
  283. details={"is_public": data.is_public}
  284. )
  285. return {"id": scan_id, "is_public": data.is_public}
  286. @router.delete("/admin/scans/{scan_id}")
  287. async def admin_delete_scan(scan_id: int, admin: dict = Depends(require_admin)):
  288. scan = db.execute_query("SELECT folder_name, title_en FROM portfolio_scans WHERE id = %s", (scan_id,))
  289. if not scan:
  290. raise HTTPException(status_code=404, detail="Scan not found")
  291. folder_name = scan[0]['folder_name']
  292. title_en = scan[0]['title_en']
  293. dest_dir = os.path.join(config.UPLOAD_DIR, "scans", folder_name)
  294. try:
  295. if os.path.exists(dest_dir):
  296. shutil.rmtree(dest_dir)
  297. except Exception as e:
  298. print(f"Error removing scan directory {folder_name}: {e}")
  299. db.execute_commit("DELETE FROM portfolio_scans WHERE id = %s", (scan_id,))
  300. await audit_service.log(
  301. user_id=admin['id'],
  302. action="delete_scan_bundle",
  303. target_type="scan",
  304. target_id=scan_id,
  305. details={"title_en": title_en, "folder_name": folder_name}
  306. )
  307. return {"id": scan_id, "status": "deleted"}