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