orders.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. import db
  2. import schemas
  3. import auth_utils
  4. import notifications
  5. import config
  6. from typing import List, Optional
  7. import json
  8. import os
  9. import uuid
  10. import shutil
  11. import hashlib
  12. import preview_utils
  13. import slicer_utils
  14. from fastapi import APIRouter, Request, Form, Depends, HTTPException, BackgroundTasks, UploadFile, File
  15. from services import pricing
  16. from services import order_processing
  17. from services import event_hooks
  18. from services.audit_service import audit_service
  19. from services.rate_limit_service import rate_limit_service
  20. from dependencies import get_current_user, require_admin, get_current_user_optional
  21. from pydantic import BaseModel
  22. from datetime import datetime
  23. import locales
  24. from services.global_manager import global_manager
  25. router = APIRouter(prefix="/orders", tags=["orders"])
  26. @router.post("")
  27. async def create_order(
  28. request: Request,
  29. background_tasks: BackgroundTasks,
  30. first_name: str = Form(...),
  31. last_name: str = Form(...),
  32. phone: str = Form(...),
  33. email: str = Form(...),
  34. shipping_address: str = Form(...),
  35. model_link: Optional[str] = Form(None),
  36. allow_portfolio: bool = Form(False),
  37. notes: Optional[str] = Form(None),
  38. material_id: int = Form(...),
  39. file_ids: str = Form("[]"),
  40. file_quantities: str = Form("[]"),
  41. quantity: int = Form(1),
  42. color_name: Optional[str] = Form(None),
  43. is_company: bool = Form(False),
  44. company_name: Optional[str] = Form(None),
  45. company_pib: Optional[str] = Form(None),
  46. company_address: Optional[str] = Form(None),
  47. user: Optional[dict] = Depends(get_current_user_optional)
  48. ):
  49. ip = request.client.host if request.client else "unknown"
  50. email_addr = email.lower()
  51. lang = request.query_params.get("lang", "en")
  52. is_admin = user.get("role") == "admin" if user else False
  53. if not is_admin and rate_limit_service.is_order_flooding(email_addr, ip):
  54. raise HTTPException(
  55. status_code=429,
  56. detail=locales.translate_error("flood_control", lang)
  57. )
  58. user_id = user.get("id") if user else None
  59. parsed_ids = []
  60. parsed_quantities = []
  61. if file_ids:
  62. try:
  63. parsed_ids = json.loads(file_ids)
  64. parsed_quantities = json.loads(file_quantities)
  65. except:
  66. pass
  67. name_col = f"name_{lang}" if lang in ["en", "ru", "me"] else "name_en"
  68. mat_info = db.execute_query(f"SELECT {name_col}, price_per_cm3, price_per_hour FROM materials WHERE id = %s", (material_id,))
  69. mat_name = mat_info[0][name_col] if mat_info else "Unknown"
  70. mat_price = mat_info[0]['price_per_cm3'] if mat_info else 0.0
  71. hour_price = mat_info[0]['price_per_hour'] if mat_info and mat_info[0]['price_per_hour'] is not None else config.DEFAULT_PRINTER_HOUR_PRICE
  72. file_sizes = []
  73. if parsed_ids:
  74. format_strings = ','.join(['%s'] * len(parsed_ids))
  75. file_rows = db.execute_query(f"SELECT file_size FROM order_files WHERE id IN ({format_strings})", tuple(parsed_ids))
  76. file_sizes = [r['file_size'] for r in file_rows]
  77. estimated_price, item_prices = pricing.calculate_estimated_price(material_id, file_sizes, parsed_quantities if parsed_quantities else None, return_details=True)
  78. # Snapshoting initial parameters
  79. original_params = json.dumps({
  80. "material_name": mat_name,
  81. "material_price": float(mat_price) if mat_price is not None else 0.0,
  82. "printer_hour_price": float(hour_price),
  83. "estimated_price": float(estimated_price) if estimated_price is not None else 0.0,
  84. "quantity": quantity,
  85. "color_name": color_name,
  86. "notes": notes,
  87. "first_name": first_name,
  88. "last_name": last_name,
  89. "phone": phone,
  90. "email": email,
  91. "shipping_address": shipping_address,
  92. "model_link": model_link,
  93. "is_company": is_company,
  94. "company_name": company_name,
  95. "company_pib": company_pib,
  96. "company_address": company_address
  97. })
  98. order_query = """
  99. INSERT INTO orders (user_id, material_id, first_name, last_name, phone, email, shipping_address, model_link, status, is_company, company_name, company_pib, company_address, allow_portfolio, estimated_price, material_name, material_price, printer_hour_price, color_name, quantity, notes, original_params)
  100. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'pending', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  101. """
  102. order_params = (user_id, material_id, first_name, last_name, phone, email, shipping_address, model_link, is_company, company_name, company_pib, company_address, allow_portfolio, estimated_price, mat_name, mat_price, hour_price, color_name, quantity, notes, original_params)
  103. try:
  104. order_insert_id = db.execute_commit(order_query, order_params)
  105. if parsed_ids:
  106. for idx, f_id in enumerate(parsed_ids):
  107. qty = parsed_quantities[idx] if idx < len(parsed_quantities) else 1
  108. unit_p = item_prices[idx] if idx < len(item_prices) else 0.0
  109. db.execute_commit("UPDATE order_files SET order_id = %s, quantity = %s, unit_price = %s WHERE id = %s", (order_insert_id, qty, unit_p, f_id))
  110. # Create corresponding fixed order item
  111. file_row = db.execute_query("SELECT filename FROM order_files WHERE id = %s", (f_id,))
  112. fname = file_row[0]['filename'] if file_row else f"File #{f_id}"
  113. db.execute_commit(
  114. "INSERT INTO order_items (order_id, description, quantity, unit_price, total_price) VALUES (%s, %s, %s, %s, %s)",
  115. (order_insert_id, f"3D Print: {fname}", qty, unit_p, round(qty * unit_p, 2))
  116. )
  117. background_tasks.add_task(order_processing.process_order_slicing, order_insert_id)
  118. background_tasks.add_task(event_hooks.on_order_created, order_insert_id)
  119. # LOG ACTION
  120. await audit_service.log(
  121. user_id=user_id,
  122. action="order_created",
  123. target_type="order",
  124. target_id=order_insert_id,
  125. details={
  126. "email": email_addr,
  127. "mat_id": material_id,
  128. "price": float(estimated_price) if estimated_price is not None else 0.0,
  129. "quantity": quantity
  130. }
  131. )
  132. # Record placement for rate limiting
  133. rate_limit_service.record_order_placement(email_addr, ip)
  134. return {"status": "success", "order_id": order_insert_id, "message": "Order submitted successfully"}
  135. except Exception as e:
  136. print(f"Error creating order: {e}")
  137. raise HTTPException(status_code=500, detail="Internal server error occurred while processing order")
  138. @router.get("/my")
  139. async def get_my_orders(
  140. page: int = 1,
  141. size: int = 10,
  142. user: dict = Depends(get_current_user)
  143. ):
  144. user_id = user.get("id")
  145. offset = (page - 1) * size
  146. # Get total count
  147. count_query = "SELECT COUNT(*) as total FROM orders WHERE user_id = %s"
  148. count_res = db.execute_query(count_query, (user_id,))
  149. total = count_res[0]['total'] if count_res else 0
  150. query = """
  151. SELECT o.*,
  152. (SELECT count(*) FROM order_messages om WHERE om.order_id = o.id AND om.is_from_admin = TRUE AND om.is_read = FALSE) as unread_count,
  153. GROUP_CONCAT(IF(f.id IS NOT NULL, JSON_OBJECT('id', f.id, 'filename', f.filename, 'file_path', f.file_path, 'quantity', f.quantity, 'preview_path', f.preview_path, 'print_time', f.print_time, 'filament_g', f.filament_g, 'dimensions', f.dimensions), NULL)) as files
  154. FROM orders o
  155. LEFT JOIN order_files f ON o.id = f.order_id
  156. WHERE o.user_id = %s
  157. GROUP BY o.id
  158. ORDER BY
  159. CASE
  160. WHEN status IN ('pending', 'processing', 'shipped') THEN 0
  161. ELSE 1
  162. END ASC,
  163. o.created_at DESC
  164. LIMIT %s OFFSET %s
  165. """
  166. results = db.execute_query(query, (user_id, size, offset))
  167. for row in results:
  168. if row['files']:
  169. try: row['files'] = json.loads(f"[{row['files']}]")
  170. except: row['files'] = []
  171. else: row['files'] = []
  172. row['items'] = db.execute_query("SELECT * FROM order_items WHERE order_id = %s", (row['id'],))
  173. return {"orders": results, "total": total}
  174. @router.post("/{order_id}/review")
  175. async def post_order_review(order_id: int, review: schemas.OrderReview, user: dict = Depends(get_current_user)):
  176. # Check if order belongs to user and is in appropriate status
  177. order = db.execute_query("SELECT id, status FROM orders WHERE id = %s AND user_id = %s", (order_id, user['id']))
  178. if not order:
  179. raise HTTPException(status_code=404, detail="Order not found or access denied")
  180. if order[0]['status'] not in ['shipped', 'completed']:
  181. raise HTTPException(status_code=400, detail="Reviews can only be posted for shipped or completed orders")
  182. db.execute_commit(
  183. "UPDATE orders SET review_text = %s, rating = %s, review_approved = FALSE WHERE id = %s",
  184. (review.review_text, review.rating, order_id)
  185. )
  186. # Create audit log
  187. await audit_service.log(user['id'], "ORDER_REVIEW", f"Posted review for order {order_id}", order_id)
  188. return {"message": "Review submitted successfully and is awaiting moderation"}
  189. @router.patch("/{order_id}/review/approve")
  190. async def approve_order_review(order_id: int, admin: dict = Depends(require_admin)):
  191. db.execute_commit("UPDATE orders SET review_approved = TRUE WHERE id = %s", (order_id,))
  192. await audit_service.log(admin['id'], "ORDER_REVIEW_APPROVE", f"Approved review for order {order_id}", order_id)
  193. return {"message": "Review approved successfully"}
  194. @router.get("/reviews/public", response_model=List[schemas.PublicReview])
  195. async def get_public_reviews():
  196. # Only return approved reviews, anonymized (strictly only the first word of the first name)
  197. query = "SELECT SUBSTRING_INDEX(first_name, ' ', 1) as first_name, rating, review_text FROM orders WHERE review_approved = TRUE ORDER BY created_at DESC LIMIT 10"
  198. return db.execute_query(query)
  199. @router.post("/estimate")
  200. async def get_price_estimate(data: schemas.EstimateRequest):
  201. estimated_total, file_prices = pricing.calculate_estimated_price(
  202. data.material_id,
  203. data.file_sizes,
  204. data.file_quantities,
  205. return_details=True
  206. )
  207. qts = data.file_quantities if data.file_quantities else [1]*len(data.file_sizes)
  208. return {"file_prices": file_prices, "total_estimate": estimated_total}
  209. # --- ADMIN ORDER ENDPOINTS ---
  210. @router.get("/admin/list") # Using /admin/list to avoid conflict with /my
  211. async def get_admin_orders(
  212. search: Optional[str] = None,
  213. status: Optional[str] = None,
  214. date_from: Optional[str] = None,
  215. date_to: Optional[str] = None,
  216. admin: dict = Depends(require_admin)
  217. ):
  218. where_clauses = []
  219. params = []
  220. if search:
  221. search_term = f"%{search}%"
  222. where_clauses.append("(o.id LIKE %s OR o.email LIKE %s OR o.first_name LIKE %s OR o.last_name LIKE %s OR o.company_name LIKE %s OR o.phone LIKE %s OR o.shipping_address LIKE %s)")
  223. params.extend([search_term] * 7)
  224. if status and status != 'all':
  225. where_clauses.append("o.status = %s")
  226. params.append(status)
  227. if date_from:
  228. where_clauses.append("o.created_at >= %s")
  229. params.append(date_from)
  230. if date_to:
  231. where_clauses.append("o.created_at <= %s")
  232. params.append(date_to)
  233. where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
  234. query = f"""
  235. SELECT o.*, u.can_chat, COALESCE(o.total_price, o.estimated_price) AS invoice_amount,
  236. (SELECT count(*) FROM order_messages om WHERE om.order_id = o.id AND om.is_from_admin = FALSE AND om.is_read = FALSE) as unread_count,
  237. GROUP_CONCAT(IF(f.id IS NOT NULL, JSON_OBJECT('id', f.id, 'filename', f.filename, 'file_path', f.file_path, 'file_size', f.file_size, 'quantity', f.quantity, 'preview_path', f.preview_path, 'print_time', f.print_time, 'filament_g', f.filament_g, 'dimensions', f.dimensions), NULL)) as files
  238. FROM orders o
  239. LEFT JOIN users u ON o.user_id = u.id
  240. LEFT JOIN order_files f ON o.id = f.order_id
  241. {where_sql}
  242. GROUP BY o.id
  243. ORDER BY o.created_at DESC
  244. """
  245. results = db.execute_query(query, tuple(params))
  246. import session_utils
  247. for row in results:
  248. row['is_online'] = session_utils.is_user_online(row['user_id']) if row.get('user_id') else False
  249. if row['files']:
  250. try: row['files'] = json.loads(f"[{row['files']}]")
  251. except: row['files'] = []
  252. else: row['files'] = []
  253. row['items'] = db.execute_query("SELECT * FROM order_items WHERE order_id = %s", (row['id'],))
  254. photos = db.execute_query("SELECT id, file_path, is_public FROM order_photos WHERE order_id = %s", (row['id'],))
  255. row['photos'] = photos
  256. return results
  257. @router.patch("/{order_id}")
  258. async def update_order(
  259. order_id: int,
  260. data: schemas.AdminOrderUpdate,
  261. background_tasks: BackgroundTasks,
  262. admin: dict = Depends(require_admin)
  263. ):
  264. print(f"DEBUG: update_order {order_id} - payload: {data.model_dump(exclude_unset=True)}")
  265. order_info = db.execute_query("SELECT * FROM orders WHERE id = %s", (order_id,))
  266. if not order_info: raise HTTPException(status_code=404, detail="Order not found")
  267. update_fields = []
  268. params = []
  269. if data.status:
  270. if order_info:
  271. background_tasks.add_task(
  272. event_hooks.on_order_status_changed,
  273. order_id,
  274. data.status,
  275. order_info[0],
  276. data.send_notification
  277. )
  278. # Generate Payment Documents based on status transitions
  279. from services.invoice_service import InvoiceService
  280. o = order_info[0]
  281. price_val = data.total_price if data.total_price is not None else (o.get('total_price') or o.get('estimated_price') or 0)
  282. price = float(price_val)
  283. # 1. Proforma / Payment Slip (on 'processing' or any initial active state)
  284. if data.status in ['processing', 'shipped']:
  285. try:
  286. if o.get('is_company'):
  287. pdf_path = InvoiceService.generate_document(o, doc_type="predracun", override_price=price)
  288. else:
  289. payer_name = f"{o['first_name']} {o.get('last_name', '')}".strip()
  290. pdf_path = InvoiceService.generate_uplatnica(order_id, payer_name, o.get('shipping_address', ''), price)
  291. update_fields.append("proforma_path = %s")
  292. params.append(pdf_path)
  293. except Exception as e:
  294. print(f"Failed to generate proforma: {e}")
  295. # 2. Final Invoice (only on 'shipped')
  296. if data.status == 'shipped':
  297. try:
  298. pdf_path = InvoiceService.generate_document(o, doc_type="faktura", override_price=price)
  299. update_fields.append("invoice_path = %s")
  300. params.append(pdf_path)
  301. except Exception as e:
  302. print(f"Failed to generate final invoice: {e}")
  303. if data.status:
  304. update_fields.append("status = %s")
  305. params.append(data.status)
  306. if data.total_price is not None:
  307. update_fields.append("total_price = %s")
  308. params.append(data.total_price)
  309. # Sync estimated_price as well to ensure display consistency in all views
  310. update_fields.append("estimated_price = %s")
  311. params.append(data.total_price)
  312. if data.material_id is not None:
  313. update_fields.append("material_id = %s")
  314. params.append(data.material_id)
  315. # Also update snapshot names and prices from handbook
  316. mat_info = db.execute_query("SELECT name_en, price_per_cm3, price_per_hour FROM materials WHERE id = %s", (data.material_id,))
  317. if mat_info:
  318. update_fields.append("material_name = %s")
  319. params.append(mat_info[0]['name_en'])
  320. update_fields.append("material_price = %s")
  321. params.append(mat_info[0]['price_per_cm3'])
  322. update_fields.append("printer_hour_price = %s")
  323. params.append(mat_info[0]['price_per_hour'] if mat_info[0]['price_per_hour'] is not None else config.DEFAULT_PRINTER_HOUR_PRICE)
  324. elif data.material_name is not None:
  325. update_fields.append("material_name = %s")
  326. params.append(data.material_name)
  327. if data.color_name is not None:
  328. update_fields.append("color_name = %s")
  329. params.append(data.color_name)
  330. if data.quantity is not None:
  331. update_fields.append("quantity = %s")
  332. params.append(data.quantity)
  333. if data.fiscal_qr_url is not None:
  334. update_fields.append("fiscal_qr_url = %s")
  335. params.append(data.fiscal_qr_url)
  336. # Auto-set fiscalized_at if adding URL for the first time
  337. if order_info[0].get('fiscalized_at') is None:
  338. update_fields.append("fiscalized_at = %s")
  339. params.append(datetime.now())
  340. if data.ikof is not None:
  341. update_fields.append("ikof = %s")
  342. params.append(data.ikof)
  343. if data.jikr is not None:
  344. update_fields.append("jikr = %s")
  345. params.append(data.jikr)
  346. if data.first_name is not None:
  347. update_fields.append("first_name = %s")
  348. params.append(data.first_name)
  349. if data.last_name is not None:
  350. update_fields.append("last_name = %s")
  351. params.append(data.last_name)
  352. if data.email is not None:
  353. update_fields.append("email = %s")
  354. params.append(data.email)
  355. if data.phone is not None:
  356. update_fields.append("phone = %s")
  357. params.append(data.phone)
  358. if data.shipping_address is not None:
  359. update_fields.append("shipping_address = %s")
  360. params.append(data.shipping_address)
  361. if data.notes is not None:
  362. update_fields.append("notes = %s")
  363. params.append(data.notes)
  364. if data.review_text is not None:
  365. update_fields.append("review_text = %s")
  366. params.append(data.review_text)
  367. if data.rating is not None:
  368. update_fields.append("rating = %s")
  369. params.append(data.rating)
  370. if data.review_approved is not None:
  371. update_fields.append("review_approved = %s")
  372. params.append(data.review_approved)
  373. if update_fields:
  374. query = f"UPDATE orders SET {', '.join(update_fields)} WHERE id = %s"
  375. params.append(order_id)
  376. db.execute_commit(query, tuple(params))
  377. # LOG ACTION
  378. await audit_service.log(
  379. user_id=admin.get("id"),
  380. action="update_order",
  381. target_type="order",
  382. target_id=order_id,
  383. details={"updated_fields": {k.split(" = ")[0]: v for k, v in zip(update_fields, params)}}
  384. )
  385. # NOTIFY USER VIA WEBSOCKET
  386. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  387. return {"id": order_id, "status": "updated"}
  388. @router.post("/{order_id}/attach-file")
  389. async def admin_attach_file(
  390. order_id: int,
  391. background_tasks: BackgroundTasks,
  392. file: UploadFile = File(...),
  393. admin: dict = Depends(require_admin)
  394. ):
  395. unique_filename = f"{uuid.uuid4()}{os.path.splitext(file.filename)[1]}"
  396. file_path = os.path.join(config.UPLOAD_DIR, unique_filename)
  397. db_file_path = f"uploads/{unique_filename}"
  398. sha256_hash = hashlib.sha256()
  399. with open(file_path, "wb") as buffer:
  400. while chunk := file.file.read(8192):
  401. sha256_hash.update(chunk)
  402. buffer.write(chunk)
  403. query = "INSERT INTO order_files (order_id, filename, file_path, file_size, quantity, file_hash, print_time, filament_g, preview_path) VALUES (%s, %s, %s, %s, 1, %s, NULL, NULL, NULL)"
  404. f_id = db.execute_commit(query, (order_id, file.filename, db_file_path, file.size, sha256_hash.hexdigest()))
  405. # Run heavy processing in background to avoid worker timeouts
  406. background_tasks.add_task(order_processing.process_single_file_async, f_id)
  407. # NOTIFY USER VIA WEBSOCKET
  408. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  409. if order_info:
  410. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  411. return {"file_id": f_id, "filename": file.filename, "status": "processing"}
  412. @router.delete("/{order_id}/files/{file_id}")
  413. async def admin_delete_file(
  414. order_id: int,
  415. file_id: int,
  416. admin: dict = Depends(require_admin)
  417. ):
  418. file_record = db.execute_query("SELECT file_path, preview_path FROM order_files WHERE id = %s AND order_id = %s", (file_id, order_id))
  419. if not file_record:
  420. raise HTTPException(status_code=404, detail="File not found")
  421. base_dir = config.BASE_DIR
  422. try:
  423. if file_record[0]['file_path']:
  424. os.remove(os.path.join(base_dir, file_record[0]['file_path']))
  425. if file_record[0]['preview_path']:
  426. os.remove(os.path.join(base_dir, file_record[0]['preview_path']))
  427. except Exception as e:
  428. print(f"Error removing file from disk: {e}")
  429. db.execute_commit("DELETE FROM order_files WHERE id = %s AND order_id = %s", (file_id, order_id))
  430. # LOG ACTION
  431. await audit_service.log(
  432. user_id=admin.get("id"),
  433. action="delete_order_file",
  434. target_type="order",
  435. target_id=order_id,
  436. details={"file_id": file_id}
  437. )
  438. # NOTIFY USER VIA WEBSOCKET
  439. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  440. if order_info:
  441. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  442. return {"status": "success"}
  443. @router.patch("/{order_id}/files/{file_id}")
  444. async def admin_update_file(
  445. order_id: int,
  446. file_id: int,
  447. data: dict,
  448. admin: dict = Depends(require_admin)
  449. ):
  450. if "quantity" in data:
  451. db.execute_commit("UPDATE order_files SET quantity = %s WHERE id = %s AND order_id = %s", (data['quantity'], file_id, order_id))
  452. # Notify user/admin via WS
  453. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  454. if order_info:
  455. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  456. return {"status": "success"}
  457. class OrderItemSchema(BaseModel):
  458. description: str
  459. quantity: int
  460. unit_price: float
  461. @router.get("/{order_id}/items")
  462. async def get_order_items(order_id: int):
  463. items = db.execute_query("SELECT * FROM order_items WHERE order_id = %s", (order_id,))
  464. return items
  465. @router.put("/{order_id}/items")
  466. async def update_order_items(order_id: int, items: List[OrderItemSchema], admin: dict = Depends(require_admin)):
  467. db.execute_commit("DELETE FROM order_items WHERE order_id = %s", (order_id,))
  468. total_order_price = 0
  469. items_summary = []
  470. for item in items:
  471. tot_p = round(item.quantity * item.unit_price, 2)
  472. total_order_price += tot_p
  473. db.execute_commit(
  474. "INSERT INTO order_items (order_id, description, quantity, unit_price, total_price) VALUES (%s, %s, %s, %s, %s)",
  475. (order_id, item.description, item.quantity, item.unit_price, tot_p)
  476. )
  477. items_summary.append(item.dict())
  478. # Sync main order total_price
  479. db.execute_commit("UPDATE orders SET total_price = %s WHERE id = %s", (total_order_price, order_id))
  480. # LOG ACTION
  481. await audit_service.log(
  482. user_id=admin.get("id"),
  483. action="update_order_items",
  484. target_type="order",
  485. target_id=order_id,
  486. details={"total_price": total_order_price, "items": items_summary}
  487. )
  488. # NOTIFY USER VIA WEBSOCKET
  489. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  490. if order_info:
  491. await global_manager.notify_order_update(order_info[0]['user_id'], order_id)
  492. return {"status": "success", "total_price": total_order_price}
  493. @router.delete("/{order_id}/admin")
  494. async def delete_order_admin(
  495. order_id: int,
  496. admin: dict = Depends(require_admin)
  497. ):
  498. # Fetch user_id before deletion to notify later
  499. order_info = db.execute_query("SELECT user_id FROM orders WHERE id = %s", (order_id,))
  500. if not order_info: raise HTTPException(status_code=404, detail="Order not found")
  501. customer_id = order_info[0]['user_id']
  502. # 1. Find all related files to delete from disk
  503. files = db.execute_query("SELECT file_path, preview_path FROM order_files WHERE order_id = %s", (order_id,))
  504. photos = db.execute_query("SELECT file_path FROM order_photos WHERE order_id = %s", (order_id,))
  505. base_dir = config.BASE_DIR
  506. # Delete order_files from disk
  507. for f in files:
  508. try:
  509. if f.get('file_path'):
  510. fpath = os.path.join(base_dir, f['file_path'])
  511. if os.path.exists(fpath): os.remove(fpath)
  512. if f.get('preview_path'):
  513. ppath = os.path.join(base_dir, f['preview_path'])
  514. if os.path.exists(ppath): os.remove(ppath)
  515. except Exception as e:
  516. print(f"Error deleting order file {f.get('file_path')}: {e}")
  517. # Delete photos from disk
  518. for p in photos:
  519. try:
  520. if p.get('file_path'):
  521. fpath = os.path.join(base_dir, p['file_path'])
  522. if os.path.exists(fpath): os.remove(fpath)
  523. except Exception as e:
  524. print(f"Error deleting order photo {p.get('file_path')}: {e}")
  525. # 2. Delete from DB tables (due to possible lack of CASCADE or to be explicit)
  526. try:
  527. db.execute_commit("DELETE FROM order_messages WHERE order_id = %s", (order_id,))
  528. db.execute_commit("DELETE FROM order_items WHERE order_id = %s", (order_id,))
  529. db.execute_commit("DELETE FROM order_files WHERE order_id = %s", (order_id,))
  530. db.execute_commit("DELETE FROM order_photos WHERE order_id = %s", (order_id,))
  531. db.execute_commit("DELETE FROM orders WHERE id = %s", (order_id,))
  532. # LOG ACTION
  533. await audit_service.log(
  534. user_id=admin.get("id"),
  535. action="delete_order_entirely",
  536. target_type="order",
  537. target_id=order_id,
  538. details={"order_id": order_id}
  539. )
  540. # NOTIFY USER VIA WEBSOCKET
  541. await global_manager.notify_order_update(customer_id, order_id)
  542. return {"status": "success", "message": f"Order {order_id} deleted entirely"}
  543. except Exception as e:
  544. print(f"Failed to delete order {order_id}: {e}")
  545. raise HTTPException(status_code=500, detail=str(e))