orders.py 27 KB

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