projects.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  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 both ``project`` and ``created_by`` eagerly loaded.
  591. # ``archive_to_response`` accesses ``archive.created_by.username`` to
  592. # surface the creator on the archive card; without selectinload that's
  593. # a lazy attribute access on a closed async session, which throws
  594. # ``MissingGreenlet`` and produces a 500. ``ArchiveService.list_archives``
  595. # already loads both — this route just got out of step.
  596. query = (
  597. select(PrintArchive)
  598. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  599. .where(PrintArchive.project_id == project_id)
  600. .order_by(PrintArchive.created_at.desc())
  601. .limit(limit)
  602. .offset(offset)
  603. )
  604. result = await db.execute(query)
  605. archives = result.scalars().all()
  606. # Import the response converter from archives module
  607. from backend.app.api.routes.archives import archive_to_response
  608. return [archive_to_response(a) for a in archives]
  609. @router.get("/{project_id}/queue")
  610. async def list_project_queue(
  611. project_id: int,
  612. db: AsyncSession = Depends(get_db),
  613. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  614. ):
  615. """List queue items in a project."""
  616. # Verify project exists
  617. result = await db.execute(select(Project).where(Project.id == project_id))
  618. if not result.scalar_one_or_none():
  619. raise HTTPException(status_code=404, detail="Project not found")
  620. # Get queue items
  621. query = select(PrintQueueItem).where(PrintQueueItem.project_id == project_id).order_by(PrintQueueItem.position)
  622. result = await db.execute(query)
  623. items = result.scalars().all()
  624. return items
  625. @router.post("/{project_id}/add-archives")
  626. async def add_archives_to_project(
  627. project_id: int,
  628. data: BatchAddArchives,
  629. db: AsyncSession = Depends(get_db),
  630. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  631. ):
  632. """Batch add archives to a project."""
  633. # Verify project exists
  634. result = await db.execute(select(Project).where(Project.id == project_id))
  635. if not result.scalar_one_or_none():
  636. raise HTTPException(status_code=404, detail="Project not found")
  637. # Update archives
  638. updated = 0
  639. for archive_id in data.archive_ids:
  640. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  641. archive = result.scalar_one_or_none()
  642. if archive:
  643. archive.project_id = project_id
  644. updated += 1
  645. return {"message": f"Added {updated} archives to project"}
  646. @router.post("/{project_id}/add-queue")
  647. async def add_queue_items_to_project(
  648. project_id: int,
  649. data: BatchAddQueueItems,
  650. db: AsyncSession = Depends(get_db),
  651. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  652. ):
  653. """Batch add queue items to a project."""
  654. # Verify project exists
  655. result = await db.execute(select(Project).where(Project.id == project_id))
  656. if not result.scalar_one_or_none():
  657. raise HTTPException(status_code=404, detail="Project not found")
  658. # Update queue items
  659. updated = 0
  660. for item_id in data.queue_item_ids:
  661. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  662. item = result.scalar_one_or_none()
  663. if item:
  664. item.project_id = project_id
  665. updated += 1
  666. return {"message": f"Added {updated} queue items to project"}
  667. @router.post("/{project_id}/remove-archives")
  668. async def remove_archives_from_project(
  669. project_id: int,
  670. data: BatchAddArchives,
  671. db: AsyncSession = Depends(get_db),
  672. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  673. ):
  674. """Remove archives from a project (sets project_id to NULL)."""
  675. updated = 0
  676. for archive_id in data.archive_ids:
  677. result = await db.execute(
  678. select(PrintArchive).where(
  679. PrintArchive.id == archive_id,
  680. PrintArchive.project_id == project_id,
  681. )
  682. )
  683. archive = result.scalar_one_or_none()
  684. if archive:
  685. archive.project_id = None
  686. updated += 1
  687. return {"message": f"Removed {updated} archives from project"}
  688. def get_project_attachments_dir(project_id: int) -> Path:
  689. """Get the attachments directory for a project."""
  690. base_dir = Path(settings.archive_dir)
  691. return base_dir / "projects" / str(project_id) / "attachments"
  692. # Cover-image upload accepts only common web-renderable image types (#1155).
  693. # Subset of ALLOWED_ATTACHMENT_EXTENSIONS minus .svg/.ico because those don't
  694. # render well as a card thumbnail.
  695. COVER_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
  696. COVER_IMAGE_CONTENT_TYPES = {
  697. ".jpg": "image/jpeg",
  698. ".jpeg": "image/jpeg",
  699. ".png": "image/png",
  700. ".gif": "image/gif",
  701. ".webp": "image/webp",
  702. }
  703. # Allowed file extensions for attachments
  704. ALLOWED_ATTACHMENT_EXTENSIONS = {
  705. # Images
  706. ".jpg",
  707. ".jpeg",
  708. ".png",
  709. ".gif",
  710. ".webp",
  711. ".svg",
  712. ".bmp",
  713. ".ico",
  714. # Documents
  715. ".pdf",
  716. ".doc",
  717. ".docx",
  718. ".xls",
  719. ".xlsx",
  720. ".ppt",
  721. ".pptx",
  722. ".odt",
  723. ".ods",
  724. ".odp",
  725. ".txt",
  726. ".rtf",
  727. ".csv",
  728. ".md",
  729. # 3D/CAD files
  730. ".stl",
  731. ".obj",
  732. ".3mf",
  733. ".step",
  734. ".stp",
  735. ".iges",
  736. ".igs",
  737. ".f3d",
  738. ".scad",
  739. # Archives
  740. ".zip",
  741. ".rar",
  742. ".7z",
  743. ".tar",
  744. ".gz",
  745. # Code/scripts (for Klipper macros, scripts, etc.)
  746. ".py",
  747. ".sh",
  748. ".cfg",
  749. ".conf",
  750. ".gcode",
  751. ".ini",
  752. # Other common formats
  753. ".json",
  754. ".xml",
  755. ".yaml",
  756. ".yml",
  757. }
  758. @router.post("/{project_id}/attachments")
  759. async def upload_attachment(
  760. project_id: int,
  761. file: UploadFile = File(...),
  762. db: AsyncSession = Depends(get_db),
  763. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  764. ):
  765. """Upload an attachment to a project."""
  766. logger.info("=== UPLOAD START: %s for project %s ===", file.filename, project_id)
  767. # Verify project exists
  768. result = await db.execute(select(Project).where(Project.id == project_id))
  769. project = result.scalar_one_or_none()
  770. if not project:
  771. raise HTTPException(status_code=404, detail="Project not found")
  772. # Validate file extension
  773. original_name = file.filename or "unknown"
  774. ext = os.path.splitext(original_name)[1].lower()
  775. if ext not in ALLOWED_ATTACHMENT_EXTENSIONS:
  776. raise HTTPException(
  777. status_code=400,
  778. detail=f"File type '{ext}' not supported. Allowed: images, PDFs, documents, STL, 3MF, archives.",
  779. )
  780. # Create attachments directory
  781. attachments_dir = get_project_attachments_dir(project_id)
  782. attachments_dir.mkdir(parents=True, exist_ok=True)
  783. # Generate unique filename
  784. unique_filename = f"{uuid.uuid4().hex}{ext}"
  785. file_path = attachments_dir / unique_filename
  786. # Save file
  787. try:
  788. with open(file_path, "wb") as f:
  789. content = await file.read()
  790. f.write(content)
  791. logger.info("=== FILE SAVED: %s, size: %s ===", file_path, len(content))
  792. except Exception as e:
  793. logger.error("Failed to save attachment: %s", e)
  794. raise HTTPException(status_code=500, detail="Failed to save attachment")
  795. # Update project attachments JSON
  796. attachments = list(project.attachments or [])
  797. new_attachment = {
  798. "filename": unique_filename,
  799. "original_name": original_name,
  800. "size": len(content),
  801. "uploaded_at": datetime.now().isoformat(),
  802. }
  803. attachments.append(new_attachment)
  804. # Simple ORM update
  805. project.attachments = attachments
  806. db.add(project) # Explicitly add to session
  807. logger.info("=== BEFORE COMMIT: %s attachments ===", len(attachments))
  808. await db.flush()
  809. await db.commit()
  810. logger.info("=== AFTER COMMIT ===")
  811. # Verify by re-querying
  812. result = await db.execute(select(Project).where(Project.id == project_id))
  813. fresh_project = result.scalar_one()
  814. logger.info("=== VERIFIED: %s attachments ===", len(fresh_project.attachments or []))
  815. return {
  816. "status": "success",
  817. "filename": unique_filename,
  818. "original_name": original_name,
  819. "attachments": fresh_project.attachments,
  820. }
  821. @router.get("/{project_id}/attachments/{filename}")
  822. async def download_attachment(
  823. project_id: int,
  824. filename: str,
  825. db: AsyncSession = Depends(get_db),
  826. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  827. ):
  828. """Download an attachment from a project."""
  829. # Validate filename to prevent path traversal
  830. if "/" in filename or "\\" in filename or ".." in filename or not filename:
  831. raise HTTPException(status_code=400, detail="Invalid filename")
  832. # Verify project exists
  833. result = await db.execute(select(Project).where(Project.id == project_id))
  834. project = result.scalar_one_or_none()
  835. if not project:
  836. raise HTTPException(status_code=404, detail="Project not found")
  837. # Verify attachment exists in project
  838. attachments = project.attachments or []
  839. attachment = next((a for a in attachments if a.get("filename") == filename), None)
  840. if not attachment:
  841. raise HTTPException(status_code=404, detail="Attachment not found")
  842. # Check file exists
  843. file_path = get_project_attachments_dir(project_id) / filename
  844. if not file_path.exists():
  845. raise HTTPException(status_code=404, detail="Attachment file not found")
  846. return FileResponse(
  847. file_path,
  848. filename=attachment.get("original_name", filename),
  849. media_type="application/octet-stream",
  850. )
  851. @router.delete("/{project_id}/attachments/{filename}")
  852. async def delete_attachment(
  853. project_id: int,
  854. filename: str,
  855. db: AsyncSession = Depends(get_db),
  856. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  857. ):
  858. """Delete an attachment from a project."""
  859. # Validate filename to prevent path traversal
  860. if "/" in filename or "\\" in filename or ".." in filename or not filename:
  861. raise HTTPException(status_code=400, detail="Invalid filename")
  862. # Verify project exists
  863. result = await db.execute(select(Project).where(Project.id == project_id))
  864. project = result.scalar_one_or_none()
  865. if not project:
  866. raise HTTPException(status_code=404, detail="Project not found")
  867. # Find and remove attachment from list
  868. attachments = project.attachments or []
  869. attachment = next((a for a in attachments if a.get("filename") == filename), None)
  870. if not attachment:
  871. raise HTTPException(status_code=404, detail="Attachment not found")
  872. # Remove from list
  873. attachments = [a for a in attachments if a.get("filename") != filename]
  874. project.attachments = attachments if attachments else None
  875. # Delete file
  876. file_path = get_project_attachments_dir(project_id) / filename
  877. if file_path.exists():
  878. try:
  879. os.remove(file_path)
  880. except Exception as e:
  881. logger.warning("Failed to delete attachment file: %s", e)
  882. await db.flush()
  883. await db.refresh(project)
  884. return {
  885. "status": "success",
  886. "message": "Attachment deleted",
  887. "attachments": project.attachments,
  888. }
  889. # ============ #1155: Cover image ============
  890. @router.post("/{project_id}/cover-image")
  891. async def upload_project_cover_image(
  892. project_id: int,
  893. file: UploadFile = File(...),
  894. db: AsyncSession = Depends(get_db),
  895. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  896. ):
  897. """Upload (or replace) the project's cover image (#1155).
  898. Stored alongside other attachments but tracked via Project.cover_image_filename
  899. so swap/delete operations don't touch the attachments list. Replaces any
  900. existing cover image — the prior file is deleted on disk before the new one
  901. lands so a stuck filesystem reference can't accumulate orphaned images.
  902. """
  903. result = await db.execute(select(Project).where(Project.id == project_id))
  904. project = result.scalar_one_or_none()
  905. if not project:
  906. raise HTTPException(status_code=404, detail="Project not found")
  907. original_name = file.filename or "cover"
  908. ext = os.path.splitext(original_name)[1].lower()
  909. if ext not in COVER_IMAGE_EXTENSIONS:
  910. raise HTTPException(
  911. status_code=400,
  912. detail=f"Cover image must be one of {sorted(COVER_IMAGE_EXTENSIONS)}",
  913. )
  914. attachments_dir = get_project_attachments_dir(project_id)
  915. attachments_dir.mkdir(parents=True, exist_ok=True)
  916. # Remove the previous cover-image file from disk first so we don't accumulate
  917. # orphans when users repeatedly replace it. Best-effort: a missing/locked file
  918. # shouldn't block a successful replacement.
  919. if project.cover_image_filename:
  920. old_path = attachments_dir / project.cover_image_filename
  921. if old_path.exists():
  922. try:
  923. os.remove(old_path)
  924. except OSError as e:
  925. logger.warning("Failed to delete old cover image %s: %s", old_path, e)
  926. unique_filename = f"cover_{uuid.uuid4().hex}{ext}"
  927. file_path = attachments_dir / unique_filename
  928. try:
  929. with open(file_path, "wb") as f:
  930. content = await file.read()
  931. f.write(content)
  932. except OSError as e:
  933. logger.error("Failed to save cover image: %s", e)
  934. raise HTTPException(status_code=500, detail="Failed to save cover image")
  935. project.cover_image_filename = unique_filename
  936. db.add(project)
  937. await db.flush()
  938. await db.commit()
  939. return {
  940. "status": "success",
  941. "filename": unique_filename,
  942. "size": len(content),
  943. }
  944. @router.get("/{project_id}/cover-image")
  945. async def get_project_cover_image(
  946. project_id: int,
  947. db: AsyncSession = Depends(get_db),
  948. _: None = RequireCameraStreamTokenIfAuthEnabled,
  949. ):
  950. """Stream the project's cover image (#1155).
  951. Browsers can't attach `Authorization: Bearer ...` to `<img src>` requests,
  952. so this route accepts the same `?token=` stream-credential as
  953. /archives/{id}/thumbnail. The frontend wraps URLs with `withStreamToken`."""
  954. result = await db.execute(select(Project).where(Project.id == project_id))
  955. project = result.scalar_one_or_none()
  956. if not project:
  957. raise HTTPException(status_code=404, detail="Project not found")
  958. if not project.cover_image_filename:
  959. raise HTTPException(status_code=404, detail="No cover image set")
  960. file_path = get_project_attachments_dir(project_id) / project.cover_image_filename
  961. if not file_path.exists():
  962. # DB references a file that vanished from disk — clear the dangling
  963. # reference so future GETs get a clean 404 instead of repeatedly
  964. # touching the filesystem.
  965. logger.warning("Cover image file missing for project %s: %s", project_id, file_path)
  966. project.cover_image_filename = None
  967. await db.commit()
  968. raise HTTPException(status_code=404, detail="Cover image file not found")
  969. ext = os.path.splitext(project.cover_image_filename)[1].lower()
  970. media_type = COVER_IMAGE_CONTENT_TYPES.get(ext, "application/octet-stream")
  971. return FileResponse(file_path, media_type=media_type)
  972. @router.delete("/{project_id}/cover-image")
  973. async def delete_project_cover_image(
  974. project_id: int,
  975. db: AsyncSession = Depends(get_db),
  976. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  977. ):
  978. """Remove the project's cover image (#1155)."""
  979. result = await db.execute(select(Project).where(Project.id == project_id))
  980. project = result.scalar_one_or_none()
  981. if not project:
  982. raise HTTPException(status_code=404, detail="Project not found")
  983. if project.cover_image_filename:
  984. file_path = get_project_attachments_dir(project_id) / project.cover_image_filename
  985. if file_path.exists():
  986. try:
  987. os.remove(file_path)
  988. except OSError as e:
  989. logger.warning("Failed to delete cover image file %s: %s", file_path, e)
  990. project.cover_image_filename = None
  991. db.add(project)
  992. await db.flush()
  993. await db.commit()
  994. return {"status": "success"}
  995. # ============ Phase 7: BOM Endpoints ============
  996. @router.get("/{project_id}/bom", response_model=list[BOMItemResponse])
  997. async def list_bom_items(
  998. project_id: int,
  999. db: AsyncSession = Depends(get_db),
  1000. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1001. ):
  1002. """List all BOM items for a project."""
  1003. # Verify project exists
  1004. result = await db.execute(select(Project).where(Project.id == project_id))
  1005. if not result.scalar_one_or_none():
  1006. raise HTTPException(status_code=404, detail="Project not found")
  1007. # Get BOM items
  1008. result = await db.execute(
  1009. select(ProjectBOMItem)
  1010. .where(ProjectBOMItem.project_id == project_id)
  1011. .order_by(ProjectBOMItem.sort_order, ProjectBOMItem.id)
  1012. )
  1013. items = result.scalars().all()
  1014. response = []
  1015. for item in items:
  1016. # Get archive name if linked
  1017. archive_name = None
  1018. if item.archive_id:
  1019. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  1020. archive_name = archive_result.scalar()
  1021. response.append(
  1022. BOMItemResponse(
  1023. id=item.id,
  1024. project_id=item.project_id,
  1025. name=item.name,
  1026. quantity_needed=item.quantity_needed,
  1027. quantity_acquired=item.quantity_acquired,
  1028. unit_price=item.unit_price,
  1029. sourcing_url=item.sourcing_url,
  1030. archive_id=item.archive_id,
  1031. archive_name=archive_name,
  1032. stl_filename=item.stl_filename,
  1033. remarks=item.remarks,
  1034. sort_order=item.sort_order,
  1035. is_complete=item.quantity_acquired >= item.quantity_needed,
  1036. created_at=item.created_at,
  1037. updated_at=item.updated_at,
  1038. )
  1039. )
  1040. return response
  1041. @router.post("/{project_id}/bom", response_model=BOMItemResponse)
  1042. async def create_bom_item(
  1043. project_id: int,
  1044. data: BOMItemCreate,
  1045. db: AsyncSession = Depends(get_db),
  1046. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1047. ):
  1048. """Add a BOM item to a project."""
  1049. # Verify project exists
  1050. result = await db.execute(select(Project).where(Project.id == project_id))
  1051. if not result.scalar_one_or_none():
  1052. raise HTTPException(status_code=404, detail="Project not found")
  1053. # Get max sort order
  1054. max_order_result = await db.execute(
  1055. select(func.max(ProjectBOMItem.sort_order)).where(ProjectBOMItem.project_id == project_id)
  1056. )
  1057. max_order = max_order_result.scalar() or 0
  1058. item = ProjectBOMItem(
  1059. project_id=project_id,
  1060. name=data.name,
  1061. quantity_needed=data.quantity_needed,
  1062. unit_price=data.unit_price,
  1063. sourcing_url=data.sourcing_url,
  1064. archive_id=data.archive_id,
  1065. stl_filename=data.stl_filename,
  1066. remarks=data.remarks,
  1067. sort_order=max_order + 1,
  1068. )
  1069. db.add(item)
  1070. await db.flush()
  1071. await db.refresh(item)
  1072. # Get archive name if linked
  1073. archive_name = None
  1074. if item.archive_id:
  1075. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  1076. archive_name = archive_result.scalar()
  1077. return BOMItemResponse(
  1078. id=item.id,
  1079. project_id=item.project_id,
  1080. name=item.name,
  1081. quantity_needed=item.quantity_needed,
  1082. quantity_acquired=item.quantity_acquired,
  1083. unit_price=item.unit_price,
  1084. sourcing_url=item.sourcing_url,
  1085. archive_id=item.archive_id,
  1086. archive_name=archive_name,
  1087. stl_filename=item.stl_filename,
  1088. remarks=item.remarks,
  1089. sort_order=item.sort_order,
  1090. is_complete=item.quantity_acquired >= item.quantity_needed,
  1091. created_at=item.created_at,
  1092. updated_at=item.updated_at,
  1093. )
  1094. @router.patch("/{project_id}/bom/{item_id}", response_model=BOMItemResponse)
  1095. async def update_bom_item(
  1096. project_id: int,
  1097. item_id: int,
  1098. data: BOMItemUpdate,
  1099. db: AsyncSession = Depends(get_db),
  1100. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1101. ):
  1102. """Update a BOM item."""
  1103. result = await db.execute(
  1104. select(ProjectBOMItem).where(
  1105. ProjectBOMItem.id == item_id,
  1106. ProjectBOMItem.project_id == project_id,
  1107. )
  1108. )
  1109. item = result.scalar_one_or_none()
  1110. if not item:
  1111. raise HTTPException(status_code=404, detail="BOM item not found")
  1112. if data.name is not None:
  1113. item.name = data.name
  1114. if data.quantity_needed is not None:
  1115. item.quantity_needed = data.quantity_needed
  1116. if data.quantity_acquired is not None:
  1117. item.quantity_acquired = data.quantity_acquired
  1118. if data.unit_price is not None:
  1119. item.unit_price = data.unit_price if data.unit_price != 0 else None
  1120. if data.sourcing_url is not None:
  1121. item.sourcing_url = data.sourcing_url if data.sourcing_url else None
  1122. if data.archive_id is not None:
  1123. item.archive_id = data.archive_id if data.archive_id != 0 else None
  1124. if data.stl_filename is not None:
  1125. item.stl_filename = data.stl_filename if data.stl_filename else None
  1126. if data.remarks is not None:
  1127. item.remarks = data.remarks if data.remarks else None
  1128. await db.flush()
  1129. await db.refresh(item)
  1130. # Get archive name if linked
  1131. archive_name = None
  1132. if item.archive_id:
  1133. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  1134. archive_name = archive_result.scalar()
  1135. return BOMItemResponse(
  1136. id=item.id,
  1137. project_id=item.project_id,
  1138. name=item.name,
  1139. quantity_needed=item.quantity_needed,
  1140. quantity_acquired=item.quantity_acquired,
  1141. unit_price=item.unit_price,
  1142. sourcing_url=item.sourcing_url,
  1143. archive_id=item.archive_id,
  1144. archive_name=archive_name,
  1145. stl_filename=item.stl_filename,
  1146. remarks=item.remarks,
  1147. sort_order=item.sort_order,
  1148. is_complete=item.quantity_acquired >= item.quantity_needed,
  1149. created_at=item.created_at,
  1150. updated_at=item.updated_at,
  1151. )
  1152. @router.delete("/{project_id}/bom/{item_id}")
  1153. async def delete_bom_item(
  1154. project_id: int,
  1155. item_id: int,
  1156. db: AsyncSession = Depends(get_db),
  1157. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1158. ):
  1159. """Delete a BOM item."""
  1160. result = await db.execute(
  1161. select(ProjectBOMItem).where(
  1162. ProjectBOMItem.id == item_id,
  1163. ProjectBOMItem.project_id == project_id,
  1164. )
  1165. )
  1166. item = result.scalar_one_or_none()
  1167. if not item:
  1168. raise HTTPException(status_code=404, detail="BOM item not found")
  1169. await db.delete(item)
  1170. return {"status": "success", "message": "BOM item deleted"}
  1171. @router.post("/{project_id}/create-template", response_model=ProjectResponse)
  1172. async def create_template_from_project(
  1173. project_id: int,
  1174. db: AsyncSession = Depends(get_db),
  1175. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1176. ):
  1177. """Create a template from an existing project."""
  1178. result = await db.execute(select(Project).where(Project.id == project_id))
  1179. source = result.scalar_one_or_none()
  1180. if not source:
  1181. raise HTTPException(status_code=404, detail="Project not found")
  1182. # Create template
  1183. template = Project(
  1184. name=f"{source.name} (Template)",
  1185. description=source.description,
  1186. color=source.color,
  1187. target_count=source.target_count,
  1188. target_parts_count=source.target_parts_count,
  1189. notes=source.notes,
  1190. tags=source.tags,
  1191. priority=source.priority,
  1192. budget=source.budget,
  1193. is_template=True,
  1194. template_source_id=source.id,
  1195. url=source.url,
  1196. )
  1197. db.add(template)
  1198. await db.flush()
  1199. # Copy BOM items
  1200. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == project_id))
  1201. bom_items = bom_result.scalars().all()
  1202. for item in bom_items:
  1203. new_item = ProjectBOMItem(
  1204. project_id=template.id,
  1205. name=item.name,
  1206. quantity_needed=item.quantity_needed,
  1207. quantity_acquired=0,
  1208. unit_price=item.unit_price,
  1209. sourcing_url=item.sourcing_url,
  1210. stl_filename=item.stl_filename,
  1211. remarks=item.remarks,
  1212. sort_order=item.sort_order,
  1213. )
  1214. db.add(new_item)
  1215. await db.flush()
  1216. await db.refresh(template)
  1217. stats = await compute_project_stats(db, template.id, template.target_count, template.target_parts_count)
  1218. return ProjectResponse(
  1219. id=template.id,
  1220. name=template.name,
  1221. description=template.description,
  1222. color=template.color,
  1223. status=template.status,
  1224. target_count=template.target_count,
  1225. target_parts_count=template.target_parts_count,
  1226. notes=template.notes,
  1227. attachments=template.attachments,
  1228. url=template.url,
  1229. cover_image_filename=template.cover_image_filename,
  1230. tags=template.tags,
  1231. due_date=template.due_date,
  1232. priority=template.priority,
  1233. budget=template.budget,
  1234. is_template=template.is_template,
  1235. template_source_id=template.template_source_id,
  1236. parent_id=template.parent_id,
  1237. parent_name=None,
  1238. children=[],
  1239. created_at=template.created_at,
  1240. updated_at=template.updated_at,
  1241. stats=stats,
  1242. )
  1243. # ============ Phase 9: Timeline Endpoint ============
  1244. @router.get("/{project_id}/timeline", response_model=list[TimelineEvent])
  1245. async def get_project_timeline(
  1246. project_id: int,
  1247. limit: int = 50,
  1248. db: AsyncSession = Depends(get_db),
  1249. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1250. ):
  1251. """Get timeline of events for a project."""
  1252. # Verify project exists
  1253. result = await db.execute(select(Project).where(Project.id == project_id))
  1254. project = result.scalar_one_or_none()
  1255. if not project:
  1256. raise HTTPException(status_code=404, detail="Project not found")
  1257. events = []
  1258. # Project creation event
  1259. events.append(
  1260. TimelineEvent(
  1261. event_type="project_created",
  1262. timestamp=project.created_at,
  1263. title="Project created",
  1264. description=f"Project '{project.name}' was created",
  1265. )
  1266. )
  1267. # Get archives and add events
  1268. archives_result = await db.execute(
  1269. select(PrintArchive)
  1270. .where(PrintArchive.project_id == project_id)
  1271. .order_by(PrintArchive.created_at.desc())
  1272. .limit(limit)
  1273. )
  1274. archives = archives_result.scalars().all()
  1275. for archive in archives:
  1276. if archive.status == "completed":
  1277. events.append(
  1278. TimelineEvent(
  1279. event_type="print_completed",
  1280. timestamp=archive.completed_at or archive.created_at,
  1281. title="Print completed",
  1282. description=archive.print_name,
  1283. metadata={
  1284. "archive_id": archive.id,
  1285. "print_time_hours": round((archive.print_time_seconds or 0) / 3600, 2),
  1286. "filament_grams": round(archive.filament_used_grams or 0, 1),
  1287. },
  1288. )
  1289. )
  1290. elif archive.status == "failed":
  1291. events.append(
  1292. TimelineEvent(
  1293. event_type="print_failed",
  1294. timestamp=archive.completed_at or archive.created_at,
  1295. title="Print failed",
  1296. description=archive.print_name,
  1297. metadata={"archive_id": archive.id},
  1298. )
  1299. )
  1300. # Get queue items
  1301. queue_result = await db.execute(
  1302. select(PrintQueueItem)
  1303. .where(PrintQueueItem.project_id == project_id)
  1304. .order_by(PrintQueueItem.created_at.desc())
  1305. .limit(limit)
  1306. )
  1307. queue_items = queue_result.scalars().all()
  1308. for item in queue_items:
  1309. if item.status == "printing":
  1310. events.append(
  1311. TimelineEvent(
  1312. event_type="print_started",
  1313. timestamp=item.started_at or item.created_at,
  1314. title="Print started",
  1315. description=item.print_name,
  1316. metadata={"queue_item_id": item.id},
  1317. )
  1318. )
  1319. elif item.status == "pending":
  1320. events.append(
  1321. TimelineEvent(
  1322. event_type="queued",
  1323. timestamp=item.created_at,
  1324. title="Added to queue",
  1325. description=item.print_name,
  1326. metadata={"queue_item_id": item.id},
  1327. )
  1328. )
  1329. # Sort by timestamp descending
  1330. events.sort(key=lambda e: e.timestamp, reverse=True)
  1331. return events[:limit]
  1332. # ============ Phase 10: Import/Export Endpoints ============
  1333. @router.get("/{project_id}/export")
  1334. async def export_project(
  1335. project_id: int,
  1336. format: str = "zip", # "zip" (with files) or "json" (metadata only)
  1337. db: AsyncSession = Depends(get_db),
  1338. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1339. ):
  1340. """Export a project. Use format=zip (default) for full export with files, or format=json for metadata only."""
  1341. result = await db.execute(select(Project).where(Project.id == project_id))
  1342. project = result.scalar_one_or_none()
  1343. if not project:
  1344. raise HTTPException(status_code=404, detail="Project not found")
  1345. # Get BOM items
  1346. bom_result = await db.execute(
  1347. select(ProjectBOMItem).where(ProjectBOMItem.project_id == project_id).order_by(ProjectBOMItem.sort_order)
  1348. )
  1349. bom_items = bom_result.scalars().all()
  1350. bom_export = [
  1351. {
  1352. "name": item.name,
  1353. "quantity_needed": item.quantity_needed,
  1354. "quantity_acquired": item.quantity_acquired,
  1355. "unit_price": item.unit_price,
  1356. "sourcing_url": item.sourcing_url,
  1357. "stl_filename": item.stl_filename,
  1358. "remarks": item.remarks,
  1359. }
  1360. for item in bom_items
  1361. ]
  1362. # Get linked folders and their files
  1363. folders_result = await db.execute(
  1364. select(LibraryFolder).where(LibraryFolder.project_id == project_id).order_by(LibraryFolder.name)
  1365. )
  1366. linked_folders = folders_result.scalars().all()
  1367. folders_export = []
  1368. files_to_include = [] # (archive_path, zip_path)
  1369. for folder in linked_folders:
  1370. # Get files in this folder
  1371. files_result = await db.execute(
  1372. LibraryFile.active().where(LibraryFile.folder_id == folder.id).order_by(LibraryFile.filename)
  1373. )
  1374. files = files_result.scalars().all()
  1375. folder_files = []
  1376. for f in files:
  1377. folder_files.append(
  1378. {
  1379. "filename": f.filename,
  1380. "file_type": f.file_type,
  1381. "notes": f.notes,
  1382. }
  1383. )
  1384. # Add file to include in ZIP
  1385. library_dir = get_library_dir()
  1386. file_path = library_dir / f.file_path
  1387. if file_path.exists():
  1388. zip_path = f"files/{folder.name}/{f.filename}"
  1389. files_to_include.append((file_path, zip_path))
  1390. # Also include thumbnail if exists
  1391. if f.thumbnail_path:
  1392. thumb_path = library_dir / f.thumbnail_path
  1393. if thumb_path.exists():
  1394. thumb_zip_path = f"files/{folder.name}/.thumbnails/{f.filename}.png"
  1395. files_to_include.append((thumb_path, thumb_zip_path))
  1396. folders_export.append(
  1397. {
  1398. "name": folder.name,
  1399. "files": folder_files,
  1400. }
  1401. )
  1402. # Build project JSON
  1403. project_data = {
  1404. "name": project.name,
  1405. "description": project.description,
  1406. "color": project.color,
  1407. "status": project.status,
  1408. "target_count": project.target_count,
  1409. "target_parts_count": project.target_parts_count,
  1410. "notes": project.notes,
  1411. "tags": project.tags,
  1412. "due_date": project.due_date.isoformat() if project.due_date else None,
  1413. "priority": project.priority,
  1414. "budget": project.budget,
  1415. "bom_items": bom_export,
  1416. "linked_folders": folders_export,
  1417. }
  1418. # Return JSON if requested (for bulk export)
  1419. if format == "json":
  1420. return project_data
  1421. # Create ZIP in memory
  1422. zip_buffer = io.BytesIO()
  1423. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  1424. # Add project.json
  1425. zf.writestr("project.json", json.dumps(project_data, indent=2))
  1426. # Add files
  1427. for file_path, zip_path in files_to_include:
  1428. zf.write(file_path, zip_path)
  1429. zip_buffer.seek(0)
  1430. # Generate filename
  1431. safe_name = "".join(c if c.isalnum() or c in "-_ " else "_" for c in project.name)
  1432. filename = f"{safe_name}_{datetime.now().strftime('%Y-%m-%d')}.zip"
  1433. return StreamingResponse(
  1434. zip_buffer,
  1435. media_type="application/zip",
  1436. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  1437. )
  1438. @router.post("/import", response_model=ProjectResponse)
  1439. async def import_project(
  1440. data: ProjectImport,
  1441. db: AsyncSession = Depends(get_db),
  1442. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1443. ):
  1444. """Import a project with optional BOM items and linked folders."""
  1445. # Create the project
  1446. project = Project(
  1447. name=data.name,
  1448. description=data.description,
  1449. color=data.color,
  1450. status=data.status,
  1451. target_count=data.target_count,
  1452. target_parts_count=data.target_parts_count,
  1453. notes=data.notes,
  1454. tags=data.tags,
  1455. due_date=data.due_date,
  1456. priority=data.priority,
  1457. budget=data.budget,
  1458. )
  1459. db.add(project)
  1460. await db.flush()
  1461. # Create BOM items
  1462. for idx, bom_data in enumerate(data.bom_items):
  1463. bom_item = ProjectBOMItem(
  1464. project_id=project.id,
  1465. name=bom_data.name,
  1466. quantity_needed=bom_data.quantity_needed,
  1467. quantity_acquired=bom_data.quantity_acquired,
  1468. unit_price=bom_data.unit_price,
  1469. sourcing_url=bom_data.sourcing_url,
  1470. stl_filename=bom_data.stl_filename,
  1471. remarks=bom_data.remarks,
  1472. sort_order=idx,
  1473. )
  1474. db.add(bom_item)
  1475. # Create linked folders in library
  1476. for folder_data in data.linked_folders:
  1477. # Check if folder with this name already exists at root level
  1478. existing_result = await db.execute(
  1479. select(LibraryFolder).where(
  1480. LibraryFolder.name == folder_data.name,
  1481. LibraryFolder.parent_id.is_(None),
  1482. )
  1483. )
  1484. existing_folder = existing_result.scalar_one_or_none()
  1485. if existing_folder:
  1486. # Link existing folder to project
  1487. existing_folder.project_id = project.id
  1488. else:
  1489. # Create new folder linked to project
  1490. new_folder = LibraryFolder(
  1491. name=folder_data.name,
  1492. project_id=project.id,
  1493. is_external=False,
  1494. external_readonly=False,
  1495. external_show_hidden=False,
  1496. )
  1497. db.add(new_folder)
  1498. await db.flush()
  1499. await db.refresh(project)
  1500. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  1501. return ProjectResponse(
  1502. id=project.id,
  1503. name=project.name,
  1504. description=project.description,
  1505. color=project.color,
  1506. status=project.status,
  1507. target_count=project.target_count,
  1508. target_parts_count=project.target_parts_count,
  1509. notes=project.notes,
  1510. attachments=project.attachments,
  1511. url=project.url,
  1512. cover_image_filename=project.cover_image_filename,
  1513. tags=project.tags,
  1514. due_date=project.due_date,
  1515. priority=project.priority,
  1516. budget=project.budget,
  1517. is_template=project.is_template,
  1518. template_source_id=project.template_source_id,
  1519. parent_id=project.parent_id,
  1520. parent_name=None,
  1521. children=[],
  1522. created_at=project.created_at,
  1523. updated_at=project.updated_at,
  1524. stats=stats,
  1525. )
  1526. @router.post("/import/file", response_model=ProjectResponse)
  1527. async def import_project_file(
  1528. file: UploadFile = File(...),
  1529. db: AsyncSession = Depends(get_db),
  1530. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1531. ):
  1532. """Import a project from a ZIP or JSON file."""
  1533. if not file.filename:
  1534. raise HTTPException(status_code=400, detail="No filename provided")
  1535. # Determine file type
  1536. filename_lower = file.filename.lower()
  1537. content = await file.read()
  1538. if filename_lower.endswith(".zip"):
  1539. # Extract project.json from ZIP
  1540. try:
  1541. with zipfile.ZipFile(io.BytesIO(content)) as zf:
  1542. if "project.json" not in zf.namelist():
  1543. raise HTTPException(status_code=400, detail="ZIP must contain project.json")
  1544. project_json = zf.read("project.json")
  1545. data = json.loads(project_json)
  1546. # Get list of files in the ZIP
  1547. zip_files = {name: zf.read(name) for name in zf.namelist() if name.startswith("files/")}
  1548. except zipfile.BadZipFile:
  1549. raise HTTPException(status_code=400, detail="Invalid ZIP file")
  1550. elif filename_lower.endswith(".json"):
  1551. try:
  1552. data = json.loads(content)
  1553. zip_files = {}
  1554. except json.JSONDecodeError:
  1555. raise HTTPException(status_code=400, detail="Invalid JSON file")
  1556. else:
  1557. raise HTTPException(status_code=400, detail="File must be .zip or .json")
  1558. # Create the project
  1559. project = Project(
  1560. name=data.get("name", "Imported Project"),
  1561. description=data.get("description"),
  1562. color=data.get("color"),
  1563. status=data.get("status", "active"),
  1564. target_count=data.get("target_count"),
  1565. target_parts_count=data.get("target_parts_count"),
  1566. notes=data.get("notes"),
  1567. tags=data.get("tags"),
  1568. due_date=datetime.fromisoformat(data["due_date"]) if data.get("due_date") else None,
  1569. priority=data.get("priority", 0),
  1570. budget=data.get("budget"),
  1571. )
  1572. db.add(project)
  1573. await db.flush()
  1574. # Create BOM items
  1575. for idx, bom_data in enumerate(data.get("bom_items", [])):
  1576. bom_item = ProjectBOMItem(
  1577. project_id=project.id,
  1578. name=bom_data.get("name", "Unnamed"),
  1579. quantity_needed=bom_data.get("quantity_needed", 1),
  1580. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1581. unit_price=bom_data.get("unit_price"),
  1582. sourcing_url=bom_data.get("sourcing_url"),
  1583. stl_filename=bom_data.get("stl_filename"),
  1584. remarks=bom_data.get("remarks"),
  1585. sort_order=idx,
  1586. )
  1587. db.add(bom_item)
  1588. # Create linked folders and files
  1589. library_dir = get_library_dir()
  1590. for folder_data in data.get("linked_folders", []):
  1591. folder_name = folder_data.get("name")
  1592. if not folder_name:
  1593. continue
  1594. # Check if folder exists
  1595. existing_result = await db.execute(
  1596. select(LibraryFolder).where(
  1597. LibraryFolder.name == folder_name,
  1598. LibraryFolder.parent_id.is_(None),
  1599. )
  1600. )
  1601. existing_folder = existing_result.scalar_one_or_none()
  1602. if existing_folder:
  1603. # Link existing folder to project
  1604. existing_folder.project_id = project.id
  1605. folder = existing_folder
  1606. else:
  1607. # Create new folder
  1608. folder = LibraryFolder(
  1609. name=folder_name,
  1610. project_id=project.id,
  1611. is_external=False,
  1612. external_readonly=False,
  1613. external_show_hidden=False,
  1614. )
  1615. db.add(folder)
  1616. await db.flush()
  1617. # Create folder on disk
  1618. folder_path = library_dir / folder_name
  1619. folder_path.mkdir(parents=True, exist_ok=True)
  1620. # Import files for this folder from ZIP
  1621. folder_prefix = f"files/{folder_name}/"
  1622. for zip_path, file_content in zip_files.items():
  1623. if not zip_path.startswith(folder_prefix):
  1624. continue
  1625. if "/.thumbnails/" in zip_path:
  1626. continue # Skip thumbnails, we'll regenerate them
  1627. relative_path = zip_path[len(folder_prefix) :]
  1628. if not relative_path:
  1629. continue
  1630. # Write file to disk
  1631. file_disk_path = library_dir / folder_name / relative_path
  1632. file_disk_path.parent.mkdir(parents=True, exist_ok=True)
  1633. file_disk_path.write_bytes(file_content)
  1634. # Determine file type
  1635. ext = Path(relative_path).suffix.lower()
  1636. if ext in [".stl", ".3mf", ".obj"]:
  1637. file_type = "model"
  1638. elif ext in [".gcode"]:
  1639. file_type = "gcode"
  1640. elif ext in [".jpg", ".jpeg", ".png", ".gif", ".webp"]:
  1641. file_type = "image"
  1642. else:
  1643. file_type = "other"
  1644. # Create library file record
  1645. lib_file = LibraryFile(
  1646. folder_id=folder.id,
  1647. filename=relative_path,
  1648. file_path=f"{folder_name}/{relative_path}",
  1649. file_type=file_type,
  1650. file_size=len(file_content),
  1651. is_external=False,
  1652. )
  1653. db.add(lib_file)
  1654. await db.flush()
  1655. await db.refresh(project)
  1656. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  1657. return ProjectResponse(
  1658. id=project.id,
  1659. name=project.name,
  1660. description=project.description,
  1661. color=project.color,
  1662. status=project.status,
  1663. target_count=project.target_count,
  1664. target_parts_count=project.target_parts_count,
  1665. notes=project.notes,
  1666. attachments=project.attachments,
  1667. url=project.url,
  1668. cover_image_filename=project.cover_image_filename,
  1669. tags=project.tags,
  1670. due_date=project.due_date,
  1671. priority=project.priority,
  1672. budget=project.budget,
  1673. is_template=project.is_template,
  1674. template_source_id=project.template_source_id,
  1675. parent_id=project.parent_id,
  1676. parent_name=None,
  1677. children=[],
  1678. created_at=project.created_at,
  1679. updated_at=project.updated_at,
  1680. stats=stats,
  1681. )