projects.py 66 KB

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