projects.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. import io
  2. import json
  3. import logging
  4. import os
  5. import uuid
  6. import zipfile
  7. from datetime import datetime
  8. from pathlib import Path
  9. from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
  10. from fastapi.responses import FileResponse, StreamingResponse
  11. from sqlalchemy import case, func, select
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from sqlalchemy.orm import selectinload
  14. from backend.app.api.routes.library import get_library_dir
  15. from backend.app.core.auth import RequireCameraStreamTokenIfAuthEnabled, RequirePermissionIfAuthEnabled
  16. from backend.app.core.config import settings
  17. from backend.app.core.database import get_db
  18. from backend.app.core.permissions import Permission
  19. from backend.app.models.archive import PrintArchive
  20. from backend.app.models.library import LibraryFile, LibraryFolder
  21. from backend.app.models.print_queue import PrintQueueItem
  22. from backend.app.models.project import Project
  23. from backend.app.models.project_bom import ProjectBOMItem
  24. from backend.app.models.user import User
  25. from backend.app.schemas.project import (
  26. ArchivePreview,
  27. BatchAddArchives,
  28. BatchAddQueueItems,
  29. BOMItemCreate,
  30. BOMItemResponse,
  31. BOMItemUpdate,
  32. ProjectChildPreview,
  33. ProjectCreate,
  34. ProjectImport,
  35. ProjectListResponse,
  36. ProjectResponse,
  37. ProjectStats,
  38. ProjectUpdate,
  39. TimelineEvent,
  40. )
  41. from backend.app.utils.http import build_content_disposition
  42. logger = logging.getLogger(__name__)
  43. router = APIRouter(prefix="/projects", tags=["projects"])
  44. async def compute_project_stats(
  45. db: AsyncSession, project_id: int, target_count: int | None = None, target_parts_count: int | None = None
  46. ) -> ProjectStats:
  47. """Compute statistics for a project."""
  48. # Count total archives (distinct print jobs)
  49. total_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.project_id == project_id))
  50. total_archives = total_result.scalar() or 0
  51. # Sum total items (using quantity field)
  52. total_items_result = await db.execute(
  53. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(PrintArchive.project_id == project_id)
  54. )
  55. total_items = total_items_result.scalar() or 0
  56. # Count failed archives (number of print jobs) - includes all failure states
  57. failed_result = await db.execute(
  58. select(func.count(PrintArchive.id)).where(
  59. PrintArchive.project_id == project_id,
  60. PrintArchive.status.in_(["failed", "aborted", "cancelled", "stopped"]),
  61. )
  62. )
  63. failed_prints = failed_result.scalar() or 0
  64. # Sum print time, filament, and energy
  65. sums_result = await db.execute(
  66. select(
  67. func.coalesce(func.sum(PrintArchive.print_time_seconds), 0).label("total_time"),
  68. func.coalesce(func.sum(PrintArchive.filament_used_grams), 0).label("total_filament"),
  69. func.coalesce(func.sum(PrintArchive.cost), 0).label("total_filament_cost"),
  70. func.coalesce(func.sum(PrintArchive.energy_kwh), 0).label("total_energy"),
  71. func.coalesce(func.sum(PrintArchive.energy_cost), 0).label("total_energy_cost"),
  72. ).where(PrintArchive.project_id == project_id)
  73. )
  74. sums = sums_result.first()
  75. # Count queued items
  76. queued_result = await db.execute(
  77. select(func.count(PrintQueueItem.id)).where(
  78. PrintQueueItem.project_id == project_id, PrintQueueItem.status == "pending"
  79. )
  80. )
  81. queued_prints = queued_result.scalar() or 0
  82. # Count in-progress items
  83. in_progress_result = await db.execute(
  84. select(func.count(PrintQueueItem.id)).where(
  85. PrintQueueItem.project_id == project_id, PrintQueueItem.status == "printing"
  86. )
  87. )
  88. in_progress_prints = in_progress_result.scalar() or 0
  89. # Sum completed items (parts) - sum of quantities for actually printed jobs
  90. completed_items_result = await db.execute(
  91. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  92. PrintArchive.project_id == project_id,
  93. PrintArchive.status == "completed",
  94. )
  95. )
  96. completed_items = int(completed_items_result.scalar() or 0)
  97. # Calculate progress for plates (target_count vs total_archives)
  98. progress_percent = None
  99. remaining_prints = None
  100. if target_count and target_count > 0:
  101. progress_percent = round((total_archives / target_count) * 100, 1)
  102. remaining_prints = max(0, target_count - total_archives)
  103. # Calculate progress for parts (target_parts_count vs completed_items)
  104. parts_progress_percent = None
  105. remaining_parts = None
  106. if target_parts_count and target_parts_count > 0:
  107. parts_progress_percent = round((completed_items / target_parts_count) * 100, 1)
  108. remaining_parts = max(0, target_parts_count - completed_items)
  109. # BOM stats
  110. bom_result = await db.execute(
  111. select(
  112. func.count(ProjectBOMItem.id).label("total"),
  113. func.sum(case((ProjectBOMItem.quantity_acquired >= ProjectBOMItem.quantity_needed, 1), else_=0)).label(
  114. "completed"
  115. ),
  116. func.coalesce(func.sum(ProjectBOMItem.unit_price * ProjectBOMItem.quantity_needed), 0).label("bom_cost"),
  117. ).where(ProjectBOMItem.project_id == project_id)
  118. )
  119. bom_stats = bom_result.first()
  120. return ProjectStats(
  121. total_archives=total_archives,
  122. total_items=int(total_items),
  123. completed_prints=completed_items, # Now reflects sum of quantities for completed prints
  124. failed_prints=int(failed_prints),
  125. queued_prints=queued_prints,
  126. in_progress_prints=in_progress_prints,
  127. total_print_time_hours=round((sums.total_time or 0) / 3600, 2),
  128. total_filament_grams=round(sums.total_filament or 0, 2),
  129. progress_percent=progress_percent,
  130. parts_progress_percent=parts_progress_percent,
  131. estimated_cost=round((sums.total_filament_cost or 0), 2),
  132. total_energy_kwh=round((sums.total_energy or 0), 3),
  133. total_energy_cost=round((sums.total_energy_cost or 0), 3),
  134. remaining_prints=remaining_prints,
  135. remaining_parts=remaining_parts,
  136. bom_total_items=bom_stats.total or 0,
  137. bom_completed_items=int(bom_stats.completed or 0),
  138. bom_cost=round(float(bom_stats.bom_cost or 0), 2),
  139. )
  140. @router.get("", response_model=list[ProjectListResponse])
  141. @router.get("/", response_model=list[ProjectListResponse])
  142. async def list_projects(
  143. status: str | None = None,
  144. db: AsyncSession = Depends(get_db),
  145. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  146. ):
  147. """List all projects with basic stats."""
  148. query = select(Project)
  149. if status:
  150. query = query.where(Project.status == status)
  151. query = query.order_by(Project.updated_at.desc())
  152. result = await db.execute(query)
  153. projects = result.scalars().all()
  154. # Compute quick stats for each project
  155. response = []
  156. for project in projects:
  157. # Get archive count (number of print jobs)
  158. archive_count_result = await db.execute(
  159. select(func.count(PrintArchive.id)).where(PrintArchive.project_id == project.id)
  160. )
  161. archive_count = archive_count_result.scalar() or 0
  162. # Get total items (sum of quantities)
  163. total_items_result = await db.execute(
  164. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(PrintArchive.project_id == project.id)
  165. )
  166. total_items = int(total_items_result.scalar() or 0)
  167. # Get queue count
  168. queue_count_result = await db.execute(
  169. select(func.count(PrintQueueItem.id)).where(
  170. PrintQueueItem.project_id == project.id,
  171. PrintQueueItem.status.in_(["pending", "printing"]),
  172. )
  173. )
  174. queue_count = queue_count_result.scalar() or 0
  175. # Sum completed parts (quantities) - only actually printed jobs
  176. completed_result = await db.execute(
  177. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  178. PrintArchive.project_id == project.id,
  179. PrintArchive.status == "completed",
  180. )
  181. )
  182. completed_count = int(completed_result.scalar() or 0)
  183. # Sum failed parts (quantities) - includes all failure states
  184. failed_result = await db.execute(
  185. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  186. PrintArchive.project_id == project.id,
  187. PrintArchive.status.in_(["failed", "aborted", "cancelled", "stopped"]),
  188. )
  189. )
  190. failed_count = int(failed_result.scalar() or 0)
  191. # Plates progress: archive_count / target_count
  192. progress_percent = None
  193. if project.target_count and project.target_count > 0:
  194. progress_percent = round((archive_count / project.target_count) * 100, 1)
  195. # Get archive previews (up to 6 most recent)
  196. archives_result = await db.execute(
  197. select(PrintArchive)
  198. .where(PrintArchive.project_id == project.id)
  199. .order_by(PrintArchive.created_at.desc())
  200. .limit(6)
  201. )
  202. archives = archives_result.scalars().all()
  203. archive_previews = [
  204. ArchivePreview(
  205. id=a.id,
  206. print_name=a.print_name,
  207. thumbnail_path=a.thumbnail_path,
  208. status=a.status,
  209. filament_type=a.filament_type,
  210. filament_color=a.filament_color,
  211. )
  212. for a in archives
  213. ]
  214. response.append(
  215. ProjectListResponse(
  216. id=project.id,
  217. name=project.name,
  218. description=project.description,
  219. color=project.color,
  220. status=project.status,
  221. target_count=project.target_count,
  222. target_parts_count=project.target_parts_count,
  223. budget=project.budget,
  224. created_at=project.created_at,
  225. archive_count=archive_count,
  226. total_items=total_items,
  227. completed_count=completed_count,
  228. failed_count=failed_count,
  229. queue_count=queue_count,
  230. progress_percent=progress_percent,
  231. archives=archive_previews,
  232. url=project.url,
  233. cover_image_filename=project.cover_image_filename,
  234. )
  235. )
  236. return response
  237. @router.post("/", response_model=ProjectResponse)
  238. async def create_project(
  239. data: ProjectCreate,
  240. db: AsyncSession = Depends(get_db),
  241. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  242. ):
  243. """Create a new project."""
  244. # Verify parent exists if specified
  245. parent_name = None
  246. if data.parent_id:
  247. parent_result = await db.execute(select(Project).where(Project.id == data.parent_id))
  248. parent = parent_result.scalar_one_or_none()
  249. if not parent:
  250. raise HTTPException(status_code=400, detail="Parent project not found")
  251. parent_name = parent.name
  252. project = Project(
  253. name=data.name,
  254. description=data.description,
  255. color=data.color,
  256. target_count=data.target_count,
  257. target_parts_count=data.target_parts_count,
  258. notes=data.notes,
  259. tags=data.tags,
  260. due_date=data.due_date,
  261. priority=data.priority,
  262. budget=data.budget,
  263. parent_id=data.parent_id,
  264. url=data.url,
  265. )
  266. db.add(project)
  267. await db.flush()
  268. await db.refresh(project)
  269. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  270. return ProjectResponse(
  271. id=project.id,
  272. name=project.name,
  273. description=project.description,
  274. color=project.color,
  275. status=project.status,
  276. target_count=project.target_count,
  277. target_parts_count=project.target_parts_count,
  278. notes=project.notes,
  279. attachments=project.attachments,
  280. url=project.url,
  281. cover_image_filename=project.cover_image_filename,
  282. tags=project.tags,
  283. due_date=project.due_date,
  284. priority=project.priority,
  285. budget=project.budget,
  286. is_template=project.is_template,
  287. template_source_id=project.template_source_id,
  288. parent_id=project.parent_id,
  289. parent_name=parent_name,
  290. children=[],
  291. created_at=project.created_at,
  292. updated_at=project.updated_at,
  293. stats=stats,
  294. )
  295. # ============ Phase 8: Template Endpoints (Static routes BEFORE dynamic {project_id}) ============
  296. @router.get("/templates", response_model=list[ProjectListResponse])
  297. async def list_templates(
  298. db: AsyncSession = Depends(get_db),
  299. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  300. ):
  301. """List all project templates."""
  302. result = await db.execute(select(Project).where(Project.is_template.is_(True)).order_by(Project.name))
  303. templates = result.scalars().all()
  304. response = []
  305. for project in templates:
  306. # Get archive count
  307. archive_count_result = await db.execute(
  308. select(func.count(PrintArchive.id)).where(PrintArchive.project_id == project.id)
  309. )
  310. archive_count = archive_count_result.scalar() or 0
  311. response.append(
  312. ProjectListResponse(
  313. id=project.id,
  314. name=project.name,
  315. description=project.description,
  316. color=project.color,
  317. status=project.status,
  318. target_count=project.target_count,
  319. budget=project.budget,
  320. created_at=project.created_at,
  321. archive_count=archive_count,
  322. queue_count=0,
  323. progress_percent=None,
  324. archives=[],
  325. url=project.url,
  326. cover_image_filename=project.cover_image_filename,
  327. )
  328. )
  329. return response
  330. @router.post("/from-template/{template_id}", response_model=ProjectResponse)
  331. async def create_project_from_template(
  332. template_id: int,
  333. name: str = None,
  334. db: AsyncSession = Depends(get_db),
  335. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  336. ):
  337. """Create a new project from a template."""
  338. result = await db.execute(select(Project).where(Project.id == template_id))
  339. template = result.scalar_one_or_none()
  340. if not template:
  341. raise HTTPException(status_code=404, detail="Template not found")
  342. if not template.is_template:
  343. raise HTTPException(status_code=400, detail="Project is not a template")
  344. # Create new project
  345. project = Project(
  346. name=name or template.name.replace(" (Template)", ""),
  347. description=template.description,
  348. color=template.color,
  349. target_count=template.target_count,
  350. target_parts_count=template.target_parts_count,
  351. notes=template.notes,
  352. tags=template.tags,
  353. priority=template.priority,
  354. budget=template.budget,
  355. is_template=False,
  356. template_source_id=template.id,
  357. url=template.url,
  358. )
  359. db.add(project)
  360. await db.flush()
  361. # Copy BOM items
  362. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == template_id))
  363. bom_items = bom_result.scalars().all()
  364. for item in bom_items:
  365. new_item = ProjectBOMItem(
  366. project_id=project.id,
  367. name=item.name,
  368. quantity_needed=item.quantity_needed,
  369. quantity_acquired=0,
  370. unit_price=item.unit_price,
  371. sourcing_url=item.sourcing_url,
  372. stl_filename=item.stl_filename,
  373. remarks=item.remarks,
  374. sort_order=item.sort_order,
  375. )
  376. db.add(new_item)
  377. await db.flush()
  378. await db.refresh(project)
  379. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  380. return ProjectResponse(
  381. id=project.id,
  382. name=project.name,
  383. description=project.description,
  384. color=project.color,
  385. status=project.status,
  386. target_count=project.target_count,
  387. target_parts_count=project.target_parts_count,
  388. notes=project.notes,
  389. attachments=project.attachments,
  390. url=project.url,
  391. cover_image_filename=project.cover_image_filename,
  392. tags=project.tags,
  393. due_date=project.due_date,
  394. priority=project.priority,
  395. budget=project.budget,
  396. is_template=project.is_template,
  397. template_source_id=project.template_source_id,
  398. parent_id=project.parent_id,
  399. parent_name=None,
  400. children=[],
  401. created_at=project.created_at,
  402. updated_at=project.updated_at,
  403. stats=stats,
  404. )
  405. # ============ Dynamic {project_id} Routes ============
  406. async def get_child_previews(db: AsyncSession, parent_id: int) -> list[ProjectChildPreview]:
  407. """Get preview info for child projects."""
  408. result = await db.execute(select(Project).where(Project.parent_id == parent_id).order_by(Project.name))
  409. children = result.scalars().all()
  410. previews = []
  411. for child in children:
  412. # Get completed count for progress (sum of quantities)
  413. completed_result = await db.execute(
  414. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  415. PrintArchive.project_id == child.id,
  416. PrintArchive.status == "completed",
  417. )
  418. )
  419. completed_count = completed_result.scalar() or 0
  420. progress = None
  421. if child.target_count and child.target_count > 0:
  422. progress = round((int(completed_count) / child.target_count) * 100, 1)
  423. previews.append(
  424. ProjectChildPreview(
  425. id=child.id,
  426. name=child.name,
  427. color=child.color,
  428. status=child.status,
  429. progress_percent=progress,
  430. )
  431. )
  432. return previews
  433. @router.get("/{project_id}", response_model=ProjectResponse)
  434. async def get_project(
  435. project_id: int,
  436. db: AsyncSession = Depends(get_db),
  437. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  438. ):
  439. """Get a project by ID with detailed stats."""
  440. result = await db.execute(select(Project).where(Project.id == project_id))
  441. project = result.scalar_one_or_none()
  442. if not project:
  443. raise HTTPException(status_code=404, detail="Project not found")
  444. # Get parent name
  445. parent_name = None
  446. if project.parent_id:
  447. parent_result = await db.execute(select(Project.name).where(Project.id == project.parent_id))
  448. parent_name = parent_result.scalar()
  449. # Get children
  450. children = await get_child_previews(db, project.id)
  451. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  452. return ProjectResponse(
  453. id=project.id,
  454. name=project.name,
  455. description=project.description,
  456. color=project.color,
  457. status=project.status,
  458. target_count=project.target_count,
  459. target_parts_count=project.target_parts_count,
  460. notes=project.notes,
  461. attachments=project.attachments,
  462. url=project.url,
  463. cover_image_filename=project.cover_image_filename,
  464. tags=project.tags,
  465. due_date=project.due_date,
  466. priority=project.priority,
  467. budget=project.budget,
  468. is_template=project.is_template,
  469. template_source_id=project.template_source_id,
  470. parent_id=project.parent_id,
  471. parent_name=parent_name,
  472. children=children,
  473. created_at=project.created_at,
  474. updated_at=project.updated_at,
  475. stats=stats,
  476. )
  477. @router.patch("/{project_id}", response_model=ProjectResponse)
  478. async def update_project(
  479. project_id: int,
  480. data: ProjectUpdate,
  481. db: AsyncSession = Depends(get_db),
  482. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  483. ):
  484. """Update a project."""
  485. result = await db.execute(select(Project).where(Project.id == project_id))
  486. project = result.scalar_one_or_none()
  487. if not project:
  488. raise HTTPException(status_code=404, detail="Project not found")
  489. # Update fields if provided
  490. if data.name is not None:
  491. project.name = data.name
  492. if data.description is not None:
  493. project.description = data.description
  494. if data.color is not None:
  495. project.color = data.color
  496. if data.status is not None:
  497. if data.status not in ["active", "completed", "archived"]:
  498. raise HTTPException(status_code=400, detail="Invalid status")
  499. project.status = data.status
  500. if data.target_count is not None:
  501. project.target_count = data.target_count
  502. if data.target_parts_count is not None:
  503. project.target_parts_count = data.target_parts_count
  504. if data.notes is not None:
  505. project.notes = data.notes
  506. if data.tags is not None:
  507. project.tags = data.tags
  508. if data.due_date is not None:
  509. project.due_date = data.due_date
  510. if data.priority is not None:
  511. if data.priority not in ["low", "normal", "high", "urgent"]:
  512. raise HTTPException(status_code=400, detail="Invalid priority")
  513. project.priority = data.priority
  514. if "budget" in data.model_fields_set:
  515. project.budget = data.budget
  516. if "url" in data.model_fields_set:
  517. # Pydantic validator already guarantees http(s) prefix or None.
  518. project.url = data.url
  519. if data.parent_id is not None:
  520. # Verify parent exists and prevent circular reference
  521. if data.parent_id == project_id:
  522. raise HTTPException(status_code=400, detail="Project cannot be its own parent")
  523. if data.parent_id != 0: # 0 means remove parent
  524. parent_result = await db.execute(select(Project).where(Project.id == data.parent_id))
  525. if not parent_result.scalar_one_or_none():
  526. raise HTTPException(status_code=400, detail="Parent project not found")
  527. project.parent_id = data.parent_id
  528. else:
  529. project.parent_id = None
  530. await db.flush()
  531. await db.refresh(project)
  532. # Get parent name
  533. parent_name = None
  534. if project.parent_id:
  535. parent_result = await db.execute(select(Project.name).where(Project.id == project.parent_id))
  536. parent_name = parent_result.scalar()
  537. # Get children
  538. children = await get_child_previews(db, project.id)
  539. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  540. return ProjectResponse(
  541. id=project.id,
  542. name=project.name,
  543. description=project.description,
  544. color=project.color,
  545. status=project.status,
  546. target_count=project.target_count,
  547. target_parts_count=project.target_parts_count,
  548. notes=project.notes,
  549. attachments=project.attachments,
  550. url=project.url,
  551. cover_image_filename=project.cover_image_filename,
  552. tags=project.tags,
  553. due_date=project.due_date,
  554. priority=project.priority,
  555. budget=project.budget,
  556. is_template=project.is_template,
  557. template_source_id=project.template_source_id,
  558. parent_id=project.parent_id,
  559. parent_name=parent_name,
  560. children=children,
  561. created_at=project.created_at,
  562. updated_at=project.updated_at,
  563. stats=stats,
  564. )
  565. @router.delete("/{project_id}")
  566. async def delete_project(
  567. project_id: int,
  568. db: AsyncSession = Depends(get_db),
  569. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_DELETE),
  570. ):
  571. """Delete a project. Archives and queue items will have project_id set to NULL."""
  572. result = await db.execute(select(Project).where(Project.id == project_id))
  573. project = result.scalar_one_or_none()
  574. if not project:
  575. raise HTTPException(status_code=404, detail="Project not found")
  576. await db.delete(project)
  577. return {"message": "Project deleted"}
  578. @router.get("/{project_id}/archives")
  579. async def list_project_archives(
  580. project_id: int,
  581. limit: int = 100,
  582. offset: int = 0,
  583. db: AsyncSession = Depends(get_db),
  584. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  585. ):
  586. """List archives in a project."""
  587. # Verify project exists
  588. result = await db.execute(select(Project).where(Project.id == project_id))
  589. if not result.scalar_one_or_none():
  590. raise HTTPException(status_code=404, detail="Project not found")
  591. # Get archives with both ``project`` and ``created_by`` eagerly loaded.
  592. # ``archive_to_response`` accesses ``archive.created_by.username`` to
  593. # surface the creator on the archive card; without selectinload that's
  594. # a lazy attribute access on a closed async session, which throws
  595. # ``MissingGreenlet`` and produces a 500. ``ArchiveService.list_archives``
  596. # already loads both — this route just got out of step.
  597. query = (
  598. select(PrintArchive)
  599. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  600. .where(PrintArchive.project_id == project_id)
  601. .order_by(PrintArchive.created_at.desc())
  602. .limit(limit)
  603. .offset(offset)
  604. )
  605. result = await db.execute(query)
  606. archives = result.scalars().all()
  607. # Import the response converter from archives module
  608. from backend.app.api.routes.archives import archive_to_response
  609. return [archive_to_response(a) for a in archives]
  610. @router.get("/{project_id}/queue")
  611. async def list_project_queue(
  612. project_id: int,
  613. db: AsyncSession = Depends(get_db),
  614. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  615. ):
  616. """List queue items in a project."""
  617. # Verify project exists
  618. result = await db.execute(select(Project).where(Project.id == project_id))
  619. if not result.scalar_one_or_none():
  620. raise HTTPException(status_code=404, detail="Project not found")
  621. # Get queue items
  622. query = select(PrintQueueItem).where(PrintQueueItem.project_id == project_id).order_by(PrintQueueItem.position)
  623. result = await db.execute(query)
  624. items = result.scalars().all()
  625. return items
  626. @router.post("/{project_id}/add-archives")
  627. async def add_archives_to_project(
  628. project_id: int,
  629. data: BatchAddArchives,
  630. db: AsyncSession = Depends(get_db),
  631. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  632. ):
  633. """Batch add archives to a project."""
  634. # Verify project exists
  635. result = await db.execute(select(Project).where(Project.id == project_id))
  636. if not result.scalar_one_or_none():
  637. raise HTTPException(status_code=404, detail="Project not found")
  638. # Update archives
  639. updated = 0
  640. for archive_id in data.archive_ids:
  641. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  642. archive = result.scalar_one_or_none()
  643. if archive:
  644. archive.project_id = project_id
  645. updated += 1
  646. return {"message": f"Added {updated} archives to project"}
  647. @router.post("/{project_id}/add-queue")
  648. async def add_queue_items_to_project(
  649. project_id: int,
  650. data: BatchAddQueueItems,
  651. db: AsyncSession = Depends(get_db),
  652. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  653. ):
  654. """Batch add queue items to a project."""
  655. # Verify project exists
  656. result = await db.execute(select(Project).where(Project.id == project_id))
  657. if not result.scalar_one_or_none():
  658. raise HTTPException(status_code=404, detail="Project not found")
  659. # Update queue items
  660. updated = 0
  661. for item_id in data.queue_item_ids:
  662. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  663. item = result.scalar_one_or_none()
  664. if item:
  665. item.project_id = project_id
  666. updated += 1
  667. return {"message": f"Added {updated} queue items to project"}
  668. @router.post("/{project_id}/remove-archives")
  669. async def remove_archives_from_project(
  670. project_id: int,
  671. data: BatchAddArchives,
  672. db: AsyncSession = Depends(get_db),
  673. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  674. ):
  675. """Remove archives from a project (sets project_id to NULL)."""
  676. updated = 0
  677. for archive_id in data.archive_ids:
  678. result = await db.execute(
  679. select(PrintArchive).where(
  680. PrintArchive.id == archive_id,
  681. PrintArchive.project_id == project_id,
  682. )
  683. )
  684. archive = result.scalar_one_or_none()
  685. if archive:
  686. archive.project_id = None
  687. updated += 1
  688. return {"message": f"Removed {updated} archives from project"}
  689. def get_project_attachments_dir(project_id: int) -> Path:
  690. """Get the attachments directory for a project."""
  691. base_dir = Path(settings.archive_dir)
  692. return base_dir / "projects" / str(project_id) / "attachments"
  693. # Cover-image upload accepts only common web-renderable image types (#1155).
  694. # Subset of ALLOWED_ATTACHMENT_EXTENSIONS minus .svg/.ico because those don't
  695. # render well as a card thumbnail.
  696. COVER_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
  697. COVER_IMAGE_CONTENT_TYPES = {
  698. ".jpg": "image/jpeg",
  699. ".jpeg": "image/jpeg",
  700. ".png": "image/png",
  701. ".gif": "image/gif",
  702. ".webp": "image/webp",
  703. }
  704. # Allowed file extensions for attachments
  705. ALLOWED_ATTACHMENT_EXTENSIONS = {
  706. # Images
  707. ".jpg",
  708. ".jpeg",
  709. ".png",
  710. ".gif",
  711. ".webp",
  712. ".svg",
  713. ".bmp",
  714. ".ico",
  715. # Documents
  716. ".pdf",
  717. ".doc",
  718. ".docx",
  719. ".xls",
  720. ".xlsx",
  721. ".ppt",
  722. ".pptx",
  723. ".odt",
  724. ".ods",
  725. ".odp",
  726. ".txt",
  727. ".rtf",
  728. ".csv",
  729. ".md",
  730. # 3D/CAD files
  731. ".stl",
  732. ".obj",
  733. ".3mf",
  734. ".step",
  735. ".stp",
  736. ".iges",
  737. ".igs",
  738. ".f3d",
  739. ".scad",
  740. # Archives
  741. ".zip",
  742. ".rar",
  743. ".7z",
  744. ".tar",
  745. ".gz",
  746. # Code/scripts (for Klipper macros, scripts, etc.)
  747. ".py",
  748. ".sh",
  749. ".cfg",
  750. ".conf",
  751. ".gcode",
  752. ".ini",
  753. # Other common formats
  754. ".json",
  755. ".xml",
  756. ".yaml",
  757. ".yml",
  758. }
  759. @router.post("/{project_id}/attachments")
  760. async def upload_attachment(
  761. project_id: int,
  762. file: UploadFile = File(...),
  763. db: AsyncSession = Depends(get_db),
  764. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  765. ):
  766. """Upload an attachment to a project."""
  767. logger.info("=== UPLOAD START: %s for project %s ===", file.filename, project_id)
  768. # Verify project exists
  769. result = await db.execute(select(Project).where(Project.id == project_id))
  770. project = result.scalar_one_or_none()
  771. if not project:
  772. raise HTTPException(status_code=404, detail="Project not found")
  773. # Validate file extension
  774. original_name = file.filename or "unknown"
  775. ext = os.path.splitext(original_name)[1].lower()
  776. if ext not in ALLOWED_ATTACHMENT_EXTENSIONS:
  777. raise HTTPException(
  778. status_code=400,
  779. detail=f"File type '{ext}' not supported. Allowed: images, PDFs, documents, STL, 3MF, archives.",
  780. )
  781. # Create attachments directory
  782. attachments_dir = get_project_attachments_dir(project_id)
  783. attachments_dir.mkdir(parents=True, exist_ok=True)
  784. # Generate unique filename
  785. unique_filename = f"{uuid.uuid4().hex}{ext}"
  786. file_path = attachments_dir / unique_filename
  787. # Save file
  788. try:
  789. with open(file_path, "wb") as f:
  790. content = await file.read()
  791. f.write(content)
  792. logger.info("=== FILE SAVED: %s, size: %s ===", file_path, len(content))
  793. except Exception as e:
  794. logger.error("Failed to save attachment: %s", e)
  795. raise HTTPException(status_code=500, detail="Failed to save attachment")
  796. # Update project attachments JSON
  797. attachments = list(project.attachments or [])
  798. new_attachment = {
  799. "filename": unique_filename,
  800. "original_name": original_name,
  801. "size": len(content),
  802. "uploaded_at": datetime.now().isoformat(),
  803. }
  804. attachments.append(new_attachment)
  805. # Simple ORM update
  806. project.attachments = attachments
  807. db.add(project) # Explicitly add to session
  808. logger.info("=== BEFORE COMMIT: %s attachments ===", len(attachments))
  809. await db.flush()
  810. await db.commit()
  811. logger.info("=== AFTER COMMIT ===")
  812. # Verify by re-querying
  813. result = await db.execute(select(Project).where(Project.id == project_id))
  814. fresh_project = result.scalar_one()
  815. logger.info("=== VERIFIED: %s attachments ===", len(fresh_project.attachments or []))
  816. return {
  817. "status": "success",
  818. "filename": unique_filename,
  819. "original_name": original_name,
  820. "attachments": fresh_project.attachments,
  821. }
  822. @router.get("/{project_id}/attachments/{filename}")
  823. async def download_attachment(
  824. project_id: int,
  825. filename: str,
  826. db: AsyncSession = Depends(get_db),
  827. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  828. ):
  829. """Download an attachment from a project."""
  830. # Validate filename to prevent path traversal
  831. if "/" in filename or "\\" in filename or ".." in filename or not filename:
  832. raise HTTPException(status_code=400, detail="Invalid filename")
  833. # Verify project exists
  834. result = await db.execute(select(Project).where(Project.id == project_id))
  835. project = result.scalar_one_or_none()
  836. if not project:
  837. raise HTTPException(status_code=404, detail="Project not found")
  838. # Verify attachment exists in project
  839. attachments = project.attachments or []
  840. attachment = next((a for a in attachments if a.get("filename") == filename), None)
  841. if not attachment:
  842. raise HTTPException(status_code=404, detail="Attachment not found")
  843. # Check file exists
  844. file_path = get_project_attachments_dir(project_id) / filename
  845. if not file_path.exists():
  846. raise HTTPException(status_code=404, detail="Attachment file not found")
  847. return FileResponse(
  848. file_path,
  849. filename=attachment.get("original_name", filename),
  850. media_type="application/octet-stream",
  851. )
  852. @router.delete("/{project_id}/attachments/{filename}")
  853. async def delete_attachment(
  854. project_id: int,
  855. filename: str,
  856. db: AsyncSession = Depends(get_db),
  857. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  858. ):
  859. """Delete an attachment from a project."""
  860. # Validate filename to prevent path traversal
  861. if "/" in filename or "\\" in filename or ".." in filename or not filename:
  862. raise HTTPException(status_code=400, detail="Invalid filename")
  863. # Verify project exists
  864. result = await db.execute(select(Project).where(Project.id == project_id))
  865. project = result.scalar_one_or_none()
  866. if not project:
  867. raise HTTPException(status_code=404, detail="Project not found")
  868. # Find and remove attachment from list
  869. attachments = project.attachments or []
  870. attachment = next((a for a in attachments if a.get("filename") == filename), None)
  871. if not attachment:
  872. raise HTTPException(status_code=404, detail="Attachment not found")
  873. # Remove from list
  874. attachments = [a for a in attachments if a.get("filename") != filename]
  875. project.attachments = attachments if attachments else None
  876. # Delete file
  877. file_path = get_project_attachments_dir(project_id) / filename
  878. if file_path.exists():
  879. try:
  880. os.remove(file_path)
  881. except Exception as e:
  882. logger.warning("Failed to delete attachment file: %s", e)
  883. await db.flush()
  884. await db.refresh(project)
  885. return {
  886. "status": "success",
  887. "message": "Attachment deleted",
  888. "attachments": project.attachments,
  889. }
  890. # ============ #1155: Cover image ============
  891. @router.post("/{project_id}/cover-image")
  892. async def upload_project_cover_image(
  893. project_id: int,
  894. file: UploadFile = File(...),
  895. db: AsyncSession = Depends(get_db),
  896. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  897. ):
  898. """Upload (or replace) the project's cover image (#1155).
  899. Stored alongside other attachments but tracked via Project.cover_image_filename
  900. so swap/delete operations don't touch the attachments list. Replaces any
  901. existing cover image — the prior file is deleted on disk before the new one
  902. lands so a stuck filesystem reference can't accumulate orphaned images.
  903. """
  904. result = await db.execute(select(Project).where(Project.id == project_id))
  905. project = result.scalar_one_or_none()
  906. if not project:
  907. raise HTTPException(status_code=404, detail="Project not found")
  908. original_name = file.filename or "cover"
  909. ext = os.path.splitext(original_name)[1].lower()
  910. if ext not in COVER_IMAGE_EXTENSIONS:
  911. raise HTTPException(
  912. status_code=400,
  913. detail=f"Cover image must be one of {sorted(COVER_IMAGE_EXTENSIONS)}",
  914. )
  915. attachments_dir = get_project_attachments_dir(project_id)
  916. attachments_dir.mkdir(parents=True, exist_ok=True)
  917. # Remove the previous cover-image file from disk first so we don't accumulate
  918. # orphans when users repeatedly replace it. Best-effort: a missing/locked file
  919. # shouldn't block a successful replacement.
  920. if project.cover_image_filename:
  921. old_path = attachments_dir / project.cover_image_filename
  922. if old_path.exists():
  923. try:
  924. os.remove(old_path)
  925. except OSError as e:
  926. logger.warning("Failed to delete old cover image %s: %s", old_path, e)
  927. unique_filename = f"cover_{uuid.uuid4().hex}{ext}"
  928. file_path = attachments_dir / unique_filename
  929. try:
  930. with open(file_path, "wb") as f:
  931. content = await file.read()
  932. f.write(content)
  933. except OSError as e:
  934. logger.error("Failed to save cover image: %s", e)
  935. raise HTTPException(status_code=500, detail="Failed to save cover image")
  936. project.cover_image_filename = unique_filename
  937. db.add(project)
  938. await db.flush()
  939. await db.commit()
  940. return {
  941. "status": "success",
  942. "filename": unique_filename,
  943. "size": len(content),
  944. }
  945. @router.get("/{project_id}/cover-image")
  946. async def get_project_cover_image(
  947. project_id: int,
  948. db: AsyncSession = Depends(get_db),
  949. _: None = RequireCameraStreamTokenIfAuthEnabled,
  950. ):
  951. """Stream the project's cover image (#1155).
  952. Browsers can't attach `Authorization: Bearer ...` to `<img src>` requests,
  953. so this route accepts the same `?token=` stream-credential as
  954. /archives/{id}/thumbnail. The frontend wraps URLs with `withStreamToken`."""
  955. result = await db.execute(select(Project).where(Project.id == project_id))
  956. project = result.scalar_one_or_none()
  957. if not project:
  958. raise HTTPException(status_code=404, detail="Project not found")
  959. if not project.cover_image_filename:
  960. raise HTTPException(status_code=404, detail="No cover image set")
  961. file_path = get_project_attachments_dir(project_id) / project.cover_image_filename
  962. if not file_path.exists():
  963. # DB references a file that vanished from disk — clear the dangling
  964. # reference so future GETs get a clean 404 instead of repeatedly
  965. # touching the filesystem.
  966. logger.warning("Cover image file missing for project %s: %s", project_id, file_path)
  967. project.cover_image_filename = None
  968. await db.commit()
  969. raise HTTPException(status_code=404, detail="Cover image file not found")
  970. ext = os.path.splitext(project.cover_image_filename)[1].lower()
  971. media_type = COVER_IMAGE_CONTENT_TYPES.get(ext, "application/octet-stream")
  972. return FileResponse(file_path, media_type=media_type)
  973. @router.delete("/{project_id}/cover-image")
  974. async def delete_project_cover_image(
  975. project_id: int,
  976. db: AsyncSession = Depends(get_db),
  977. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  978. ):
  979. """Remove the project's cover image (#1155)."""
  980. result = await db.execute(select(Project).where(Project.id == project_id))
  981. project = result.scalar_one_or_none()
  982. if not project:
  983. raise HTTPException(status_code=404, detail="Project not found")
  984. if project.cover_image_filename:
  985. file_path = get_project_attachments_dir(project_id) / project.cover_image_filename
  986. if file_path.exists():
  987. try:
  988. os.remove(file_path)
  989. except OSError as e:
  990. logger.warning("Failed to delete cover image file %s: %s", file_path, e)
  991. project.cover_image_filename = None
  992. db.add(project)
  993. await db.flush()
  994. await db.commit()
  995. return {"status": "success"}
  996. # ============ Phase 7: BOM Endpoints ============
  997. @router.get("/{project_id}/bom", response_model=list[BOMItemResponse])
  998. async def list_bom_items(
  999. project_id: int,
  1000. db: AsyncSession = Depends(get_db),
  1001. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1002. ):
  1003. """List all BOM items for a project."""
  1004. # Verify project exists
  1005. result = await db.execute(select(Project).where(Project.id == project_id))
  1006. if not result.scalar_one_or_none():
  1007. raise HTTPException(status_code=404, detail="Project not found")
  1008. # Get BOM items
  1009. result = await db.execute(
  1010. select(ProjectBOMItem)
  1011. .where(ProjectBOMItem.project_id == project_id)
  1012. .order_by(ProjectBOMItem.sort_order, ProjectBOMItem.id)
  1013. )
  1014. items = result.scalars().all()
  1015. response = []
  1016. for item in items:
  1017. # Get archive name if linked
  1018. archive_name = None
  1019. if item.archive_id:
  1020. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  1021. archive_name = archive_result.scalar()
  1022. response.append(
  1023. BOMItemResponse(
  1024. id=item.id,
  1025. project_id=item.project_id,
  1026. name=item.name,
  1027. quantity_needed=item.quantity_needed,
  1028. quantity_acquired=item.quantity_acquired,
  1029. unit_price=item.unit_price,
  1030. sourcing_url=item.sourcing_url,
  1031. archive_id=item.archive_id,
  1032. archive_name=archive_name,
  1033. stl_filename=item.stl_filename,
  1034. remarks=item.remarks,
  1035. sort_order=item.sort_order,
  1036. is_complete=item.quantity_acquired >= item.quantity_needed,
  1037. created_at=item.created_at,
  1038. updated_at=item.updated_at,
  1039. )
  1040. )
  1041. return response
  1042. @router.post("/{project_id}/bom", response_model=BOMItemResponse)
  1043. async def create_bom_item(
  1044. project_id: int,
  1045. data: BOMItemCreate,
  1046. db: AsyncSession = Depends(get_db),
  1047. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1048. ):
  1049. """Add a BOM item to a project."""
  1050. # Verify project exists
  1051. result = await db.execute(select(Project).where(Project.id == project_id))
  1052. if not result.scalar_one_or_none():
  1053. raise HTTPException(status_code=404, detail="Project not found")
  1054. # Get max sort order
  1055. max_order_result = await db.execute(
  1056. select(func.max(ProjectBOMItem.sort_order)).where(ProjectBOMItem.project_id == project_id)
  1057. )
  1058. max_order = max_order_result.scalar() or 0
  1059. item = ProjectBOMItem(
  1060. project_id=project_id,
  1061. name=data.name,
  1062. quantity_needed=data.quantity_needed,
  1063. unit_price=data.unit_price,
  1064. sourcing_url=data.sourcing_url,
  1065. archive_id=data.archive_id,
  1066. stl_filename=data.stl_filename,
  1067. remarks=data.remarks,
  1068. sort_order=max_order + 1,
  1069. )
  1070. db.add(item)
  1071. await db.flush()
  1072. await db.refresh(item)
  1073. # Get archive name if linked
  1074. archive_name = None
  1075. if item.archive_id:
  1076. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  1077. archive_name = archive_result.scalar()
  1078. return BOMItemResponse(
  1079. id=item.id,
  1080. project_id=item.project_id,
  1081. name=item.name,
  1082. quantity_needed=item.quantity_needed,
  1083. quantity_acquired=item.quantity_acquired,
  1084. unit_price=item.unit_price,
  1085. sourcing_url=item.sourcing_url,
  1086. archive_id=item.archive_id,
  1087. archive_name=archive_name,
  1088. stl_filename=item.stl_filename,
  1089. remarks=item.remarks,
  1090. sort_order=item.sort_order,
  1091. is_complete=item.quantity_acquired >= item.quantity_needed,
  1092. created_at=item.created_at,
  1093. updated_at=item.updated_at,
  1094. )
  1095. @router.patch("/{project_id}/bom/{item_id}", response_model=BOMItemResponse)
  1096. async def update_bom_item(
  1097. project_id: int,
  1098. item_id: int,
  1099. data: BOMItemUpdate,
  1100. db: AsyncSession = Depends(get_db),
  1101. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1102. ):
  1103. """Update a BOM item."""
  1104. result = await db.execute(
  1105. select(ProjectBOMItem).where(
  1106. ProjectBOMItem.id == item_id,
  1107. ProjectBOMItem.project_id == project_id,
  1108. )
  1109. )
  1110. item = result.scalar_one_or_none()
  1111. if not item:
  1112. raise HTTPException(status_code=404, detail="BOM item not found")
  1113. if data.name is not None:
  1114. item.name = data.name
  1115. if data.quantity_needed is not None:
  1116. item.quantity_needed = data.quantity_needed
  1117. if data.quantity_acquired is not None:
  1118. item.quantity_acquired = data.quantity_acquired
  1119. if data.unit_price is not None:
  1120. item.unit_price = data.unit_price if data.unit_price != 0 else None
  1121. if data.sourcing_url is not None:
  1122. item.sourcing_url = data.sourcing_url if data.sourcing_url else None
  1123. if data.archive_id is not None:
  1124. item.archive_id = data.archive_id if data.archive_id != 0 else None
  1125. if data.stl_filename is not None:
  1126. item.stl_filename = data.stl_filename if data.stl_filename else None
  1127. if data.remarks is not None:
  1128. item.remarks = data.remarks if data.remarks else None
  1129. await db.flush()
  1130. await db.refresh(item)
  1131. # Get archive name if linked
  1132. archive_name = None
  1133. if item.archive_id:
  1134. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  1135. archive_name = archive_result.scalar()
  1136. return BOMItemResponse(
  1137. id=item.id,
  1138. project_id=item.project_id,
  1139. name=item.name,
  1140. quantity_needed=item.quantity_needed,
  1141. quantity_acquired=item.quantity_acquired,
  1142. unit_price=item.unit_price,
  1143. sourcing_url=item.sourcing_url,
  1144. archive_id=item.archive_id,
  1145. archive_name=archive_name,
  1146. stl_filename=item.stl_filename,
  1147. remarks=item.remarks,
  1148. sort_order=item.sort_order,
  1149. is_complete=item.quantity_acquired >= item.quantity_needed,
  1150. created_at=item.created_at,
  1151. updated_at=item.updated_at,
  1152. )
  1153. @router.delete("/{project_id}/bom/{item_id}")
  1154. async def delete_bom_item(
  1155. project_id: int,
  1156. item_id: int,
  1157. db: AsyncSession = Depends(get_db),
  1158. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1159. ):
  1160. """Delete a BOM item."""
  1161. result = await db.execute(
  1162. select(ProjectBOMItem).where(
  1163. ProjectBOMItem.id == item_id,
  1164. ProjectBOMItem.project_id == project_id,
  1165. )
  1166. )
  1167. item = result.scalar_one_or_none()
  1168. if not item:
  1169. raise HTTPException(status_code=404, detail="BOM item not found")
  1170. await db.delete(item)
  1171. return {"status": "success", "message": "BOM item deleted"}
  1172. @router.post("/{project_id}/create-template", response_model=ProjectResponse)
  1173. async def create_template_from_project(
  1174. project_id: int,
  1175. db: AsyncSession = Depends(get_db),
  1176. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1177. ):
  1178. """Create a template from an existing project."""
  1179. result = await db.execute(select(Project).where(Project.id == project_id))
  1180. source = result.scalar_one_or_none()
  1181. if not source:
  1182. raise HTTPException(status_code=404, detail="Project not found")
  1183. # Create template
  1184. template = Project(
  1185. name=f"{source.name} (Template)",
  1186. description=source.description,
  1187. color=source.color,
  1188. target_count=source.target_count,
  1189. target_parts_count=source.target_parts_count,
  1190. notes=source.notes,
  1191. tags=source.tags,
  1192. priority=source.priority,
  1193. budget=source.budget,
  1194. is_template=True,
  1195. template_source_id=source.id,
  1196. url=source.url,
  1197. )
  1198. db.add(template)
  1199. await db.flush()
  1200. # Copy BOM items
  1201. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == project_id))
  1202. bom_items = bom_result.scalars().all()
  1203. for item in bom_items:
  1204. new_item = ProjectBOMItem(
  1205. project_id=template.id,
  1206. name=item.name,
  1207. quantity_needed=item.quantity_needed,
  1208. quantity_acquired=0,
  1209. unit_price=item.unit_price,
  1210. sourcing_url=item.sourcing_url,
  1211. stl_filename=item.stl_filename,
  1212. remarks=item.remarks,
  1213. sort_order=item.sort_order,
  1214. )
  1215. db.add(new_item)
  1216. await db.flush()
  1217. await db.refresh(template)
  1218. stats = await compute_project_stats(db, template.id, template.target_count, template.target_parts_count)
  1219. return ProjectResponse(
  1220. id=template.id,
  1221. name=template.name,
  1222. description=template.description,
  1223. color=template.color,
  1224. status=template.status,
  1225. target_count=template.target_count,
  1226. target_parts_count=template.target_parts_count,
  1227. notes=template.notes,
  1228. attachments=template.attachments,
  1229. url=template.url,
  1230. cover_image_filename=template.cover_image_filename,
  1231. tags=template.tags,
  1232. due_date=template.due_date,
  1233. priority=template.priority,
  1234. budget=template.budget,
  1235. is_template=template.is_template,
  1236. template_source_id=template.template_source_id,
  1237. parent_id=template.parent_id,
  1238. parent_name=None,
  1239. children=[],
  1240. created_at=template.created_at,
  1241. updated_at=template.updated_at,
  1242. stats=stats,
  1243. )
  1244. # ============ Phase 9: Timeline Endpoint ============
  1245. @router.get("/{project_id}/timeline", response_model=list[TimelineEvent])
  1246. async def get_project_timeline(
  1247. project_id: int,
  1248. limit: int = 50,
  1249. db: AsyncSession = Depends(get_db),
  1250. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1251. ):
  1252. """Get timeline of events for a project."""
  1253. # Verify project exists
  1254. result = await db.execute(select(Project).where(Project.id == project_id))
  1255. project = result.scalar_one_or_none()
  1256. if not project:
  1257. raise HTTPException(status_code=404, detail="Project not found")
  1258. events = []
  1259. # Project creation event
  1260. events.append(
  1261. TimelineEvent(
  1262. event_type="project_created",
  1263. timestamp=project.created_at,
  1264. title="Project created",
  1265. description=f"Project '{project.name}' was created",
  1266. )
  1267. )
  1268. # Get archives and add events
  1269. archives_result = await db.execute(
  1270. select(PrintArchive)
  1271. .where(PrintArchive.project_id == project_id)
  1272. .order_by(PrintArchive.created_at.desc())
  1273. .limit(limit)
  1274. )
  1275. archives = archives_result.scalars().all()
  1276. for archive in archives:
  1277. if archive.status == "completed":
  1278. events.append(
  1279. TimelineEvent(
  1280. event_type="print_completed",
  1281. timestamp=archive.completed_at or archive.created_at,
  1282. title="Print completed",
  1283. description=archive.print_name,
  1284. metadata={
  1285. "archive_id": archive.id,
  1286. "print_time_hours": round((archive.print_time_seconds or 0) / 3600, 2),
  1287. "filament_grams": round(archive.filament_used_grams or 0, 1),
  1288. },
  1289. )
  1290. )
  1291. elif archive.status == "failed":
  1292. events.append(
  1293. TimelineEvent(
  1294. event_type="print_failed",
  1295. timestamp=archive.completed_at or archive.created_at,
  1296. title="Print failed",
  1297. description=archive.print_name,
  1298. metadata={"archive_id": archive.id},
  1299. )
  1300. )
  1301. # Get queue items
  1302. queue_result = await db.execute(
  1303. select(PrintQueueItem)
  1304. .where(PrintQueueItem.project_id == project_id)
  1305. .order_by(PrintQueueItem.created_at.desc())
  1306. .limit(limit)
  1307. )
  1308. queue_items = queue_result.scalars().all()
  1309. for item in queue_items:
  1310. if item.status == "printing":
  1311. events.append(
  1312. TimelineEvent(
  1313. event_type="print_started",
  1314. timestamp=item.started_at or item.created_at,
  1315. title="Print started",
  1316. description=item.print_name,
  1317. metadata={"queue_item_id": item.id},
  1318. )
  1319. )
  1320. elif item.status == "pending":
  1321. events.append(
  1322. TimelineEvent(
  1323. event_type="queued",
  1324. timestamp=item.created_at,
  1325. title="Added to queue",
  1326. description=item.print_name,
  1327. metadata={"queue_item_id": item.id},
  1328. )
  1329. )
  1330. # Sort by timestamp descending
  1331. events.sort(key=lambda e: e.timestamp, reverse=True)
  1332. return events[:limit]
  1333. # ============ Phase 10: Import/Export Endpoints ============
  1334. @router.get("/{project_id}/export")
  1335. async def export_project(
  1336. project_id: int,
  1337. format: str = "zip", # "zip" (with files) or "json" (metadata only)
  1338. db: AsyncSession = Depends(get_db),
  1339. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1340. ):
  1341. """Export a project. Use format=zip (default) for full export with files, or format=json for metadata only."""
  1342. result = await db.execute(select(Project).where(Project.id == project_id))
  1343. project = result.scalar_one_or_none()
  1344. if not project:
  1345. raise HTTPException(status_code=404, detail="Project not found")
  1346. # Get BOM items
  1347. bom_result = await db.execute(
  1348. select(ProjectBOMItem).where(ProjectBOMItem.project_id == project_id).order_by(ProjectBOMItem.sort_order)
  1349. )
  1350. bom_items = bom_result.scalars().all()
  1351. bom_export = [
  1352. {
  1353. "name": item.name,
  1354. "quantity_needed": item.quantity_needed,
  1355. "quantity_acquired": item.quantity_acquired,
  1356. "unit_price": item.unit_price,
  1357. "sourcing_url": item.sourcing_url,
  1358. "stl_filename": item.stl_filename,
  1359. "remarks": item.remarks,
  1360. }
  1361. for item in bom_items
  1362. ]
  1363. # Get linked folders and their files
  1364. folders_result = await db.execute(
  1365. select(LibraryFolder).where(LibraryFolder.project_id == project_id).order_by(LibraryFolder.name)
  1366. )
  1367. linked_folders = folders_result.scalars().all()
  1368. folders_export = []
  1369. files_to_include = [] # (archive_path, zip_path)
  1370. for folder in linked_folders:
  1371. # Get files in this folder
  1372. files_result = await db.execute(
  1373. LibraryFile.active().where(LibraryFile.folder_id == folder.id).order_by(LibraryFile.filename)
  1374. )
  1375. files = files_result.scalars().all()
  1376. folder_files = []
  1377. for f in files:
  1378. folder_files.append(
  1379. {
  1380. "filename": f.filename,
  1381. "file_type": f.file_type,
  1382. "notes": f.notes,
  1383. }
  1384. )
  1385. # Add file to include in ZIP
  1386. library_dir = get_library_dir()
  1387. file_path = library_dir / f.file_path
  1388. if file_path.exists():
  1389. zip_path = f"files/{folder.name}/{f.filename}"
  1390. files_to_include.append((file_path, zip_path))
  1391. # Also include thumbnail if exists
  1392. if f.thumbnail_path:
  1393. thumb_path = library_dir / f.thumbnail_path
  1394. if thumb_path.exists():
  1395. thumb_zip_path = f"files/{folder.name}/.thumbnails/{f.filename}.png"
  1396. files_to_include.append((thumb_path, thumb_zip_path))
  1397. folders_export.append(
  1398. {
  1399. "name": folder.name,
  1400. "files": folder_files,
  1401. }
  1402. )
  1403. # Build project JSON
  1404. project_data = {
  1405. "name": project.name,
  1406. "description": project.description,
  1407. "color": project.color,
  1408. "status": project.status,
  1409. "target_count": project.target_count,
  1410. "target_parts_count": project.target_parts_count,
  1411. "notes": project.notes,
  1412. "tags": project.tags,
  1413. "due_date": project.due_date.isoformat() if project.due_date else None,
  1414. "priority": project.priority,
  1415. "budget": project.budget,
  1416. "bom_items": bom_export,
  1417. "linked_folders": folders_export,
  1418. }
  1419. # Return JSON if requested (for bulk export)
  1420. if format == "json":
  1421. return project_data
  1422. # Create ZIP in memory
  1423. zip_buffer = io.BytesIO()
  1424. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  1425. # Add project.json
  1426. zf.writestr("project.json", json.dumps(project_data, indent=2))
  1427. # Add files
  1428. for file_path, zip_path in files_to_include:
  1429. zf.write(file_path, zip_path)
  1430. zip_buffer.seek(0)
  1431. # Generate filename
  1432. safe_name = "".join(c if c.isalnum() or c in "-_ " else "_" for c in project.name)
  1433. filename = f"{safe_name}_{datetime.now().strftime('%Y-%m-%d')}.zip"
  1434. return StreamingResponse(
  1435. zip_buffer,
  1436. media_type="application/zip",
  1437. headers={"Content-Disposition": build_content_disposition(filename)},
  1438. )
  1439. @router.post("/import", response_model=ProjectResponse)
  1440. async def import_project(
  1441. data: ProjectImport,
  1442. db: AsyncSession = Depends(get_db),
  1443. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1444. ):
  1445. """Import a project with optional BOM items and linked folders."""
  1446. # Create the project
  1447. project = Project(
  1448. name=data.name,
  1449. description=data.description,
  1450. color=data.color,
  1451. status=data.status,
  1452. target_count=data.target_count,
  1453. target_parts_count=data.target_parts_count,
  1454. notes=data.notes,
  1455. tags=data.tags,
  1456. due_date=data.due_date,
  1457. priority=data.priority,
  1458. budget=data.budget,
  1459. )
  1460. db.add(project)
  1461. await db.flush()
  1462. # Create BOM items
  1463. for idx, bom_data in enumerate(data.bom_items):
  1464. bom_item = ProjectBOMItem(
  1465. project_id=project.id,
  1466. name=bom_data.name,
  1467. quantity_needed=bom_data.quantity_needed,
  1468. quantity_acquired=bom_data.quantity_acquired,
  1469. unit_price=bom_data.unit_price,
  1470. sourcing_url=bom_data.sourcing_url,
  1471. stl_filename=bom_data.stl_filename,
  1472. remarks=bom_data.remarks,
  1473. sort_order=idx,
  1474. )
  1475. db.add(bom_item)
  1476. # Create linked folders in library
  1477. for folder_data in data.linked_folders:
  1478. # Check if folder with this name already exists at root level
  1479. existing_result = await db.execute(
  1480. select(LibraryFolder).where(
  1481. LibraryFolder.name == folder_data.name,
  1482. LibraryFolder.parent_id.is_(None),
  1483. )
  1484. )
  1485. existing_folder = existing_result.scalar_one_or_none()
  1486. if existing_folder:
  1487. # Link existing folder to project
  1488. existing_folder.project_id = project.id
  1489. else:
  1490. # Create new folder linked to project
  1491. new_folder = LibraryFolder(
  1492. name=folder_data.name,
  1493. project_id=project.id,
  1494. is_external=False,
  1495. external_readonly=False,
  1496. external_show_hidden=False,
  1497. )
  1498. db.add(new_folder)
  1499. await db.flush()
  1500. await db.refresh(project)
  1501. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  1502. return ProjectResponse(
  1503. id=project.id,
  1504. name=project.name,
  1505. description=project.description,
  1506. color=project.color,
  1507. status=project.status,
  1508. target_count=project.target_count,
  1509. target_parts_count=project.target_parts_count,
  1510. notes=project.notes,
  1511. attachments=project.attachments,
  1512. url=project.url,
  1513. cover_image_filename=project.cover_image_filename,
  1514. tags=project.tags,
  1515. due_date=project.due_date,
  1516. priority=project.priority,
  1517. budget=project.budget,
  1518. is_template=project.is_template,
  1519. template_source_id=project.template_source_id,
  1520. parent_id=project.parent_id,
  1521. parent_name=None,
  1522. children=[],
  1523. created_at=project.created_at,
  1524. updated_at=project.updated_at,
  1525. stats=stats,
  1526. )
  1527. @router.post("/import/file", response_model=ProjectResponse)
  1528. async def import_project_file(
  1529. file: UploadFile = File(...),
  1530. db: AsyncSession = Depends(get_db),
  1531. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1532. ):
  1533. """Import a project from a ZIP or JSON file."""
  1534. if not file.filename:
  1535. raise HTTPException(status_code=400, detail="No filename provided")
  1536. # Determine file type
  1537. filename_lower = file.filename.lower()
  1538. content = await file.read()
  1539. if filename_lower.endswith(".zip"):
  1540. # Extract project.json from ZIP
  1541. try:
  1542. with zipfile.ZipFile(io.BytesIO(content)) as zf:
  1543. if "project.json" not in zf.namelist():
  1544. raise HTTPException(status_code=400, detail="ZIP must contain project.json")
  1545. project_json = zf.read("project.json")
  1546. data = json.loads(project_json)
  1547. # Get list of files in the ZIP
  1548. zip_files = {name: zf.read(name) for name in zf.namelist() if name.startswith("files/")}
  1549. except zipfile.BadZipFile:
  1550. raise HTTPException(status_code=400, detail="Invalid ZIP file")
  1551. elif filename_lower.endswith(".json"):
  1552. try:
  1553. data = json.loads(content)
  1554. zip_files = {}
  1555. except json.JSONDecodeError:
  1556. raise HTTPException(status_code=400, detail="Invalid JSON file")
  1557. else:
  1558. raise HTTPException(status_code=400, detail="File must be .zip or .json")
  1559. # Create the project
  1560. project = Project(
  1561. name=data.get("name", "Imported Project"),
  1562. description=data.get("description"),
  1563. color=data.get("color"),
  1564. status=data.get("status", "active"),
  1565. target_count=data.get("target_count"),
  1566. target_parts_count=data.get("target_parts_count"),
  1567. notes=data.get("notes"),
  1568. tags=data.get("tags"),
  1569. due_date=datetime.fromisoformat(data["due_date"]) if data.get("due_date") else None,
  1570. priority=data.get("priority", 0),
  1571. budget=data.get("budget"),
  1572. )
  1573. db.add(project)
  1574. await db.flush()
  1575. # Create BOM items
  1576. for idx, bom_data in enumerate(data.get("bom_items", [])):
  1577. bom_item = ProjectBOMItem(
  1578. project_id=project.id,
  1579. name=bom_data.get("name", "Unnamed"),
  1580. quantity_needed=bom_data.get("quantity_needed", 1),
  1581. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1582. unit_price=bom_data.get("unit_price"),
  1583. sourcing_url=bom_data.get("sourcing_url"),
  1584. stl_filename=bom_data.get("stl_filename"),
  1585. remarks=bom_data.get("remarks"),
  1586. sort_order=idx,
  1587. )
  1588. db.add(bom_item)
  1589. # Create linked folders and files
  1590. library_dir = get_library_dir()
  1591. for folder_data in data.get("linked_folders", []):
  1592. folder_name = folder_data.get("name")
  1593. if not folder_name:
  1594. continue
  1595. # Check if folder exists
  1596. existing_result = await db.execute(
  1597. select(LibraryFolder).where(
  1598. LibraryFolder.name == folder_name,
  1599. LibraryFolder.parent_id.is_(None),
  1600. )
  1601. )
  1602. existing_folder = existing_result.scalar_one_or_none()
  1603. if existing_folder:
  1604. # Link existing folder to project
  1605. existing_folder.project_id = project.id
  1606. folder = existing_folder
  1607. else:
  1608. # Create new folder
  1609. folder = LibraryFolder(
  1610. name=folder_name,
  1611. project_id=project.id,
  1612. is_external=False,
  1613. external_readonly=False,
  1614. external_show_hidden=False,
  1615. )
  1616. db.add(folder)
  1617. await db.flush()
  1618. # Create folder on disk
  1619. folder_path = library_dir / folder_name
  1620. folder_path.mkdir(parents=True, exist_ok=True)
  1621. # Import files for this folder from ZIP
  1622. folder_prefix = f"files/{folder_name}/"
  1623. for zip_path, file_content in zip_files.items():
  1624. if not zip_path.startswith(folder_prefix):
  1625. continue
  1626. if "/.thumbnails/" in zip_path:
  1627. continue # Skip thumbnails, we'll regenerate them
  1628. relative_path = zip_path[len(folder_prefix) :]
  1629. if not relative_path:
  1630. continue
  1631. # Write file to disk
  1632. file_disk_path = library_dir / folder_name / relative_path
  1633. file_disk_path.parent.mkdir(parents=True, exist_ok=True)
  1634. file_disk_path.write_bytes(file_content)
  1635. # Determine file type
  1636. ext = Path(relative_path).suffix.lower()
  1637. if ext in [".stl", ".3mf", ".obj"]:
  1638. file_type = "model"
  1639. elif ext in [".gcode"]:
  1640. file_type = "gcode"
  1641. elif ext in [".jpg", ".jpeg", ".png", ".gif", ".webp"]:
  1642. file_type = "image"
  1643. else:
  1644. file_type = "other"
  1645. # Create library file record
  1646. lib_file = LibraryFile(
  1647. folder_id=folder.id,
  1648. filename=relative_path,
  1649. file_path=f"{folder_name}/{relative_path}",
  1650. file_type=file_type,
  1651. file_size=len(file_content),
  1652. is_external=False,
  1653. )
  1654. db.add(lib_file)
  1655. await db.flush()
  1656. await db.refresh(project)
  1657. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  1658. return ProjectResponse(
  1659. id=project.id,
  1660. name=project.name,
  1661. description=project.description,
  1662. color=project.color,
  1663. status=project.status,
  1664. target_count=project.target_count,
  1665. target_parts_count=project.target_parts_count,
  1666. notes=project.notes,
  1667. attachments=project.attachments,
  1668. url=project.url,
  1669. cover_image_filename=project.cover_image_filename,
  1670. tags=project.tags,
  1671. due_date=project.due_date,
  1672. priority=project.priority,
  1673. budget=project.budget,
  1674. is_template=project.is_template,
  1675. template_source_id=project.template_source_id,
  1676. parent_id=project.parent_id,
  1677. parent_name=None,
  1678. children=[],
  1679. created_at=project.created_at,
  1680. updated_at=project.updated_at,
  1681. stats=stats,
  1682. )