client.ts 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473
  1. const API_BASE = '/api/v1';
  2. async function request<T>(
  3. endpoint: string,
  4. options: RequestInit = {}
  5. ): Promise<T> {
  6. const response = await fetch(`${API_BASE}${endpoint}`, {
  7. ...options,
  8. headers: {
  9. 'Content-Type': 'application/json',
  10. ...options.headers,
  11. },
  12. });
  13. if (!response.ok) {
  14. const error = await response.json().catch(() => ({}));
  15. const detail = error.detail;
  16. const message = typeof detail === 'string'
  17. ? detail
  18. : (detail ? JSON.stringify(detail) : `HTTP ${response.status}`);
  19. throw new Error(message);
  20. }
  21. return await response.json();
  22. }
  23. // Printer types
  24. export interface Printer {
  25. id: number;
  26. name: string;
  27. serial_number: string;
  28. ip_address: string;
  29. access_code: string;
  30. model: string | null;
  31. location: string | null; // Group/location name
  32. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  33. is_active: boolean;
  34. auto_archive: boolean;
  35. created_at: string;
  36. updated_at: string;
  37. }
  38. export interface HMSError {
  39. code: string;
  40. attr: number; // Attribute value for constructing wiki URL
  41. module: number;
  42. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  43. }
  44. export interface AMSTray {
  45. id: number;
  46. tray_color: string | null;
  47. tray_type: string | null;
  48. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  49. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  50. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  51. remain: number;
  52. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  53. cali_idx: number | null; // Calibration index for K-profile lookup
  54. tag_uid: string | null; // RFID tag UID (any tag)
  55. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  56. nozzle_temp_min: number | null; // Min nozzle temperature
  57. nozzle_temp_max: number | null; // Max nozzle temperature
  58. }
  59. export interface AMSUnit {
  60. id: number;
  61. humidity: number | null;
  62. temp: number | null;
  63. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  64. tray: AMSTray[];
  65. }
  66. export interface NozzleInfo {
  67. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  68. nozzle_diameter: string; // e.g., "0.4"
  69. }
  70. export interface PrintOptions {
  71. // Core AI detectors
  72. spaghetti_detector: boolean;
  73. print_halt: boolean;
  74. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  75. first_layer_inspector: boolean;
  76. printing_monitor: boolean;
  77. buildplate_marker_detector: boolean;
  78. allow_skip_parts: boolean;
  79. // Additional AI detectors (decoded from cfg bitmask)
  80. nozzle_clumping_detector: boolean;
  81. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  82. pileup_detector: boolean;
  83. pileup_sensitivity: string; // "low", "medium", "high"
  84. airprint_detector: boolean;
  85. airprint_sensitivity: string; // "low", "medium", "high"
  86. auto_recovery_step_loss: boolean;
  87. filament_tangle_detect: boolean;
  88. }
  89. export interface PrinterStatus {
  90. id: number;
  91. name: string;
  92. connected: boolean;
  93. state: string | null;
  94. current_print: string | null;
  95. subtask_name: string | null;
  96. gcode_file: string | null;
  97. progress: number | null;
  98. remaining_time: number | null;
  99. layer_num: number | null;
  100. total_layers: number | null;
  101. temperatures: {
  102. bed?: number;
  103. bed_target?: number;
  104. bed_heating?: boolean; // Actual heater state from MQTT
  105. nozzle?: number;
  106. nozzle_target?: number;
  107. nozzle_heating?: boolean; // Actual heater state from MQTT
  108. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  109. nozzle_2_target?: number;
  110. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  111. chamber?: number;
  112. chamber_target?: number;
  113. chamber_heating?: boolean; // Actual heater state from MQTT
  114. } | null;
  115. cover_url: string | null;
  116. hms_errors: HMSError[];
  117. ams: AMSUnit[];
  118. ams_exists: boolean;
  119. vt_tray: AMSTray | null; // Virtual tray / external spool
  120. sdcard: boolean; // SD card inserted
  121. store_to_sdcard: boolean; // Store sent files on SD card
  122. timelapse: boolean; // Timelapse recording active
  123. ipcam: boolean; // Live view enabled
  124. wifi_signal: number | null; // WiFi signal strength in dBm
  125. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  126. print_options: PrintOptions | null; // AI detection and print options
  127. // Calibration stage tracking
  128. stg_cur: number; // Current stage number (-1 = not calibrating)
  129. stg_cur_name: string | null; // Human-readable current stage name
  130. stg: number[]; // List of stage numbers in calibration sequence
  131. // Air conditioning mode (0=cooling, 1=heating)
  132. airduct_mode: number;
  133. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  134. speed_level: number;
  135. // Chamber light on/off
  136. chamber_light: boolean;
  137. // Active extruder for dual nozzle (0=right, 1=left)
  138. active_extruder: number;
  139. // AMS mapping - which AMS is connected to which nozzle
  140. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  141. ams_mapping: number[];
  142. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  143. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  144. // Note: JSON keys are always strings
  145. ams_extruder_map: Record<string, number>;
  146. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  147. tray_now: number;
  148. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  149. ams_status_main: number;
  150. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  151. ams_status_sub: number;
  152. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  153. mc_print_sub_stage: number;
  154. // Timestamp of last AMS data update (for RFID refresh detection)
  155. last_ams_update: number;
  156. // Number of printable objects in current print (for skip objects feature)
  157. printable_objects_count: number;
  158. }
  159. export interface PrinterCreate {
  160. name: string;
  161. serial_number: string;
  162. ip_address: string;
  163. access_code: string;
  164. model?: string;
  165. location?: string;
  166. auto_archive?: boolean;
  167. }
  168. // Archive types
  169. export interface ArchiveDuplicate {
  170. id: number;
  171. print_name: string | null;
  172. created_at: string;
  173. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  174. }
  175. export interface Archive {
  176. id: number;
  177. printer_id: number | null;
  178. project_id: number | null;
  179. project_name: string | null;
  180. filename: string;
  181. file_path: string;
  182. file_size: number;
  183. content_hash: string | null;
  184. thumbnail_path: string | null;
  185. timelapse_path: string | null;
  186. source_3mf_path: string | null;
  187. duplicates: ArchiveDuplicate[] | null;
  188. duplicate_count: number;
  189. print_name: string | null;
  190. print_time_seconds: number | null;
  191. actual_time_seconds: number | null; // Computed from started_at/completed_at
  192. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  193. filament_used_grams: number | null;
  194. filament_type: string | null;
  195. filament_color: string | null;
  196. layer_height: number | null;
  197. total_layers: number | null;
  198. nozzle_diameter: number | null;
  199. bed_temperature: number | null;
  200. nozzle_temperature: number | null;
  201. status: string;
  202. started_at: string | null;
  203. completed_at: string | null;
  204. extra_data: Record<string, unknown> | null;
  205. makerworld_url: string | null;
  206. designer: string | null;
  207. is_favorite: boolean;
  208. tags: string | null;
  209. notes: string | null;
  210. cost: number | null;
  211. photos: string[] | null;
  212. failure_reason: string | null;
  213. energy_kwh: number | null;
  214. energy_cost: number | null;
  215. created_at: string;
  216. }
  217. export interface ArchiveStats {
  218. total_prints: number;
  219. successful_prints: number;
  220. failed_prints: number;
  221. total_print_time_hours: number;
  222. total_filament_grams: number;
  223. total_cost: number;
  224. prints_by_filament_type: Record<string, number>;
  225. prints_by_printer: Record<string, number>;
  226. average_time_accuracy: number | null;
  227. time_accuracy_by_printer: Record<string, number> | null;
  228. total_energy_kwh: number;
  229. total_energy_cost: number;
  230. }
  231. export interface FailureAnalysis {
  232. period_days: number;
  233. total_prints: number;
  234. failed_prints: number;
  235. failure_rate: number;
  236. failures_by_reason: Record<string, number>;
  237. failures_by_filament: Record<string, number>;
  238. failures_by_printer: Record<string, number>;
  239. failures_by_hour: Record<number, number>;
  240. recent_failures: Array<{
  241. id: number;
  242. print_name: string;
  243. failure_reason: string | null;
  244. filament_type: string | null;
  245. printer_id: number | null;
  246. created_at: string | null;
  247. }>;
  248. trend: Array<{
  249. week_start: string;
  250. total_prints: number;
  251. failed_prints: number;
  252. failure_rate: number;
  253. }>;
  254. }
  255. export interface BulkUploadResult {
  256. uploaded: number;
  257. failed: number;
  258. results: Array<{ filename: string; id: number; status: string }>;
  259. errors: Array<{ filename: string; error: string }>;
  260. }
  261. // Archive Comparison types
  262. export interface ComparisonArchiveInfo {
  263. id: number;
  264. print_name: string;
  265. status: string;
  266. created_at: string | null;
  267. printer_id: number | null;
  268. project_name: string | null;
  269. }
  270. export interface ComparisonField {
  271. field: string;
  272. label: string;
  273. unit: string | null;
  274. values: (string | number | null)[];
  275. raw_values: (string | number | null)[];
  276. has_difference: boolean;
  277. }
  278. export interface SuccessCorrelationInsight {
  279. field: string;
  280. label: string;
  281. insight: string;
  282. success_avg?: number;
  283. failed_avg?: number;
  284. success_values?: string[];
  285. failed_values?: string[];
  286. }
  287. export interface SuccessCorrelation {
  288. has_both_outcomes: boolean;
  289. message?: string;
  290. successful_count?: number;
  291. failed_count?: number;
  292. insights?: SuccessCorrelationInsight[];
  293. }
  294. export interface ArchiveComparison {
  295. archives: ComparisonArchiveInfo[];
  296. comparison: ComparisonField[];
  297. differences: ComparisonField[];
  298. success_correlation: SuccessCorrelation;
  299. }
  300. export interface SimilarArchive {
  301. archive: {
  302. id: number;
  303. print_name: string;
  304. status: string;
  305. created_at: string | null;
  306. };
  307. match_reason: string;
  308. match_score: number;
  309. }
  310. // Project types
  311. export interface ProjectStats {
  312. total_archives: number;
  313. completed_prints: number;
  314. failed_prints: number;
  315. queued_prints: number;
  316. in_progress_prints: number;
  317. total_print_time_hours: number;
  318. total_filament_grams: number;
  319. progress_percent: number | null;
  320. estimated_cost: number;
  321. total_energy_kwh: number;
  322. total_energy_cost: number;
  323. remaining_prints: number | null;
  324. bom_total_items: number;
  325. bom_completed_items: number;
  326. }
  327. export interface ProjectChildPreview {
  328. id: number;
  329. name: string;
  330. color: string | null;
  331. status: string;
  332. progress_percent: number | null;
  333. }
  334. export interface Project {
  335. id: number;
  336. name: string;
  337. description: string | null;
  338. color: string | null;
  339. status: string; // active, completed, archived
  340. target_count: number | null;
  341. notes: string | null;
  342. attachments: ProjectAttachment[] | null;
  343. tags: string | null;
  344. due_date: string | null;
  345. priority: string; // low, normal, high, urgent
  346. budget: number | null;
  347. is_template: boolean;
  348. template_source_id: number | null;
  349. parent_id: number | null;
  350. parent_name: string | null;
  351. children: ProjectChildPreview[];
  352. created_at: string;
  353. updated_at: string;
  354. stats?: ProjectStats;
  355. }
  356. export interface ProjectAttachment {
  357. filename: string;
  358. original_name: string;
  359. size: number;
  360. uploaded_at: string;
  361. }
  362. export interface ArchivePreview {
  363. id: number;
  364. print_name: string | null;
  365. thumbnail_path: string | null;
  366. status: string;
  367. filament_type: string | null;
  368. filament_color: string | null;
  369. }
  370. export interface ProjectListItem {
  371. id: number;
  372. name: string;
  373. description: string | null;
  374. color: string | null;
  375. status: string;
  376. target_count: number | null;
  377. created_at: string;
  378. archive_count: number;
  379. queue_count: number;
  380. progress_percent: number | null;
  381. archives: ArchivePreview[];
  382. }
  383. export interface ProjectCreate {
  384. name: string;
  385. description?: string;
  386. color?: string;
  387. target_count?: number;
  388. notes?: string;
  389. tags?: string;
  390. due_date?: string;
  391. priority?: string;
  392. budget?: number;
  393. parent_id?: number;
  394. }
  395. export interface ProjectUpdate {
  396. name?: string;
  397. description?: string;
  398. color?: string;
  399. status?: string;
  400. target_count?: number;
  401. notes?: string;
  402. tags?: string;
  403. due_date?: string;
  404. priority?: string;
  405. budget?: number;
  406. parent_id?: number;
  407. }
  408. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  409. export interface BOMItem {
  410. id: number;
  411. project_id: number;
  412. name: string;
  413. quantity_needed: number;
  414. quantity_acquired: number;
  415. unit_price: number | null;
  416. sourcing_url: string | null;
  417. archive_id: number | null;
  418. archive_name: string | null;
  419. stl_filename: string | null;
  420. remarks: string | null;
  421. sort_order: number;
  422. is_complete: boolean;
  423. created_at: string;
  424. updated_at: string;
  425. }
  426. export interface BOMItemCreate {
  427. name: string;
  428. quantity_needed?: number;
  429. unit_price?: number;
  430. sourcing_url?: string;
  431. archive_id?: number;
  432. stl_filename?: string;
  433. remarks?: string;
  434. }
  435. export interface BOMItemUpdate {
  436. name?: string;
  437. quantity_needed?: number;
  438. quantity_acquired?: number;
  439. unit_price?: number;
  440. sourcing_url?: string;
  441. archive_id?: number;
  442. stl_filename?: string;
  443. remarks?: string;
  444. }
  445. // Timeline Types
  446. export interface TimelineEvent {
  447. event_type: string;
  448. timestamp: string;
  449. title: string;
  450. description: string | null;
  451. metadata: Record<string, unknown> | null;
  452. }
  453. // API Key types
  454. export interface APIKey {
  455. id: number;
  456. name: string;
  457. key_prefix: string;
  458. can_queue: boolean;
  459. can_control_printer: boolean;
  460. can_read_status: boolean;
  461. printer_ids: number[] | null;
  462. enabled: boolean;
  463. last_used: string | null;
  464. created_at: string;
  465. expires_at: string | null;
  466. }
  467. export interface APIKeyCreate {
  468. name: string;
  469. can_queue?: boolean;
  470. can_control_printer?: boolean;
  471. can_read_status?: boolean;
  472. printer_ids?: number[] | null;
  473. expires_at?: string | null;
  474. }
  475. export interface APIKeyCreateResponse extends APIKey {
  476. key: string; // Full key, only shown on creation
  477. }
  478. export interface APIKeyUpdate {
  479. name?: string;
  480. can_queue?: boolean;
  481. can_control_printer?: boolean;
  482. can_read_status?: boolean;
  483. printer_ids?: number[] | null;
  484. enabled?: boolean;
  485. expires_at?: string | null;
  486. }
  487. // Settings types
  488. export interface AppSettings {
  489. auto_archive: boolean;
  490. save_thumbnails: boolean;
  491. capture_finish_photo: boolean;
  492. default_filament_cost: number;
  493. currency: string;
  494. energy_cost_per_kwh: number;
  495. energy_tracking_mode: 'print' | 'total';
  496. check_updates: boolean;
  497. notification_language: string;
  498. // AMS threshold settings
  499. ams_humidity_good: number; // <= this is green
  500. ams_humidity_fair: number; // <= this is orange, > is red
  501. ams_temp_good: number; // <= this is green/blue
  502. ams_temp_fair: number; // <= this is orange, > is red
  503. ams_history_retention_days: number; // days to keep AMS sensor history
  504. // Date/time format settings
  505. date_format: 'system' | 'us' | 'eu' | 'iso';
  506. time_format: 'system' | '12h' | '24h';
  507. // Default printer
  508. default_printer_id: number | null;
  509. // Telemetry
  510. telemetry_enabled: boolean;
  511. // Dark mode theme settings
  512. dark_style: 'classic' | 'glow' | 'vibrant';
  513. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  514. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  515. // Light mode theme settings
  516. light_style: 'classic' | 'glow' | 'vibrant';
  517. light_background: 'neutral' | 'warm' | 'cool';
  518. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  519. }
  520. export type AppSettingsUpdate = Partial<AppSettings>;
  521. // Cloud types
  522. export interface CloudAuthStatus {
  523. is_authenticated: boolean;
  524. email: string | null;
  525. }
  526. export interface CloudLoginResponse {
  527. success: boolean;
  528. needs_verification: boolean;
  529. message: string;
  530. }
  531. export interface SlicerSetting {
  532. setting_id: string;
  533. name: string;
  534. type: string;
  535. version: string | null;
  536. user_id: string | null;
  537. updated_time: string | null;
  538. }
  539. export interface SlicerSettingsResponse {
  540. filament: SlicerSetting[];
  541. printer: SlicerSetting[];
  542. process: SlicerSetting[];
  543. }
  544. export interface SlicerSettingDetail {
  545. message?: string | null;
  546. code?: string | null;
  547. error?: string | null;
  548. public: boolean;
  549. version?: string | null;
  550. type: string;
  551. name: string;
  552. update_time?: string | null;
  553. nickname?: string | null;
  554. base_id?: string | null;
  555. setting: Record<string, unknown>;
  556. filament_id?: string | null;
  557. setting_id?: string | null;
  558. }
  559. export interface SlicerSettingCreate {
  560. type: string; // 'filament', 'print', or 'printer'
  561. name: string;
  562. base_id: string;
  563. setting: Record<string, unknown>;
  564. }
  565. export interface SlicerSettingUpdate {
  566. name?: string;
  567. setting?: Record<string, unknown>;
  568. }
  569. export interface SlicerSettingDeleteResponse {
  570. success: boolean;
  571. message: string;
  572. }
  573. export interface FieldOption {
  574. value: string;
  575. label: string;
  576. }
  577. export interface FieldDefinition {
  578. key: string;
  579. label: string;
  580. type: 'text' | 'number' | 'boolean' | 'select';
  581. category: string;
  582. description?: string;
  583. options?: FieldOption[];
  584. unit?: string;
  585. min?: number;
  586. max?: number;
  587. step?: number;
  588. }
  589. export interface FieldDefinitionsResponse {
  590. version: string;
  591. description: string;
  592. fields: FieldDefinition[];
  593. }
  594. export interface CloudDevice {
  595. dev_id: string;
  596. name: string;
  597. dev_model_name: string | null;
  598. dev_product_name: string | null;
  599. online: boolean;
  600. }
  601. // Smart Plug types
  602. export interface SmartPlug {
  603. id: number;
  604. name: string;
  605. ip_address: string;
  606. printer_id: number | null;
  607. enabled: boolean;
  608. auto_on: boolean;
  609. auto_off: boolean;
  610. off_delay_mode: 'time' | 'temperature';
  611. off_delay_minutes: number;
  612. off_temp_threshold: number;
  613. username: string | null;
  614. password: string | null;
  615. // Power alerts
  616. power_alert_enabled: boolean;
  617. power_alert_high: number | null;
  618. power_alert_low: number | null;
  619. power_alert_last_triggered: string | null;
  620. // Schedule
  621. schedule_enabled: boolean;
  622. schedule_on_time: string | null;
  623. schedule_off_time: string | null;
  624. // Switchbar visibility
  625. show_in_switchbar: boolean;
  626. // Status
  627. last_state: string | null;
  628. last_checked: string | null;
  629. auto_off_executed: boolean; // True when auto-off was triggered after print
  630. created_at: string;
  631. updated_at: string;
  632. }
  633. export interface SmartPlugCreate {
  634. name: string;
  635. ip_address: string;
  636. printer_id?: number | null;
  637. enabled?: boolean;
  638. auto_on?: boolean;
  639. auto_off?: boolean;
  640. off_delay_mode?: 'time' | 'temperature';
  641. off_delay_minutes?: number;
  642. off_temp_threshold?: number;
  643. username?: string | null;
  644. password?: string | null;
  645. // Power alerts
  646. power_alert_enabled?: boolean;
  647. power_alert_high?: number | null;
  648. power_alert_low?: number | null;
  649. // Schedule
  650. schedule_enabled?: boolean;
  651. schedule_on_time?: string | null;
  652. schedule_off_time?: string | null;
  653. // Switchbar visibility
  654. show_in_switchbar?: boolean;
  655. }
  656. export interface SmartPlugUpdate {
  657. name?: string;
  658. ip_address?: string;
  659. printer_id?: number | null;
  660. enabled?: boolean;
  661. auto_on?: boolean;
  662. auto_off?: boolean;
  663. off_delay_mode?: 'time' | 'temperature';
  664. off_delay_minutes?: number;
  665. off_temp_threshold?: number;
  666. username?: string | null;
  667. password?: string | null;
  668. // Power alerts
  669. power_alert_enabled?: boolean;
  670. power_alert_high?: number | null;
  671. power_alert_low?: number | null;
  672. // Schedule
  673. schedule_enabled?: boolean;
  674. schedule_on_time?: string | null;
  675. schedule_off_time?: string | null;
  676. // Switchbar visibility
  677. show_in_switchbar?: boolean;
  678. }
  679. export interface SmartPlugEnergy {
  680. power: number | null; // Current watts
  681. voltage: number | null; // Volts
  682. current: number | null; // Amps
  683. today: number | null; // kWh used today
  684. yesterday: number | null; // kWh used yesterday
  685. total: number | null; // Total kWh
  686. factor: number | null; // Power factor (0-1)
  687. apparent_power: number | null; // VA
  688. reactive_power: number | null; // VAr
  689. }
  690. export interface SmartPlugStatus {
  691. state: string | null;
  692. reachable: boolean;
  693. device_name: string | null;
  694. energy: SmartPlugEnergy | null;
  695. }
  696. export interface SmartPlugTestResult {
  697. success: boolean;
  698. state: string | null;
  699. device_name: string | null;
  700. }
  701. // Tasmota Discovery types
  702. export interface TasmotaScanStatus {
  703. running: boolean;
  704. scanned: number;
  705. total: number;
  706. }
  707. export interface DiscoveredTasmotaDevice {
  708. ip_address: string;
  709. name: string;
  710. module: number | null;
  711. state: string | null;
  712. discovered_at: string | null;
  713. }
  714. // Print Queue types
  715. export interface PrintQueueItem {
  716. id: number;
  717. printer_id: number;
  718. archive_id: number;
  719. position: number;
  720. scheduled_time: string | null;
  721. require_previous_success: boolean;
  722. auto_off_after: boolean;
  723. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  724. started_at: string | null;
  725. completed_at: string | null;
  726. error_message: string | null;
  727. created_at: string;
  728. archive_name?: string | null;
  729. archive_thumbnail?: string | null;
  730. printer_name?: string | null;
  731. print_time_seconds?: number | null; // Estimated print time from archive
  732. }
  733. export interface PrintQueueItemCreate {
  734. printer_id: number;
  735. archive_id: number;
  736. scheduled_time?: string | null;
  737. require_previous_success?: boolean;
  738. auto_off_after?: boolean;
  739. }
  740. export interface PrintQueueItemUpdate {
  741. printer_id?: number;
  742. position?: number;
  743. scheduled_time?: string | null;
  744. require_previous_success?: boolean;
  745. auto_off_after?: boolean;
  746. }
  747. // MQTT Logging types
  748. export interface MQTTLogEntry {
  749. timestamp: string;
  750. topic: string;
  751. direction: 'in' | 'out';
  752. payload: Record<string, unknown>;
  753. }
  754. export interface MQTTLogsResponse {
  755. logging_enabled: boolean;
  756. logs: MQTTLogEntry[];
  757. }
  758. // K-Profile types
  759. export interface KProfile {
  760. slot_id: number;
  761. extruder_id: number;
  762. nozzle_id: string;
  763. nozzle_diameter: string;
  764. filament_id: string;
  765. name: string;
  766. k_value: string;
  767. n_coef: string;
  768. ams_id: number;
  769. tray_id: number;
  770. setting_id: string | null;
  771. }
  772. export interface KProfileCreate {
  773. slot_id?: number; // Storage slot, 0 for new profiles
  774. extruder_id?: number;
  775. nozzle_id: string;
  776. nozzle_diameter: string;
  777. filament_id: string;
  778. name: string;
  779. k_value: string;
  780. n_coef?: string;
  781. ams_id?: number;
  782. tray_id?: number;
  783. setting_id?: string | null;
  784. }
  785. export interface KProfileDelete {
  786. slot_id: number; // cali_idx - calibration index to delete
  787. extruder_id: number;
  788. nozzle_id: string; // e.g., "HH00-0.4"
  789. nozzle_diameter: string; // e.g., "0.4"
  790. filament_id: string; // Bambu filament identifier
  791. setting_id?: string | null; // Setting ID (for X1C series)
  792. }
  793. export interface KProfilesResponse {
  794. profiles: KProfile[];
  795. nozzle_diameter: string;
  796. }
  797. export interface KProfileNote {
  798. setting_id: string;
  799. note: string;
  800. }
  801. export interface KProfileNotesResponse {
  802. notes: Record<string, string>; // setting_id -> note
  803. }
  804. // Slot Preset Mapping
  805. export interface SlotPresetMapping {
  806. ams_id: number;
  807. tray_id: number;
  808. preset_id: string;
  809. preset_name: string;
  810. }
  811. // Filament types
  812. export interface Filament {
  813. id: number;
  814. name: string;
  815. type: string; // PLA, PETG, ABS, etc.
  816. brand: string | null;
  817. color: string | null;
  818. color_hex: string | null;
  819. cost_per_kg: number;
  820. spool_weight_g: number;
  821. currency: string;
  822. density: number | null;
  823. print_temp_min: number | null;
  824. print_temp_max: number | null;
  825. bed_temp_min: number | null;
  826. bed_temp_max: number | null;
  827. created_at: string;
  828. updated_at: string;
  829. }
  830. // Notification Provider types
  831. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook';
  832. export interface NotificationProvider {
  833. id: number;
  834. name: string;
  835. provider_type: ProviderType;
  836. enabled: boolean;
  837. config: Record<string, unknown>;
  838. // Print lifecycle events
  839. on_print_start: boolean;
  840. on_print_complete: boolean;
  841. on_print_failed: boolean;
  842. on_print_stopped: boolean;
  843. on_print_progress: boolean;
  844. // Printer status events
  845. on_printer_offline: boolean;
  846. on_printer_error: boolean;
  847. on_filament_low: boolean;
  848. on_maintenance_due: boolean;
  849. // AMS environmental alarms (regular AMS)
  850. on_ams_humidity_high: boolean;
  851. on_ams_temperature_high: boolean;
  852. // AMS-HT environmental alarms
  853. on_ams_ht_humidity_high: boolean;
  854. on_ams_ht_temperature_high: boolean;
  855. // Quiet hours
  856. quiet_hours_enabled: boolean;
  857. quiet_hours_start: string | null;
  858. quiet_hours_end: string | null;
  859. // Daily digest
  860. daily_digest_enabled: boolean;
  861. daily_digest_time: string | null;
  862. // Printer filter
  863. printer_id: number | null;
  864. // Status tracking
  865. last_success: string | null;
  866. last_error: string | null;
  867. last_error_at: string | null;
  868. // Timestamps
  869. created_at: string;
  870. updated_at: string;
  871. }
  872. export interface NotificationProviderCreate {
  873. name: string;
  874. provider_type: ProviderType;
  875. enabled?: boolean;
  876. config: Record<string, unknown>;
  877. // Print lifecycle events
  878. on_print_start?: boolean;
  879. on_print_complete?: boolean;
  880. on_print_failed?: boolean;
  881. on_print_stopped?: boolean;
  882. on_print_progress?: boolean;
  883. // Printer status events
  884. on_printer_offline?: boolean;
  885. on_printer_error?: boolean;
  886. on_filament_low?: boolean;
  887. on_maintenance_due?: boolean;
  888. // AMS environmental alarms (regular AMS)
  889. on_ams_humidity_high?: boolean;
  890. on_ams_temperature_high?: boolean;
  891. // AMS-HT environmental alarms
  892. on_ams_ht_humidity_high?: boolean;
  893. on_ams_ht_temperature_high?: boolean;
  894. // Quiet hours
  895. quiet_hours_enabled?: boolean;
  896. quiet_hours_start?: string | null;
  897. quiet_hours_end?: string | null;
  898. // Daily digest
  899. daily_digest_enabled?: boolean;
  900. daily_digest_time?: string | null;
  901. // Printer filter
  902. printer_id?: number | null;
  903. }
  904. export interface NotificationProviderUpdate {
  905. name?: string;
  906. provider_type?: ProviderType;
  907. enabled?: boolean;
  908. config?: Record<string, unknown>;
  909. // Print lifecycle events
  910. on_print_start?: boolean;
  911. on_print_complete?: boolean;
  912. on_print_failed?: boolean;
  913. on_print_stopped?: boolean;
  914. on_print_progress?: boolean;
  915. // Printer status events
  916. on_printer_offline?: boolean;
  917. on_printer_error?: boolean;
  918. on_filament_low?: boolean;
  919. on_maintenance_due?: boolean;
  920. // AMS environmental alarms (regular AMS)
  921. on_ams_humidity_high?: boolean;
  922. on_ams_temperature_high?: boolean;
  923. // AMS-HT environmental alarms
  924. on_ams_ht_humidity_high?: boolean;
  925. on_ams_ht_temperature_high?: boolean;
  926. // Quiet hours
  927. quiet_hours_enabled?: boolean;
  928. quiet_hours_start?: string | null;
  929. quiet_hours_end?: string | null;
  930. // Daily digest
  931. daily_digest_enabled?: boolean;
  932. daily_digest_time?: string | null;
  933. // Printer filter
  934. printer_id?: number | null;
  935. }
  936. export interface NotificationTestRequest {
  937. provider_type: ProviderType;
  938. config: Record<string, unknown>;
  939. }
  940. export interface NotificationTestResponse {
  941. success: boolean;
  942. message: string;
  943. }
  944. // Provider-specific config types for reference
  945. export interface CallMeBotConfig {
  946. phone: string;
  947. apikey: string;
  948. }
  949. export interface NtfyConfig {
  950. server?: string;
  951. topic: string;
  952. auth_token?: string | null;
  953. }
  954. export interface PushoverConfig {
  955. user_key: string;
  956. app_token: string;
  957. priority?: number;
  958. }
  959. export interface TelegramConfig {
  960. bot_token: string;
  961. chat_id: string;
  962. }
  963. export interface EmailConfig {
  964. smtp_server: string;
  965. smtp_port?: number;
  966. username: string;
  967. password: string;
  968. from_email: string;
  969. to_email: string;
  970. use_tls?: boolean;
  971. }
  972. // Notification Template types
  973. export interface NotificationTemplate {
  974. id: number;
  975. event_type: string;
  976. name: string;
  977. title_template: string;
  978. body_template: string;
  979. is_default: boolean;
  980. created_at: string;
  981. updated_at: string;
  982. }
  983. export interface NotificationTemplateUpdate {
  984. title_template?: string;
  985. body_template?: string;
  986. }
  987. export interface EventVariablesResponse {
  988. event_type: string;
  989. event_name: string;
  990. variables: string[];
  991. }
  992. export interface TemplatePreviewRequest {
  993. event_type: string;
  994. title_template: string;
  995. body_template: string;
  996. }
  997. export interface TemplatePreviewResponse {
  998. title: string;
  999. body: string;
  1000. }
  1001. // Notification Log types
  1002. export interface NotificationLogEntry {
  1003. id: number;
  1004. provider_id: number;
  1005. provider_name: string | null;
  1006. provider_type: string | null;
  1007. event_type: string;
  1008. title: string;
  1009. message: string;
  1010. success: boolean;
  1011. error_message: string | null;
  1012. printer_id: number | null;
  1013. printer_name: string | null;
  1014. created_at: string;
  1015. }
  1016. export interface NotificationLogStats {
  1017. total: number;
  1018. success_count: number;
  1019. failure_count: number;
  1020. by_event_type: Record<string, number>;
  1021. by_provider: Record<string, number>;
  1022. }
  1023. // Spoolman types
  1024. export interface SpoolmanStatus {
  1025. enabled: boolean;
  1026. connected: boolean;
  1027. url: string | null;
  1028. }
  1029. export interface SpoolmanSyncResult {
  1030. success: boolean;
  1031. synced_count: number;
  1032. errors: string[];
  1033. }
  1034. // Update types
  1035. export interface VersionInfo {
  1036. version: string;
  1037. repo: string;
  1038. }
  1039. export interface UpdateCheckResult {
  1040. update_available: boolean;
  1041. current_version: string;
  1042. latest_version: string | null;
  1043. release_name?: string;
  1044. release_notes?: string;
  1045. release_url?: string;
  1046. published_at?: string;
  1047. error?: string;
  1048. message?: string;
  1049. }
  1050. export interface UpdateStatus {
  1051. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  1052. progress: number;
  1053. message: string;
  1054. error: string | null;
  1055. }
  1056. // Maintenance types
  1057. export interface MaintenanceType {
  1058. id: number;
  1059. name: string;
  1060. description: string | null;
  1061. default_interval_hours: number;
  1062. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  1063. icon: string | null;
  1064. is_system: boolean;
  1065. created_at: string;
  1066. }
  1067. export interface MaintenanceTypeCreate {
  1068. name: string;
  1069. description?: string | null;
  1070. default_interval_hours?: number;
  1071. interval_type?: 'hours' | 'days';
  1072. icon?: string | null;
  1073. }
  1074. export interface MaintenanceStatus {
  1075. id: number;
  1076. printer_id: number;
  1077. printer_name: string;
  1078. maintenance_type_id: number;
  1079. maintenance_type_name: string;
  1080. maintenance_type_icon: string | null;
  1081. enabled: boolean;
  1082. interval_hours: number; // For hours type: print hours; for days type: number of days
  1083. interval_type: 'hours' | 'days';
  1084. current_hours: number;
  1085. hours_since_maintenance: number;
  1086. hours_until_due: number;
  1087. days_since_maintenance: number | null; // For days type
  1088. days_until_due: number | null; // For days type
  1089. is_due: boolean;
  1090. is_warning: boolean;
  1091. last_performed_at: string | null;
  1092. }
  1093. export interface PrinterMaintenanceOverview {
  1094. printer_id: number;
  1095. printer_name: string;
  1096. total_print_hours: number;
  1097. maintenance_items: MaintenanceStatus[];
  1098. due_count: number;
  1099. warning_count: number;
  1100. }
  1101. export interface MaintenanceHistory {
  1102. id: number;
  1103. printer_maintenance_id: number;
  1104. performed_at: string;
  1105. hours_at_maintenance: number;
  1106. notes: string | null;
  1107. }
  1108. export interface MaintenanceSummary {
  1109. total_due: number;
  1110. total_warning: number;
  1111. printers_with_issues: Array<{
  1112. printer_id: number;
  1113. printer_name: string;
  1114. due_count: number;
  1115. warning_count: number;
  1116. }>;
  1117. }
  1118. // External Links (sidebar)
  1119. export interface ExternalLink {
  1120. id: number;
  1121. name: string;
  1122. url: string;
  1123. icon: string;
  1124. custom_icon: string | null;
  1125. sort_order: number;
  1126. created_at: string;
  1127. updated_at: string;
  1128. }
  1129. export interface ExternalLinkCreate {
  1130. name: string;
  1131. url: string;
  1132. icon: string;
  1133. }
  1134. export interface ExternalLinkUpdate {
  1135. name?: string;
  1136. url?: string;
  1137. icon?: string;
  1138. }
  1139. // API functions
  1140. export const api = {
  1141. // Printers
  1142. getPrinters: () => request<Printer[]>('/printers/'),
  1143. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  1144. createPrinter: (data: PrinterCreate) =>
  1145. request<Printer>('/printers/', {
  1146. method: 'POST',
  1147. body: JSON.stringify(data),
  1148. }),
  1149. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  1150. request<Printer>(`/printers/${id}`, {
  1151. method: 'PATCH',
  1152. body: JSON.stringify(data),
  1153. }),
  1154. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  1155. request<{ status: string; archives_deleted: boolean }>(
  1156. `/printers/${id}?delete_archives=${deleteArchives}`,
  1157. { method: 'DELETE' }
  1158. ),
  1159. getPrinterStatus: (id: number) =>
  1160. request<PrinterStatus>(`/printers/${id}/status`),
  1161. refreshPrinterStatus: (id: number) =>
  1162. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  1163. method: 'POST',
  1164. }),
  1165. connectPrinter: (id: number) =>
  1166. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  1167. method: 'POST',
  1168. }),
  1169. disconnectPrinter: (id: number) =>
  1170. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  1171. method: 'POST',
  1172. }),
  1173. // Print Control
  1174. stopPrint: (printerId: number) =>
  1175. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  1176. method: 'POST',
  1177. }),
  1178. pausePrint: (printerId: number) =>
  1179. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  1180. method: 'POST',
  1181. }),
  1182. resumePrint: (printerId: number) =>
  1183. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  1184. method: 'POST',
  1185. }),
  1186. // Skip Objects
  1187. getPrintableObjects: (printerId: number) =>
  1188. request<{
  1189. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  1190. total: number;
  1191. skipped_count: number;
  1192. is_printing: boolean;
  1193. }>(`/printers/${printerId}/print/objects`),
  1194. skipObjects: (printerId: number, objectIds: number[]) =>
  1195. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  1196. `/printers/${printerId}/print/skip-objects`,
  1197. {
  1198. method: 'POST',
  1199. body: JSON.stringify(objectIds),
  1200. }
  1201. ),
  1202. // AMS Control
  1203. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  1204. request<{ success: boolean; message: string }>(
  1205. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  1206. { method: 'POST' }
  1207. ),
  1208. // MQTT Debug Logging
  1209. enableMQTTLogging: (printerId: number) =>
  1210. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  1211. method: 'POST',
  1212. }),
  1213. disableMQTTLogging: (printerId: number) =>
  1214. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  1215. method: 'POST',
  1216. }),
  1217. getMQTTLogs: (printerId: number) =>
  1218. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  1219. clearMQTTLogs: (printerId: number) =>
  1220. request<{ status: string }>(`/printers/${printerId}/logging`, {
  1221. method: 'DELETE',
  1222. }),
  1223. // Printer File Manager
  1224. getPrinterFiles: (printerId: number, path = '/') =>
  1225. request<{
  1226. path: string;
  1227. files: Array<{
  1228. name: string;
  1229. is_directory: boolean;
  1230. size: number;
  1231. path: string;
  1232. }>;
  1233. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  1234. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  1235. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  1236. deletePrinterFile: (printerId: number, path: string) =>
  1237. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  1238. method: 'DELETE',
  1239. }),
  1240. getPrinterStorage: (printerId: number) =>
  1241. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  1242. // Archives
  1243. getArchives: (printerId?: number, projectId?: number, limit = 50, offset = 0) => {
  1244. const params = new URLSearchParams();
  1245. if (printerId) params.set('printer_id', String(printerId));
  1246. if (projectId) params.set('project_id', String(projectId));
  1247. params.set('limit', String(limit));
  1248. params.set('offset', String(offset));
  1249. return request<Archive[]>(`/archives/?${params}`);
  1250. },
  1251. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  1252. searchArchives: (query: string, options?: {
  1253. printerId?: number;
  1254. projectId?: number;
  1255. status?: string;
  1256. limit?: number;
  1257. offset?: number;
  1258. }) => {
  1259. const params = new URLSearchParams();
  1260. params.set('q', query);
  1261. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1262. if (options?.projectId) params.set('project_id', String(options.projectId));
  1263. if (options?.status) params.set('status', options.status);
  1264. if (options?.limit) params.set('limit', String(options.limit));
  1265. if (options?.offset) params.set('offset', String(options.offset));
  1266. return request<Archive[]>(`/archives/search?${params}`);
  1267. },
  1268. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  1269. updateArchive: (id: number, data: {
  1270. printer_id?: number | null;
  1271. project_id?: number | null;
  1272. print_name?: string;
  1273. is_favorite?: boolean;
  1274. tags?: string;
  1275. notes?: string;
  1276. cost?: number;
  1277. failure_reason?: string | null;
  1278. status?: string;
  1279. }) =>
  1280. request<Archive>(`/archives/${id}`, {
  1281. method: 'PATCH',
  1282. body: JSON.stringify(data),
  1283. }),
  1284. toggleFavorite: (id: number) =>
  1285. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  1286. deleteArchive: (id: number) =>
  1287. request<void>(`/archives/${id}`, { method: 'DELETE' }),
  1288. getArchiveStats: () => request<ArchiveStats>('/archives/stats'),
  1289. getFailureAnalysis: (options?: { days?: number; printerId?: number; projectId?: number }) => {
  1290. const params = new URLSearchParams();
  1291. if (options?.days) params.set('days', String(options.days));
  1292. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1293. if (options?.projectId) params.set('project_id', String(options.projectId));
  1294. return request<FailureAnalysis>(`/archives/analysis/failures?${params}`);
  1295. },
  1296. compareArchives: (archiveIds: number[]) =>
  1297. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  1298. findSimilarArchives: (archiveId: number, limit = 10) =>
  1299. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  1300. exportArchives: async (options?: {
  1301. format?: 'csv' | 'xlsx';
  1302. fields?: string[];
  1303. printerId?: number;
  1304. projectId?: number;
  1305. status?: string;
  1306. dateFrom?: string;
  1307. dateTo?: string;
  1308. search?: string;
  1309. }): Promise<{ blob: Blob; filename: string }> => {
  1310. const params = new URLSearchParams();
  1311. if (options?.format) params.set('format', options.format);
  1312. if (options?.fields) params.set('fields', options.fields.join(','));
  1313. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1314. if (options?.projectId) params.set('project_id', String(options.projectId));
  1315. if (options?.status) params.set('status', options.status);
  1316. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  1317. if (options?.dateTo) params.set('date_to', options.dateTo);
  1318. if (options?.search) params.set('search', options.search);
  1319. const response = await fetch(`${API_BASE}/archives/export?${params}`);
  1320. if (!response.ok) {
  1321. const error = await response.json().catch(() => ({}));
  1322. throw new Error(error.detail || `HTTP ${response.status}`);
  1323. }
  1324. const contentDisposition = response.headers.get('Content-Disposition');
  1325. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  1326. if (contentDisposition) {
  1327. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  1328. if (match) filename = match[1];
  1329. }
  1330. const blob = await response.blob();
  1331. return { blob, filename };
  1332. },
  1333. exportStats: async (options?: {
  1334. format?: 'csv' | 'xlsx';
  1335. days?: number;
  1336. printerId?: number;
  1337. projectId?: number;
  1338. }): Promise<{ blob: Blob; filename: string }> => {
  1339. const params = new URLSearchParams();
  1340. if (options?.format) params.set('format', options.format);
  1341. if (options?.days) params.set('days', String(options.days));
  1342. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1343. if (options?.projectId) params.set('project_id', String(options.projectId));
  1344. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`);
  1345. if (!response.ok) {
  1346. const error = await response.json().catch(() => ({}));
  1347. throw new Error(error.detail || `HTTP ${response.status}`);
  1348. }
  1349. const contentDisposition = response.headers.get('Content-Disposition');
  1350. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  1351. if (contentDisposition) {
  1352. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  1353. if (match) filename = match[1];
  1354. }
  1355. const blob = await response.blob();
  1356. return { blob, filename };
  1357. },
  1358. getArchiveDuplicates: (id: number) =>
  1359. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  1360. backfillContentHashes: () =>
  1361. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  1362. method: 'POST',
  1363. }),
  1364. getArchiveThumbnail: (id: number) => `${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`,
  1365. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  1366. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  1367. getArchiveTimelapse: (id: number) => `${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`,
  1368. scanArchiveTimelapse: (id: number) =>
  1369. request<{
  1370. status: string;
  1371. message: string;
  1372. filename?: string;
  1373. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  1374. }>(`/archives/${id}/timelapse/scan`, {
  1375. method: 'POST',
  1376. }),
  1377. selectArchiveTimelapse: (id: number, filename: string) =>
  1378. request<{ status: string; message: string; filename: string }>(
  1379. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  1380. { method: 'POST' }
  1381. ),
  1382. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  1383. const formData = new FormData();
  1384. formData.append('file', file);
  1385. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  1386. method: 'POST',
  1387. body: formData,
  1388. });
  1389. if (!response.ok) {
  1390. const error = await response.json().catch(() => ({}));
  1391. throw new Error(error.detail || `HTTP ${response.status}`);
  1392. }
  1393. return response.json();
  1394. },
  1395. // Timelapse Editor
  1396. getTimelapseInfo: (archiveId: number) =>
  1397. request<{
  1398. duration: number;
  1399. width: number;
  1400. height: number;
  1401. fps: number;
  1402. codec: string;
  1403. file_size: number;
  1404. has_audio: boolean;
  1405. }>(`/archives/${archiveId}/timelapse/info`),
  1406. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  1407. request<{
  1408. thumbnails: string[];
  1409. timestamps: number[];
  1410. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  1411. processTimelapse: async (
  1412. archiveId: number,
  1413. params: {
  1414. trimStart?: number;
  1415. trimEnd?: number;
  1416. speed?: number;
  1417. saveMode: 'replace' | 'new';
  1418. outputFilename?: string;
  1419. },
  1420. audioFile?: File
  1421. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  1422. const formData = new FormData();
  1423. formData.append('trim_start', String(params.trimStart ?? 0));
  1424. if (params.trimEnd !== undefined) {
  1425. formData.append('trim_end', String(params.trimEnd));
  1426. }
  1427. formData.append('speed', String(params.speed ?? 1));
  1428. formData.append('save_mode', params.saveMode);
  1429. if (params.outputFilename) {
  1430. formData.append('output_filename', params.outputFilename);
  1431. }
  1432. if (audioFile) {
  1433. formData.append('audio', audioFile);
  1434. }
  1435. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  1436. method: 'POST',
  1437. body: formData,
  1438. });
  1439. if (!response.ok) {
  1440. const error = await response.json().catch(() => ({}));
  1441. throw new Error(error.detail || `HTTP ${response.status}`);
  1442. }
  1443. return response.json();
  1444. },
  1445. // Photos
  1446. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  1447. `${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`,
  1448. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  1449. const formData = new FormData();
  1450. formData.append('file', file);
  1451. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  1452. method: 'POST',
  1453. body: formData,
  1454. });
  1455. if (!response.ok) {
  1456. const error = await response.json().catch(() => ({}));
  1457. throw new Error(error.detail || `HTTP ${response.status}`);
  1458. }
  1459. return response.json();
  1460. },
  1461. deleteArchivePhoto: (archiveId: number, filename: string) =>
  1462. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  1463. method: 'DELETE',
  1464. }),
  1465. // Source 3MF (original slicer project file)
  1466. getSource3mfDownloadUrl: (archiveId: number) =>
  1467. `${API_BASE}/archives/${archiveId}/source`,
  1468. getSource3mfForSlicer: (archiveId: number, filename: string) =>
  1469. `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  1470. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  1471. const formData = new FormData();
  1472. formData.append('file', file);
  1473. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  1474. method: 'POST',
  1475. body: formData,
  1476. });
  1477. if (!response.ok) {
  1478. const error = await response.json().catch(() => ({}));
  1479. throw new Error(error.detail || `HTTP ${response.status}`);
  1480. }
  1481. return response.json();
  1482. },
  1483. deleteSource3mf: (archiveId: number) =>
  1484. request<{ status: string }>(`/archives/${archiveId}/source`, {
  1485. method: 'DELETE',
  1486. }),
  1487. // QR Code
  1488. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  1489. `${API_BASE}/archives/${archiveId}/qrcode?size=${size}`,
  1490. getArchiveCapabilities: (id: number) =>
  1491. request<{
  1492. has_model: boolean;
  1493. has_gcode: boolean;
  1494. build_volume: { x: number; y: number; z: number };
  1495. filament_colors: string[];
  1496. }>(`/archives/${id}/capabilities`),
  1497. // Project Page
  1498. getArchiveProjectPage: (id: number) =>
  1499. request<{
  1500. title: string | null;
  1501. description: string | null;
  1502. designer: string | null;
  1503. designer_user_id: string | null;
  1504. license: string | null;
  1505. copyright: string | null;
  1506. creation_date: string | null;
  1507. modification_date: string | null;
  1508. origin: string | null;
  1509. profile_title: string | null;
  1510. profile_description: string | null;
  1511. profile_cover: string | null;
  1512. profile_user_id: string | null;
  1513. profile_user_name: string | null;
  1514. design_model_id: string | null;
  1515. design_profile_id: string | null;
  1516. design_region: string | null;
  1517. model_pictures: Array<{ name: string; path: string; url: string }>;
  1518. profile_pictures: Array<{ name: string; path: string; url: string }>;
  1519. thumbnails: Array<{ name: string; path: string; url: string }>;
  1520. }>(`/archives/${id}/project-page`),
  1521. updateArchiveProjectPage: (id: number, data: {
  1522. title?: string;
  1523. description?: string;
  1524. designer?: string;
  1525. license?: string;
  1526. copyright?: string;
  1527. profile_title?: string;
  1528. profile_description?: string;
  1529. }) =>
  1530. request(`/archives/${id}/project-page`, {
  1531. method: 'PATCH',
  1532. body: JSON.stringify(data),
  1533. }),
  1534. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  1535. `${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`,
  1536. getArchiveForSlicer: (id: number, filename: string) =>
  1537. `${API_BASE}/archives/${id}/file/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  1538. getArchiveFilamentRequirements: (archiveId: number) =>
  1539. request<{
  1540. archive_id: number;
  1541. filename: string;
  1542. filaments: Array<{
  1543. slot_id: number;
  1544. type: string;
  1545. color: string;
  1546. used_grams: number;
  1547. used_meters: number;
  1548. }>;
  1549. }>(`/archives/${archiveId}/filament-requirements`),
  1550. reprintArchive: (archiveId: number, printerId: number) =>
  1551. request<{ status: string; printer_id: number; archive_id: number; filename: string }>(
  1552. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  1553. { method: 'POST' }
  1554. ),
  1555. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  1556. const formData = new FormData();
  1557. formData.append('file', file);
  1558. const url = printerId
  1559. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  1560. : `${API_BASE}/archives/upload`;
  1561. const response = await fetch(url, {
  1562. method: 'POST',
  1563. body: formData,
  1564. });
  1565. if (!response.ok) {
  1566. const error = await response.json().catch(() => ({}));
  1567. throw new Error(error.detail || `HTTP ${response.status}`);
  1568. }
  1569. return response.json();
  1570. },
  1571. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  1572. const formData = new FormData();
  1573. files.forEach((file) => formData.append('files', file));
  1574. const url = printerId
  1575. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  1576. : `${API_BASE}/archives/upload-bulk`;
  1577. const response = await fetch(url, {
  1578. method: 'POST',
  1579. body: formData,
  1580. });
  1581. if (!response.ok) {
  1582. const error = await response.json().catch(() => ({}));
  1583. throw new Error(error.detail || `HTTP ${response.status}`);
  1584. }
  1585. return response.json();
  1586. },
  1587. // Settings
  1588. getSettings: () => request<AppSettings>('/settings/'),
  1589. updateSettings: (data: AppSettingsUpdate) =>
  1590. request<AppSettings>('/settings/', {
  1591. method: 'PUT',
  1592. body: JSON.stringify(data),
  1593. }),
  1594. resetSettings: () =>
  1595. request<AppSettings>('/settings/reset', { method: 'POST' }),
  1596. exportBackup: async (categories?: Record<string, boolean>): Promise<{ blob: Blob; filename: string }> => {
  1597. const params = new URLSearchParams();
  1598. if (categories) {
  1599. if (categories.settings !== undefined) params.set('include_settings', String(categories.settings));
  1600. if (categories.notifications !== undefined) params.set('include_notifications', String(categories.notifications));
  1601. if (categories.templates !== undefined) params.set('include_templates', String(categories.templates));
  1602. if (categories.smart_plugs !== undefined) params.set('include_smart_plugs', String(categories.smart_plugs));
  1603. if (categories.external_links !== undefined) params.set('include_external_links', String(categories.external_links));
  1604. if (categories.printers !== undefined) params.set('include_printers', String(categories.printers));
  1605. if (categories.filaments !== undefined) params.set('include_filaments', String(categories.filaments));
  1606. if (categories.maintenance !== undefined) params.set('include_maintenance', String(categories.maintenance));
  1607. if (categories.archives !== undefined) params.set('include_archives', String(categories.archives));
  1608. if (categories.projects !== undefined) params.set('include_projects', String(categories.projects));
  1609. if (categories.access_codes !== undefined) params.set('include_access_codes', String(categories.access_codes));
  1610. }
  1611. const url = `${API_BASE}/settings/backup${params.toString() ? '?' + params.toString() : ''}`;
  1612. const response = await fetch(url);
  1613. // Get filename from Content-Disposition header
  1614. const contentDisposition = response.headers.get('Content-Disposition');
  1615. let filename = 'bambuddy-backup.json';
  1616. if (contentDisposition) {
  1617. const match = contentDisposition.match(/filename=([^;]+)/);
  1618. if (match) filename = match[1].trim();
  1619. }
  1620. const blob = await response.blob();
  1621. return { blob, filename };
  1622. },
  1623. importBackup: async (file: File, overwrite = false) => {
  1624. const formData = new FormData();
  1625. formData.append('file', file);
  1626. const url = `${API_BASE}/settings/restore${overwrite ? '?overwrite=true' : ''}`;
  1627. const response = await fetch(url, {
  1628. method: 'POST',
  1629. body: formData,
  1630. });
  1631. return response.json() as Promise<{
  1632. success: boolean;
  1633. message: string;
  1634. restored?: Record<string, number>;
  1635. skipped?: Record<string, number>;
  1636. skipped_details?: Record<string, string[]>;
  1637. files_restored?: number;
  1638. total_skipped?: number;
  1639. }>;
  1640. },
  1641. checkFfmpeg: () =>
  1642. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  1643. // Cloud
  1644. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  1645. cloudLogin: (email: string, password: string, region = 'global') =>
  1646. request<CloudLoginResponse>('/cloud/login', {
  1647. method: 'POST',
  1648. body: JSON.stringify({ email, password, region }),
  1649. }),
  1650. cloudVerify: (email: string, code: string) =>
  1651. request<CloudLoginResponse>('/cloud/verify', {
  1652. method: 'POST',
  1653. body: JSON.stringify({ email, code }),
  1654. }),
  1655. cloudSetToken: (access_token: string) =>
  1656. request<CloudAuthStatus>('/cloud/token', {
  1657. method: 'POST',
  1658. body: JSON.stringify({ access_token }),
  1659. }),
  1660. cloudLogout: () =>
  1661. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  1662. getCloudSettings: (version = '02.04.00.70') =>
  1663. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  1664. getCloudSettingDetail: (settingId: string) =>
  1665. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  1666. createCloudSetting: (data: SlicerSettingCreate) =>
  1667. request<SlicerSettingDetail>('/cloud/settings', {
  1668. method: 'POST',
  1669. body: JSON.stringify(data),
  1670. }),
  1671. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  1672. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  1673. method: 'PUT',
  1674. body: JSON.stringify(data),
  1675. }),
  1676. deleteCloudSetting: (settingId: string) =>
  1677. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  1678. method: 'DELETE',
  1679. }),
  1680. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  1681. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  1682. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  1683. getAllCloudFields: () =>
  1684. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  1685. getFilamentInfo: (settingIds: string[]) =>
  1686. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  1687. method: 'POST',
  1688. body: JSON.stringify(settingIds),
  1689. }),
  1690. // Smart Plugs
  1691. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  1692. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  1693. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  1694. createSmartPlug: (data: SmartPlugCreate) =>
  1695. request<SmartPlug>('/smart-plugs/', {
  1696. method: 'POST',
  1697. body: JSON.stringify(data),
  1698. }),
  1699. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  1700. request<SmartPlug>(`/smart-plugs/${id}`, {
  1701. method: 'PATCH',
  1702. body: JSON.stringify(data),
  1703. }),
  1704. deleteSmartPlug: (id: number) =>
  1705. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  1706. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  1707. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  1708. method: 'POST',
  1709. body: JSON.stringify({ action }),
  1710. }),
  1711. getSmartPlugStatus: (id: number) =>
  1712. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  1713. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  1714. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  1715. method: 'POST',
  1716. body: JSON.stringify({ ip_address, username, password }),
  1717. }),
  1718. // Tasmota Discovery (auto-detects network)
  1719. startTasmotaScan: () =>
  1720. fetch(`${API_BASE}/smart-plugs/discover/scan`, { method: 'POST' })
  1721. .then(res => res.ok ? res.json() : res.json().then(e => { throw new Error(e.detail || `HTTP ${res.status}`); })),
  1722. getTasmotaScanStatus: () =>
  1723. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  1724. stopTasmotaScan: () =>
  1725. fetch(`${API_BASE}/smart-plugs/discover/stop`, { method: 'POST' })
  1726. .then(res => res.ok ? res.json() : res.json().then(e => { throw new Error(e.detail || `HTTP ${res.status}`); })),
  1727. getDiscoveredTasmotaDevices: () =>
  1728. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  1729. // Print Queue
  1730. getQueue: (printerId?: number, status?: string) => {
  1731. const params = new URLSearchParams();
  1732. if (printerId) params.set('printer_id', String(printerId));
  1733. if (status) params.set('status', status);
  1734. return request<PrintQueueItem[]>(`/queue/?${params}`);
  1735. },
  1736. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  1737. addToQueue: (data: PrintQueueItemCreate) =>
  1738. request<PrintQueueItem>('/queue/', {
  1739. method: 'POST',
  1740. body: JSON.stringify(data),
  1741. }),
  1742. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  1743. request<PrintQueueItem>(`/queue/${id}`, {
  1744. method: 'PATCH',
  1745. body: JSON.stringify(data),
  1746. }),
  1747. removeFromQueue: (id: number) =>
  1748. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  1749. reorderQueue: (items: { id: number; position: number }[]) =>
  1750. request<{ message: string }>('/queue/reorder', {
  1751. method: 'POST',
  1752. body: JSON.stringify({ items }),
  1753. }),
  1754. cancelQueueItem: (id: number) =>
  1755. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  1756. stopQueueItem: (id: number) =>
  1757. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  1758. // K-Profiles
  1759. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  1760. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  1761. setKProfile: (printerId: number, profile: KProfileCreate) =>
  1762. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  1763. method: 'POST',
  1764. body: JSON.stringify(profile),
  1765. }),
  1766. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  1767. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  1768. method: 'DELETE',
  1769. body: JSON.stringify(profile),
  1770. }),
  1771. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  1772. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  1773. method: 'POST',
  1774. body: JSON.stringify(profiles),
  1775. }),
  1776. // K-Profile Notes (stored locally, not on printer)
  1777. getKProfileNotes: (printerId: number) =>
  1778. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  1779. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  1780. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  1781. method: 'PUT',
  1782. body: JSON.stringify({ setting_id: settingId, note }),
  1783. }),
  1784. deleteKProfileNote: (printerId: number, settingId: string) =>
  1785. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  1786. method: 'DELETE',
  1787. }),
  1788. // Slot Preset Mappings
  1789. getSlotPresets: (printerId: number) =>
  1790. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  1791. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  1792. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  1793. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string) =>
  1794. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}`, {
  1795. method: 'PUT',
  1796. }),
  1797. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  1798. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  1799. method: 'DELETE',
  1800. }),
  1801. // Filaments
  1802. listFilaments: () => request<Filament[]>('/filaments/'),
  1803. getFilament: (id: number) => request<Filament>(`/filaments/${id}`),
  1804. getFilamentsByType: (type: string) => request<Filament[]>(`/filaments/by-type/${type}`),
  1805. // Notification Providers
  1806. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  1807. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  1808. createNotificationProvider: (data: NotificationProviderCreate) =>
  1809. request<NotificationProvider>('/notifications/', {
  1810. method: 'POST',
  1811. body: JSON.stringify(data),
  1812. }),
  1813. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  1814. request<NotificationProvider>(`/notifications/${id}`, {
  1815. method: 'PATCH',
  1816. body: JSON.stringify(data),
  1817. }),
  1818. deleteNotificationProvider: (id: number) =>
  1819. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  1820. testNotificationProvider: (id: number) =>
  1821. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  1822. testNotificationConfig: (data: NotificationTestRequest) =>
  1823. request<NotificationTestResponse>('/notifications/test-config', {
  1824. method: 'POST',
  1825. body: JSON.stringify(data),
  1826. }),
  1827. testAllNotificationProviders: () =>
  1828. request<{
  1829. tested: number;
  1830. success: number;
  1831. failed: number;
  1832. results: Array<{
  1833. provider_id: number;
  1834. provider_name: string;
  1835. provider_type: string;
  1836. success: boolean;
  1837. message: string;
  1838. }>;
  1839. }>('/notifications/test-all', { method: 'POST' }),
  1840. // Notification Templates
  1841. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  1842. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  1843. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  1844. request<NotificationTemplate>(`/notification-templates/${id}`, {
  1845. method: 'PUT',
  1846. body: JSON.stringify(data),
  1847. }),
  1848. resetNotificationTemplate: (id: number) =>
  1849. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  1850. method: 'POST',
  1851. }),
  1852. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  1853. previewTemplate: (data: TemplatePreviewRequest) =>
  1854. request<TemplatePreviewResponse>('/notification-templates/preview', {
  1855. method: 'POST',
  1856. body: JSON.stringify(data),
  1857. }),
  1858. // Notification Logs
  1859. getNotificationLogs: (params?: {
  1860. limit?: number;
  1861. offset?: number;
  1862. provider_id?: number;
  1863. event_type?: string;
  1864. success?: boolean;
  1865. days?: number;
  1866. }) => {
  1867. const searchParams = new URLSearchParams();
  1868. if (params?.limit) searchParams.set('limit', String(params.limit));
  1869. if (params?.offset) searchParams.set('offset', String(params.offset));
  1870. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  1871. if (params?.event_type) searchParams.set('event_type', params.event_type);
  1872. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  1873. if (params?.days) searchParams.set('days', String(params.days));
  1874. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  1875. },
  1876. getNotificationLogStats: (days = 7) =>
  1877. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  1878. clearNotificationLogs: (olderThanDays = 30) =>
  1879. request<{ deleted: number; message: string }>(
  1880. `/notifications/logs?older_than_days=${olderThanDays}`,
  1881. { method: 'DELETE' }
  1882. ),
  1883. // Spoolman Integration
  1884. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  1885. connectSpoolman: () =>
  1886. request<{ success: boolean; message: string }>('/spoolman/connect', {
  1887. method: 'POST',
  1888. }),
  1889. disconnectSpoolman: () =>
  1890. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  1891. method: 'POST',
  1892. }),
  1893. syncPrinterAms: (printerId: number) =>
  1894. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  1895. method: 'POST',
  1896. }),
  1897. syncAllPrintersAms: () =>
  1898. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  1899. method: 'POST',
  1900. }),
  1901. getSpoolmanSpools: () =>
  1902. request<{ spools: unknown[] }>('/spoolman/spools'),
  1903. getSpoolmanFilaments: () =>
  1904. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  1905. // Updates
  1906. getVersion: () => request<VersionInfo>('/updates/version'),
  1907. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  1908. applyUpdate: () =>
  1909. request<{ success: boolean; message: string; status: UpdateStatus }>('/updates/apply', {
  1910. method: 'POST',
  1911. }),
  1912. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  1913. // Maintenance
  1914. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  1915. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  1916. request<MaintenanceType>('/maintenance/types', {
  1917. method: 'POST',
  1918. body: JSON.stringify(data),
  1919. }),
  1920. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  1921. request<MaintenanceType>(`/maintenance/types/${id}`, {
  1922. method: 'PATCH',
  1923. body: JSON.stringify(data),
  1924. }),
  1925. deleteMaintenanceType: (id: number) =>
  1926. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  1927. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  1928. getPrinterMaintenance: (printerId: number) =>
  1929. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  1930. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  1931. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  1932. method: 'PATCH',
  1933. body: JSON.stringify(data),
  1934. }),
  1935. performMaintenance: (itemId: number, notes?: string) =>
  1936. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  1937. method: 'POST',
  1938. body: JSON.stringify({ notes }),
  1939. }),
  1940. getMaintenanceHistory: (itemId: number) =>
  1941. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  1942. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  1943. setPrinterHours: (printerId: number, totalHours: number) =>
  1944. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  1945. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  1946. { method: 'PATCH' }
  1947. ),
  1948. assignMaintenanceType: (printerId: number, typeId: number) =>
  1949. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  1950. method: 'POST',
  1951. }),
  1952. removeMaintenanceItem: (itemId: number) =>
  1953. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  1954. method: 'DELETE',
  1955. }),
  1956. // Camera
  1957. getCameraStreamUrl: (printerId: number, fps = 10) =>
  1958. `${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`,
  1959. getCameraSnapshotUrl: (printerId: number) =>
  1960. `${API_BASE}/printers/${printerId}/camera/snapshot`,
  1961. testCameraConnection: (printerId: number) =>
  1962. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  1963. // External Links
  1964. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  1965. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  1966. createExternalLink: (data: ExternalLinkCreate) =>
  1967. request<ExternalLink>('/external-links/', {
  1968. method: 'POST',
  1969. body: JSON.stringify(data),
  1970. }),
  1971. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  1972. request<ExternalLink>(`/external-links/${id}`, {
  1973. method: 'PATCH',
  1974. body: JSON.stringify(data),
  1975. }),
  1976. deleteExternalLink: (id: number) =>
  1977. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  1978. reorderExternalLinks: (ids: number[]) =>
  1979. request<ExternalLink[]>('/external-links/reorder', {
  1980. method: 'PUT',
  1981. body: JSON.stringify({ ids }),
  1982. }),
  1983. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  1984. const formData = new FormData();
  1985. formData.append('file', file);
  1986. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  1987. method: 'POST',
  1988. body: formData,
  1989. });
  1990. if (!response.ok) {
  1991. const error = await response.json().catch(() => ({}));
  1992. throw new Error(error.detail || `HTTP ${response.status}`);
  1993. }
  1994. return response.json();
  1995. },
  1996. deleteExternalLinkIcon: (id: number) =>
  1997. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  1998. getExternalLinkIconUrl: (id: number) => `${API_BASE}/external-links/${id}/icon`,
  1999. // Projects
  2000. getProjects: (status?: string) => {
  2001. const params = new URLSearchParams();
  2002. if (status) params.set('status', status);
  2003. return request<ProjectListItem[]>(`/projects/?${params}`);
  2004. },
  2005. getProject: (id: number) => request<Project>(`/projects/${id}`),
  2006. createProject: (data: ProjectCreate) =>
  2007. request<Project>('/projects/', {
  2008. method: 'POST',
  2009. body: JSON.stringify(data),
  2010. }),
  2011. updateProject: (id: number, data: ProjectUpdate) =>
  2012. request<Project>(`/projects/${id}`, {
  2013. method: 'PATCH',
  2014. body: JSON.stringify(data),
  2015. }),
  2016. deleteProject: (id: number) =>
  2017. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  2018. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  2019. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  2020. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  2021. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  2022. method: 'POST',
  2023. body: JSON.stringify({ archive_ids: archiveIds }),
  2024. }),
  2025. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  2026. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  2027. method: 'POST',
  2028. body: JSON.stringify({ archive_ids: archiveIds }),
  2029. }),
  2030. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  2031. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  2032. method: 'POST',
  2033. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  2034. }),
  2035. // Project Attachments
  2036. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  2037. status: string;
  2038. filename: string;
  2039. original_name: string;
  2040. attachments: ProjectAttachment[];
  2041. }> => {
  2042. const formData = new FormData();
  2043. formData.append('file', file);
  2044. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  2045. method: 'POST',
  2046. body: formData,
  2047. });
  2048. if (!response.ok) {
  2049. const error = await response.json().catch(() => ({}));
  2050. throw new Error(error.detail || `HTTP ${response.status}`);
  2051. }
  2052. return response.json();
  2053. },
  2054. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  2055. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  2056. deleteProjectAttachment: (projectId: number, filename: string) =>
  2057. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  2058. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  2059. { method: 'DELETE' }
  2060. ),
  2061. // BOM (Bill of Materials)
  2062. getProjectBOM: (projectId: number) =>
  2063. request<BOMItem[]>(`/projects/${projectId}/bom`),
  2064. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  2065. request<BOMItem>(`/projects/${projectId}/bom`, {
  2066. method: 'POST',
  2067. body: JSON.stringify(data),
  2068. }),
  2069. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  2070. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  2071. method: 'PATCH',
  2072. body: JSON.stringify(data),
  2073. }),
  2074. deleteBOMItem: (projectId: number, itemId: number) =>
  2075. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  2076. method: 'DELETE',
  2077. }),
  2078. // Templates
  2079. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  2080. createTemplateFromProject: (projectId: number) =>
  2081. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  2082. createProjectFromTemplate: (templateId: number, name?: string) =>
  2083. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  2084. method: 'POST',
  2085. }),
  2086. // Timeline
  2087. getProjectTimeline: (projectId: number, limit = 50) =>
  2088. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  2089. // API Keys
  2090. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  2091. createAPIKey: (data: APIKeyCreate) =>
  2092. request<APIKeyCreateResponse>('/api-keys/', {
  2093. method: 'POST',
  2094. body: JSON.stringify(data),
  2095. }),
  2096. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  2097. request<APIKey>(`/api-keys/${id}`, {
  2098. method: 'PATCH',
  2099. body: JSON.stringify(data),
  2100. }),
  2101. deleteAPIKey: (id: number) =>
  2102. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  2103. // AMS History
  2104. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  2105. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  2106. // System Info
  2107. getSystemInfo: () => request<SystemInfo>('/system/info'),
  2108. };
  2109. // AMS History types
  2110. export interface AMSHistoryPoint {
  2111. recorded_at: string;
  2112. humidity: number | null;
  2113. humidity_raw: number | null;
  2114. temperature: number | null;
  2115. }
  2116. export interface AMSHistoryResponse {
  2117. printer_id: number;
  2118. ams_id: number;
  2119. data: AMSHistoryPoint[];
  2120. min_humidity: number | null;
  2121. max_humidity: number | null;
  2122. avg_humidity: number | null;
  2123. min_temperature: number | null;
  2124. max_temperature: number | null;
  2125. avg_temperature: number | null;
  2126. }
  2127. // System Info types
  2128. export interface SystemInfo {
  2129. app: {
  2130. version: string;
  2131. base_dir: string;
  2132. archive_dir: string;
  2133. };
  2134. database: {
  2135. archives: number;
  2136. archives_completed: number;
  2137. archives_failed: number;
  2138. archives_printing: number;
  2139. printers: number;
  2140. filaments: number;
  2141. projects: number;
  2142. smart_plugs: number;
  2143. total_print_time_seconds: number;
  2144. total_print_time_formatted: string;
  2145. total_filament_grams: number;
  2146. total_filament_kg: number;
  2147. };
  2148. printers: {
  2149. total: number;
  2150. connected: number;
  2151. connected_list: Array<{
  2152. id: number;
  2153. name: string;
  2154. state: string;
  2155. model: string;
  2156. }>;
  2157. };
  2158. storage: {
  2159. archive_size_bytes: number;
  2160. archive_size_formatted: string;
  2161. database_size_bytes: number;
  2162. database_size_formatted: string;
  2163. disk_total_bytes: number;
  2164. disk_total_formatted: string;
  2165. disk_used_bytes: number;
  2166. disk_used_formatted: string;
  2167. disk_free_bytes: number;
  2168. disk_free_formatted: string;
  2169. disk_percent_used: number;
  2170. };
  2171. system: {
  2172. platform: string;
  2173. platform_release: string;
  2174. platform_version: string;
  2175. architecture: string;
  2176. hostname: string;
  2177. python_version: string;
  2178. uptime_seconds: number;
  2179. uptime_formatted: string;
  2180. boot_time: string;
  2181. };
  2182. memory: {
  2183. total_bytes: number;
  2184. total_formatted: string;
  2185. available_bytes: number;
  2186. available_formatted: string;
  2187. used_bytes: number;
  2188. used_formatted: string;
  2189. percent_used: number;
  2190. };
  2191. cpu: {
  2192. count: number;
  2193. count_logical: number;
  2194. percent: number;
  2195. };
  2196. }
  2197. // Discovery types
  2198. export interface DiscoveredPrinter {
  2199. serial: string;
  2200. name: string;
  2201. ip_address: string;
  2202. model: string | null;
  2203. discovered_at: string | null;
  2204. }
  2205. export interface DiscoveryStatus {
  2206. running: boolean;
  2207. }
  2208. export interface DiscoveryInfo {
  2209. is_docker: boolean;
  2210. ssdp_running: boolean;
  2211. scan_running: boolean;
  2212. }
  2213. export interface SubnetScanStatus {
  2214. running: boolean;
  2215. scanned: number;
  2216. total: number;
  2217. }
  2218. // Discovery API
  2219. export const discoveryApi = {
  2220. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  2221. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  2222. startDiscovery: (duration: number = 10) =>
  2223. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  2224. stopDiscovery: () =>
  2225. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  2226. getDiscoveredPrinters: () =>
  2227. request<DiscoveredPrinter[]>('/discovery/printers'),
  2228. // Subnet scanning (for Docker environments)
  2229. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  2230. request<SubnetScanStatus>('/discovery/scan', {
  2231. method: 'POST',
  2232. body: JSON.stringify({ subnet, timeout }),
  2233. }),
  2234. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  2235. stopSubnetScan: () =>
  2236. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  2237. };
  2238. // Virtual Printer types
  2239. export interface VirtualPrinterStatus {
  2240. enabled: boolean;
  2241. running: boolean;
  2242. mode: 'immediate' | 'queue';
  2243. name: string;
  2244. serial: string;
  2245. model: string;
  2246. pending_files: number;
  2247. }
  2248. export interface VirtualPrinterSettings {
  2249. enabled: boolean;
  2250. access_code_set: boolean;
  2251. mode: 'immediate' | 'queue';
  2252. status: VirtualPrinterStatus;
  2253. }
  2254. export interface PendingUpload {
  2255. id: number;
  2256. filename: string;
  2257. file_size: number;
  2258. source_ip: string | null;
  2259. status: string;
  2260. tags: string | null;
  2261. notes: string | null;
  2262. project_id: number | null;
  2263. uploaded_at: string;
  2264. }
  2265. // Virtual Printer API
  2266. export const virtualPrinterApi = {
  2267. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  2268. updateSettings: (data: {
  2269. enabled?: boolean;
  2270. access_code?: string;
  2271. mode?: 'immediate' | 'queue';
  2272. }) => {
  2273. const params = new URLSearchParams();
  2274. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  2275. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  2276. if (data.mode !== undefined) params.set('mode', data.mode);
  2277. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  2278. method: 'PUT',
  2279. });
  2280. },
  2281. };
  2282. // Pending Uploads API
  2283. export const pendingUploadsApi = {
  2284. list: () => request<PendingUpload[]>('/pending-uploads/'),
  2285. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  2286. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  2287. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  2288. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  2289. method: 'POST',
  2290. body: JSON.stringify(data || {}),
  2291. }),
  2292. discard: (id: number) =>
  2293. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  2294. archiveAll: () =>
  2295. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  2296. discardAll: () =>
  2297. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  2298. };