client.ts 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409
  1. const API_BASE = '/api/v1';
  2. // Auth token storage
  3. let authToken: string | null = localStorage.getItem('auth_token');
  4. export function setAuthToken(token: string | null) {
  5. authToken = token;
  6. if (token) {
  7. localStorage.setItem('auth_token', token);
  8. } else {
  9. localStorage.removeItem('auth_token');
  10. }
  11. }
  12. export function getAuthToken(): string | null {
  13. return authToken;
  14. }
  15. async function request<T>(
  16. endpoint: string,
  17. options: RequestInit = {}
  18. ): Promise<T> {
  19. const headers: Record<string, string> = {
  20. 'Content-Type': 'application/json',
  21. ...options.headers as Record<string, string>,
  22. };
  23. // Add auth token if available
  24. if (authToken) {
  25. headers['Authorization'] = `Bearer ${authToken}`;
  26. }
  27. const response = await fetch(`${API_BASE}${endpoint}`, {
  28. ...options,
  29. cache: 'no-store', // Prevent browser caching of API responses
  30. headers,
  31. });
  32. if (!response.ok) {
  33. // Handle 401 Unauthorized - clear token and redirect to login
  34. if (response.status === 401) {
  35. setAuthToken(null);
  36. // Don't throw here - let the auth context handle redirect
  37. }
  38. const error = await response.json().catch(() => ({}));
  39. const detail = error.detail;
  40. const message = typeof detail === 'string'
  41. ? detail
  42. : (detail ? JSON.stringify(detail) : `HTTP ${response.status}`);
  43. throw new Error(message);
  44. }
  45. return await response.json();
  46. }
  47. // Printer types
  48. export interface Printer {
  49. id: number;
  50. name: string;
  51. serial_number: string;
  52. ip_address: string;
  53. access_code: string;
  54. model: string | null;
  55. location: string | null; // Group/location name
  56. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  57. is_active: boolean;
  58. auto_archive: boolean;
  59. external_camera_url: string | null;
  60. external_camera_type: string | null; // "mjpeg", "rtsp", "snapshot"
  61. external_camera_enabled: boolean;
  62. created_at: string;
  63. updated_at: string;
  64. }
  65. export interface HMSError {
  66. code: string;
  67. attr: number; // Attribute value for constructing wiki URL
  68. module: number;
  69. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  70. }
  71. export interface AMSTray {
  72. id: number;
  73. tray_color: string | null;
  74. tray_type: string | null;
  75. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  76. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  77. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  78. remain: number;
  79. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  80. cali_idx: number | null; // Calibration index for K-profile lookup
  81. tag_uid: string | null; // RFID tag UID (any tag)
  82. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  83. nozzle_temp_min: number | null; // Min nozzle temperature
  84. nozzle_temp_max: number | null; // Max nozzle temperature
  85. }
  86. export interface AMSUnit {
  87. id: number;
  88. humidity: number | null;
  89. temp: number | null;
  90. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  91. tray: AMSTray[];
  92. }
  93. export interface NozzleInfo {
  94. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  95. nozzle_diameter: string; // e.g., "0.4"
  96. }
  97. export interface PrintOptions {
  98. // Core AI detectors
  99. spaghetti_detector: boolean;
  100. print_halt: boolean;
  101. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  102. first_layer_inspector: boolean;
  103. printing_monitor: boolean;
  104. buildplate_marker_detector: boolean;
  105. allow_skip_parts: boolean;
  106. // Additional AI detectors (decoded from cfg bitmask)
  107. nozzle_clumping_detector: boolean;
  108. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  109. pileup_detector: boolean;
  110. pileup_sensitivity: string; // "low", "medium", "high"
  111. airprint_detector: boolean;
  112. airprint_sensitivity: string; // "low", "medium", "high"
  113. auto_recovery_step_loss: boolean;
  114. filament_tangle_detect: boolean;
  115. }
  116. export interface PrinterStatus {
  117. id: number;
  118. name: string;
  119. connected: boolean;
  120. state: string | null;
  121. current_print: string | null;
  122. subtask_name: string | null;
  123. gcode_file: string | null;
  124. progress: number | null;
  125. remaining_time: number | null;
  126. layer_num: number | null;
  127. total_layers: number | null;
  128. temperatures: {
  129. bed?: number;
  130. bed_target?: number;
  131. bed_heating?: boolean; // Actual heater state from MQTT
  132. nozzle?: number;
  133. nozzle_target?: number;
  134. nozzle_heating?: boolean; // Actual heater state from MQTT
  135. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  136. nozzle_2_target?: number;
  137. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  138. chamber?: number;
  139. chamber_target?: number;
  140. chamber_heating?: boolean; // Actual heater state from MQTT
  141. } | null;
  142. cover_url: string | null;
  143. hms_errors: HMSError[];
  144. ams: AMSUnit[];
  145. ams_exists: boolean;
  146. vt_tray: AMSTray | null; // Virtual tray / external spool
  147. sdcard: boolean; // SD card inserted
  148. store_to_sdcard: boolean; // Store sent files on SD card
  149. timelapse: boolean; // Timelapse recording active
  150. ipcam: boolean; // Live view enabled
  151. wifi_signal: number | null; // WiFi signal strength in dBm
  152. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  153. print_options: PrintOptions | null; // AI detection and print options
  154. // Calibration stage tracking
  155. stg_cur: number; // Current stage number (-1 = not calibrating)
  156. stg_cur_name: string | null; // Human-readable current stage name
  157. stg: number[]; // List of stage numbers in calibration sequence
  158. // Air conditioning mode (0=cooling, 1=heating)
  159. airduct_mode: number;
  160. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  161. speed_level: number;
  162. // Chamber light on/off
  163. chamber_light: boolean;
  164. // Active extruder for dual nozzle (0=right, 1=left)
  165. active_extruder: number;
  166. // AMS mapping - which AMS is connected to which nozzle
  167. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  168. ams_mapping: number[];
  169. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  170. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  171. // Note: JSON keys are always strings
  172. ams_extruder_map: Record<string, number>;
  173. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  174. tray_now: number;
  175. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  176. ams_status_main: number;
  177. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  178. ams_status_sub: number;
  179. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  180. mc_print_sub_stage: number;
  181. // Timestamp of last AMS data update (for RFID refresh detection)
  182. last_ams_update: number;
  183. // Number of printable objects in current print (for skip objects feature)
  184. printable_objects_count: number;
  185. // Fan speeds (0-100 percentage, null if not available for this model)
  186. cooling_fan_speed: number | null; // Part cooling fan
  187. big_fan1_speed: number | null; // Auxiliary fan
  188. big_fan2_speed: number | null; // Chamber/exhaust fan
  189. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  190. }
  191. export interface PrinterCreate {
  192. name: string;
  193. serial_number: string;
  194. ip_address: string;
  195. access_code: string;
  196. model?: string;
  197. location?: string;
  198. auto_archive?: boolean;
  199. external_camera_url?: string | null;
  200. external_camera_type?: string | null;
  201. external_camera_enabled?: boolean;
  202. }
  203. // Archive types
  204. export interface ArchiveDuplicate {
  205. id: number;
  206. print_name: string | null;
  207. created_at: string;
  208. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  209. }
  210. export interface Archive {
  211. id: number;
  212. printer_id: number | null;
  213. project_id: number | null;
  214. project_name: string | null;
  215. filename: string;
  216. file_path: string;
  217. file_size: number;
  218. content_hash: string | null;
  219. thumbnail_path: string | null;
  220. timelapse_path: string | null;
  221. source_3mf_path: string | null;
  222. f3d_path: string | null;
  223. duplicates: ArchiveDuplicate[] | null;
  224. duplicate_count: number;
  225. object_count: number | null;
  226. print_name: string | null;
  227. print_time_seconds: number | null;
  228. actual_time_seconds: number | null; // Computed from started_at/completed_at
  229. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  230. filament_used_grams: number | null;
  231. filament_type: string | null;
  232. filament_color: string | null;
  233. layer_height: number | null;
  234. total_layers: number | null;
  235. nozzle_diameter: number | null;
  236. bed_temperature: number | null;
  237. nozzle_temperature: number | null;
  238. status: string;
  239. started_at: string | null;
  240. completed_at: string | null;
  241. extra_data: Record<string, unknown> | null;
  242. makerworld_url: string | null;
  243. designer: string | null;
  244. external_url: string | null;
  245. is_favorite: boolean;
  246. tags: string | null;
  247. notes: string | null;
  248. cost: number | null;
  249. photos: string[] | null;
  250. failure_reason: string | null;
  251. quantity: number;
  252. energy_kwh: number | null;
  253. energy_cost: number | null;
  254. created_at: string;
  255. }
  256. export interface ArchiveStats {
  257. total_prints: number;
  258. successful_prints: number;
  259. failed_prints: number;
  260. total_print_time_hours: number;
  261. total_filament_grams: number;
  262. total_cost: number;
  263. prints_by_filament_type: Record<string, number>;
  264. prints_by_printer: Record<string, number>;
  265. average_time_accuracy: number | null;
  266. time_accuracy_by_printer: Record<string, number> | null;
  267. total_energy_kwh: number;
  268. total_energy_cost: number;
  269. }
  270. export interface FailureAnalysis {
  271. period_days: number;
  272. total_prints: number;
  273. failed_prints: number;
  274. failure_rate: number;
  275. failures_by_reason: Record<string, number>;
  276. failures_by_filament: Record<string, number>;
  277. failures_by_printer: Record<string, number>;
  278. failures_by_hour: Record<number, number>;
  279. recent_failures: Array<{
  280. id: number;
  281. print_name: string;
  282. failure_reason: string | null;
  283. filament_type: string | null;
  284. printer_id: number | null;
  285. created_at: string | null;
  286. }>;
  287. trend: Array<{
  288. week_start: string;
  289. total_prints: number;
  290. failed_prints: number;
  291. failure_rate: number;
  292. }>;
  293. }
  294. export interface BulkUploadResult {
  295. uploaded: number;
  296. failed: number;
  297. results: Array<{ filename: string; id: number; status: string }>;
  298. errors: Array<{ filename: string; error: string }>;
  299. }
  300. // Archive Comparison types
  301. export interface ComparisonArchiveInfo {
  302. id: number;
  303. print_name: string;
  304. status: string;
  305. created_at: string | null;
  306. printer_id: number | null;
  307. project_name: string | null;
  308. }
  309. export interface ComparisonField {
  310. field: string;
  311. label: string;
  312. unit: string | null;
  313. values: (string | number | null)[];
  314. raw_values: (string | number | null)[];
  315. has_difference: boolean;
  316. }
  317. export interface SuccessCorrelationInsight {
  318. field: string;
  319. label: string;
  320. insight: string;
  321. success_avg?: number;
  322. failed_avg?: number;
  323. success_values?: string[];
  324. failed_values?: string[];
  325. }
  326. export interface SuccessCorrelation {
  327. has_both_outcomes: boolean;
  328. message?: string;
  329. successful_count?: number;
  330. failed_count?: number;
  331. insights?: SuccessCorrelationInsight[];
  332. }
  333. export interface ArchiveComparison {
  334. archives: ComparisonArchiveInfo[];
  335. comparison: ComparisonField[];
  336. differences: ComparisonField[];
  337. success_correlation: SuccessCorrelation;
  338. }
  339. export interface SimilarArchive {
  340. archive: {
  341. id: number;
  342. print_name: string;
  343. status: string;
  344. created_at: string | null;
  345. };
  346. match_reason: string;
  347. match_score: number;
  348. }
  349. // Project types
  350. export interface ProjectStats {
  351. total_archives: number;
  352. total_items: number; // Sum of quantities (total items printed)
  353. completed_prints: number; // Sum of quantities for completed prints (parts)
  354. failed_prints: number;
  355. queued_prints: number;
  356. in_progress_prints: number;
  357. total_print_time_hours: number;
  358. total_filament_grams: number;
  359. progress_percent: number | null; // Plates progress (total_archives / target_count)
  360. parts_progress_percent: number | null; // Parts progress (completed_prints / target_parts_count)
  361. estimated_cost: number;
  362. total_energy_kwh: number;
  363. total_energy_cost: number;
  364. remaining_prints: number | null; // Remaining plates
  365. remaining_parts: number | null; // Remaining parts
  366. bom_total_items: number;
  367. bom_completed_items: number;
  368. }
  369. export interface ProjectChildPreview {
  370. id: number;
  371. name: string;
  372. color: string | null;
  373. status: string;
  374. progress_percent: number | null;
  375. }
  376. export interface Project {
  377. id: number;
  378. name: string;
  379. description: string | null;
  380. color: string | null;
  381. status: string; // active, completed, archived
  382. target_count: number | null; // Target number of plates/print jobs
  383. target_parts_count: number | null; // Target number of parts/objects
  384. notes: string | null;
  385. attachments: ProjectAttachment[] | null;
  386. tags: string | null;
  387. due_date: string | null;
  388. priority: string; // low, normal, high, urgent
  389. budget: number | null;
  390. is_template: boolean;
  391. template_source_id: number | null;
  392. parent_id: number | null;
  393. parent_name: string | null;
  394. children: ProjectChildPreview[];
  395. created_at: string;
  396. updated_at: string;
  397. stats?: ProjectStats;
  398. }
  399. export interface ProjectAttachment {
  400. filename: string;
  401. original_name: string;
  402. size: number;
  403. uploaded_at: string;
  404. }
  405. export interface ArchivePreview {
  406. id: number;
  407. print_name: string | null;
  408. thumbnail_path: string | null;
  409. status: string;
  410. filament_type: string | null;
  411. filament_color: string | null;
  412. }
  413. export interface ProjectListItem {
  414. id: number;
  415. name: string;
  416. description: string | null;
  417. color: string | null;
  418. status: string;
  419. target_count: number | null; // Target number of plates/print jobs
  420. target_parts_count: number | null; // Target number of parts/objects
  421. created_at: string;
  422. archive_count: number; // Number of print jobs (plates)
  423. total_items: number; // Sum of quantities (total items printed, including failed)
  424. completed_count: number; // Sum of quantities for completed prints only (parts)
  425. failed_count: number; // Sum of quantities for failed prints
  426. queue_count: number;
  427. progress_percent: number | null; // Plates progress
  428. archives: ArchivePreview[];
  429. }
  430. export interface ProjectCreate {
  431. name: string;
  432. description?: string;
  433. color?: string;
  434. target_count?: number;
  435. target_parts_count?: number;
  436. notes?: string;
  437. tags?: string;
  438. due_date?: string;
  439. priority?: string;
  440. budget?: number;
  441. parent_id?: number;
  442. }
  443. export interface ProjectUpdate {
  444. name?: string;
  445. description?: string;
  446. color?: string;
  447. status?: string;
  448. target_count?: number;
  449. target_parts_count?: number;
  450. notes?: string;
  451. tags?: string;
  452. due_date?: string;
  453. priority?: string;
  454. budget?: number;
  455. parent_id?: number;
  456. }
  457. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  458. export interface BOMItem {
  459. id: number;
  460. project_id: number;
  461. name: string;
  462. quantity_needed: number;
  463. quantity_acquired: number;
  464. unit_price: number | null;
  465. sourcing_url: string | null;
  466. archive_id: number | null;
  467. archive_name: string | null;
  468. stl_filename: string | null;
  469. remarks: string | null;
  470. sort_order: number;
  471. is_complete: boolean;
  472. created_at: string;
  473. updated_at: string;
  474. }
  475. export interface BOMItemCreate {
  476. name: string;
  477. quantity_needed?: number;
  478. unit_price?: number;
  479. sourcing_url?: string;
  480. archive_id?: number;
  481. stl_filename?: string;
  482. remarks?: string;
  483. }
  484. export interface BOMItemUpdate {
  485. name?: string;
  486. quantity_needed?: number;
  487. quantity_acquired?: number;
  488. unit_price?: number;
  489. sourcing_url?: string;
  490. archive_id?: number;
  491. stl_filename?: string;
  492. remarks?: string;
  493. }
  494. // Project Export/Import Types
  495. export interface BOMItemExport {
  496. name: string;
  497. quantity_needed: number;
  498. quantity_acquired: number;
  499. unit_price: number | null;
  500. sourcing_url: string | null;
  501. stl_filename: string | null;
  502. remarks: string | null;
  503. }
  504. export interface LinkedFolderExport {
  505. name: string;
  506. }
  507. export interface ProjectExport {
  508. name: string;
  509. description: string | null;
  510. color: string | null;
  511. status: string;
  512. target_count: number | null;
  513. target_parts_count: number | null;
  514. notes: string | null;
  515. tags: string | null;
  516. due_date: string | null;
  517. priority: string;
  518. budget: number | null;
  519. bom_items: BOMItemExport[];
  520. linked_folders: LinkedFolderExport[];
  521. }
  522. export interface ProjectImport {
  523. name: string;
  524. description?: string;
  525. color?: string;
  526. status?: string;
  527. target_count?: number;
  528. target_parts_count?: number;
  529. notes?: string;
  530. tags?: string;
  531. due_date?: string;
  532. priority?: string;
  533. budget?: number;
  534. bom_items?: BOMItemExport[];
  535. linked_folders?: LinkedFolderExport[];
  536. }
  537. // Timeline Types
  538. export interface TimelineEvent {
  539. event_type: string;
  540. timestamp: string;
  541. title: string;
  542. description: string | null;
  543. metadata: Record<string, unknown> | null;
  544. }
  545. // API Key types
  546. export interface APIKey {
  547. id: number;
  548. name: string;
  549. key_prefix: string;
  550. can_queue: boolean;
  551. can_control_printer: boolean;
  552. can_read_status: boolean;
  553. printer_ids: number[] | null;
  554. enabled: boolean;
  555. last_used: string | null;
  556. created_at: string;
  557. expires_at: string | null;
  558. }
  559. export interface APIKeyCreate {
  560. name: string;
  561. can_queue?: boolean;
  562. can_control_printer?: boolean;
  563. can_read_status?: boolean;
  564. printer_ids?: number[] | null;
  565. expires_at?: string | null;
  566. }
  567. export interface APIKeyCreateResponse extends APIKey {
  568. key: string; // Full key, only shown on creation
  569. }
  570. export interface APIKeyUpdate {
  571. name?: string;
  572. can_queue?: boolean;
  573. can_control_printer?: boolean;
  574. can_read_status?: boolean;
  575. printer_ids?: number[] | null;
  576. enabled?: boolean;
  577. expires_at?: string | null;
  578. }
  579. // Settings types
  580. export interface AppSettings {
  581. auto_archive: boolean;
  582. save_thumbnails: boolean;
  583. capture_finish_photo: boolean;
  584. default_filament_cost: number;
  585. currency: string;
  586. energy_cost_per_kwh: number;
  587. energy_tracking_mode: 'print' | 'total';
  588. check_updates: boolean;
  589. notification_language: string;
  590. // AMS threshold settings
  591. ams_humidity_good: number; // <= this is green
  592. ams_humidity_fair: number; // <= this is orange, > is red
  593. ams_temp_good: number; // <= this is green/blue
  594. ams_temp_fair: number; // <= this is orange, > is red
  595. ams_history_retention_days: number; // days to keep AMS sensor history
  596. // Print modal settings
  597. per_printer_mapping_expanded: boolean; // Whether custom mapping is expanded by default in print modal
  598. // Date/time format settings
  599. date_format: 'system' | 'us' | 'eu' | 'iso';
  600. time_format: 'system' | '12h' | '24h';
  601. // Default printer
  602. default_printer_id: number | null;
  603. // Telemetry
  604. telemetry_enabled: boolean;
  605. // Dark mode theme settings
  606. dark_style: 'classic' | 'glow' | 'vibrant';
  607. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  608. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  609. // Light mode theme settings
  610. light_style: 'classic' | 'glow' | 'vibrant';
  611. light_background: 'neutral' | 'warm' | 'cool';
  612. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  613. // FTP retry settings
  614. ftp_retry_enabled: boolean;
  615. ftp_retry_count: number;
  616. ftp_retry_delay: number;
  617. ftp_timeout: number;
  618. // MQTT relay settings
  619. mqtt_enabled: boolean;
  620. mqtt_broker: string;
  621. mqtt_port: number;
  622. mqtt_username: string;
  623. mqtt_password: string;
  624. mqtt_topic_prefix: string;
  625. mqtt_use_tls: boolean;
  626. // External URL for notifications
  627. external_url: string;
  628. // Home Assistant integration
  629. ha_enabled: boolean;
  630. ha_url: string;
  631. ha_token: string;
  632. // File Manager / Library settings
  633. library_archive_mode: 'always' | 'never' | 'ask';
  634. library_disk_warning_gb: number;
  635. // Camera view settings
  636. camera_view_mode: 'window' | 'embedded';
  637. }
  638. export type AppSettingsUpdate = Partial<AppSettings>;
  639. // MQTT relay status
  640. export interface MQTTStatus {
  641. enabled: boolean;
  642. connected: boolean;
  643. broker: string;
  644. port: number;
  645. topic_prefix: string;
  646. }
  647. // Cloud types
  648. export interface CloudAuthStatus {
  649. is_authenticated: boolean;
  650. email: string | null;
  651. }
  652. export interface CloudLoginResponse {
  653. success: boolean;
  654. needs_verification: boolean;
  655. message: string;
  656. }
  657. export interface SlicerSetting {
  658. setting_id: string;
  659. name: string;
  660. type: string;
  661. version: string | null;
  662. user_id: string | null;
  663. updated_time: string | null;
  664. }
  665. export interface SlicerSettingsResponse {
  666. filament: SlicerSetting[];
  667. printer: SlicerSetting[];
  668. process: SlicerSetting[];
  669. }
  670. export interface SlicerSettingDetail {
  671. message?: string | null;
  672. code?: string | null;
  673. error?: string | null;
  674. public: boolean;
  675. version?: string | null;
  676. type: string;
  677. name: string;
  678. update_time?: string | null;
  679. nickname?: string | null;
  680. base_id?: string | null;
  681. setting: Record<string, unknown>;
  682. filament_id?: string | null;
  683. setting_id?: string | null;
  684. }
  685. export interface SlicerSettingCreate {
  686. type: string; // 'filament', 'print', or 'printer'
  687. name: string;
  688. base_id: string;
  689. setting: Record<string, unknown>;
  690. }
  691. export interface SlicerSettingUpdate {
  692. name?: string;
  693. setting?: Record<string, unknown>;
  694. }
  695. export interface SlicerSettingDeleteResponse {
  696. success: boolean;
  697. message: string;
  698. }
  699. export interface FieldOption {
  700. value: string;
  701. label: string;
  702. }
  703. export interface FieldDefinition {
  704. key: string;
  705. label: string;
  706. type: 'text' | 'number' | 'boolean' | 'select';
  707. category: string;
  708. description?: string;
  709. options?: FieldOption[];
  710. unit?: string;
  711. min?: number;
  712. max?: number;
  713. step?: number;
  714. }
  715. export interface FieldDefinitionsResponse {
  716. version: string;
  717. description: string;
  718. fields: FieldDefinition[];
  719. }
  720. export interface CloudDevice {
  721. dev_id: string;
  722. name: string;
  723. dev_model_name: string | null;
  724. dev_product_name: string | null;
  725. online: boolean;
  726. }
  727. // Smart Plug types
  728. export interface SmartPlug {
  729. id: number;
  730. name: string;
  731. plug_type: 'tasmota' | 'homeassistant';
  732. ip_address: string | null; // Required for Tasmota
  733. ha_entity_id: string | null; // Required for Home Assistant (e.g., "switch.printer_plug")
  734. // Home Assistant energy sensor entities (optional)
  735. ha_power_entity: string | null;
  736. ha_energy_today_entity: string | null;
  737. ha_energy_total_entity: string | null;
  738. printer_id: number | null;
  739. enabled: boolean;
  740. auto_on: boolean;
  741. auto_off: boolean;
  742. off_delay_mode: 'time' | 'temperature';
  743. off_delay_minutes: number;
  744. off_temp_threshold: number;
  745. username: string | null;
  746. password: string | null;
  747. // Power alerts
  748. power_alert_enabled: boolean;
  749. power_alert_high: number | null;
  750. power_alert_low: number | null;
  751. power_alert_last_triggered: string | null;
  752. // Schedule
  753. schedule_enabled: boolean;
  754. schedule_on_time: string | null;
  755. schedule_off_time: string | null;
  756. // Switchbar visibility
  757. show_in_switchbar: boolean;
  758. // Status
  759. last_state: string | null;
  760. last_checked: string | null;
  761. auto_off_executed: boolean; // True when auto-off was triggered after print
  762. created_at: string;
  763. updated_at: string;
  764. }
  765. export interface SmartPlugCreate {
  766. name: string;
  767. plug_type?: 'tasmota' | 'homeassistant';
  768. ip_address?: string | null; // Required for Tasmota
  769. ha_entity_id?: string | null; // Required for Home Assistant
  770. // Home Assistant energy sensor entities (optional)
  771. ha_power_entity?: string | null;
  772. ha_energy_today_entity?: string | null;
  773. ha_energy_total_entity?: string | null;
  774. printer_id?: number | null;
  775. enabled?: boolean;
  776. auto_on?: boolean;
  777. auto_off?: boolean;
  778. off_delay_mode?: 'time' | 'temperature';
  779. off_delay_minutes?: number;
  780. off_temp_threshold?: number;
  781. username?: string | null;
  782. password?: string | null;
  783. // Power alerts
  784. power_alert_enabled?: boolean;
  785. power_alert_high?: number | null;
  786. power_alert_low?: number | null;
  787. // Schedule
  788. schedule_enabled?: boolean;
  789. schedule_on_time?: string | null;
  790. schedule_off_time?: string | null;
  791. // Switchbar visibility
  792. show_in_switchbar?: boolean;
  793. }
  794. export interface SmartPlugUpdate {
  795. name?: string;
  796. plug_type?: 'tasmota' | 'homeassistant';
  797. ip_address?: string | null;
  798. ha_entity_id?: string | null;
  799. // Home Assistant energy sensor entities (optional)
  800. ha_power_entity?: string | null;
  801. ha_energy_today_entity?: string | null;
  802. ha_energy_total_entity?: string | null;
  803. printer_id?: number | null;
  804. enabled?: boolean;
  805. auto_on?: boolean;
  806. auto_off?: boolean;
  807. off_delay_mode?: 'time' | 'temperature';
  808. off_delay_minutes?: number;
  809. off_temp_threshold?: number;
  810. username?: string | null;
  811. password?: string | null;
  812. // Power alerts
  813. power_alert_enabled?: boolean;
  814. power_alert_high?: number | null;
  815. power_alert_low?: number | null;
  816. // Schedule
  817. schedule_enabled?: boolean;
  818. schedule_on_time?: string | null;
  819. schedule_off_time?: string | null;
  820. // Switchbar visibility
  821. show_in_switchbar?: boolean;
  822. }
  823. // Home Assistant entity for smart plug selection
  824. export interface HAEntity {
  825. entity_id: string;
  826. friendly_name: string;
  827. state: string | null;
  828. domain: string; // "switch", "light", "input_boolean"
  829. }
  830. // Home Assistant sensor entity for energy monitoring
  831. export interface HASensorEntity {
  832. entity_id: string;
  833. friendly_name: string;
  834. state: string | null;
  835. unit_of_measurement: string | null; // "W", "kW", "kWh", "Wh"
  836. }
  837. export interface HATestConnectionResult {
  838. success: boolean;
  839. message: string | null;
  840. error: string | null;
  841. }
  842. export interface SmartPlugEnergy {
  843. power: number | null; // Current watts
  844. voltage: number | null; // Volts
  845. current: number | null; // Amps
  846. today: number | null; // kWh used today
  847. yesterday: number | null; // kWh used yesterday
  848. total: number | null; // Total kWh
  849. factor: number | null; // Power factor (0-1)
  850. apparent_power: number | null; // VA
  851. reactive_power: number | null; // VAr
  852. }
  853. export interface SmartPlugStatus {
  854. state: string | null;
  855. reachable: boolean;
  856. device_name: string | null;
  857. energy: SmartPlugEnergy | null;
  858. }
  859. export interface SmartPlugTestResult {
  860. success: boolean;
  861. state: string | null;
  862. device_name: string | null;
  863. }
  864. // Tasmota Discovery types
  865. export interface TasmotaScanStatus {
  866. running: boolean;
  867. scanned: number;
  868. total: number;
  869. }
  870. export interface DiscoveredTasmotaDevice {
  871. ip_address: string;
  872. name: string;
  873. module: number | null;
  874. state: string | null;
  875. discovered_at: string | null;
  876. }
  877. // Print Queue types
  878. export interface PrintQueueItem {
  879. id: number;
  880. printer_id: number | null; // null = unassigned
  881. // Either archive_id OR library_file_id must be set (archive created at print start)
  882. archive_id: number | null;
  883. library_file_id: number | null;
  884. position: number;
  885. scheduled_time: string | null;
  886. require_previous_success: boolean;
  887. auto_off_after: boolean;
  888. manual_start: boolean; // Requires manual trigger to start (staged)
  889. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  890. plate_id: number | null; // Plate ID for multi-plate 3MF files
  891. // Print options
  892. bed_levelling: boolean;
  893. flow_cali: boolean;
  894. vibration_cali: boolean;
  895. layer_inspect: boolean;
  896. timelapse: boolean;
  897. use_ams: boolean;
  898. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  899. started_at: string | null;
  900. completed_at: string | null;
  901. error_message: string | null;
  902. created_at: string;
  903. archive_name?: string | null;
  904. archive_thumbnail?: string | null;
  905. library_file_name?: string | null;
  906. library_file_thumbnail?: string | null;
  907. printer_name?: string | null;
  908. print_time_seconds?: number | null; // Estimated print time from archive or library file
  909. }
  910. export interface PrintQueueItemCreate {
  911. printer_id?: number | null; // null = unassigned
  912. // Either archive_id OR library_file_id must be provided
  913. archive_id?: number | null;
  914. library_file_id?: number | null;
  915. scheduled_time?: string | null;
  916. require_previous_success?: boolean;
  917. auto_off_after?: boolean;
  918. manual_start?: boolean; // Requires manual trigger to start (staged)
  919. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  920. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  921. // Print options
  922. bed_levelling?: boolean;
  923. flow_cali?: boolean;
  924. vibration_cali?: boolean;
  925. layer_inspect?: boolean;
  926. timelapse?: boolean;
  927. use_ams?: boolean;
  928. }
  929. export interface PrintQueueItemUpdate {
  930. printer_id?: number | null; // null = unassign
  931. position?: number;
  932. scheduled_time?: string | null;
  933. require_previous_success?: boolean;
  934. auto_off_after?: boolean;
  935. manual_start?: boolean;
  936. ams_mapping?: number[];
  937. plate_id?: number | null; // Plate ID for multi-plate 3MF files
  938. // Print options
  939. bed_levelling?: boolean;
  940. flow_cali?: boolean;
  941. vibration_cali?: boolean;
  942. layer_inspect?: boolean;
  943. timelapse?: boolean;
  944. use_ams?: boolean;
  945. }
  946. // MQTT Logging types
  947. export interface MQTTLogEntry {
  948. timestamp: string;
  949. topic: string;
  950. direction: 'in' | 'out';
  951. payload: Record<string, unknown>;
  952. }
  953. export interface MQTTLogsResponse {
  954. logging_enabled: boolean;
  955. logs: MQTTLogEntry[];
  956. }
  957. // K-Profile types
  958. export interface KProfile {
  959. slot_id: number;
  960. extruder_id: number;
  961. nozzle_id: string;
  962. nozzle_diameter: string;
  963. filament_id: string;
  964. name: string;
  965. k_value: string;
  966. n_coef: string;
  967. ams_id: number;
  968. tray_id: number;
  969. setting_id: string | null;
  970. }
  971. export interface KProfileCreate {
  972. slot_id?: number; // Storage slot, 0 for new profiles
  973. extruder_id?: number;
  974. nozzle_id: string;
  975. nozzle_diameter: string;
  976. filament_id: string;
  977. name: string;
  978. k_value: string;
  979. n_coef?: string;
  980. ams_id?: number;
  981. tray_id?: number;
  982. setting_id?: string | null;
  983. }
  984. export interface KProfileDelete {
  985. slot_id: number; // cali_idx - calibration index to delete
  986. extruder_id: number;
  987. nozzle_id: string; // e.g., "HH00-0.4"
  988. nozzle_diameter: string; // e.g., "0.4"
  989. filament_id: string; // Bambu filament identifier
  990. setting_id?: string | null; // Setting ID (for X1C series)
  991. }
  992. export interface KProfilesResponse {
  993. profiles: KProfile[];
  994. nozzle_diameter: string;
  995. }
  996. export interface KProfileNote {
  997. setting_id: string;
  998. note: string;
  999. }
  1000. export interface KProfileNotesResponse {
  1001. notes: Record<string, string>; // setting_id -> note
  1002. }
  1003. // Slot Preset Mapping
  1004. export interface SlotPresetMapping {
  1005. ams_id: number;
  1006. tray_id: number;
  1007. preset_id: string;
  1008. preset_name: string;
  1009. }
  1010. // Filament types
  1011. export interface Filament {
  1012. id: number;
  1013. name: string;
  1014. type: string; // PLA, PETG, ABS, etc.
  1015. brand: string | null;
  1016. color: string | null;
  1017. color_hex: string | null;
  1018. cost_per_kg: number;
  1019. spool_weight_g: number;
  1020. currency: string;
  1021. density: number | null;
  1022. print_temp_min: number | null;
  1023. print_temp_max: number | null;
  1024. bed_temp_min: number | null;
  1025. bed_temp_max: number | null;
  1026. created_at: string;
  1027. updated_at: string;
  1028. }
  1029. // Notification Provider types
  1030. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook';
  1031. export interface NotificationProvider {
  1032. id: number;
  1033. name: string;
  1034. provider_type: ProviderType;
  1035. enabled: boolean;
  1036. config: Record<string, unknown>;
  1037. // Print lifecycle events
  1038. on_print_start: boolean;
  1039. on_print_complete: boolean;
  1040. on_print_failed: boolean;
  1041. on_print_stopped: boolean;
  1042. on_print_progress: boolean;
  1043. // Printer status events
  1044. on_printer_offline: boolean;
  1045. on_printer_error: boolean;
  1046. on_filament_low: boolean;
  1047. on_maintenance_due: boolean;
  1048. // AMS environmental alarms (regular AMS)
  1049. on_ams_humidity_high: boolean;
  1050. on_ams_temperature_high: boolean;
  1051. // AMS-HT environmental alarms
  1052. on_ams_ht_humidity_high: boolean;
  1053. on_ams_ht_temperature_high: boolean;
  1054. // Quiet hours
  1055. quiet_hours_enabled: boolean;
  1056. quiet_hours_start: string | null;
  1057. quiet_hours_end: string | null;
  1058. // Daily digest
  1059. daily_digest_enabled: boolean;
  1060. daily_digest_time: string | null;
  1061. // Printer filter
  1062. printer_id: number | null;
  1063. // Status tracking
  1064. last_success: string | null;
  1065. last_error: string | null;
  1066. last_error_at: string | null;
  1067. // Timestamps
  1068. created_at: string;
  1069. updated_at: string;
  1070. }
  1071. export interface NotificationProviderCreate {
  1072. name: string;
  1073. provider_type: ProviderType;
  1074. enabled?: boolean;
  1075. config: Record<string, unknown>;
  1076. // Print lifecycle events
  1077. on_print_start?: boolean;
  1078. on_print_complete?: boolean;
  1079. on_print_failed?: boolean;
  1080. on_print_stopped?: boolean;
  1081. on_print_progress?: boolean;
  1082. // Printer status events
  1083. on_printer_offline?: boolean;
  1084. on_printer_error?: boolean;
  1085. on_filament_low?: boolean;
  1086. on_maintenance_due?: boolean;
  1087. // AMS environmental alarms (regular AMS)
  1088. on_ams_humidity_high?: boolean;
  1089. on_ams_temperature_high?: boolean;
  1090. // AMS-HT environmental alarms
  1091. on_ams_ht_humidity_high?: boolean;
  1092. on_ams_ht_temperature_high?: boolean;
  1093. // Quiet hours
  1094. quiet_hours_enabled?: boolean;
  1095. quiet_hours_start?: string | null;
  1096. quiet_hours_end?: string | null;
  1097. // Daily digest
  1098. daily_digest_enabled?: boolean;
  1099. daily_digest_time?: string | null;
  1100. // Printer filter
  1101. printer_id?: number | null;
  1102. }
  1103. export interface NotificationProviderUpdate {
  1104. name?: string;
  1105. provider_type?: ProviderType;
  1106. enabled?: boolean;
  1107. config?: Record<string, unknown>;
  1108. // Print lifecycle events
  1109. on_print_start?: boolean;
  1110. on_print_complete?: boolean;
  1111. on_print_failed?: boolean;
  1112. on_print_stopped?: boolean;
  1113. on_print_progress?: boolean;
  1114. // Printer status events
  1115. on_printer_offline?: boolean;
  1116. on_printer_error?: boolean;
  1117. on_filament_low?: boolean;
  1118. on_maintenance_due?: boolean;
  1119. // AMS environmental alarms (regular AMS)
  1120. on_ams_humidity_high?: boolean;
  1121. on_ams_temperature_high?: boolean;
  1122. // AMS-HT environmental alarms
  1123. on_ams_ht_humidity_high?: boolean;
  1124. on_ams_ht_temperature_high?: boolean;
  1125. // Quiet hours
  1126. quiet_hours_enabled?: boolean;
  1127. quiet_hours_start?: string | null;
  1128. quiet_hours_end?: string | null;
  1129. // Daily digest
  1130. daily_digest_enabled?: boolean;
  1131. daily_digest_time?: string | null;
  1132. // Printer filter
  1133. printer_id?: number | null;
  1134. }
  1135. export interface NotificationTestRequest {
  1136. provider_type: ProviderType;
  1137. config: Record<string, unknown>;
  1138. }
  1139. export interface NotificationTestResponse {
  1140. success: boolean;
  1141. message: string;
  1142. }
  1143. // Provider-specific config types for reference
  1144. export interface CallMeBotConfig {
  1145. phone: string;
  1146. apikey: string;
  1147. }
  1148. export interface NtfyConfig {
  1149. server?: string;
  1150. topic: string;
  1151. auth_token?: string | null;
  1152. }
  1153. export interface PushoverConfig {
  1154. user_key: string;
  1155. app_token: string;
  1156. priority?: number;
  1157. }
  1158. export interface TelegramConfig {
  1159. bot_token: string;
  1160. chat_id: string;
  1161. }
  1162. export interface EmailConfig {
  1163. smtp_server: string;
  1164. smtp_port?: number;
  1165. username: string;
  1166. password: string;
  1167. from_email: string;
  1168. to_email: string;
  1169. use_tls?: boolean;
  1170. }
  1171. // Notification Template types
  1172. export interface NotificationTemplate {
  1173. id: number;
  1174. event_type: string;
  1175. name: string;
  1176. title_template: string;
  1177. body_template: string;
  1178. is_default: boolean;
  1179. created_at: string;
  1180. updated_at: string;
  1181. }
  1182. export interface NotificationTemplateUpdate {
  1183. title_template?: string;
  1184. body_template?: string;
  1185. }
  1186. export interface EventVariablesResponse {
  1187. event_type: string;
  1188. event_name: string;
  1189. variables: string[];
  1190. }
  1191. export interface TemplatePreviewRequest {
  1192. event_type: string;
  1193. title_template: string;
  1194. body_template: string;
  1195. }
  1196. export interface TemplatePreviewResponse {
  1197. title: string;
  1198. body: string;
  1199. }
  1200. // Notification Log types
  1201. export interface NotificationLogEntry {
  1202. id: number;
  1203. provider_id: number;
  1204. provider_name: string | null;
  1205. provider_type: string | null;
  1206. event_type: string;
  1207. title: string;
  1208. message: string;
  1209. success: boolean;
  1210. error_message: string | null;
  1211. printer_id: number | null;
  1212. printer_name: string | null;
  1213. created_at: string;
  1214. }
  1215. export interface NotificationLogStats {
  1216. total: number;
  1217. success_count: number;
  1218. failure_count: number;
  1219. by_event_type: Record<string, number>;
  1220. by_provider: Record<string, number>;
  1221. }
  1222. // Spoolman types
  1223. export interface SpoolmanStatus {
  1224. enabled: boolean;
  1225. connected: boolean;
  1226. url: string | null;
  1227. }
  1228. export interface SkippedSpool {
  1229. location: string;
  1230. reason: string;
  1231. filament_type: string | null;
  1232. color: string | null;
  1233. }
  1234. export interface SpoolmanSyncResult {
  1235. success: boolean;
  1236. synced_count: number;
  1237. skipped_count: number;
  1238. skipped: SkippedSpool[];
  1239. errors: string[];
  1240. }
  1241. export interface UnlinkedSpool {
  1242. id: number;
  1243. filament_name: string | null;
  1244. filament_material: string | null;
  1245. filament_color_hex: string | null;
  1246. remaining_weight: number | null;
  1247. location: string | null;
  1248. }
  1249. // Update types
  1250. export interface VersionInfo {
  1251. version: string;
  1252. repo: string;
  1253. }
  1254. export interface UpdateCheckResult {
  1255. update_available: boolean;
  1256. current_version: string;
  1257. latest_version: string | null;
  1258. release_name?: string;
  1259. release_notes?: string;
  1260. release_url?: string;
  1261. published_at?: string;
  1262. error?: string;
  1263. message?: string;
  1264. is_docker?: boolean;
  1265. update_method?: 'docker' | 'git';
  1266. }
  1267. export interface UpdateStatus {
  1268. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  1269. progress: number;
  1270. message: string;
  1271. error: string | null;
  1272. }
  1273. // Maintenance types
  1274. export interface MaintenanceType {
  1275. id: number;
  1276. name: string;
  1277. description: string | null;
  1278. default_interval_hours: number;
  1279. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  1280. icon: string | null;
  1281. wiki_url: string | null; // Documentation link
  1282. is_system: boolean;
  1283. created_at: string;
  1284. }
  1285. export interface MaintenanceTypeCreate {
  1286. name: string;
  1287. description?: string | null;
  1288. default_interval_hours?: number;
  1289. interval_type?: 'hours' | 'days';
  1290. icon?: string | null;
  1291. wiki_url?: string | null;
  1292. }
  1293. export interface MaintenanceStatus {
  1294. id: number;
  1295. printer_id: number;
  1296. printer_name: string;
  1297. printer_model: string | null;
  1298. maintenance_type_id: number;
  1299. maintenance_type_name: string;
  1300. maintenance_type_icon: string | null;
  1301. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  1302. enabled: boolean;
  1303. interval_hours: number; // For hours type: print hours; for days type: number of days
  1304. interval_type: 'hours' | 'days';
  1305. current_hours: number;
  1306. hours_since_maintenance: number;
  1307. hours_until_due: number;
  1308. days_since_maintenance: number | null; // For days type
  1309. days_until_due: number | null; // For days type
  1310. is_due: boolean;
  1311. is_warning: boolean;
  1312. last_performed_at: string | null;
  1313. }
  1314. export interface PrinterMaintenanceOverview {
  1315. printer_id: number;
  1316. printer_name: string;
  1317. printer_model: string | null;
  1318. total_print_hours: number;
  1319. maintenance_items: MaintenanceStatus[];
  1320. due_count: number;
  1321. warning_count: number;
  1322. }
  1323. export interface MaintenanceHistory {
  1324. id: number;
  1325. printer_maintenance_id: number;
  1326. performed_at: string;
  1327. hours_at_maintenance: number;
  1328. notes: string | null;
  1329. }
  1330. export interface MaintenanceSummary {
  1331. total_due: number;
  1332. total_warning: number;
  1333. printers_with_issues: Array<{
  1334. printer_id: number;
  1335. printer_name: string;
  1336. due_count: number;
  1337. warning_count: number;
  1338. }>;
  1339. }
  1340. // External Links (sidebar)
  1341. export interface ExternalLink {
  1342. id: number;
  1343. name: string;
  1344. url: string;
  1345. icon: string;
  1346. custom_icon: string | null;
  1347. sort_order: number;
  1348. created_at: string;
  1349. updated_at: string;
  1350. }
  1351. export interface ExternalLinkCreate {
  1352. name: string;
  1353. url: string;
  1354. icon: string;
  1355. }
  1356. export interface ExternalLinkUpdate {
  1357. name?: string;
  1358. url?: string;
  1359. icon?: string;
  1360. }
  1361. // Auth types
  1362. export interface LoginRequest {
  1363. username: string;
  1364. password: string;
  1365. }
  1366. export interface LoginResponse {
  1367. access_token: string;
  1368. token_type: string;
  1369. user: UserResponse;
  1370. }
  1371. export interface UserResponse {
  1372. id: number;
  1373. username: string;
  1374. role: string;
  1375. is_active: boolean;
  1376. created_at: string;
  1377. }
  1378. export interface UserCreate {
  1379. username: string;
  1380. password: string;
  1381. role: string;
  1382. }
  1383. export interface UserUpdate {
  1384. username?: string;
  1385. password?: string;
  1386. role?: string;
  1387. is_active?: boolean;
  1388. }
  1389. export interface SetupRequest {
  1390. auth_enabled: boolean;
  1391. admin_username?: string;
  1392. admin_password?: string;
  1393. }
  1394. export interface SetupResponse {
  1395. auth_enabled: boolean;
  1396. admin_created?: boolean;
  1397. }
  1398. export interface AuthStatus {
  1399. auth_enabled: boolean;
  1400. requires_setup: boolean;
  1401. }
  1402. // API functions
  1403. export const api = {
  1404. // Authentication
  1405. getAuthStatus: () => request<AuthStatus>('/auth/status'),
  1406. setupAuth: (data: SetupRequest) =>
  1407. request<SetupResponse>('/auth/setup', {
  1408. method: 'POST',
  1409. body: JSON.stringify(data),
  1410. }),
  1411. login: (data: LoginRequest) =>
  1412. request<LoginResponse>('/auth/login', {
  1413. method: 'POST',
  1414. body: JSON.stringify(data),
  1415. }),
  1416. logout: () =>
  1417. request<{ message: string }>('/auth/logout', {
  1418. method: 'POST',
  1419. }),
  1420. getCurrentUser: () => request<UserResponse>('/auth/me'),
  1421. disableAuth: () =>
  1422. request<{ message: string; auth_enabled: boolean }>('/auth/disable', {
  1423. method: 'POST',
  1424. }),
  1425. // Users (admin only)
  1426. getUsers: () => request<UserResponse[]>('/users/'),
  1427. getUser: (id: number) => request<UserResponse>(`/users/${id}`),
  1428. createUser: (data: UserCreate) =>
  1429. request<UserResponse>('/users/', {
  1430. method: 'POST',
  1431. body: JSON.stringify(data),
  1432. }),
  1433. updateUser: (id: number, data: UserUpdate) =>
  1434. request<UserResponse>(`/users/${id}`, {
  1435. method: 'PATCH',
  1436. body: JSON.stringify(data),
  1437. }),
  1438. deleteUser: (id: number) =>
  1439. request<void>(`/users/${id}`, {
  1440. method: 'DELETE',
  1441. }),
  1442. // Printers
  1443. getPrinters: () => request<Printer[]>('/printers/'),
  1444. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  1445. createPrinter: (data: PrinterCreate) =>
  1446. request<Printer>('/printers/', {
  1447. method: 'POST',
  1448. body: JSON.stringify(data),
  1449. }),
  1450. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  1451. request<Printer>(`/printers/${id}`, {
  1452. method: 'PATCH',
  1453. body: JSON.stringify(data),
  1454. }),
  1455. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  1456. request<{ status: string; archives_deleted: boolean }>(
  1457. `/printers/${id}?delete_archives=${deleteArchives}`,
  1458. { method: 'DELETE' }
  1459. ),
  1460. getPrinterStatus: (id: number) =>
  1461. request<PrinterStatus>(`/printers/${id}/status`),
  1462. refreshPrinterStatus: (id: number) =>
  1463. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  1464. method: 'POST',
  1465. }),
  1466. connectPrinter: (id: number) =>
  1467. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  1468. method: 'POST',
  1469. }),
  1470. disconnectPrinter: (id: number) =>
  1471. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  1472. method: 'POST',
  1473. }),
  1474. testExternalCamera: (printerId: number, url: string, cameraType: string) =>
  1475. request<{ success: boolean; error?: string; resolution?: string }>(
  1476. `/printers/${printerId}/camera/external/test?url=${encodeURIComponent(url)}&camera_type=${encodeURIComponent(cameraType)}`,
  1477. { method: 'POST' }
  1478. ),
  1479. // Print Control
  1480. stopPrint: (printerId: number) =>
  1481. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  1482. method: 'POST',
  1483. }),
  1484. pausePrint: (printerId: number) =>
  1485. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  1486. method: 'POST',
  1487. }),
  1488. resumePrint: (printerId: number) =>
  1489. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  1490. method: 'POST',
  1491. }),
  1492. // Chamber Light Control
  1493. setChamberLight: (printerId: number, on: boolean) =>
  1494. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  1495. method: 'POST',
  1496. }),
  1497. // Skip Objects
  1498. getPrintableObjects: (printerId: number) =>
  1499. request<{
  1500. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  1501. total: number;
  1502. skipped_count: number;
  1503. is_printing: boolean;
  1504. bbox_all: [number, number, number, number] | null;
  1505. }>(`/printers/${printerId}/print/objects`),
  1506. skipObjects: (printerId: number, objectIds: number[]) =>
  1507. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  1508. `/printers/${printerId}/print/skip-objects`,
  1509. {
  1510. method: 'POST',
  1511. body: JSON.stringify(objectIds),
  1512. }
  1513. ),
  1514. // AMS Control
  1515. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  1516. request<{ success: boolean; message: string }>(
  1517. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  1518. { method: 'POST' }
  1519. ),
  1520. // MQTT Debug Logging
  1521. enableMQTTLogging: (printerId: number) =>
  1522. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  1523. method: 'POST',
  1524. }),
  1525. disableMQTTLogging: (printerId: number) =>
  1526. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  1527. method: 'POST',
  1528. }),
  1529. getMQTTLogs: (printerId: number) =>
  1530. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  1531. clearMQTTLogs: (printerId: number) =>
  1532. request<{ status: string }>(`/printers/${printerId}/logging`, {
  1533. method: 'DELETE',
  1534. }),
  1535. // Printer File Manager
  1536. getPrinterFiles: (printerId: number, path = '/') =>
  1537. request<{
  1538. path: string;
  1539. files: Array<{
  1540. name: string;
  1541. is_directory: boolean;
  1542. size: number;
  1543. path: string;
  1544. mtime?: string;
  1545. }>;
  1546. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  1547. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  1548. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  1549. downloadPrinterFilesAsZip: async (printerId: number, paths: string[]): Promise<Blob> => {
  1550. const response = await fetch(`${API_BASE}/printers/${printerId}/files/download-zip`, {
  1551. method: 'POST',
  1552. headers: { 'Content-Type': 'application/json' },
  1553. body: JSON.stringify({ paths }),
  1554. });
  1555. if (!response.ok) {
  1556. const error = await response.json().catch(() => ({}));
  1557. throw new Error(error.detail || `HTTP ${response.status}`);
  1558. }
  1559. return response.blob();
  1560. },
  1561. deletePrinterFile: (printerId: number, path: string) =>
  1562. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  1563. method: 'DELETE',
  1564. }),
  1565. getPrinterStorage: (printerId: number) =>
  1566. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  1567. // Archives
  1568. getArchives: (printerId?: number, projectId?: number, limit = 50, offset = 0) => {
  1569. const params = new URLSearchParams();
  1570. if (printerId) params.set('printer_id', String(printerId));
  1571. if (projectId) params.set('project_id', String(projectId));
  1572. params.set('limit', String(limit));
  1573. params.set('offset', String(offset));
  1574. return request<Archive[]>(`/archives/?${params}`);
  1575. },
  1576. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  1577. searchArchives: (query: string, options?: {
  1578. printerId?: number;
  1579. projectId?: number;
  1580. status?: string;
  1581. limit?: number;
  1582. offset?: number;
  1583. }) => {
  1584. const params = new URLSearchParams();
  1585. params.set('q', query);
  1586. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1587. if (options?.projectId) params.set('project_id', String(options.projectId));
  1588. if (options?.status) params.set('status', options.status);
  1589. if (options?.limit) params.set('limit', String(options.limit));
  1590. if (options?.offset) params.set('offset', String(options.offset));
  1591. return request<Archive[]>(`/archives/search?${params}`);
  1592. },
  1593. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  1594. updateArchive: (id: number, data: {
  1595. printer_id?: number | null;
  1596. project_id?: number | null;
  1597. print_name?: string;
  1598. is_favorite?: boolean;
  1599. tags?: string;
  1600. notes?: string;
  1601. cost?: number;
  1602. failure_reason?: string | null;
  1603. status?: string;
  1604. quantity?: number;
  1605. external_url?: string | null;
  1606. }) =>
  1607. request<Archive>(`/archives/${id}`, {
  1608. method: 'PATCH',
  1609. body: JSON.stringify(data),
  1610. }),
  1611. toggleFavorite: (id: number) =>
  1612. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  1613. deleteArchive: (id: number) =>
  1614. request<void>(`/archives/${id}`, { method: 'DELETE' }),
  1615. getArchiveStats: () => request<ArchiveStats>('/archives/stats'),
  1616. recalculateCosts: () =>
  1617. request<{ message: string; updated: number }>('/archives/recalculate-costs', { method: 'POST' }),
  1618. getFailureAnalysis: (options?: { days?: number; printerId?: number; projectId?: number }) => {
  1619. const params = new URLSearchParams();
  1620. if (options?.days) params.set('days', String(options.days));
  1621. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1622. if (options?.projectId) params.set('project_id', String(options.projectId));
  1623. return request<FailureAnalysis>(`/archives/analysis/failures?${params}`);
  1624. },
  1625. compareArchives: (archiveIds: number[]) =>
  1626. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  1627. findSimilarArchives: (archiveId: number, limit = 10) =>
  1628. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  1629. exportArchives: async (options?: {
  1630. format?: 'csv' | 'xlsx';
  1631. fields?: string[];
  1632. printerId?: number;
  1633. projectId?: number;
  1634. status?: string;
  1635. dateFrom?: string;
  1636. dateTo?: string;
  1637. search?: string;
  1638. }): Promise<{ blob: Blob; filename: string }> => {
  1639. const params = new URLSearchParams();
  1640. if (options?.format) params.set('format', options.format);
  1641. if (options?.fields) params.set('fields', options.fields.join(','));
  1642. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1643. if (options?.projectId) params.set('project_id', String(options.projectId));
  1644. if (options?.status) params.set('status', options.status);
  1645. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  1646. if (options?.dateTo) params.set('date_to', options.dateTo);
  1647. if (options?.search) params.set('search', options.search);
  1648. const response = await fetch(`${API_BASE}/archives/export?${params}`);
  1649. if (!response.ok) {
  1650. const error = await response.json().catch(() => ({}));
  1651. throw new Error(error.detail || `HTTP ${response.status}`);
  1652. }
  1653. const contentDisposition = response.headers.get('Content-Disposition');
  1654. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  1655. if (contentDisposition) {
  1656. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  1657. if (match) filename = match[1];
  1658. }
  1659. const blob = await response.blob();
  1660. return { blob, filename };
  1661. },
  1662. exportStats: async (options?: {
  1663. format?: 'csv' | 'xlsx';
  1664. days?: number;
  1665. printerId?: number;
  1666. projectId?: number;
  1667. }): Promise<{ blob: Blob; filename: string }> => {
  1668. const params = new URLSearchParams();
  1669. if (options?.format) params.set('format', options.format);
  1670. if (options?.days) params.set('days', String(options.days));
  1671. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1672. if (options?.projectId) params.set('project_id', String(options.projectId));
  1673. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`);
  1674. if (!response.ok) {
  1675. const error = await response.json().catch(() => ({}));
  1676. throw new Error(error.detail || `HTTP ${response.status}`);
  1677. }
  1678. const contentDisposition = response.headers.get('Content-Disposition');
  1679. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  1680. if (contentDisposition) {
  1681. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  1682. if (match) filename = match[1];
  1683. }
  1684. const blob = await response.blob();
  1685. return { blob, filename };
  1686. },
  1687. getArchiveDuplicates: (id: number) =>
  1688. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  1689. backfillContentHashes: () =>
  1690. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  1691. method: 'POST',
  1692. }),
  1693. getArchiveThumbnail: (id: number) => `${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`,
  1694. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  1695. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  1696. getArchivePlatePreview: (id: number) => `${API_BASE}/archives/${id}/plate-preview`,
  1697. getArchiveTimelapse: (id: number) => `${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`,
  1698. scanArchiveTimelapse: (id: number) =>
  1699. request<{
  1700. status: string;
  1701. message: string;
  1702. filename?: string;
  1703. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  1704. }>(`/archives/${id}/timelapse/scan`, {
  1705. method: 'POST',
  1706. }),
  1707. selectArchiveTimelapse: (id: number, filename: string) =>
  1708. request<{ status: string; message: string; filename: string }>(
  1709. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  1710. { method: 'POST' }
  1711. ),
  1712. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  1713. const formData = new FormData();
  1714. formData.append('file', file);
  1715. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  1716. method: 'POST',
  1717. body: formData,
  1718. });
  1719. if (!response.ok) {
  1720. const error = await response.json().catch(() => ({}));
  1721. throw new Error(error.detail || `HTTP ${response.status}`);
  1722. }
  1723. return response.json();
  1724. },
  1725. // Timelapse Editor
  1726. getTimelapseInfo: (archiveId: number) =>
  1727. request<{
  1728. duration: number;
  1729. width: number;
  1730. height: number;
  1731. fps: number;
  1732. codec: string;
  1733. file_size: number;
  1734. has_audio: boolean;
  1735. }>(`/archives/${archiveId}/timelapse/info`),
  1736. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  1737. request<{
  1738. thumbnails: string[];
  1739. timestamps: number[];
  1740. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  1741. processTimelapse: async (
  1742. archiveId: number,
  1743. params: {
  1744. trimStart?: number;
  1745. trimEnd?: number;
  1746. speed?: number;
  1747. saveMode: 'replace' | 'new';
  1748. outputFilename?: string;
  1749. },
  1750. audioFile?: File
  1751. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  1752. const formData = new FormData();
  1753. formData.append('trim_start', String(params.trimStart ?? 0));
  1754. if (params.trimEnd !== undefined) {
  1755. formData.append('trim_end', String(params.trimEnd));
  1756. }
  1757. formData.append('speed', String(params.speed ?? 1));
  1758. formData.append('save_mode', params.saveMode);
  1759. if (params.outputFilename) {
  1760. formData.append('output_filename', params.outputFilename);
  1761. }
  1762. if (audioFile) {
  1763. formData.append('audio', audioFile);
  1764. }
  1765. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  1766. method: 'POST',
  1767. body: formData,
  1768. });
  1769. if (!response.ok) {
  1770. const error = await response.json().catch(() => ({}));
  1771. throw new Error(error.detail || `HTTP ${response.status}`);
  1772. }
  1773. return response.json();
  1774. },
  1775. // Photos
  1776. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  1777. `${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`,
  1778. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  1779. const formData = new FormData();
  1780. formData.append('file', file);
  1781. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  1782. method: 'POST',
  1783. body: formData,
  1784. });
  1785. if (!response.ok) {
  1786. const error = await response.json().catch(() => ({}));
  1787. throw new Error(error.detail || `HTTP ${response.status}`);
  1788. }
  1789. return response.json();
  1790. },
  1791. deleteArchivePhoto: (archiveId: number, filename: string) =>
  1792. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  1793. method: 'DELETE',
  1794. }),
  1795. // Source 3MF (original slicer project file)
  1796. getSource3mfDownloadUrl: (archiveId: number) =>
  1797. `${API_BASE}/archives/${archiveId}/source`,
  1798. getSource3mfForSlicer: (archiveId: number, filename: string) =>
  1799. `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  1800. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  1801. const formData = new FormData();
  1802. formData.append('file', file);
  1803. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  1804. method: 'POST',
  1805. body: formData,
  1806. });
  1807. if (!response.ok) {
  1808. const error = await response.json().catch(() => ({}));
  1809. throw new Error(error.detail || `HTTP ${response.status}`);
  1810. }
  1811. return response.json();
  1812. },
  1813. deleteSource3mf: (archiveId: number) =>
  1814. request<{ status: string }>(`/archives/${archiveId}/source`, {
  1815. method: 'DELETE',
  1816. }),
  1817. // F3D (Fusion 360 design file)
  1818. getF3dDownloadUrl: (archiveId: number) =>
  1819. `${API_BASE}/archives/${archiveId}/f3d`,
  1820. uploadF3d: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  1821. const formData = new FormData();
  1822. formData.append('file', file);
  1823. const response = await fetch(`${API_BASE}/archives/${archiveId}/f3d`, {
  1824. method: 'POST',
  1825. body: formData,
  1826. });
  1827. if (!response.ok) {
  1828. const error = await response.json().catch(() => ({}));
  1829. throw new Error(error.detail || `HTTP ${response.status}`);
  1830. }
  1831. return response.json();
  1832. },
  1833. deleteF3d: (archiveId: number) =>
  1834. request<{ status: string }>(`/archives/${archiveId}/f3d`, {
  1835. method: 'DELETE',
  1836. }),
  1837. // QR Code
  1838. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  1839. `${API_BASE}/archives/${archiveId}/qrcode?size=${size}`,
  1840. getArchiveCapabilities: (id: number) =>
  1841. request<{
  1842. has_model: boolean;
  1843. has_gcode: boolean;
  1844. has_source: boolean;
  1845. build_volume: { x: number; y: number; z: number };
  1846. filament_colors: string[];
  1847. }>(`/archives/${id}/capabilities`),
  1848. // Project Page
  1849. getArchiveProjectPage: (id: number) =>
  1850. request<{
  1851. title: string | null;
  1852. description: string | null;
  1853. designer: string | null;
  1854. designer_user_id: string | null;
  1855. license: string | null;
  1856. copyright: string | null;
  1857. creation_date: string | null;
  1858. modification_date: string | null;
  1859. origin: string | null;
  1860. profile_title: string | null;
  1861. profile_description: string | null;
  1862. profile_cover: string | null;
  1863. profile_user_id: string | null;
  1864. profile_user_name: string | null;
  1865. design_model_id: string | null;
  1866. design_profile_id: string | null;
  1867. design_region: string | null;
  1868. model_pictures: Array<{ name: string; path: string; url: string }>;
  1869. profile_pictures: Array<{ name: string; path: string; url: string }>;
  1870. thumbnails: Array<{ name: string; path: string; url: string }>;
  1871. }>(`/archives/${id}/project-page`),
  1872. updateArchiveProjectPage: (id: number, data: {
  1873. title?: string;
  1874. description?: string;
  1875. designer?: string;
  1876. license?: string;
  1877. copyright?: string;
  1878. profile_title?: string;
  1879. profile_description?: string;
  1880. }) =>
  1881. request(`/archives/${id}/project-page`, {
  1882. method: 'PATCH',
  1883. body: JSON.stringify(data),
  1884. }),
  1885. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  1886. `${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`,
  1887. getArchiveForSlicer: (id: number, filename: string) =>
  1888. `${API_BASE}/archives/${id}/file/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  1889. getArchivePlates: (archiveId: number) =>
  1890. request<{
  1891. archive_id: number;
  1892. filename: string;
  1893. plates: Array<{
  1894. index: number;
  1895. name: string | null;
  1896. objects: string[];
  1897. has_thumbnail: boolean;
  1898. thumbnail_url: string | null;
  1899. print_time_seconds: number | null;
  1900. filament_used_grams: number | null;
  1901. filaments: Array<{
  1902. slot_id: number;
  1903. type: string;
  1904. color: string;
  1905. used_grams: number;
  1906. used_meters: number;
  1907. }>;
  1908. }>;
  1909. is_multi_plate: boolean;
  1910. }>(`/archives/${archiveId}/plates`),
  1911. getArchiveFilamentRequirements: (archiveId: number, plateId?: number) =>
  1912. request<{
  1913. archive_id: number;
  1914. filename: string;
  1915. plate_id: number | null;
  1916. filaments: Array<{
  1917. slot_id: number;
  1918. type: string;
  1919. color: string;
  1920. used_grams: number;
  1921. used_meters: number;
  1922. }>;
  1923. }>(`/archives/${archiveId}/filament-requirements${plateId !== undefined ? `?plate_id=${plateId}` : ''}`),
  1924. reprintArchive: (
  1925. archiveId: number,
  1926. printerId: number,
  1927. options?: {
  1928. plate_id?: number;
  1929. ams_mapping?: number[];
  1930. timelapse?: boolean;
  1931. bed_levelling?: boolean;
  1932. flow_cali?: boolean;
  1933. vibration_cali?: boolean;
  1934. layer_inspect?: boolean;
  1935. use_ams?: boolean;
  1936. }
  1937. ) =>
  1938. request<{ status: string; printer_id: number; archive_id: number; filename: string }>(
  1939. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  1940. {
  1941. method: 'POST',
  1942. headers: options ? { 'Content-Type': 'application/json' } : undefined,
  1943. body: options ? JSON.stringify(options) : undefined,
  1944. }
  1945. ),
  1946. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  1947. const formData = new FormData();
  1948. formData.append('file', file);
  1949. const url = printerId
  1950. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  1951. : `${API_BASE}/archives/upload`;
  1952. const response = await fetch(url, {
  1953. method: 'POST',
  1954. body: formData,
  1955. });
  1956. if (!response.ok) {
  1957. const error = await response.json().catch(() => ({}));
  1958. throw new Error(error.detail || `HTTP ${response.status}`);
  1959. }
  1960. return response.json();
  1961. },
  1962. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  1963. const formData = new FormData();
  1964. files.forEach((file) => formData.append('files', file));
  1965. const url = printerId
  1966. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  1967. : `${API_BASE}/archives/upload-bulk`;
  1968. const response = await fetch(url, {
  1969. method: 'POST',
  1970. body: formData,
  1971. });
  1972. if (!response.ok) {
  1973. const error = await response.json().catch(() => ({}));
  1974. throw new Error(error.detail || `HTTP ${response.status}`);
  1975. }
  1976. return response.json();
  1977. },
  1978. // Settings
  1979. getSettings: () => request<AppSettings>('/settings/'),
  1980. updateSettings: (data: AppSettingsUpdate) =>
  1981. request<AppSettings>('/settings/', {
  1982. method: 'PUT',
  1983. body: JSON.stringify(data),
  1984. }),
  1985. getMQTTStatus: () => request<MQTTStatus>('/settings/mqtt/status'),
  1986. resetSettings: () =>
  1987. request<AppSettings>('/settings/reset', { method: 'POST' }),
  1988. exportBackup: async (categories?: Record<string, boolean>): Promise<{ blob: Blob; filename: string }> => {
  1989. const params = new URLSearchParams();
  1990. if (categories) {
  1991. if (categories.settings !== undefined) params.set('include_settings', String(categories.settings));
  1992. if (categories.notifications !== undefined) params.set('include_notifications', String(categories.notifications));
  1993. if (categories.templates !== undefined) params.set('include_templates', String(categories.templates));
  1994. if (categories.smart_plugs !== undefined) params.set('include_smart_plugs', String(categories.smart_plugs));
  1995. if (categories.external_links !== undefined) params.set('include_external_links', String(categories.external_links));
  1996. if (categories.printers !== undefined) params.set('include_printers', String(categories.printers));
  1997. if (categories.filaments !== undefined) params.set('include_filaments', String(categories.filaments));
  1998. if (categories.maintenance !== undefined) params.set('include_maintenance', String(categories.maintenance));
  1999. if (categories.archives !== undefined) params.set('include_archives', String(categories.archives));
  2000. if (categories.projects !== undefined) params.set('include_projects', String(categories.projects));
  2001. if (categories.pending_uploads !== undefined) params.set('include_pending_uploads', String(categories.pending_uploads));
  2002. if (categories.access_codes !== undefined) params.set('include_access_codes', String(categories.access_codes));
  2003. if (categories.api_keys !== undefined) params.set('include_api_keys', String(categories.api_keys));
  2004. }
  2005. const url = `${API_BASE}/settings/backup${params.toString() ? '?' + params.toString() : ''}`;
  2006. const response = await fetch(url);
  2007. // Check for errors
  2008. if (!response.ok) {
  2009. const errorText = await response.text();
  2010. throw new Error(errorText || `Backup failed with status ${response.status}`);
  2011. }
  2012. // Get filename from Content-Disposition header
  2013. const contentDisposition = response.headers.get('Content-Disposition');
  2014. let filename = 'bambuddy-backup.json';
  2015. if (contentDisposition) {
  2016. const match = contentDisposition.match(/filename=([^;]+)/);
  2017. if (match) filename = match[1].trim();
  2018. }
  2019. const blob = await response.blob();
  2020. return { blob, filename };
  2021. },
  2022. importBackup: async (file: File, overwrite = false) => {
  2023. const formData = new FormData();
  2024. formData.append('file', file);
  2025. const url = `${API_BASE}/settings/restore${overwrite ? '?overwrite=true' : ''}`;
  2026. const response = await fetch(url, {
  2027. method: 'POST',
  2028. body: formData,
  2029. });
  2030. return response.json() as Promise<{
  2031. success: boolean;
  2032. message: string;
  2033. restored?: Record<string, number>;
  2034. skipped?: Record<string, number>;
  2035. skipped_details?: Record<string, string[]>;
  2036. files_restored?: number;
  2037. total_skipped?: number;
  2038. }>;
  2039. },
  2040. checkFfmpeg: () =>
  2041. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  2042. // Cloud
  2043. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  2044. cloudLogin: (email: string, password: string, region = 'global') =>
  2045. request<CloudLoginResponse>('/cloud/login', {
  2046. method: 'POST',
  2047. body: JSON.stringify({ email, password, region }),
  2048. }),
  2049. cloudVerify: (email: string, code: string) =>
  2050. request<CloudLoginResponse>('/cloud/verify', {
  2051. method: 'POST',
  2052. body: JSON.stringify({ email, code }),
  2053. }),
  2054. cloudSetToken: (access_token: string) =>
  2055. request<CloudAuthStatus>('/cloud/token', {
  2056. method: 'POST',
  2057. body: JSON.stringify({ access_token }),
  2058. }),
  2059. cloudLogout: () =>
  2060. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  2061. getCloudSettings: (version = '02.04.00.70') =>
  2062. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  2063. getCloudSettingDetail: (settingId: string) =>
  2064. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  2065. createCloudSetting: (data: SlicerSettingCreate) =>
  2066. request<SlicerSettingDetail>('/cloud/settings', {
  2067. method: 'POST',
  2068. body: JSON.stringify(data),
  2069. }),
  2070. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  2071. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  2072. method: 'PUT',
  2073. body: JSON.stringify(data),
  2074. }),
  2075. deleteCloudSetting: (settingId: string) =>
  2076. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  2077. method: 'DELETE',
  2078. }),
  2079. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  2080. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  2081. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  2082. getAllCloudFields: () =>
  2083. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  2084. getFilamentInfo: (settingIds: string[]) =>
  2085. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  2086. method: 'POST',
  2087. body: JSON.stringify(settingIds),
  2088. }),
  2089. // Smart Plugs
  2090. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  2091. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  2092. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  2093. createSmartPlug: (data: SmartPlugCreate) =>
  2094. request<SmartPlug>('/smart-plugs/', {
  2095. method: 'POST',
  2096. body: JSON.stringify(data),
  2097. }),
  2098. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  2099. request<SmartPlug>(`/smart-plugs/${id}`, {
  2100. method: 'PATCH',
  2101. body: JSON.stringify(data),
  2102. }),
  2103. deleteSmartPlug: (id: number) =>
  2104. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  2105. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  2106. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  2107. method: 'POST',
  2108. body: JSON.stringify({ action }),
  2109. }),
  2110. getSmartPlugStatus: (id: number) =>
  2111. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  2112. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  2113. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  2114. method: 'POST',
  2115. body: JSON.stringify({ ip_address, username, password }),
  2116. }),
  2117. // Tasmota Discovery (auto-detects network)
  2118. startTasmotaScan: () =>
  2119. fetch(`${API_BASE}/smart-plugs/discover/scan`, { method: 'POST' })
  2120. .then(res => res.ok ? res.json() : res.json().then(e => { throw new Error(e.detail || `HTTP ${res.status}`); })),
  2121. getTasmotaScanStatus: () =>
  2122. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  2123. stopTasmotaScan: () =>
  2124. fetch(`${API_BASE}/smart-plugs/discover/stop`, { method: 'POST' })
  2125. .then(res => res.ok ? res.json() : res.json().then(e => { throw new Error(e.detail || `HTTP ${res.status}`); })),
  2126. getDiscoveredTasmotaDevices: () =>
  2127. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  2128. // Home Assistant Integration
  2129. testHAConnection: (url: string, token: string) =>
  2130. request<HATestConnectionResult>('/smart-plugs/ha/test-connection', {
  2131. method: 'POST',
  2132. body: JSON.stringify({ url, token }),
  2133. }),
  2134. getHAEntities: (search?: string) => {
  2135. const params = search ? `?search=${encodeURIComponent(search)}` : '';
  2136. return request<HAEntity[]>(`/smart-plugs/ha/entities${params}`);
  2137. },
  2138. getHASensorEntities: () =>
  2139. request<HASensorEntity[]>('/smart-plugs/ha/sensors'),
  2140. // Print Queue
  2141. getQueue: (printerId?: number, status?: string) => {
  2142. const params = new URLSearchParams();
  2143. if (printerId) params.set('printer_id', String(printerId));
  2144. if (status) params.set('status', status);
  2145. return request<PrintQueueItem[]>(`/queue/?${params}`);
  2146. },
  2147. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  2148. addToQueue: (data: PrintQueueItemCreate) =>
  2149. request<PrintQueueItem>('/queue/', {
  2150. method: 'POST',
  2151. body: JSON.stringify(data),
  2152. }),
  2153. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  2154. request<PrintQueueItem>(`/queue/${id}`, {
  2155. method: 'PATCH',
  2156. body: JSON.stringify(data),
  2157. }),
  2158. removeFromQueue: (id: number) =>
  2159. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  2160. reorderQueue: (items: { id: number; position: number }[]) =>
  2161. request<{ message: string }>('/queue/reorder', {
  2162. method: 'POST',
  2163. body: JSON.stringify({ items }),
  2164. }),
  2165. cancelQueueItem: (id: number) =>
  2166. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  2167. stopQueueItem: (id: number) =>
  2168. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  2169. startQueueItem: (id: number) =>
  2170. request<PrintQueueItem>(`/queue/${id}/start`, { method: 'POST' }),
  2171. // K-Profiles
  2172. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  2173. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  2174. setKProfile: (printerId: number, profile: KProfileCreate) =>
  2175. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  2176. method: 'POST',
  2177. body: JSON.stringify(profile),
  2178. }),
  2179. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  2180. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  2181. method: 'DELETE',
  2182. body: JSON.stringify(profile),
  2183. }),
  2184. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  2185. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  2186. method: 'POST',
  2187. body: JSON.stringify(profiles),
  2188. }),
  2189. // K-Profile Notes (stored locally, not on printer)
  2190. getKProfileNotes: (printerId: number) =>
  2191. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  2192. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  2193. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  2194. method: 'PUT',
  2195. body: JSON.stringify({ setting_id: settingId, note }),
  2196. }),
  2197. deleteKProfileNote: (printerId: number, settingId: string) =>
  2198. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  2199. method: 'DELETE',
  2200. }),
  2201. // Slot Preset Mappings
  2202. getSlotPresets: (printerId: number) =>
  2203. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  2204. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  2205. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  2206. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string) =>
  2207. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}`, {
  2208. method: 'PUT',
  2209. }),
  2210. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  2211. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  2212. method: 'DELETE',
  2213. }),
  2214. configureAmsSlot: (
  2215. printerId: number,
  2216. amsId: number,
  2217. trayId: number,
  2218. config: {
  2219. tray_info_idx: string;
  2220. tray_type: string;
  2221. tray_sub_brands: string;
  2222. tray_color: string;
  2223. nozzle_temp_min: number;
  2224. nozzle_temp_max: number;
  2225. cali_idx: number;
  2226. nozzle_diameter: string;
  2227. setting_id?: string;
  2228. kprofile_filament_id?: string;
  2229. kprofile_setting_id?: string;
  2230. k_value?: number;
  2231. }
  2232. ) => {
  2233. const params = new URLSearchParams({
  2234. tray_info_idx: config.tray_info_idx,
  2235. tray_type: config.tray_type,
  2236. tray_sub_brands: config.tray_sub_brands,
  2237. tray_color: config.tray_color,
  2238. nozzle_temp_min: config.nozzle_temp_min.toString(),
  2239. nozzle_temp_max: config.nozzle_temp_max.toString(),
  2240. cali_idx: config.cali_idx.toString(),
  2241. nozzle_diameter: config.nozzle_diameter,
  2242. });
  2243. if (config.setting_id) {
  2244. params.set('setting_id', config.setting_id);
  2245. }
  2246. if (config.kprofile_filament_id) {
  2247. params.set('kprofile_filament_id', config.kprofile_filament_id);
  2248. }
  2249. if (config.kprofile_setting_id) {
  2250. params.set('kprofile_setting_id', config.kprofile_setting_id);
  2251. }
  2252. if (config.k_value !== undefined && config.k_value > 0) {
  2253. params.set('k_value', config.k_value.toString());
  2254. }
  2255. return request<{ success: boolean; message: string }>(
  2256. `/printers/${printerId}/slots/${amsId}/${trayId}/configure?${params}`,
  2257. { method: 'POST' }
  2258. );
  2259. },
  2260. resetAmsSlot: (printerId: number, amsId: number, trayId: number) =>
  2261. request<{ success: boolean; message: string }>(
  2262. `/printers/${printerId}/ams/${amsId}/tray/${trayId}/reset`,
  2263. { method: 'POST' }
  2264. ),
  2265. // Filaments
  2266. listFilaments: () => request<Filament[]>('/filaments/'),
  2267. getFilament: (id: number) => request<Filament>(`/filaments/${id}`),
  2268. getFilamentsByType: (type: string) => request<Filament[]>(`/filaments/by-type/${type}`),
  2269. // Notification Providers
  2270. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  2271. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  2272. createNotificationProvider: (data: NotificationProviderCreate) =>
  2273. request<NotificationProvider>('/notifications/', {
  2274. method: 'POST',
  2275. body: JSON.stringify(data),
  2276. }),
  2277. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  2278. request<NotificationProvider>(`/notifications/${id}`, {
  2279. method: 'PATCH',
  2280. body: JSON.stringify(data),
  2281. }),
  2282. deleteNotificationProvider: (id: number) =>
  2283. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  2284. testNotificationProvider: (id: number) =>
  2285. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  2286. testNotificationConfig: (data: NotificationTestRequest) =>
  2287. request<NotificationTestResponse>('/notifications/test-config', {
  2288. method: 'POST',
  2289. body: JSON.stringify(data),
  2290. }),
  2291. testAllNotificationProviders: () =>
  2292. request<{
  2293. tested: number;
  2294. success: number;
  2295. failed: number;
  2296. results: Array<{
  2297. provider_id: number;
  2298. provider_name: string;
  2299. provider_type: string;
  2300. success: boolean;
  2301. message: string;
  2302. }>;
  2303. }>('/notifications/test-all', { method: 'POST' }),
  2304. // Notification Templates
  2305. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  2306. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  2307. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  2308. request<NotificationTemplate>(`/notification-templates/${id}`, {
  2309. method: 'PUT',
  2310. body: JSON.stringify(data),
  2311. }),
  2312. resetNotificationTemplate: (id: number) =>
  2313. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  2314. method: 'POST',
  2315. }),
  2316. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  2317. previewTemplate: (data: TemplatePreviewRequest) =>
  2318. request<TemplatePreviewResponse>('/notification-templates/preview', {
  2319. method: 'POST',
  2320. body: JSON.stringify(data),
  2321. }),
  2322. // Notification Logs
  2323. getNotificationLogs: (params?: {
  2324. limit?: number;
  2325. offset?: number;
  2326. provider_id?: number;
  2327. event_type?: string;
  2328. success?: boolean;
  2329. days?: number;
  2330. }) => {
  2331. const searchParams = new URLSearchParams();
  2332. if (params?.limit) searchParams.set('limit', String(params.limit));
  2333. if (params?.offset) searchParams.set('offset', String(params.offset));
  2334. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  2335. if (params?.event_type) searchParams.set('event_type', params.event_type);
  2336. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  2337. if (params?.days) searchParams.set('days', String(params.days));
  2338. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  2339. },
  2340. getNotificationLogStats: (days = 7) =>
  2341. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  2342. clearNotificationLogs: (olderThanDays = 30) =>
  2343. request<{ deleted: number; message: string }>(
  2344. `/notifications/logs?older_than_days=${olderThanDays}`,
  2345. { method: 'DELETE' }
  2346. ),
  2347. // Spoolman Integration
  2348. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  2349. connectSpoolman: () =>
  2350. request<{ success: boolean; message: string }>('/spoolman/connect', {
  2351. method: 'POST',
  2352. }),
  2353. disconnectSpoolman: () =>
  2354. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  2355. method: 'POST',
  2356. }),
  2357. syncPrinterAms: (printerId: number) =>
  2358. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  2359. method: 'POST',
  2360. }),
  2361. syncAllPrintersAms: () =>
  2362. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  2363. method: 'POST',
  2364. }),
  2365. getSpoolmanSpools: () =>
  2366. request<{ spools: unknown[] }>('/spoolman/spools'),
  2367. getSpoolmanFilaments: () =>
  2368. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  2369. getUnlinkedSpools: () =>
  2370. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  2371. linkSpool: (spoolId: number, trayUuid: string) =>
  2372. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  2373. method: 'POST',
  2374. body: JSON.stringify({ tray_uuid: trayUuid }),
  2375. }),
  2376. // Updates
  2377. getVersion: () => request<VersionInfo>('/updates/version'),
  2378. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  2379. applyUpdate: () =>
  2380. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean }>('/updates/apply', {
  2381. method: 'POST',
  2382. }),
  2383. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  2384. // Maintenance
  2385. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  2386. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  2387. request<MaintenanceType>('/maintenance/types', {
  2388. method: 'POST',
  2389. body: JSON.stringify(data),
  2390. }),
  2391. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  2392. request<MaintenanceType>(`/maintenance/types/${id}`, {
  2393. method: 'PATCH',
  2394. body: JSON.stringify(data),
  2395. }),
  2396. deleteMaintenanceType: (id: number) =>
  2397. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  2398. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  2399. getPrinterMaintenance: (printerId: number) =>
  2400. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  2401. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  2402. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  2403. method: 'PATCH',
  2404. body: JSON.stringify(data),
  2405. }),
  2406. performMaintenance: (itemId: number, notes?: string) =>
  2407. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  2408. method: 'POST',
  2409. body: JSON.stringify({ notes }),
  2410. }),
  2411. getMaintenanceHistory: (itemId: number) =>
  2412. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  2413. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  2414. setPrinterHours: (printerId: number, totalHours: number) =>
  2415. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  2416. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  2417. { method: 'PATCH' }
  2418. ),
  2419. assignMaintenanceType: (printerId: number, typeId: number) =>
  2420. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  2421. method: 'POST',
  2422. }),
  2423. removeMaintenanceItem: (itemId: number) =>
  2424. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  2425. method: 'DELETE',
  2426. }),
  2427. // Camera
  2428. getCameraStreamUrl: (printerId: number, fps = 10) =>
  2429. `${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`,
  2430. getCameraSnapshotUrl: (printerId: number) =>
  2431. `${API_BASE}/printers/${printerId}/camera/snapshot`,
  2432. testCameraConnection: (printerId: number) =>
  2433. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  2434. // External Links
  2435. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  2436. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  2437. createExternalLink: (data: ExternalLinkCreate) =>
  2438. request<ExternalLink>('/external-links/', {
  2439. method: 'POST',
  2440. body: JSON.stringify(data),
  2441. }),
  2442. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  2443. request<ExternalLink>(`/external-links/${id}`, {
  2444. method: 'PATCH',
  2445. body: JSON.stringify(data),
  2446. }),
  2447. deleteExternalLink: (id: number) =>
  2448. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  2449. reorderExternalLinks: (ids: number[]) =>
  2450. request<ExternalLink[]>('/external-links/reorder', {
  2451. method: 'PUT',
  2452. body: JSON.stringify({ ids }),
  2453. }),
  2454. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  2455. const formData = new FormData();
  2456. formData.append('file', file);
  2457. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  2458. method: 'POST',
  2459. body: formData,
  2460. });
  2461. if (!response.ok) {
  2462. const error = await response.json().catch(() => ({}));
  2463. throw new Error(error.detail || `HTTP ${response.status}`);
  2464. }
  2465. return response.json();
  2466. },
  2467. deleteExternalLinkIcon: (id: number) =>
  2468. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  2469. getExternalLinkIconUrl: (id: number) => `${API_BASE}/external-links/${id}/icon`,
  2470. // Projects
  2471. getProjects: (status?: string) => {
  2472. const params = new URLSearchParams();
  2473. if (status) params.set('status', status);
  2474. return request<ProjectListItem[]>(`/projects/?${params}`);
  2475. },
  2476. getProject: (id: number) => request<Project>(`/projects/${id}`),
  2477. createProject: (data: ProjectCreate) =>
  2478. request<Project>('/projects/', {
  2479. method: 'POST',
  2480. body: JSON.stringify(data),
  2481. }),
  2482. updateProject: (id: number, data: ProjectUpdate) =>
  2483. request<Project>(`/projects/${id}`, {
  2484. method: 'PATCH',
  2485. body: JSON.stringify(data),
  2486. }),
  2487. deleteProject: (id: number) =>
  2488. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  2489. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  2490. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  2491. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  2492. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  2493. method: 'POST',
  2494. body: JSON.stringify({ archive_ids: archiveIds }),
  2495. }),
  2496. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  2497. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  2498. method: 'POST',
  2499. body: JSON.stringify({ archive_ids: archiveIds }),
  2500. }),
  2501. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  2502. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  2503. method: 'POST',
  2504. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  2505. }),
  2506. // Project Attachments
  2507. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  2508. status: string;
  2509. filename: string;
  2510. original_name: string;
  2511. attachments: ProjectAttachment[];
  2512. }> => {
  2513. const formData = new FormData();
  2514. formData.append('file', file);
  2515. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  2516. method: 'POST',
  2517. body: formData,
  2518. });
  2519. if (!response.ok) {
  2520. const error = await response.json().catch(() => ({}));
  2521. throw new Error(error.detail || `HTTP ${response.status}`);
  2522. }
  2523. return response.json();
  2524. },
  2525. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  2526. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  2527. deleteProjectAttachment: (projectId: number, filename: string) =>
  2528. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  2529. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  2530. { method: 'DELETE' }
  2531. ),
  2532. // BOM (Bill of Materials)
  2533. getProjectBOM: (projectId: number) =>
  2534. request<BOMItem[]>(`/projects/${projectId}/bom`),
  2535. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  2536. request<BOMItem>(`/projects/${projectId}/bom`, {
  2537. method: 'POST',
  2538. body: JSON.stringify(data),
  2539. }),
  2540. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  2541. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  2542. method: 'PATCH',
  2543. body: JSON.stringify(data),
  2544. }),
  2545. deleteBOMItem: (projectId: number, itemId: number) =>
  2546. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  2547. method: 'DELETE',
  2548. }),
  2549. // Templates
  2550. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  2551. createTemplateFromProject: (projectId: number) =>
  2552. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  2553. createProjectFromTemplate: (templateId: number, name?: string) =>
  2554. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  2555. method: 'POST',
  2556. }),
  2557. // Timeline
  2558. getProjectTimeline: (projectId: number, limit = 50) =>
  2559. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  2560. // Project Export/Import
  2561. exportProjectJson: (projectId: number) =>
  2562. request<ProjectExport>(`/projects/${projectId}/export?format=json`),
  2563. importProject: (data: ProjectImport) =>
  2564. request<Project>('/projects/import', {
  2565. method: 'POST',
  2566. body: JSON.stringify(data),
  2567. }),
  2568. // API Keys
  2569. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  2570. createAPIKey: (data: APIKeyCreate) =>
  2571. request<APIKeyCreateResponse>('/api-keys/', {
  2572. method: 'POST',
  2573. body: JSON.stringify(data),
  2574. }),
  2575. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  2576. request<APIKey>(`/api-keys/${id}`, {
  2577. method: 'PATCH',
  2578. body: JSON.stringify(data),
  2579. }),
  2580. deleteAPIKey: (id: number) =>
  2581. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  2582. // AMS History
  2583. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  2584. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  2585. // System Info
  2586. getSystemInfo: () => request<SystemInfo>('/system/info'),
  2587. // Library (File Manager)
  2588. getLibraryFolders: () => request<LibraryFolderTree[]>('/library/folders'),
  2589. createLibraryFolder: (data: LibraryFolderCreate) =>
  2590. request<LibraryFolder>('/library/folders', {
  2591. method: 'POST',
  2592. body: JSON.stringify(data),
  2593. }),
  2594. updateLibraryFolder: (id: number, data: LibraryFolderUpdate) =>
  2595. request<LibraryFolder>(`/library/folders/${id}`, {
  2596. method: 'PUT',
  2597. body: JSON.stringify(data),
  2598. }),
  2599. deleteLibraryFolder: (id: number) =>
  2600. request<{ status: string; message: string }>(`/library/folders/${id}`, { method: 'DELETE' }),
  2601. getLibraryFoldersByProject: (projectId: number) =>
  2602. request<LibraryFolder[]>(`/library/folders/by-project/${projectId}`),
  2603. getLibraryFoldersByArchive: (archiveId: number) =>
  2604. request<LibraryFolder[]>(`/library/folders/by-archive/${archiveId}`),
  2605. getLibraryFiles: (folderId?: number | null, includeRoot = true) => {
  2606. const params = new URLSearchParams();
  2607. if (folderId !== undefined && folderId !== null) {
  2608. params.set('folder_id', String(folderId));
  2609. }
  2610. params.set('include_root', String(includeRoot));
  2611. return request<LibraryFileListItem[]>(`/library/files?${params}`);
  2612. },
  2613. getLibraryFile: (id: number) => request<LibraryFile>(`/library/files/${id}`),
  2614. uploadLibraryFile: async (file: File, folderId?: number | null): Promise<LibraryFileUploadResponse> => {
  2615. const formData = new FormData();
  2616. formData.append('file', file);
  2617. const params = folderId ? `?folder_id=${folderId}` : '';
  2618. const response = await fetch(`${API_BASE}/library/files${params}`, {
  2619. method: 'POST',
  2620. body: formData,
  2621. });
  2622. if (!response.ok) {
  2623. const error = await response.json().catch(() => ({}));
  2624. throw new Error(error.detail || `HTTP ${response.status}`);
  2625. }
  2626. return response.json();
  2627. },
  2628. extractZipFile: async (
  2629. file: File,
  2630. folderId?: number | null,
  2631. preserveStructure: boolean = true,
  2632. createFolderFromZip: boolean = false
  2633. ): Promise<ZipExtractResponse> => {
  2634. const formData = new FormData();
  2635. formData.append('file', file);
  2636. const params = new URLSearchParams();
  2637. if (folderId) params.set('folder_id', String(folderId));
  2638. params.set('preserve_structure', String(preserveStructure));
  2639. params.set('create_folder_from_zip', String(createFolderFromZip));
  2640. const response = await fetch(`${API_BASE}/library/files/extract-zip?${params}`, {
  2641. method: 'POST',
  2642. body: formData,
  2643. });
  2644. if (!response.ok) {
  2645. const error = await response.json().catch(() => ({}));
  2646. throw new Error(error.detail || `HTTP ${response.status}`);
  2647. }
  2648. return response.json();
  2649. },
  2650. updateLibraryFile: (id: number, data: LibraryFileUpdate) =>
  2651. request<LibraryFile>(`/library/files/${id}`, {
  2652. method: 'PUT',
  2653. body: JSON.stringify(data),
  2654. }),
  2655. deleteLibraryFile: (id: number) =>
  2656. request<{ status: string; message: string }>(`/library/files/${id}`, { method: 'DELETE' }),
  2657. getLibraryFileDownloadUrl: (id: number) => `${API_BASE}/library/files/${id}/download`,
  2658. getLibraryFileThumbnailUrl: (id: number) => `${API_BASE}/library/files/${id}/thumbnail`,
  2659. getLibraryFileGcodeUrl: (id: number) => `${API_BASE}/library/files/${id}/gcode`,
  2660. moveLibraryFiles: (fileIds: number[], folderId: number | null) =>
  2661. request<{ status: string; moved: number }>('/library/files/move', {
  2662. method: 'POST',
  2663. body: JSON.stringify({ file_ids: fileIds, folder_id: folderId }),
  2664. }),
  2665. bulkDeleteLibrary: (fileIds: number[], folderIds: number[]) =>
  2666. request<{ deleted_files: number; deleted_folders: number }>('/library/bulk-delete', {
  2667. method: 'POST',
  2668. body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds }),
  2669. }),
  2670. getLibraryStats: () => request<LibraryStats>('/library/stats'),
  2671. addLibraryFilesToQueue: (fileIds: number[]) =>
  2672. request<AddToQueueResponse>('/library/files/add-to-queue', {
  2673. method: 'POST',
  2674. body: JSON.stringify({ file_ids: fileIds }),
  2675. }),
  2676. printLibraryFile: (
  2677. fileId: number,
  2678. printerId: number,
  2679. options?: {
  2680. plate_id?: number;
  2681. ams_mapping?: number[];
  2682. bed_levelling?: boolean;
  2683. flow_cali?: boolean;
  2684. vibration_cali?: boolean;
  2685. layer_inspect?: boolean;
  2686. timelapse?: boolean;
  2687. use_ams?: boolean;
  2688. }
  2689. ) =>
  2690. request<{ status: string; printer_id: number; archive_id: number; filename: string }>(
  2691. `/library/files/${fileId}/print?printer_id=${printerId}`,
  2692. {
  2693. method: 'POST',
  2694. body: options ? JSON.stringify(options) : undefined,
  2695. }
  2696. ),
  2697. getLibraryFilePlates: (fileId: number) =>
  2698. request<{
  2699. file_id: number;
  2700. filename: string;
  2701. plates: Array<{
  2702. index: number;
  2703. name: string | null;
  2704. objects: string[];
  2705. has_thumbnail: boolean;
  2706. thumbnail_url: string | null;
  2707. print_time_seconds: number | null;
  2708. filament_used_grams: number | null;
  2709. filaments: Array<{
  2710. slot_id: number;
  2711. type: string;
  2712. color: string;
  2713. used_grams: number;
  2714. used_meters: number;
  2715. }>;
  2716. }>;
  2717. is_multi_plate: boolean;
  2718. }>(`/library/files/${fileId}/plates`),
  2719. getLibraryFileFilamentRequirements: (fileId: number, plateId?: number) =>
  2720. request<{
  2721. file_id: number;
  2722. filename: string;
  2723. filaments: Array<{
  2724. slot_id: number;
  2725. type: string;
  2726. color: string;
  2727. used_grams: number;
  2728. used_meters: number;
  2729. }>;
  2730. }>(`/library/files/${fileId}/filament-requirements${plateId !== undefined ? `?plate_id=${plateId}` : ''}`),
  2731. };
  2732. // AMS History types
  2733. export interface AMSHistoryPoint {
  2734. recorded_at: string;
  2735. humidity: number | null;
  2736. humidity_raw: number | null;
  2737. temperature: number | null;
  2738. }
  2739. export interface AMSHistoryResponse {
  2740. printer_id: number;
  2741. ams_id: number;
  2742. data: AMSHistoryPoint[];
  2743. min_humidity: number | null;
  2744. max_humidity: number | null;
  2745. avg_humidity: number | null;
  2746. min_temperature: number | null;
  2747. max_temperature: number | null;
  2748. avg_temperature: number | null;
  2749. }
  2750. // System Info types
  2751. export interface SystemInfo {
  2752. app: {
  2753. version: string;
  2754. base_dir: string;
  2755. archive_dir: string;
  2756. };
  2757. database: {
  2758. archives: number;
  2759. archives_completed: number;
  2760. archives_failed: number;
  2761. archives_printing: number;
  2762. printers: number;
  2763. filaments: number;
  2764. projects: number;
  2765. smart_plugs: number;
  2766. total_print_time_seconds: number;
  2767. total_print_time_formatted: string;
  2768. total_filament_grams: number;
  2769. total_filament_kg: number;
  2770. };
  2771. printers: {
  2772. total: number;
  2773. connected: number;
  2774. connected_list: Array<{
  2775. id: number;
  2776. name: string;
  2777. state: string;
  2778. model: string;
  2779. }>;
  2780. };
  2781. storage: {
  2782. archive_size_bytes: number;
  2783. archive_size_formatted: string;
  2784. database_size_bytes: number;
  2785. database_size_formatted: string;
  2786. disk_total_bytes: number;
  2787. disk_total_formatted: string;
  2788. disk_used_bytes: number;
  2789. disk_used_formatted: string;
  2790. disk_free_bytes: number;
  2791. disk_free_formatted: string;
  2792. disk_percent_used: number;
  2793. };
  2794. system: {
  2795. platform: string;
  2796. platform_release: string;
  2797. platform_version: string;
  2798. architecture: string;
  2799. hostname: string;
  2800. python_version: string;
  2801. uptime_seconds: number;
  2802. uptime_formatted: string;
  2803. boot_time: string;
  2804. };
  2805. memory: {
  2806. total_bytes: number;
  2807. total_formatted: string;
  2808. available_bytes: number;
  2809. available_formatted: string;
  2810. used_bytes: number;
  2811. used_formatted: string;
  2812. percent_used: number;
  2813. };
  2814. cpu: {
  2815. count: number;
  2816. count_logical: number;
  2817. percent: number;
  2818. };
  2819. }
  2820. // Library (File Manager) types
  2821. export interface LibraryFolderTree {
  2822. id: number;
  2823. name: string;
  2824. parent_id: number | null;
  2825. project_id: number | null;
  2826. archive_id: number | null;
  2827. project_name: string | null;
  2828. archive_name: string | null;
  2829. file_count: number;
  2830. children: LibraryFolderTree[];
  2831. }
  2832. export interface LibraryFolder {
  2833. id: number;
  2834. name: string;
  2835. parent_id: number | null;
  2836. project_id: number | null;
  2837. archive_id: number | null;
  2838. project_name: string | null;
  2839. archive_name: string | null;
  2840. file_count: number;
  2841. created_at: string;
  2842. updated_at: string;
  2843. }
  2844. export interface LibraryFolderCreate {
  2845. name: string;
  2846. parent_id?: number | null;
  2847. project_id?: number | null;
  2848. archive_id?: number | null;
  2849. }
  2850. export interface LibraryFolderUpdate {
  2851. name?: string;
  2852. parent_id?: number | null;
  2853. project_id?: number | null; // 0 to unlink
  2854. archive_id?: number | null; // 0 to unlink
  2855. }
  2856. export interface LibraryFileDuplicate {
  2857. id: number;
  2858. filename: string;
  2859. folder_id: number | null;
  2860. folder_name: string | null;
  2861. created_at: string;
  2862. }
  2863. export interface LibraryFile {
  2864. id: number;
  2865. folder_id: number | null;
  2866. folder_name: string | null;
  2867. project_id: number | null;
  2868. project_name: string | null;
  2869. filename: string;
  2870. file_path: string;
  2871. file_type: string;
  2872. file_size: number;
  2873. file_hash: string | null;
  2874. thumbnail_path: string | null;
  2875. metadata: Record<string, unknown> | null;
  2876. print_count: number;
  2877. last_printed_at: string | null;
  2878. notes: string | null;
  2879. duplicates: LibraryFileDuplicate[] | null;
  2880. duplicate_count: number;
  2881. created_at: string;
  2882. updated_at: string;
  2883. }
  2884. export interface LibraryFileListItem {
  2885. id: number;
  2886. folder_id: number | null;
  2887. filename: string;
  2888. file_type: string;
  2889. file_size: number;
  2890. thumbnail_path: string | null;
  2891. print_count: number;
  2892. duplicate_count: number;
  2893. created_at: string;
  2894. print_name: string | null;
  2895. print_time_seconds: number | null;
  2896. filament_used_grams: number | null;
  2897. }
  2898. export interface LibraryFileUpdate {
  2899. filename?: string;
  2900. folder_id?: number | null;
  2901. project_id?: number | null;
  2902. notes?: string | null;
  2903. }
  2904. export interface LibraryFileUploadResponse {
  2905. id: number;
  2906. filename: string;
  2907. file_type: string;
  2908. file_size: number;
  2909. thumbnail_path: string | null;
  2910. duplicate_of: number | null;
  2911. metadata: Record<string, unknown> | null;
  2912. }
  2913. export interface LibraryStats {
  2914. total_files: number;
  2915. total_folders: number;
  2916. total_size_bytes: number;
  2917. files_by_type: Record<string, number>;
  2918. total_prints: number;
  2919. disk_free_bytes: number;
  2920. disk_total_bytes: number;
  2921. disk_used_bytes: number;
  2922. }
  2923. export interface ZipExtractResult {
  2924. filename: string;
  2925. file_id: number;
  2926. folder_id: number | null;
  2927. }
  2928. export interface ZipExtractError {
  2929. filename: string;
  2930. error: string;
  2931. }
  2932. export interface ZipExtractResponse {
  2933. extracted: number;
  2934. folders_created: number;
  2935. files: ZipExtractResult[];
  2936. errors: ZipExtractError[];
  2937. }
  2938. // Library Queue types
  2939. export interface AddToQueueResult {
  2940. file_id: number;
  2941. filename: string;
  2942. queue_item_id: number;
  2943. archive_id: number;
  2944. }
  2945. export interface AddToQueueError {
  2946. file_id: number;
  2947. filename: string;
  2948. error: string;
  2949. }
  2950. export interface AddToQueueResponse {
  2951. added: AddToQueueResult[];
  2952. errors: AddToQueueError[];
  2953. }
  2954. // Discovery types
  2955. export interface DiscoveredPrinter {
  2956. serial: string;
  2957. name: string;
  2958. ip_address: string;
  2959. model: string | null;
  2960. discovered_at: string | null;
  2961. }
  2962. export interface DiscoveryStatus {
  2963. running: boolean;
  2964. }
  2965. export interface DiscoveryInfo {
  2966. is_docker: boolean;
  2967. ssdp_running: boolean;
  2968. scan_running: boolean;
  2969. }
  2970. export interface SubnetScanStatus {
  2971. running: boolean;
  2972. scanned: number;
  2973. total: number;
  2974. }
  2975. // Discovery API
  2976. export const discoveryApi = {
  2977. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  2978. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  2979. startDiscovery: (duration: number = 10) =>
  2980. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  2981. stopDiscovery: () =>
  2982. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  2983. getDiscoveredPrinters: () =>
  2984. request<DiscoveredPrinter[]>('/discovery/printers'),
  2985. // Subnet scanning (for Docker environments)
  2986. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  2987. request<SubnetScanStatus>('/discovery/scan', {
  2988. method: 'POST',
  2989. body: JSON.stringify({ subnet, timeout }),
  2990. }),
  2991. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  2992. stopSubnetScan: () =>
  2993. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  2994. };
  2995. // Virtual Printer types
  2996. export interface VirtualPrinterStatus {
  2997. enabled: boolean;
  2998. running: boolean;
  2999. mode: 'immediate' | 'queue' | 'review' | 'print_queue'; // 'queue' is legacy, normalized to 'review'
  3000. name: string;
  3001. serial: string;
  3002. model: string;
  3003. model_name: string;
  3004. pending_files: number;
  3005. }
  3006. export interface VirtualPrinterSettings {
  3007. enabled: boolean;
  3008. access_code_set: boolean;
  3009. mode: 'immediate' | 'queue' | 'review' | 'print_queue'; // 'queue' is legacy, normalized to 'review'
  3010. model: string;
  3011. status: VirtualPrinterStatus;
  3012. }
  3013. export interface VirtualPrinterModels {
  3014. models: Record<string, string>; // SSDP code -> display name
  3015. default: string;
  3016. }
  3017. export interface PendingUpload {
  3018. id: number;
  3019. filename: string;
  3020. file_size: number;
  3021. source_ip: string | null;
  3022. status: string;
  3023. tags: string | null;
  3024. notes: string | null;
  3025. project_id: number | null;
  3026. uploaded_at: string;
  3027. }
  3028. // Virtual Printer API
  3029. export const virtualPrinterApi = {
  3030. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  3031. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  3032. updateSettings: (data: {
  3033. enabled?: boolean;
  3034. access_code?: string;
  3035. mode?: 'immediate' | 'review' | 'print_queue';
  3036. model?: string;
  3037. }) => {
  3038. const params = new URLSearchParams();
  3039. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  3040. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  3041. if (data.mode !== undefined) params.set('mode', data.mode);
  3042. if (data.model !== undefined) params.set('model', data.model);
  3043. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  3044. method: 'PUT',
  3045. });
  3046. },
  3047. };
  3048. // Pending Uploads API
  3049. export const pendingUploadsApi = {
  3050. list: () => request<PendingUpload[]>('/pending-uploads/'),
  3051. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  3052. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  3053. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  3054. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  3055. method: 'POST',
  3056. body: JSON.stringify(data || {}),
  3057. }),
  3058. discard: (id: number) =>
  3059. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  3060. archiveAll: () =>
  3061. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  3062. discardAll: () =>
  3063. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  3064. };
  3065. // Firmware API Types
  3066. export interface FirmwareUpdateInfo {
  3067. printer_id: number;
  3068. printer_name: string;
  3069. model: string | null;
  3070. current_version: string | null;
  3071. latest_version: string | null;
  3072. update_available: boolean;
  3073. download_url: string | null;
  3074. release_notes: string | null;
  3075. }
  3076. export interface FirmwareUploadPrepare {
  3077. can_proceed: boolean;
  3078. sd_card_present: boolean;
  3079. sd_card_free_space: number;
  3080. firmware_size: number;
  3081. space_sufficient: boolean;
  3082. update_available: boolean;
  3083. current_version: string | null;
  3084. latest_version: string | null;
  3085. firmware_filename: string | null;
  3086. errors: string[];
  3087. }
  3088. export interface FirmwareUploadStatus {
  3089. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  3090. progress: number;
  3091. message: string;
  3092. error: string | null;
  3093. firmware_filename: string | null;
  3094. firmware_version: string | null;
  3095. }
  3096. // Firmware API
  3097. export const firmwareApi = {
  3098. checkUpdates: () =>
  3099. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  3100. checkPrinterUpdate: (printerId: number) =>
  3101. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  3102. prepareUpload: (printerId: number) =>
  3103. request<FirmwareUploadPrepare>(`/firmware/updates/${printerId}/prepare`),
  3104. startUpload: (printerId: number) =>
  3105. request<{ started: boolean; message: string }>(`/firmware/updates/${printerId}/upload`, {
  3106. method: 'POST',
  3107. }),
  3108. getUploadStatus: (printerId: number) =>
  3109. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  3110. };
  3111. // Support types
  3112. export interface DebugLoggingState {
  3113. enabled: boolean;
  3114. enabled_at: string | null;
  3115. duration_seconds: number | null;
  3116. }
  3117. export interface LogEntry {
  3118. timestamp: string;
  3119. level: string;
  3120. logger_name: string;
  3121. message: string;
  3122. }
  3123. export interface LogsResponse {
  3124. entries: LogEntry[];
  3125. total_in_file: number;
  3126. filtered_count: number;
  3127. }
  3128. // Support API
  3129. export const supportApi = {
  3130. getDebugLoggingState: () =>
  3131. request<DebugLoggingState>('/support/debug-logging'),
  3132. setDebugLogging: (enabled: boolean) =>
  3133. request<DebugLoggingState>('/support/debug-logging', {
  3134. method: 'POST',
  3135. body: JSON.stringify({ enabled }),
  3136. }),
  3137. downloadSupportBundle: async () => {
  3138. const response = await fetch(`${API_BASE}/support/bundle`);
  3139. if (!response.ok) {
  3140. const error = await response.json().catch(() => ({}));
  3141. throw new Error(error.detail || `HTTP ${response.status}`);
  3142. }
  3143. // Get filename from Content-Disposition header or use default
  3144. const disposition = response.headers.get('Content-Disposition');
  3145. const filenameMatch = disposition?.match(/filename=(.+)/);
  3146. const filename = filenameMatch ? filenameMatch[1] : 'bambuddy-support.zip';
  3147. // Download the blob
  3148. const blob = await response.blob();
  3149. const url = window.URL.createObjectURL(blob);
  3150. const a = document.createElement('a');
  3151. a.href = url;
  3152. a.download = filename;
  3153. document.body.appendChild(a);
  3154. a.click();
  3155. document.body.removeChild(a);
  3156. window.URL.revokeObjectURL(url);
  3157. },
  3158. getLogs: (params?: { limit?: number; level?: string; search?: string }) => {
  3159. const searchParams = new URLSearchParams();
  3160. if (params?.limit) searchParams.set('limit', params.limit.toString());
  3161. if (params?.level) searchParams.set('level', params.level);
  3162. if (params?.search) searchParams.set('search', params.search);
  3163. const query = searchParams.toString();
  3164. return request<LogsResponse>(`/support/logs${query ? `?${query}` : ''}`);
  3165. },
  3166. clearLogs: () =>
  3167. request<{ message: string }>('/support/logs', { method: 'DELETE' }),
  3168. };