projects.py 59 KB

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